Search code examples
rcbind

neutral element to cbind with dataframe


i can do the following:

a <- rep(5,5)

> cbind(6,a)
       a
[1,] 6 5
[2,] 6 5
[3,] 6 5
[4,] 6 5
[5,] 6 5
> cbind(NULL,a)
     a
[1,] 5
[2,] 5
[3,] 5
[4,] 5
[5,] 5

When i do it with a dataframe it gives me an error

> cbind(NULL,mtcars)

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

What is the neutral element so that:

cbind(neutralElement,DF) = DF 

EDIT:

I have a code where something goes like cbind(IDCOL,DF). In the function IDCOL can also be non-Exisiting so it would be convinient to just set IDCOL to the neutral element so the code still runs smooth.


Solution

  • What you are looking for is unlikely to exist.

    Documentation of the cbind and rbind command:

    If there are several matrix arguments, they must all have the same number of columns (or rows) and this will be the number of columns (or rows) of the result. If all the arguments are vectors, the number of columns (rows) in the result is equal to the length of the longest vector. Values in shorter arguments are recycled to achieve this length (with a warning if they are recycled only fractionally). ... For cbind (rbind), vectors of zero length (including NULL) are ignored unless the result would have zero rows (columns), for S compatibility.

    Thus, I would suggest working with an if-else condition:

    if(length(IDCOL) > 0) {
       cbind(IDCOL, df) # make sure lengths are identical
    } else {
       df # do whatever you want here
    }