Search code examples
rcbind

If there is the same nrows cbind two datas


How to tell R to cbind two matrix only if they have the same number of rows ?

I know that I can check it manually.


Solution

  • Make a function, like:

    ckbind = function (a, b) 
    {
        a = as.matrix(a)
        b = as.matrix(b)
        if (nrow(a) == nrow(b)) {
            return(cbind(a, b))
        } else {
            stop("Differing number of rows")
        }
    }
    

    Note the matrix conversion so it works with vectors. Test:

    > ckbind(1:3,2:4)
         [,1] [,2]
    [1,]    1    2
    [2,]    2    3
    [3,]    3    4
    > ckbind(1:3,2:6)
    Error in ckbind(1:3, 2:6) : Differing number of rows
    

    and check it works with matrices:

    > ckbind( ckbind(1:3,2:4), ckbind(3:5,4:6))
         [,1] [,2] [,3] [,4]
    [1,]    1    2    3    4
    [2,]    2    3    4    5
    [3,]    3    4    5    6