Converting list -> data.frame

Edit: needs to be in base R

Here is the starting point:

the_list = list()
the_list$a = 1
the_list$b = 2
...

Ultimately after this, my goal equivalent would like something like this:

data.frame(variable = c('a', 'b'), #...
           value = c(1, 2)) #...

I tried data.frame(t(data.frame(the_list))) but returned 0 rows. How can I achieve this?

How about this?

library(tidyverse)

enframe(the_list) %>% 
  unnest()

# # A tibble: 2 x 2
# name  value
# <chr> <dbl>
# 1 a         1
# 2 b         2
1 Like

Oh oops, I should have mentioned that it needs to be in base R. Is it possible?

the_list = list()
the_list$a = 1
the_list$b = 2
the_list
#> $a
#> [1] 1
#> 
#> $b
#> [1] 2
(exemplar <- data.frame(a = 1, b = 2))
#>   a b
#> 1 1 2
(coerced <- as.data.frame(the_list))
#>   a b
#> 1 1 2
identical(exemplar,coerced)
#> [1] TRUE

Not sure anymore:

the_list = list()
the_list$a = 1
the_list$b = 2
the_list
#> $a
#> [1] 1
#> 
#> $b
#> [1] 2
(exemplar <- data.frame(variable = c('a', 'b'), value = c(1, 2)))
#>   variable value
#> 1        a     1
#> 2        b     2
coerced <- unlist(the_list) |> as.data.frame()
coerced$variable <- rownames(coerced)
colnames(coerced)[1] <- "value" 
coerced <- coerced[2:1]
rownames(coerced) <- NULL
coerced
#>   variable value
#> 1        a     1
#> 2        b     2
identical(exemplar,coerced)
#> [1] TRUE
2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.