简体   繁体   English

R data.table 将 function 应用于使用列作为 ZDBC11CAA5BDA99F77E6FB4DABD8E 的行返回的多个值(A向量)

[英]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:对原始想法的最小更改:

  • make the function return a list and使 function 返回一个列表并
  • assign the result with :=:=分配结果

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.

相关问题 R data.table将函数应用于使用列作为参数的行 - R data.table apply function to rows using columns as arguments 使用列作为参数在data.table中逐行应用函数 - Apply function by row in data.table using columns as arguments 如何通过 R 中的多个列将 function 应用于 data.table 子集? - How to apply a function to a data.table subset by multiple columns in R? 如何调用一个返回data.table中多个行和列的函数? - How to call a function that returns multiple rows and columns in a data.table? 如何使用两个或更多列中的数据与R data.table的比较来应用函数 - How do I apply a function using comparisons of data in two or more columns with R data.table R:如何将用户定义的函数应用于数据表的多列并在滑动窗口中进行评估,即移动平均 - R: How to apply user defined functions to multiple columns of data table and evaluate in a sliding window, i.e. moving average 使用函数的字符名称和参数作为字符向量将函数应用于data.table - Apply function to data.table using function's character name and arguments as character vector 对 R 中的多列使用 data.table 中的 melt() 函数 - Using melt() function from data.table for multiple columns in R R使用值作为参数将函数应用于数据框的行 - R apply function to rows of data frame using values as arguments 如何根据R中data.table中具有对称值的两列删除某些行? - How can I delete certain rows according to two columns which have symmetricl values in data.table in R?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM