rdataframenested-lists

Create a nested list from a dataframe using multiple columns


I have a dataframe that I would like to convert to a nested list, by row. However, I need to group several columns into separate matrices in each nested element. All of the solutions I've seen put each column into a unique element. I want to create separate matrices using the column values.

For example, if I have a dataframe as below:

df = data.frame(a=c("foo", "bar", "baz"), b=1:3, c=3:1, d=4:6, e=6:4)

I'd like to convert it to something like this:

dflist <- list(foo=list(as.matrix(c(1,3)),
                        as.matrix(c(4,6))),
               bar=list(as.matrix(c(2,2)),
                        as.matrix(c(5,5))),
               baz=list(as.matrix(c(3,1)),
                        as.matrix(c(6,4))))

Solution

  • Using purrr:

    mylist <- pmap(df, \(b, c, d, e, ...) {
      list(as.matrix(c(b, c)), as.matrix(c(d, e)))
    }) |> setNames(df$a)