Adding a new column to matrix error

前端 未结 1 927
广开言路
广开言路 2020-12-11 15:20

I\'m trying to add a new column to existing matrix, but getting warning everytime.

I\'m trying this code:

normDisMatrix$newColumn <- labels


        
相关标签:
1条回答
  • 2020-12-11 16:14

    As @thelatemail pointed out, the $ operator cannot be used to subset a matrix. This is because a matrix is just a single vector with a dimension attribute. When you used $ to try to add a new column, R converted your matrix to the lowest structure where $ can be used on the vector, which is a list.

    The function you want is cbind() (column bind). Suppose I have the matrix m

    (m <- matrix(51:70, 4))
    #      [,1] [,2] [,3] [,4] [,5]
    # [1,]   51   55   59   63   67
    # [2,]   52   56   60   64   68
    # [3,]   53   57   61   65   69
    # [4,]   54   58   62   66   70
    

    To add the a new column from a vector called labels, we can do

    labels <- 1:4
    cbind(m, newColumn = labels)
    #                     newColumn
    # [1,] 51 55 59 63 67         1
    # [2,] 52 56 60 64 68         2
    # [3,] 53 57 61 65 69         3
    # [4,] 54 58 62 66 70         4
    
    0 讨论(0)
提交回复
热议问题