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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With