将向量列表转换为数据框 [英] 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.
我的目的是实例化一个空白列表,在for循环中填充包含有关该循环迭代信息的向量,然后在完成后将其转换为数据帧.
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
输出:
> [[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
现在我希望它成为具有2个变量的5个观察值的数据框,但是尝试从'vectorList'创建数据框
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)
对5个变量进行2次观察.
results in 2 observations of 5 variables.
奇怪的是,它甚至不会被reshape2强制(我知道这很糟糕,但是我尝试过).
Weirdly it won't even be coerced with reshape2 (which I know would be an awful work around, but I tried).
任何人都有见识吗?
推荐答案
您可以使用:
as.data.frame(do.call(rbind, vectorList))
或者:
library(data.table)
rbindlist(lapply(vectorList, as.data.frame.list))
或者:
library(dplyr)
bind_rows(lapply(vectorList, as.data.frame.list))
这篇关于将向量列表转换为数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!