Bogaso
Bogaso

Reputation: 3308

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-

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-

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.

Is there any way to do this?

Upvotes: 1

Views: 969

Answers (1)

s_baldur
s_baldur

Reputation: 33488

Minimal changes to your original idea:

  • make the function return a list and
  • 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

Upvotes: 3

Related Questions