Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R data.table function doesn't recognize an already-specified argument

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)
like image 514
Jiexing Wu Avatar asked Mar 22 '18 01:03

Jiexing Wu


1 Answers

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
like image 86
jangorecki Avatar answered Oct 03 '22 09:10

jangorecki