根据vetcor选择矩阵列

时间:2014-08-22 14:57:33

标签: r matrix vector

我认为我没有在标题中明确说明,所以我只是说明了问题: assdt是一个载体:

assdt
 [1] 18 19  1  0 33 26  3  2 31 42 43 41 44

dt是一个矩阵:

dt 0 dt 1 dt 2 dt 3 dt 4 dt 5 dt 6 dt 7 dt 8 dt 9 dt 10 dt 11 dt 12 dt 13 dt 14 dt 15 dt 16 dt 17 dt 18 dt 19 dt 20
[1,] "0"  "0"  "0"  "1"  "0"  "1"  "0"  "0"  "0"  "0"  "0"   "0"   "1"   "0"   "1"   "0"   "0"   "0"   "0"   "0"   "0"  
[2,] "0"  "0"  "0"  "1"  "0"  "1"  "0"  "1"  "0"  "0"  "0"   "0"   "0"   "0"   "1"   "0"   "0"   "0"   "0"   "0"   "0"  
[3,] "0"  "0"  "0"  "1"  "0"  "0"  "0"  "1"  "0"  "0"  "0"   "0"   "0"   "0"   "1"   "0"   "0"   "0"   "0"   "0"   "0"  
[4,] "0"  "0"  "0"  "1"  "0"  "0"  "0"  "1"  "0"  "0"  "0"   "0"   "0"   "0"   "1"   "0"   "0"   "0"   "0"   "0"   "0"  
[5,] "0"  "0"  "0"  "1"  "0"  "0"  "0"  "0"  "0"  "0"  "0"   "0"   "0"   "0"   "1"   "0"   "0"   "0"   "0"   "0"   "0"  
[6,] "0"  "0"  "0"  "1"  "0"  "0"  "1"  "0"  "1"  "0"  "0"   "0"   "0"   "0"   "1"   "0"   "0"   "0"   "0"   "0"   "0"  
     dt 21 dt 22 dt 23 dt 24 dt 25 dt 26 dt 27 dt 28 dt 29 dt 30 dt 31 dt 32 dt 33 dt 34 dt 35 dt 36 dt 37 dt 38 dt 39
[1,] "0"   "0"   "0"   "0"   "0"   "0"   "1"   "1"   "0"   "0"   "0"   "0"   "0"   "0"   "0"   "0"   "1"   "1"   "0"  
[2,] "0"   "0"   "0"   "0"   "0"   "0"   "1"   "1"   "0"   "0"   "0"   "0"   "0"   "0"   "0"   "0"   "1"   "1"   "0"  
[3,] "0"   "0"   "0"   "0"   "0"   "0"   "1"   "1"   "0"   "0"   "0"   "0"   "0"   "0"   "0"   "0"   "1"   "1"   "0"  
[4,] "0"   "0"   "0"   "0"   "0"   "0"   "1"   "1"   "0"   "0"   "0"   "0"   "0"   "0"   "0"   "0"   "1"   "1"   "0"  
[5,] "0"   "0"   "0"   "0"   "0"   "0"   "1"   "1"   "0"   "0"   "0"   "0"   "0"   "0"   "0"   "0"   "1"   "1"   "0"  
[6,] "0"   "0"   "0"   "0"   "0"   "0"   "1"   "1"   "0"   "0"   "0"   "0"   "0"   "0"   "0"   "0"   "1"   "1"   "0"  
     dt 40
[1,] "1"  
[2,] "1"  
[3,] "1"  
[4,] "1"  
[5,] "1"  
[6,] "1"  

我想选择selectdt <- c(18,19,1,0,33,26,3,2,31,42,43,41,44)中的列。 dt中没有第42,43,44列,所以只是忽略它们,我做dt[,selectdt]时出现错误subscript out of bounds。怎么做?

1 个答案:

答案 0 :(得分:1)

mat <- as.matrix(mtcars)

cols <- c(1,5,20)
mat[, cols]
#Error in mat[, cols] : subscript out of bounds

mat[, cols[cols <= ncol(mat)]]
#                     mpg drat
#Mazda RX4           21.0 3.90
#Mazda RX4 Wag       21.0 3.90
#...