在 R 中使用 lapply 时自定义函数 returns 出错

Custom function returns error when using lapply in R

我有一个要传递给函数的列表。如果我手动循环遍历此列表,则此功能有效。但是当我使用 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)```

我相信您想遍历函数中的每个元素“abc”、“bcd”和“cde”。在这种情况下,您应该传递 c("abc", "bcd", "cde")list("abc", "bcd", "cde") 而不是 list(c(..) 到 lapply.

的混合

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

我无法重现你的代码,因为你没有在上面的代码中指定 d 是什么