-2

I'm have a list of lists, and I'm looking to turn this into a data frame where each sub-list is a row, and each element of the sub-lists are columns. I have a working solution, but it doesn't feel efficient.

# Sample data
data <- list(structure(list(pop_size = 31874, p_value = 0.373458207009449), .Names = c("pop_size", 
"p_value")), structure(list(pop_size = 41874, p_value = 0.303284884476696), .Names = c("pop_size", 
"p_value")), structure(list(pop_size = 51874, p_value = 0.249409377411917), .Names = c("pop_size", 
"p_value")), structure(list(pop_size = 61874, p_value = 0.206924824186035), .Names = c("pop_size", 
"p_value")), structure(list(pop_size = 71874, p_value = 0.172823408801164), .Names = c("pop_size", 
"p_value")))

# My solution
matrix <- matrix(NA,nrow=length(data),ncol=2)
for(i in 1:length(data)){
  matrix[i,1] <- data[[i]]$pop_size
  matrix[i,2] <- data[[i]]$p_value
}
df <- data.frame(matrix)
colnames(df) <- c("pop_size","p_value")
df
  pop_size   p_value
1    31874 0.3734582
2    41874 0.3032849
3    51874 0.2494094
4    61874 0.2069248
5    71874 0.1728234

I get the result I'd like, I'm just looking for a better way. Thanks!

Edit Turns out this was already answered in a different thread. I personally found this to be the best solution.

library(plyr)
df <- ldply(data, data.frame)
ZachTurn
  • 636
  • 1
  • 5
  • 14

3 Answers3

3
 df <- data.frame(matrix(unlist(data), nrow=5, byrow=T))

This should solve your problem

Shweta Kamble
  • 432
  • 2
  • 10
  • 21
2

This should work:

df <- matrix(unlist(data),ncol=2,byrow=T)
Buzz Lightyear
  • 824
  • 1
  • 7
  • 18
1

You can try this:

do.call(rbind, lapply(data, as.data.frame))
  pop_size   p_value
1    31874 0.3734582
2    41874 0.3032849
3    51874 0.2494094
4    61874 0.2069248
5    71874 0.1728234
Psidom
  • 209,562
  • 33
  • 339
  • 356