How to delete specific rows and columns from a matrix in a smarter way?

前端 未结 4 1234
花落未央
花落未央 2021-02-05 00:45

Let\'s say t1 is :

t1 <- array(1:20, dim=c(10,10))

      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
 [1,]    1   11    1   11    1   11          


        
4条回答
  •  囚心锁ツ
    2021-02-05 01:28

    > S = matrix(c(1,2,3,4,5,2,1,2,3,4,3,2,1,2,3,4,3,2,1,2,5,4,3,2,1),ncol = 5,byrow = TRUE);S
    [,1] [,2] [,3] [,4] [,5]
    [1,]    1    2    3    4    5
    [2,]    2    1    2    3    4
    [3,]    3    2    1    2    3
    [4,]    4    3    2    1    2
    [5,]    5    4    3    2    1
    > S<-S[,-2]
    > S
    [,1] [,2] [,3] [,4]
    [1,]    1    3    4    5
    [2,]    2    2    3    4
    [3,]    3    1    2    3
    [4,]    4    2    1    2
    [5,]    5    3    2    1
    

    Just use the command S <- S[,-2] to remove the second column. Similarly to delete a row, for example, to delete the second row use S <- S[-2,].

提交回复
热议问题