Unlists columns of lists by row creating combinations of values in the process.

list_unlister(indt, addRN = TRUE)

Arguments

indt

The input data.table. The input can also be a list, possibly with elements of different lengths.

addRN

Logical. Should a column named "rn" be added to the data.table? Such a column is required, so if it does not already exist, it is suggested to keep this set to TRUE, the default.

Value

A data.table.

References

http://stackoverflow.com/q/23217958/1270695

Author

Ananda Mahto

Examples

L1 <- list(list("A", c("B", "C")), list(1:2, 1:3)) list_unlister(L1)
#> rn V1 V2 #> 1: 1 A 1 #> 2: 1 A 2 #> 3: 2 B 1 #> 4: 2 C 1 #> 5: 2 B 2 #> 6: 2 C 2 #> 7: 2 B 3 #> 8: 2 C 3
## Note the NULLs and the shorter length of the first list item L2 <- list(V1 = list("A", c("A", "B"), "X", NULL), V2 = list(1, c(1, 2, 3), c(1, 2), c(1, 2, 3, 4), 1), V3 = list(c("a", "b"), "c", "d", c("e", "f"), c("g", "h", "i"))) list_unlister(L2)
#> rn V1 V2 V3 #> 1: 1 A 1 a #> 2: 1 A 1 b #> 3: 2 A 1 c #> 4: 2 B 1 c #> 5: 2 A 2 c #> 6: 2 B 2 c #> 7: 2 A 3 c #> 8: 2 B 3 c #> 9: 3 X 1 d #> 10: 3 X 2 d #> 11: 4 <NA> 1 e #> 12: 4 <NA> 2 e #> 13: 4 <NA> 3 e #> 14: 4 <NA> 4 e #> 15: 4 <NA> 1 f #> 16: 4 <NA> 2 f #> 17: 4 <NA> 3 f #> 18: 4 <NA> 4 f #> 19: 5 <NA> 1 g #> 20: 5 <NA> 1 h #> 21: 5 <NA> 1 i #> rn V1 V2 V3
DT <- data.table::data.table( x1 = list("A", c("A", "B"), "X", NULL, c("Z", "W")), x2 = list(1, c(1, 2, 3), c(1, 2), c(1, 2, 3, 4), 1), x3 = list(c("a", "b"), "c", "d", c("e", "f"), c("g", "h", "i"))) list_unlister(DT)
#> rn x1 x2 x3 #> 1: 1 A 1 a #> 2: 1 A 1 b #> 3: 2 A 1 c #> 4: 2 B 1 c #> 5: 2 A 2 c #> 6: 2 B 2 c #> 7: 2 A 3 c #> 8: 2 B 3 c #> 9: 3 X 1 d #> 10: 3 X 2 d #> 11: 4 <NA> 1 e #> 12: 4 <NA> 2 e #> 13: 4 <NA> 3 e #> 14: 4 <NA> 4 e #> 15: 4 <NA> 1 f #> 16: 4 <NA> 2 f #> 17: 4 <NA> 3 f #> 18: 4 <NA> 4 f #> 19: 5 Z 1 g #> 20: 5 W 1 g #> 21: 5 Z 1 h #> 22: 5 W 1 h #> 23: 5 Z 1 i #> 24: 5 W 1 i #> rn x1 x2 x3