2

我需要在我的矩阵 X 中添加一列。它必须是 X 的第一列,并且所有值都应该是“1”。我尝试使用 cbind 命令,但不知何故我无法完成它。如果有人可以帮助我,那就太好了。

X 的代码(来自名为“wagedata”的数据集。

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

数据集的结构是这样的——对于 X 我只有 educ 和 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
4

1 回答 1

5

这似乎有效。如果它对您不起作用,也许一列包含字符数据?

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

要在矩阵中间添加新列,请尝试:

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
于 2013-09-28T15:56:55.483 回答