user88911 user88911 - 3 months ago 9
R Question

How to make format clean and elegant after casting list to data.frame?

I have set of vector in the list. I want to cast my list to data.frame object for fast manipulation. There is already solution for casting list to data.frame in this site. However, I tried this solution, it works good but format is bit of mass, not perfectly formatted. Can anyone propose any idea to make casting result more clean/ elegant? How can make this happen efficiently ?

mini example

myList <- list(
a = c(1,2,3,4,5,6,7),
b = c(1,1,1,2,0,3,4),
c = c(1,2,4,4,5,0,6)
)


I used following solution:

do.call(rbind, lapply(myList, data.frame, stringsAsFactors=FALSE))


my desired output

output <- data.frame(
a = c(1,2,3,4,5,6,7),
b = c(1,1,1,2,0,3,4),
c = c(1,2,4,4,5,0,6))


How can I get my expected output? Thanks a lot

Answer

as.data.frame has method for coercing a list (read ?as.data.frame). So you can do:

myList <- list(
  a = c(1,2,3,4,5,6,7),
  b = c(1,1,1,2,0,3,4),
  c = c(1,2,4,4,5,0,6))

as.data.frame(myList)

#  a b c
#1 1 1 1
#2 2 1 2
#3 3 1 4
#4 4 2 4
#5 5 0 5
#6 6 3 0
#7 7 4 6