I would like to build a data frame in a loop adding a new column each time using cbind
. I try the following:
test <- NULL
df <- data.frame(x=c(1,2,3,4))
test <- cbind(test, df)
This generates an error:
Error in data.frame(..., check.names = FALSE) : arguments imply differing number of rows: 0, 4
What is the correct way to instantiate a blank data frame in R and then bind to it in a loop?
Thanks
cbind() function in R Language is used to combine specified Vector, Matrix or Data Frame by columns.
cbind() and rbind() both create matrices by combining several vectors of the same length. cbind() combines vectors as columns, while rbind() combines them as rows.
The cbind() and rbind() functions are generic methods for data frames. These data frame functions will be used if at least one argument is a data frame and the other are vectors or matrices. To merge two data frames (datasets) horizontally, use the merge() function in the R language.
Cbind () — column bind function is used for merging two data frames together given that the number of rows in both the data frames are equal. cbind can append vectors, matrices or any data frame by columns. This recipe demonstrates an example using cbind.
You need to create test
as a structure that has the same number of rows so that cbind.data.frame
will not throw an error:
test <-data.frame(row.names=1:4)
df <- data.frame(x=c(1,2,3,4))
test <- cbind(test, df)
test
x
1 1
2 2
3 3
4 4
Two other methods:
> test <-data.frame(row.names=1:4)
> test[['x']] <-c(1,2,3,4)
> test
x
1 1
2 2
3 3
4 4
> test <-data.frame(row.names=1:4)
> test[1] <-list(x=c(1,2,3,4))
> test
x
1 1
2 2
3 3
4 4
As Roman Luštrik pointed out it may be inefficient to use cbind. You can start with empty list and after loop convert it to data.frame.
test <- list()
# inner loop assigment
test <- c(test,list(c(1:4)))
# after loop
test <- as.data.frame(test)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With