问题
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
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
I've also tried to perform the rbind
inside of a for loop:
for (i in 1:length(ls))
df <- rbind(df, ls[[i]])
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.
Any help would be greatly appreciated.
回答1:
You could use
data.frame(do.call(rbind, ls))
as a quick and simple way to turn your list of vectors into a matrix and then a data.frame
来源:https://stackoverflow.com/questions/24988483/combine-vectors-inside-of-a-list-to-create-a-dataframe-r