Home > Blockchain >  Function call from argument passed to data.table but its still a character vec
Function call from argument passed to data.table but its still a character vec

Time:09-11

I wrote a function that takes the following arguments:

library(data.table)

df <- data.table(data = c(2.68719220295551, 1.63699824970758, 0.558315275795336,
                          1.50499717176723, 1.08486383823679, 1.3, 2.05026695212586, 
                          1.16129386585915, 2.79883781159714, 0.487299412886244),
                 month = c(11, 11, 11, 11, 11, 11, 11, 12, 12, 12))

g <- function(dt, group, func) {
rndi <- dt[, list(data = func(data)), by = group]
rndi
}

When I call the function:

g(df, group = "month", func = "mean")

the func is not applied to the data since its just a character vector. This is what should happen:

dfi[, list(data = mean(data)), by = "month"]

Result: 
   month     data
1:    11 1.546091
2:    12 1.482477

How do I make the argument func(data) a function I can apply to my data table? (here func could be mean, var or any other function)

CodePudding user response:

You can just pass the function, instead of a string:

g(df,group="month", mean)

Output:

   month     data
1:    11 1.546091
2:    12 1.482477

CodePudding user response:

Use match.fun to ensure it's a function. It works well because you can pass a function literal or a string naming the function:

match.fun("mean")
# function (x, ...) 
# UseMethod("mean")
# <bytecode: 0x000000001d6bb578>
# <environment: namespace:base>
match.fun(mean)
# function (x, ...) 
# UseMethod("mean")
# <bytecode: 0x000000001d6bb578>
# <environment: namespace:base>

g <- function(dt, group, func) {
  func <- match.fun(func)
  rndi <- dt[, list(data = func(data)), by = group]
  rndi
}

g(df, group = "month", func = "mean")
#    month     data
#    <num>    <num>
# 1:    11 1.546091
# 2:    12 1.482477
g(df, group = "month", func = mean)
#    month     data
#    <num>    <num>
# 1:    11 1.546091
# 2:    12 1.482477
  • Related