rdata.tableunnest

Expand nested elements of a list within a data.table in R, according to a second list column


I have a data.table in R that is

> data.table(value="one",list1=list(c(list("one1"),list("one2"),list(c("one3 1","one3 2")))),position=list(c(0,1,2)))
     value     list1  position
  1:   one <list[3]>     0,1,2

where the <list[3]> element is

[[1]]
[[1]][[1]]
[1] "one1"

[[1]][[2]]
[1] "one2"

[[1]][[3]]
[1] "one3 1" "one3 2"

I want to lengthen the data.table so that I have

value   list1     position
one     "one1"    0
one     "one2"    1
one     "one3 1"  2
one     "one3 2"  2

where "one3 2" corresponds to position 2. So far, all my attempts result in position 3 being listed for "one3 2". Is there a fix for this?


Solution

  • Using data.table

    library(data.table)
     dt1[, .(value, list1 = unlist(list1),
       position = c(mapply(\(x, y) rep(x, lengths(y)), position, list1)))]
    

    -output

        value  list1 position
    1:   one   one1        0
    2:   one   one2        1
    3:   one one3 1        2
    4:   one one3 2        2