Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert a list of vectors to data frame

Tags:

list

dataframe

r

I have a list of vectors. this vectors consists of names A1,A2.. and numeric values:

a <- list()
a$`p1`["A1"] <- 1
a$`p1`["A2"] <- 0.5
a$`p1`["A3"] <- 0.3
a$`p2`["A3"] <- 2
a$`p2`["A4"] <- 2.5
a$`p2`["A5"] <- 2.3

I wish to convert it to a data frame with the following structure

P <- c("p1","p1","p1","p2","p2","p2")
A <- c("A1","A2","A3","A3","A4","A5")
V <- c(1,0.5,0.3,2,2.5,2.3)
out <- data.frame(P,A,V)

Thanks :)

like image 530
Lucas Avatar asked Apr 29 '20 16:04

Lucas


Video Answer


2 Answers

One purrr and tibble option could be:

map_dfr(a, ~ enframe(., name = "A", value = "V"), .id = "P")

  P     A         V
  <chr> <chr> <dbl>
1 p1    A1      1  
2 p1    A2      0.5
3 p1    A3      0.3
4 p2    A3      2  
5 p2    A4      2.5
6 p2    A5      2.3
like image 53
tmfmnk Avatar answered Oct 09 '22 06:10

tmfmnk


df_list = lapply(a, function(x) data.frame(A = names(x), V = x, stringsAsFactors = FALSE))
dplyr::bind_rows(df_list, .id = "P")
#    P  A   V
# 1 p1 A1 1.0
# 2 p1 A2 0.5
# 3 p1 A3 0.3
# 4 p2 A3 2.0
# 5 p2 A4 2.5
# 6 p2 A5 2.3

I like the way above, but here's an option that might be more efficient on a large list:

data.frame(V = unlist(a)) %>% 
  tibble::rownames_to_column() %>%
  tidyr::separate(rowname, into = c("P", "A"))
like image 3
Gregor Thomas Avatar answered Oct 09 '22 04:10

Gregor Thomas