【问题标题】:Function works fine alone, but returns error with apply functions: attempt to select less than one element in get1index函数单独工作正常,但应用函数返回错误:尝试在 get1index 中选择少于一个元素
【发布时间】: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


    【解决方案1】:

    注意i 在可行的个别情况下替换列表的索引,例如i=2:f(list[[2]], "histology results", upto = "diagnosed by")

    在您的lapply 函数中,您实际上调用的是类似于list[[list]] 而不是list[[1]], list[[2]], ..., list[[length(list)]]。因此,您要给lapply 迭代的对象是索引列表1:length(list)。试试:

    lapply(1:length(list), function(i) f(list[[i]], "histology results", upto = "diagnosed by"))
    

    或者将list 对象提供给lapply 并直接在其上调用f 函数而不使用子集。试试:

    lapply(list, function(i) f(i, "histology results", upto = "diagnosed by"))
    

    【讨论】:

    • 这太棒了!谢谢!不过我还是不太明白这个概念。 :-/
    • 如果你熟悉 for 循环,这类似于:for (i in 1: length(list) { f(list[[i]], "histology results", upto = "diagnosed by") }。你试试这些练习怎么样,看看返回什么lapply(1:length(list), function(i) print(i))lapply(1:length(list), function(i) list[[i]])
    • 你也可以试试lapply(list, function(i) print(i),然后lapply(list, function(i) f(i, "histology results", upto = "diagnosed by"))
    猜你喜欢
    • 2023-04-04
    • 2020-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-13
    • 1970-01-01
    相关资源
    最近更新 更多