Question

I use following code:

tempdata <- rbind(tempdata,newdata)  # bind rowwise

as far as I know, tempdata (like all objects, variables, ...) needs to be defined. Because there are only numerical values, I define it as tempdata<-0. It's not a really big problem, but when using rbind afterwards, the first row with 0 is kept at the first place and I have to use some kind of

tempdata<-tempdata[-1,] # deletes first row

I can't define it as tempdata<-'', because this would be a character, right?

Well as I said, not really a problem for me, but would there be a better way, especially if I or someone would use rbind() many times in the code and therefore maybe the first row has to be "cleared" not only once...

The same could be a problem when using cbind().

Maybe someone knows a better solution?

Was it helpful?

Solution

If you are using rbind/cbind to build some results from an iterative procedure, you may declare the "empty" object to store the data in. For numeric data, use numeric(0), which is a zero-length numeric vector. It is compatible with any binding:

rbind(numeric(0), 1:3)
     [,1] [,2] [,3]
[1,]    1    2    3
cbind(numeric(0), 1:3)
     [,1]
[1,]    1
[2,]    2
[3,]    3

The same holds for NULL (as pointed by @jbaums). It may even be more convenient since you don't have to specify the data type manually (the same will also work with numeric(0) due to implicit type conversion):

rbind(NULL, letters[1:3])
     [,1] [,2] [,3]
[1,] "a"  "b"  "c" 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top