ragesz ragesz - 3 months ago 22
R Question

R - convert named list of named vectors into dataframe where one vector is placed in one cell

I have a named list of named vectors:

my_list <- list('first'=c('foo_1'=7, 'bar_1'=3), 'second'=c('foo_2'=4, 'bar_2'=2, 'baz'=1))


I want to convert it into a dataframe where the names of list elements should be the dataframe index, and the named vectors should be dataframe cell values. Something like this (or any similar in
my_vectors
column):

my_vectors
first 'foo_1'=7, 'bar_1'=3
second 'foo_2'=4, 'bar_2'=2, 'baz'=1


How can I do this?

Thank you!

Answer

I'm not sure why you would want to do such a thing, but if you really needed to, here's one way:

library(dplyr)
library(tidyr)

# convert lists to data frame
unlisted <- unlist(my_list) %>% data.frame

# majority of data transformation
unlisted <- mutate(unlisted, variable = rownames(unlisted), value = `.`) %>% 
    separate(variable, c('vector', 'item'), sep = '\\.') %>% 
    group_by(vector) %>% 
    summarize(my_vectors = paste(sprintf('%s = %i', item, value), collapse = ', ')) %>% 
    data.frame

# remove superfluous "vector" column and move those values to row indices
rownames(unlisted) <- unlisted$vector
unlisted$vector <- NULL

Result:

                          my_vectors
first           foo_1 = 7, bar_1 = 3
second foo_2 = 4, bar_2 = 2, baz = 1
Comments