【发布时间】:2018-03-23 17:18:44
【问题描述】:
我有一个看起来像这样的字符向量列表:
[[1]]
[1] "medical" "center" "name
[7] "laboratory" "medicine" "william"
[13] "laboratories" "2431" "highway"
...
[680]
...
[[100]]
..
[590]
列表的每个成员都代表一个患者,每个成员的字符向量是他们的标记化医疗报告。我正在挖掘列表中的每个成员的某些参数,并使用以下代码来执行此操作:
f <- function(x, phrase, n_words = 3L, upto = NULL) {
x <- paste0(x, collapse = ' ')
word <- '\\b\\w+\\b\\s*'
p <- if (!is.null(upto))
sprintf('(?:%s)\\s*((%s)+)%s|.', phrase, word, upto)
else sprintf('(?:%s)\\s*((%s){1,%s})|.', phrase, word, n_words)
trimws(gsub(p, '\\1', x))
}
在单个字符向量对象上使用此函数时效果很好。例如:
>f(P1, "histology results", upto = "diagnosed by"))
[1] highly differentiated, stage 4 out of 4
其中 P1 是标记词的字符对象。
但是,使用列表并使用 lapply 函数时,我得到了一个错误。
> lapply(list, f, list[[i]], "histology results", upto = "diagnosed by")
Error in list[[i]] :
attempt to select less than one element in get1index
当我运行选择列表中各个成员的函数时,它对每个成员都运行良好,不会引发任何错误。举个例子:
> f(list[[2]], "histology results", upto = "diagnosed by")
[1] "mildly differentiated stage 1 of 4"
我做错了什么?
【问题讨论】:
标签: r function error-handling lapply