【问题标题】:Custom function returns error when using lapply in R在 R 中使用 lapply 时自定义函数返回错误
【发布时间】:2021-03-17 00:46:29
【问题描述】:

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

【问题讨论】:

  • 试试list("abc", "bcd","cde")。使用list(c(...)),您可以创建一个包含一个组件的列表,该组件是一个长度为3 的字符向量。这就是您收到警告argument 'pattern' has length &gt; 1 的原因。但只是猜测,因为缺少d,我无法运行您的代码。

标签: r lapply


【解决方案1】:

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

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

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

【讨论】:

  • 像魅力一样工作。谢谢。
  • @Kay 如果答案有帮助,请随时单击左侧的复选标记接受答案。每个帖子只能接受一个答案。参考 - stackoverflow.com/help/someone-answers
猜你喜欢
  • 1970-01-01
  • 2020-09-14
  • 1970-01-01
  • 2021-05-30
  • 2018-04-16
  • 1970-01-01
  • 1970-01-01
  • 2016-05-18
  • 1970-01-01
相关资源
最近更新 更多