首页 > 解决方案 > 在 R 中使用 lapply 时自定义函数返回错误

问题描述

我有一个要传递给函数的列表。如果我手动遍历此列表,此功能将起作用。但是当我使用 lapply 时,我看到了这个错误:

argument 'pattern' has length > 1 and only the first element will be used[[1]]

这是我的示例代码


columns_to_collapse <- list(c(
                         "abc",
                         "bcd",
                         "cde"))
                         
merge_cols <- function(cn) {
  # return column indices
  cn <- eval(cn)
  x <- d[, grep(cn, names(d))]
  x_1 <- as.numeric(x[1])
  x_2 <- as.numeric(x[2])
  # create a new column
  d[, substitute(cn) := do.call(paste, .SD), .SDcols = c(x_1,x_2)]
  # delete the old ones
  d[, (c(x_1,x_2)) := NULL]
  return(d)

}

lapply(columns_to_collapse, merge_cols)```

标签: rlapply

解决方案


我相信您想遍历函数中的每个元素“abc”、“bcd”和“cde”。在这种情况下,您应该通过其中一个c("abc", "bcd", "cde")list("abc", "bcd", "cde")但不是混合的list(c(..)to lapply。

在您的公式中, lapply 正在列表的每个元素上运行该函数 - 您的列表只有 1 个元素,它是 3 个字符的向量,并且 grep 不接受向量参数,因此您收到错误消息length is > 1

我无法重现您的代码,因为您没有指定d上面代码中的内容


推荐阅读