I have a column of lists in R:
DT <- data.table(foo = c(list(c("a","b","c")), list(c("b","c")), list(c("a","b")), list(c("a"))), id = c(1,1,2,2))
DT
foo id
1: a,b,c 1
2: b,c 1
3: a,b 2
4: a 2
What I would like to do is replicate typical shift behavior to get:
foo id
1: b,c 1
2: NA 1
3: a 2
4: NA 2
For a normal column I would use shift, but this splits the lists into columns and shifts those (and flags a warning):
DT[ , shift(foo,1,type = "lead"), by = id]
id V1 V2
1: 1 b c
2: 1 c NA
3: 1 NA c
4: 2 b NA
5: 2 NA NA
If I wrap the shift call into a list, the return is a list but only the vector elements have been shifted:
DT[ , list(shift(foo,1,type = "lead")), by = id]
id V1
1: 1 b,c,NA
2: 1 c,NA
3: 2 b,NA
4: 2 NA
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…