How can I add a list of vectors to a preallocated data.frame such that the vectors form the rows of the data.frame?
eg.
ll<-list(c(1,2,3),c(2,3,4))
dd<-data.frame(matrix(nrow=10,ncol=3))
I need dd to look like
1 2 3
2 3 4
How can I add a list of vectors to a preallocated data.frame such that the vectors form the rows of the data.frame?
eg.
ll<-list(c(1,2,3),c(2,3,4))
dd<-data.frame(matrix(nrow=10,ncol=3))
I need dd to look like
1 2 3
2 3 4
There's something odd about the question: You construct a dataframe with 10 rows, filled with NA values, but you need dd to have only 2 rows.
To answer your question first : sometimes the obvious isn't a bad solution.
ll<-list(c(1,2,3),c(2,3,4))
dd<-data.frame(matrix(nrow=5,ncol=3))
for(i in 1:length(ll)){
dd[i,] <- ll[[i]]
}
dd
If you're staring at the ugly for-loop: this is a case where you could actually use a for-loop without problems. But this keeps dd having tons of NA values. If you want to get rid of them, you either initialize your dataframe as
dd<-data.frame(X1=numeric(0),X2=numeric(0),X3=numeric(0))
which gives you an empty dataframe, or you use complete.cases() to remove all NAs :
dd <- dd[complete.cases(dd),]
do.call(rbind, ll)
To add to an existing data frame
rbind(dd, do.call(rbind, ll)
# OR
do.call(rbind, c(ll, list(dd))
If you're doing this for many data frames, see rbind.fill
in the plyr
package for a much more efficient approach.