gpt4 book ai didi

r - 如何向矩阵添加一列

转载 作者:行者123 更新时间:2023-12-02 21:48:45 25 4
gpt4 key购买 nike

我需要向矩阵 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com