Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
87 views
in Technique[技术] by (71.8m points)

r - Convert list of vectors to data frame

I'm trying to convert a list of vectors (a multidimensional array essentially) into a data frame, but every time I try I'm getting unexpected results.

My aim is to instantiate a blank list, populate it in a for loop with vectors containing information about that iteration of the loop, then convert it into a data frame after it's finished.

> vectorList <- list()
> for(i in  1:5){
+     vectorList[[i]] <- c("number" = i, "square root" = sqrt(i))
+ }
> vectorList

Outputs:

> [[1]]
>      number square root 
>           1           1 
> 
> [[2]]
>      number square root 
>    2.000000    1.414214 
> 
> [[3]]
>      number square root 
>    3.000000    1.732051 
> 
> [[4]]
>      number square root 
>           4           2 
> 
> [[5]]
>      number square root 
>    5.000000    2.236068

Now I want this to become a data frame with 5 observations of 2 variables, but trying to create a data frame from 'vectorList'

numbers <- data.frame(vectorList)

results in 2 observations of 5 variables.

Weirdly it won't even be coerced with reshape2 (which I know would be an awful work around, but I tried).

Anyone got any insight?

question from:https://stackoverflow.com/questions/43662457/convert-list-of-vectors-to-data-frame

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use:

as.data.frame(do.call(rbind, vectorList))

Or:

library(data.table)
rbindlist(lapply(vectorList, as.data.frame.list))

Or:

library(dplyr)
bind_rows(lapply(vectorList, as.data.frame.list))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...