rcbindfunction-parameterr-colnames

cbind() - how to label a vector dynamically in one line


Consider:

cbind("1" = 1:4)
## giving.
     1
[1,] 1
[2,] 2
[3,] 3
[4,] 4

What I am trying to achieve is replacing "1" with a function that returns a character expression, e.g.

cbind(as.character(1) = 1:4)

But this gives:

Error: unexpected '=' in "cbind(as.character(1) ="

Any idea how to do this? Preferably in base R.

Note: I like compact coding.


Solution

  • Use `colnames<-`().

    > `colnames<-`(cbind(1:4), 1)
         1
    [1,] 1
    [2,] 2
    [3,] 3
    [4,] 4
    
    > `colnames<-`(matrix(0, 3, 2), 1:2)
         1 2
    [1,] 0 0
    [2,] 0 0
    [3,] 0 0
    
    > `colnames<-`(matrix(0, 3, 2), letters[1:2])
         a b
    [1,] 0 0
    [2,] 0 0
    [3,] 0 0