使用取决于data.table行类型的函数计算幅度

时间:2019-02-02 12:04:35

标签: r data.table

我想计算一个取决于data.table行类型的幅度:

library (data.table)

n1 <- c(1,2,3)
n2 <- c(10,20,30,40)
num <- list(n1,n2)
type <- c("price", "volume") 
dt1 <- data.table (num, type)
dt1 [, cons.fun := "sum"]
dt1[type=="price", cons.fun := "mean"]

> dt1
           num   type cons.fun
1:       1,2,3  price     mean
2: 10,20,30,40 volume      sum

因此,我需要基于magnitude值创建一个新列cons.fun。我尝试过:

dt1 [, magnitude:=match.fun(cons.fun)(num)],并收到错误消息:

Error in match.fun(cons.fun) : 
  'c("mean", "sum")' is not a function, character or symbol

而不是预期的:

> dt1
           num   type cons.fun magnitude
1:       1,2,3  price     mean         2
2: 10,20,30,40 volume      sum       100

如何正确处理?谢谢!

1 个答案:

答案 0 :(得分:1)

这是一种方法。遍历各行,get字符串的值并将该函数应用于“ num”列

dt1[, magnitude := get(cons.fun)(num[[1]]), 1:nrow(dt1)]
dt1
#          num   type cons.fun magnitude
#1:       1,2,3  price     mean         2
#2: 10,20,30,40 volume      sum       100

或者当OP使用match.fun时,'cons.fun'可以与mapply一起循环以提取功能对象并将功能应用于相应的list列'num '

dt1[, magnitude := mapply(function(x, y) match.fun(x)(y), cons.fun, num)]