1

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?

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for this awesome reply. One further question though. Let say instead of passing argument as the name of columns of data.table, can we just pass entire row as vector assuming all columns of data.table are numeric. The column name of my original data.table is variable therefore keep changing. So I am trying to avoid to pass the column names
@Bogaso Yes, you can do that easily.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.