如何向矩阵添加一列

SWR*_*SWR 2 r matrix

我需要向矩阵 X 添加一列。它需要是 X 的第一列,并且所有值都应为“1”。我尝试使用 cbind 命令,但不知怎的我无法完成它。如果有人能帮助我那就太好了。

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

X <- as.matrix(wagedata[3:4])
Run Code Online (Sandbox Code Playgroud)

数据集的结构如下 - 对于 X i 仅 ned 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
Run Code Online (Sandbox Code Playgroud)

Mar*_*ler 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
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)

  • 您不需要调用“rep”。`cbind(1, my.matrix)` 就足够了。 (4认同)