Reputation: 1133
I have a data.table with the following format:
ColName xvalue yvalue
Column1 5 10
Column2 3 5
Column3 2 4
I have defined a function as follows:
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:
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. Is there a data.table way of doing this? Thanks!
Upvotes: 0
Views: 259
Reputation: 887991
An option is to apply the opt
and then use as.list
with(df1, as.list(setNames(opt(xvalue, yvalue), ColName)))
#$Column1
#[1] 15
#$Column2
#[1] 8
#$Column3
#[1] 6
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))
Upvotes: 1
Reputation: 51622
You can simply do,
split(rowSums(df[-1]), df$ColName)
#$Column1
#[1] 15
#$Column2
#[1] 8
#$Column3
#[1] 6
Upvotes: 2
Reputation: 389355
You can use Map
to get output as list :
setNames(Map(opt, df$xvalue, df$yvalue), df$ColName)
#$Column1
#[1] 15
#$Column2
#[1] 8
#$Column3
#[1] 6
Upvotes: 0