r - 在 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)```
解决方案
我相信您想遍历函数中的每个元素“abc”、“bcd”和“cde”。在这种情况下,您应该通过其中一个c("abc", "bcd", "cde")
或list("abc", "bcd", "cde")
但不是混合的list(c(..)
to lapply。
在您的公式中, lapply 正在列表的每个元素上运行该函数 - 您的列表只有 1 个元素,它是 3 个字符的向量,并且 grep 不接受向量参数,因此您收到错误消息length is > 1
我无法重现您的代码,因为您没有指定d
上面代码中的内容
推荐阅读
- perl - 在 Linux 的 Windows 子系统上安装 Bio::Grep 失败
- go - Go 接口在方法之间强制执行相同的参数类型(但可以是任何类型)
- c# - 如何检查是否在 Sharepoint 团队网站中使用 CSOM 检查了“允许访问请求”
- html - 需要帮助使按钮的左侧向左流动
- sql - 是否可以在 SQL 查询中将 24 小时时间戳转换为秒?
- c++ - 数组打印功能
- java - 使用 Byte Buddy 添加 Bean 以启动 Spring Boot
- r - 总结 r 中分组变量的比例
- node.js - 在 NestJS 中向 HTTP 请求添加证书
- c++ - int* 和 int[] 类型的无效操作数到二元运算符+