Reputation: 10646
I declare an empty data frame as this:
df <- data.frame()
then I go though processing some files and as process, I need to build my df
data frame. I need to keep adding columns to it:
For example, I process some file and build a data frame called new_df
, I now need to add this new_df
to my df
:
I've tried this:
latest_df <- cbind(latest_df, new_df)
I get this error:
Error in data.frame(..., check.names = FALSE) : arguments imply differing number of rows: 0, 1
Upvotes: 8
Views: 13269
Reputation: 1
If you simply want an empty data frame of the proper size before you enter the loop, and assuming "df" and "new_df" have the same number of rows x, try
df <- data.frame(matrix(nrow=x))
for (i in 1:n){
temp[i] <- % some vector of length x
}
Upvotes: 0
Reputation: 446
Just put data into the index after the last column
new_df = data.frame()
new_df[,ncol(new_df)+1] = NA
So if you knew you had 3 columns then:
new_df[,4] = c('a','b','c')
Example:
new_df = data.frame('a'=NA)
for(i in 1:10){
new_df[,ncol(new_df)+1] = NA
}
new_df
EDIT:
ProcessExample <- function(){
return(c(5)) #just returns 5 as fake data everytime
}
new_df = data.frame(matrix(nrow=1))
for(i in 1:10){
new_df[,ncol(new_df)+1] = ProcessExample()
}
latest_df <- new_df[,-1]
Or just add rows and transpose the data set
new_df = data.frame()
for(i in 1:10){
new_df[i,1] = ProcessExample()
}
latest_df <- t(new_df)
Upvotes: 5