IndyZa
IndyZa

Reputation: 498

Merge multiple numeric column as list typed column in data.table [R]

I'm trying to find a way to merge multiple column numeric column as a new list type column.

Data Table

dt <- data.table(
  a=c(1,2,3),
  b=c(4,5,6),
  c=c(7,8,9)
)

Expected Result

   a b c   d
1: 1 4 7 1,4,7
2: 2 5 8 2,5,8
3: 3 6 9 3,6,9

Attempt 1

I have tried doing append with a list with dt[,d:=list(c(a,b,c))] but it just append everything instead and get the incorrect result

   a b c       d
1: 1 4 7 1,2,3,4,5,6,...
2: 2 5 8 1,2,3,4,5,6,...
3: 3 6 9 1,2,3,4,5,6,...

Upvotes: 0

Views: 141

Answers (2)

det
det

Reputation: 5232

dt[, d := purrr::pmap(.SD, ~c(...))]

Upvotes: 1

akrun
akrun

Reputation: 887991

Do a group by row and place the elements in the list

dt[, d := .(list(unlist(.SD, recursive = FALSE))), 1:nrow(dt)]

-output

dt
   a b c     d
1: 1 4 7 1,4,7
2: 2 5 8 2,5,8
3: 3 6 9 3,6,9

Or another option is paste and strsplit

dt[, d := strsplit(do.call(paste, c(.SD, sep=",")), ",")]

Or may use transpose

dt[, d := lapply(data.table::transpose(unname(.SD)), unlist)]
dt
   a b c     d
1: 1 4 7 1,4,7
2: 2 5 8 2,5,8
3: 3 6 9 3,6,9

Upvotes: 2

Related Questions