Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (5.3k points)
edited by

What is the best way to assign to multiple columns using data.table? For example:

f <- function(x) {c("hi", "hello")}

x <- data.table(id = 1:10)

I would like to do something like this (of course this syntax is incorrect):

x[ , (col1, col2) := f(), by = "id"]

And to extend that, I may have many columns with names stored in a variable (say col_names) and I would like to do:

x[ , col_names := another_f(), by = "id", with = FALSE]

What is the correct way to do something like this?

1 Answer

0 votes
by
edited by

To assign values to multiple columns using := operator in a data table, do the following:

library(data.table)

f <- function(x) {list("hi", "hello")}

x <- data.table(id = 1:10)

x[ , c("col1", "col2") := f(), by = id][]

     id col1  col2

 1:  1   hi hello

 2:  2   hi hello

 3:  3   hi hello

 4:  4   hi hello

 5:  5   hi hello

 6:  6   hi hello

 7:  7   hi hello

 8:  8   hi hello

 9:  9   hi hello

10: 10   hi hello

Another example:

x <- data.table(a = 1:3, b = 1:6)

f <- function(x) {list("hi", "hello")}

x[ , c("mean", "sum") := list(mean(b), sum(b)), by = a][]

   a b col1  col2 mean sum

1: 1 1   hi hello  2.5   5

2: 2 2   hi hello  3.5   7

3: 3 3   hi hello  4.5   9

4: 1 4   hi hello  2.5   5

5: 2 5   hi hello  3.5   7

6: 3 6   hi hello  4.5   9

Related questions

1.2k questions

2.7k answers

501 comments

693 users

Browse Categories

...