Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamically expand a data frame columns using cbind

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

like image 930
Alex Avatar asked Jan 15 '12 04:01

Alex


People also ask

What does Cbind () do in R?

cbind() function in R Language is used to combine specified Vector, Matrix or Data Frame by columns.

What is the use of Rbind () and Cbind () in R?

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.

How do I Cbind two data frames in R?

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.

What is Cbind?

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.


2 Answers

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
like image 172
IRTFM Avatar answered Sep 28 '22 08:09

IRTFM


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)
like image 25
Wojciech Sobala Avatar answered Sep 28 '22 07:09

Wojciech Sobala