Vni
Vni

Reputation: 21

R error with using cbind() on a data.frame() in a for loop

d <- data.frame(stringsAsFactors=F)

for (i in 1:ncol(data)) { d <- cbind(d,data[,i])}

Error in data.frame(..., check.names = FALSE) : 
  arguments imply differing number of rows: 0, 132680

Why I am getting the error above?

Upvotes: 1

Views: 5186

Answers (2)

Ben Bolker
Ben Bolker

Reputation: 226087

It's possible to hack a solution along the lines of what you have above, but you probably don't want to. What is your goal here?

d <- data.frame(matrix(ncol=0,nrow=5),stringsAsFactors=FALSE)
set.seed(101)
dat <- matrix(sample(LETTERS,replace=TRUE,size=10),ncol=2)
for (i in 1:ncol(dat)) { d <- cbind(d,dat[,i])}
d2 <- as.data.frame(dat,stringsAsFactors=FALSE)

In this particular example dat is a matrix of character; d is a data frame with two factor columns (note that stringsAsFactors=FALSE does not set an attribute of the data frame, so your later cbind() calls induce conversion to factor anyway!); and d2 is perhaps (???) what you wanted, the original data set converted to a data frame ...

> str(dat)
 chr [1:5, 1:2] "J" "B" "S" "R" "G" "H" "P" "I" "Q" "O"
> str(d)
'data.frame':   5 obs. of  2 variables:
 $ dat[, i]: Factor w/ 5 levels "B","G","J","R",..: 3 1 5 4 2
 $ dat[, i]: Factor w/ 5 levels "H","I","O","P",..: 1 4 2 5 3
> str(d2)
'data.frame':   5 obs. of  2 variables:
 $ V1: chr  "J" "B" "S" "R" ...
 $ V2: chr  "H" "P" "I" "Q" ...

Upvotes: 0

joran
joran

Reputation: 173547

Probably for the precise reason R told you it went wrong: the two items you are trying to cbind together have different numbers of rows.

Your data frame d is emtpy, and so has 0 rows. Apparently your data frame data (which you've provided us zero information on, by the way) has 132680 rows.

There's probably a better way to do what you're attempting (cbinding columns in a for loop is often not terribly optimal), but it's difficult to propose a solution without more details.

Upvotes: 3

Related Questions