[R] rbind-ing with empty data frame produces error

Marc Schwartz marc_schwartz at comcast.net
Thu Jan 25 17:15:35 CET 2007


On Thu, 2007-01-25 at 15:22 +0000, Jon Clayden wrote:
> Hi all,
> 
> I'm having some trouble with rbind - this may be a bug or it may be my
> misunderstanding. If I do
> 
> fileName <- paste(tempdir(),"test.txt",sep="/")
> file.create(fileName)
> x <- read.table(fileName, col.names=c("one","two","three"))
> 
> I get a data frame with no rows, as documented. If I then try to rbind
> this with another data frame with the same column names, I get an
> error:
> 
> y <- data.frame(one=1,two=2,three=3)
> rbind(x,y)
> 
> "Error in `*tmp*`[[jj]] : subscript out of bounds"
> 
> On the other hand, doing "rbind(as.matrix(x),as.matrix(y))" works as
> expected. If this is, in fact, intended behaviour, could anyone
> suggest another way of achieving what I want, please? I'm trying to
> append to a data frame stored in a text file every so often, and of
> course I need to create it, as above, the first time around...
> 
> My system is R-2.4.1/i686-pc-linux-gnu. Thanks in advance for your advice.
> 
> Regards,
> Jon

The problem is that the classes of the columns in 'x' are:

> sapply(x, class)
   one    two  three 
"NULL" "NULL" "NULL" 


You might get more insight by reversing the two arguments:

> rbind(y, x)
Error in value[[jj]][ri] <- if (is.factor(xij)) as.vector(xij) else
xij : 
        incompatible types (from NULL to double) in subassignment type
fix


If you review the Details in ?rbind, you will note that there is a class
checking component to the rbind'ing process for data frames.  The lack
of a class type for the columns in 'x' is the source of the problem.

This is not part of rbind'ing matrices, since they can only be of a
single data type.

An alternative would be to use ifelse():

  NewDF <- ifelse(nrow(x) == 0, y, rbind(x, y))

HTH,

Marc Schwartz



More information about the R-help mailing list