Reputation: 313
I encounter a weird problem that a data.table
function doesn't recognize a well-defined argument if the function is used in another function.
Here is a simple example:
I get an error when the first function testFun1
,
Error in fun(value) : could not find function "fun"
However, it is clear that there is default value of fun
.
There is no issue using reshape2::dcast
, See 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)
Upvotes: 13
Views: 317
Reputation: 16697
This issue has been already resolved by recent improvements to dcast
by made Arun. They will be soon available on CRAN as 1.12.2 version.
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)
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
Upvotes: 1
Reputation: 21
This seems to be a bug that had existed in a previous version of data.table, was fixed, and has popped up again.
The solution was to change the parameter name in your wrapper function from fun
to fun.aggregate
so that it matches the name of the data.table::dcast
parameter.
Example:
testFun1 <- function(data, formula, fun.aggregate = sum, value.var = "value") {
data.table::dcast(data = data, formula = formula,
fun.aggregate = fun.aggregate, value.var = "value")
}
Upvotes: 0