Home > Mobile >  Converting a list of named list to data frame
Converting a list of named list to data frame

Time:09-13

I have a list returned by sapply which looks like this:

> my_list
        [,1]    [,2]    [,3]     [,4]    
val     1.73    2.73    4.71     5.27     
cost    10.1    8.71    9.95     0.01
time    5.36    5.84    5.68     2.10

I'd like to convert it into a data frame:

id val cost time
1 1.73 10.1 5.36
2 2.73 8.71 5.84
3 4.71 9.95 5.68
4 5.27 0.01 2.10

How can I transform the list into the data frame this way?

Edit: Here is the output of dput(my_list):

structure(list(1.73, 10.1, 5.36,2.73,8.71,5.84, 
  4.71,9.95,5.68, 5.27, 0.01, 2.10), 
  dim = c(3L, 4L), dimnames = list(c("val", 
  "cost", "time"), NULL))

CodePudding user response:

Use t

t(dat) |>
  transform(id = seq(ncol(dat)))
   val cost time id
1 1.73 10.1 5.36  1
2 2.73 8.71 5.84  2
3 4.71 9.95 5.68  3
4 5.27 0.01  2.1  4

CodePudding user response:

The elements in the data are list elements, if we want to make it regular vectors, an option is unnest

library(dplyr)
library(tidyr)
t(my_list) %>% 
  as_tibble %>% 
  unnest(where(is.list)) %>% 
  mutate(id = row_number(), .before = 1)

-output

# A tibble: 4 × 4
     id   val  cost  time
  <int> <dbl> <dbl> <dbl>
1     1  1.73 10.1   5.36
2     2  2.73  8.71  5.84
3     3  4.71  9.95  5.68
4     4  5.27  0.01  2.1 
  • Related