【发布时间】: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 > 1的原因。但只是猜测,因为缺少d,我无法运行您的代码。