简体   繁体   English

在 data.table 上应用 function 并将结果存储在列表中

[英]Applying function over data.table and storing results in a list

I have a data.table with the following format:我有一个 data.table 格式如下:

ColName  xvalue   yvalue

Column1  5       10
Column2  3        5
Column3  2        4

I have defined a function as follows:我定义了一个 function 如下:

opt <- function (x,y){
return(x+y)
}

I want to apply the function over each row of the data.table and store the resulting value in a list like below:我想在 data.table 的每一行上应用 function 并将结果值存储在如下列表中:

x
$column1
[1]15

$column2
[1]8

$column3
[1]6

Essentially I am applying a function that takes each row of the data.table as input parameters and stores the output as members of a list.本质上,我正在应用一个 function ,它将 data.table 的每一行作为输入参数,并将 output 存储为列表的成员。 Is there a data.table way of doing this?有没有这样做的 data.table 方式? Thanks!谢谢!

You can simply do,你可以简单地做,

split(rowSums(df[-1]), df$ColName)

#$Column1
#[1] 15

#$Column2
#[1] 8

#$Column3
#[1] 6

An option is to apply the opt and then use as.list一个选项是应用opt然后使用as.list

with(df1, as.list(setNames(opt(xvalue, yvalue), ColName)))
#$Column1
#[1] 15

#$Column2
#[1] 8

#$Column3
#[1] 6

data数据

df1 <- structure(list(ColName = c("Column1", "Column2", "Column3"), 
    xvalue = c(5L, 3L, 2L), yvalue = c(10L, 5L, 4L)), 
    class = "data.frame", row.names = c(NA, 
-3L))

You can use Map to get output as list:您可以使用Map获取 output 作为列表:

setNames(Map(opt, df$xvalue, df$yvalue), df$ColName)

#$Column1
#[1] 15

#$Column2
#[1] 8

#$Column3
#[1] 6

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM