13

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

I'm trying this code:

normDisMatrix$newColumn <- labels

Getting this message:

Warning message: In normDisMatrix$newColumn <- labels : Coercing LHS to a list

After it, when I check the matrix, it seems null:

dim(normDisMatrix)
NULL

Note: labels are just vectors which have numbers between 1 and 4.

What can be the problem?

zx8754
  • 52,746
  • 12
  • 114
  • 209
seleucia
  • 1,046
  • 4
  • 17
  • 30
  • 5
    You can't use `$` to subset matrices - see the bottom part of my previous answer to this question: http://stackoverflow.com/questions/16682576/r-error-dimx-must-have-a-positive-length/16682747#16682747 – thelatemail Jan 06 '15 at 01:22
  • You might give us some data where we can reproduce the error. As is I have no clue what 'labels' is nor 'normDisMatrix' nor myMatrix – Jason Jan 06 '15 at 01:25
  • @thelatemai thank you for answer, can you suggest me a way to add a column to matrix. – seleucia Jan 06 '15 at 01:30

1 Answers1

24

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
Rich Scriven
  • 97,041
  • 11
  • 181
  • 245