2

I need to add a column to my matrix X. It needs to be the first column of X and all values should be "1". I tried with the cbind command, but somehow I couldn't get it done. If someone could help me that would be great.

Code for X (from a dataset called "wagedata".

X <- as.matrix(wagedata[3:4])

The dataset is structured this way - For X i only ned educ and exper:

wage    IQ  educ    exper   tenure  age married black   south
    769 93  12  11  2   31  1   0   0
    808 119 18  11  16  37  1   0   0
SWR
  • 507
  • 1
  • 8
  • 17
  • Please help us help you by providing us with a reproducible example (i.e. code and example data), see http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example for details. – Paul Hiemstra Sep 28 '13 at 15:47
  • Did you try `cbind(1, wagedata[3:4])`? – sgibb Sep 28 '13 at 15:56

1 Answers1

5

This seems to work. If it does not work for you, perhaps a column contains character data?

my.data <- read.table(text = '
wage    IQ  educ    exper   tenure  age married black   south
    769 93  12  11  2   31  1   0   0
    808 119 18  11  16  37  1   0   0
', header = TRUE)

my.matrix <- as.matrix(my.data)

new.column <- rep(1, nrow(my.matrix))
my.matrix <- cbind(new.column, my.matrix)
my.matrix

#      new.column wage  IQ educ exper tenure age married black south
# [1,]          1  769  93   12    11      2  31       1     0     0
# [2,]          1  808 119   18    11     16  37       1     0     0

my.matrix[,c(1,3,4)]
#      new.column  IQ educ
# [1,]          1  93   12
# [2,]          1 119   18

my.matrix[,c(1,4,5)]
#      new.column educ exper
# [1,]          1   12    11
# [2,]          1   18    11

To add the new column in the middle of the matrix try:

my.matrix2 <- as.matrix(my.data)
my.matrix2 <- cbind(my.matrix2[,1:5], new.column, my.matrix2[,6:9])
my.matrix2

#      wage  IQ educ exper tenure new.column age married black south
# [1,]  769  93   12    11      2          1  31       1     0     0
# [2,]  808 119   18    11     16          1  37       1     0     0
Mark Miller
  • 12,483
  • 23
  • 78
  • 132
  • 4
    You do not need to call `rep`. `cbind(1, my.matrix)` is sufficient. – sgibb Sep 28 '13 at 16:00
  • @sgibb Thank you. I am still learning details like that. You can edit the post if you want. Or we can leave it as is with your tip for improvement as a comment. – Mark Miller Sep 28 '13 at 16:15
  • 1
    So there is no way to dynamically allocate additional columns to a matrix like you can to vector-like objects and data.frames (with a warning in the latter case)? Example: `foo<-runif(5);foo;foo[7]<-42;foo;` – bokov Sep 28 '13 at 16:35
  • @f1r3br4nd I do not know. If there are better ways hopefully others will post them. – Mark Miller Sep 28 '13 at 16:40
  • Your `cbind(new.column, my.matrix)` saved my life THANK YOU @MarkMiller! –  Jan 08 '14 at 11:06