[英]Compute a magnitude using a function that depends on the type of a data.table row
I want to compute a magnitude that depends on the type of a data.table row:我想计算一个取决于 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
Thus, I need to create a new column magnitude
based on the cons.fun
value.因此,我需要根据
cons.fun
值创建一个新的列magnitude
。 I tried:我试过:
dt1 [, magnitude:=match.fun(cons.fun)(num)]
, and got the error: dt1 [, magnitude:=match.fun(cons.fun)(num)]
,并得到错误:
Error in match.fun(cons.fun) :
'c("mean", "sum")' is not a function, character or symbol
Instead of the expected:而不是预期的:
> dt1
num type cons.fun magnitude
1: 1,2,3 price mean 2
2: 10,20,30,40 volume sum 100
How can I get it right?我怎样才能做对? Thank you!
谢谢!
Here is one approach.这是一种方法。 Loop through the rows,
get
the value of the string and apply the function on the 'num' column循环遍历行,
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
Or as the OP was using match.fun
, 'cons.fun' can be looped with mapply
to extract the function object and to apply the function on the corresponding list
column 'num'或者因为 OP 正在使用
match.fun
,'cons.fun' 可以用mapply
循环以提取函数对象并将函数应用于相应的list
列 'num'
dt1[, magnitude := mapply(function(x, y) match.fun(x)(y), cons.fun, num)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.