我遇到一个奇怪的问题,如果在另一个函数中使用该函数,data.table
函数不能识别明确定义的参数。
这是一个简单的例子:
第一个函数testFun1
,
Error in fun(value) : could not find function "fun"
但是,很明显默认值为fun
。
使用reshape2::dcast
没有问题,请参阅testFun2
。
testFun1 <- function(data, formula, fun = sum, value.var = "value") {
data.table::dcast(data = data, formula = formula, fun.aggregate = fun,
value.var = "value")
}
testFun2 <- function(data, formula, fun = sum, value.var = "value") {
reshape2::dcast(data = data, formula = formula, fun.aggregate = fun,
value.var = "value")
}
d <- data.table(x = c("a", "b"), y = c("c", "d"), value = 1)
testFun1(d, x ~ y)
# Error in fun(value) : could not find function "fun"
testFun2(d, x ~ y)
答案 0 :(得分:0)
这似乎是先前版本的data.table中存在的一个错误,已修复,并再次弹出。
解决方案是将包装函数中的参数名称从fun
更改为fun.aggregate
,以使其与data.table::dcast
参数的名称匹配。
示例:
testFun1 <- function(data, formula, fun.aggregate = sum, value.var = "value") {
data.table::dcast(data = data, formula = formula,
fun.aggregate = fun.aggregate, value.var = "value")
}
答案 1 :(得分:0)
Arun对dcast
的最新改进已经解决了该问题。它们很快将以1.12.2版本在CRAN上可用。
install.packages("data.table", repos="https://Rdatatable.gitlab.io/data.table")
library(data.table)
testFun1 <- function(data, formula, fun = sum, value.var = "value") {
data.table::dcast(data = data, formula = formula, fun.aggregate = fun,
value.var = "value")
}
d <- data.table(x = c("a", "b"), y = c("c", "d"), value = 1)
testFun1(d, x ~ y)testFun1 <- function(data, formula, fun = sum, value.var = "value") {
data.table::dcast(data = data, formula = formula, fun.aggregate = fun,
value.var = "value")
}
testFun2 <- function(data, formula, fun = sum, value.var = "value") {
reshape2::dcast(data = data, formula = formula, fun.aggregate = fun,
value.var = "value")
}
d <- data.table(x = c("a", "b"), y = c("c", "d"), value = 1)
all.equal(testFun1(d, x ~ y), as.data.table(testFun2(d, x ~ y)), check.attributes=FALSE)
#[1] TRUE