[英]R data.table apply function to rows using columns as arguments which returns a vector (i.e. multiple values)
Let say I have below data.table-假设我有以下data.table-
library(data.table)
x = structure(list(f1 = 1:3, f2 = 3:5), .Names = c("f1", "f2"), row.names = c(NA, -3L), class = c("data.table", "data.frame"))
Now I want to apply below function on every rows-现在我想在每一行上申请 function 下面-
func.text <- function(arg1,arg2){ return(c(10, arg1 + exp(arg2)))}
With that, I see below result-有了这个,我看到下面的结果 -
> x[, func.text(f1, f2), by = seq_len(nrow(x))]
seq_len V1
1: 1 10.00000
2: 1 21.08554
3: 2 10.00000
4: 2 56.59815
5: 3 10.00000
6: 3 151.41316
However, I wanted to get 2 extra columns in the final result because this function returning 2 values, same number of rows as with original data.table.但是,我想在最终结果中获得 2 个额外的列,因为这个 function 返回 2 个值,与原始 data.table 的行数相同。
Is there any way to do this?有没有办法做到这一点?
Minimal changes to your original idea:对原始想法的最小更改:
:=
:=
分配结果func.text <- function(arg1,arg2){ return(list(10, arg1 + exp(arg2)))}
x[, c("var1", "var2") := func.text(f1, f2), by = seq_len(nrow(x))]
x
f1 f2 var2 var1
1: 1 3 21.08554 10
2: 2 4 56.59815 10
3: 3 5 151.41316 10
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.