0

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

jyson
  • 245
  • 1
  • 8
  • 27

3 Answers3

1

This should work?

output <- data.frame(myList)
colnames(output) <- c("a", "b", "c")
emehex
  • 9,874
  • 10
  • 54
  • 100
1

If we need to convert to data.table, use setDT directly on the list

library(data.table)
setDT(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
akrun
  • 874,273
  • 37
  • 540
  • 662
0

You should use cbind instead of rbind and set data frame names.

output <- do.call(cbind,lapply(myList,data.frame, stringsAsFactors=FALSE))
names(output) <- c("a","b","c")
alingir
  • 1
  • 1