r - 如何向矩阵添加一列

标签 r matrix

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

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

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

数据集的结构如下 - 对于 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

最佳答案

这似乎有效。如果它不适合您,也许一列包含字符数据?

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

关于r - 如何向矩阵添加一列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19068693/

相关文章:

r - 为 dplyr do 操作的列表输出分配名称

r - 为机器学习准备时间序列 - 长格式到宽格式

r - R 中 2 个 DTM 的余弦相似度

performance - 如何加速matlab中的双循环

c - 添加两行并将总和存储在最后一行

android - 尝试旋转图像时 : Cannot resolve method mtx. postRotate(int)

r - 为数据框中的所有字符串分配相同的值

r - 如何在 R 中使用每一侧多个变量进行模糊连接

c - 根据我的编译器的说法,我错误地使用了指针来设置二维数组的值。但是,我不确定我到底做错了什么

java - 如何在 Java 中打印矩阵的所有对角线