这似乎有效。如果它对您不起作用,也许一列包含字符数据?
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