1

For example there is the following data.table:

dt <- data.table(x = list(1:2, 3:5, 6:9), y = c(1,2,3))

#          x y
# 1:     1,2 1
# 2:   3,4,5 2
# 3: 6,7,8,9 3

I need to create a new data.table, where values of the y column will be appended to lists stored in the x column:

#            z
# 1:     1,2,1
# 2:   3,4,5,2
# 3: 6,7,8,9,3

I've tried lapply, cbind, list, c functions. But I can't get the table I need.

UPDATE: The question is different from paste two data.table columns because a trivial solution with paste function or something like this doesn't work.

Community
  • 1
  • 1
Denis
  • 1,167
  • 1
  • 10
  • 30

2 Answers2

2

This will do it

# Merge two lists
dt[, z := mapply(c, x, y, SIMPLIFY=FALSE)]

print(dt)
         x y         z
1:     1,2 1     1,2,1
2:   3,4,5 2   3,4,5,2
3: 6,7,8,9 3 6,7,8,9,3

And deleting the original x and y columns

dt[, c("x", "y") := NULL]

print(dt)
           z
1:     1,2,1
2:   3,4,5,2
3: 6,7,8,9,3
Jaime Caffarel
  • 2,401
  • 4
  • 30
  • 42
1

I would like to suggest a general approach for this kind of task in case you have multiple columns that you would like to combine into a single column

An example data with multiple columns

dt <- data.table(x = list(1:2, 3:5, 6:9), y = 1:3, z = list(4:6, NULL, 5:8))

Solution

res <- melt(dt, measure.vars = names(dt))[, .(.(unlist(value))), by = rowid(variable)]
res$V1
# [[1]]
# [1] 1 2 1 4 5 6
# 
# [[2]]
# [1] 3 4 5 2
# 
# [[3]]
# [1] 6 7 8 9 3 5 6 7 8

The idea here is to convert to long format and then unlist/list by group (You will receive an warning due to different classes in the resulting value column)

David Arenburg
  • 91,361
  • 17
  • 137
  • 196