简体   繁体   中英

How do I return data.tables that contain lists or vectors of length greater than 1 in a cell?

I'd like to specify in j that I want to return full lists in a given column. Below, when I try to return lists in column c , it expands it so that each cell in c is a single item. I actually want there to be 4 rows returned, with every row in c showing the list list('testing1', 'testing2', 'testing3', 'testing4') .

> x <- data.table(a=1:4, b=5:8)
> x[, list(b, c=list('testing1', 'testing2', 'testing3', 'testing4')), by=a]
    a b        c
 1: 1 5 testing1
 2: 1 5 testing2
 3: 1 5 testing3
 4: 1 5 testing4
 5: 2 6 testing1
 6: 2 6 testing2
 7: 2 6 testing3
 8: 2 6 testing4
 9: 3 7 testing1
10: 3 7 testing2
11: 3 7 testing3
12: 3 7 testing4
13: 4 8 testing1
14: 4 8 testing2
15: 4 8 testing3
16: 4 8 testing4

You say you want this:

y <- x[, list(b, c=list(list('testing1', 'testing2', 'testing3', 'testing4'))), by=a]
y[1,c]
# [[1]]
# [[1]][[1]]
# [1] "testing1"
# 
# [[1]][[2]]
# [1] "testing2"
# 
# [[1]][[3]]
# [1] "testing3"
# 
# [[1]][[4]]
# [1] "testing4"

But I suspect you want this:

x[, list(b, c=list(c('testing1', 'testing2', 'testing3', 'testing4'))), by=a]
#   a b                                   c
#1: 1 5 testing1,testing2,testing3,testing4
#2: 2 6 testing1,testing2,testing3,testing4
#3: 3 7 testing1,testing2,testing3,testing4
#4: 4 8 testing1,testing2,testing3,testing4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM