在列表内组合向量以创建数据框R [英] Combine Vectors inside of a List to Create a Dataframe R

查看:118
本文介绍了在列表内组合向量以创建数据框R的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个大小均匀的字符向量列表,我希望将它们有效地组合成一个数据帧,列表中的向量成为新数据帧的行.在下面的内容中,ls是我的列表,df是我的预分配数据帧.

I have a list of evenly sized characters vectors, and I wish to efficiently combine them into one dataframe, with the vectors in the list to become the rows of the new dataframe. In the following, ls is my list and df is my pre-allocated dataframe.

ls <- list(c("r1c1", "r1c2", "r1c3"),
           c("r2c1", "r2c2", "r2c3"))

df <- data.frame(col1 = character(), col2 = character(), col3 = character(),
                 stringsAsFactors = F)

# Desired Result:
  col1   col2   col3
1  r1c1   r1c2   r1c3       
2  r2c1   r2c2   r2c3  

到目前为止,我已经尝试过rbind(df, ls),它似乎按列创建了新的数据帧,使得df看起来像:

As of now, I've tried rbind(df, ls) which seemingly creates the new dataframe by column, such that df looks like:

  c..r1c1....r1c2....r1c3.. c..r2c1....r2c2....r2c3..
4                      r1c1                      r2c1
5                      r1c2                      r2c2
6                      r1c3                      r2c3

我还尝试在for循环内执行rbind:

I've also tried to perform the rbind inside of a for loop:

for (i in 1:length(ls))
  df <- rbind(df, ls[[i]])

但是,这会给我警告消息:invalid factor level, NA generated,即使我最初将stringsAsFactors设置为false.当不断在较大的列表上执行时,Rbind似乎也是一个缓慢的过程,因此,我想尽可能地减少其使用.

This, however, gives me the warning message: invalid factor level, NA generated, even though I originally set stringsAsFactors to false. Rbind also seems to be a slow process when constantly performed on larger lists, so I would like to minimize its use if possible.

任何帮助将不胜感激.

推荐答案

您可以使用

 data.frame(do.call(rbind, ls))

一种快速简单的方法将向量列表转换为矩阵,然后转换为data.frame

as a quick and simple way to turn your list of vectors into a matrix and then a data.frame

这篇关于在列表内组合向量以创建数据框R的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆