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

前端 未结 4 1232
花落未央
花落未央 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:25

    You can use

    t1<- t1[-4:-6,-7:-9]  
    

    or

    t1 <- t1[-(4:6), -(7:9)]
    

    or

    t1 <- t1[-c(4, 5, 6), -c(7, 8, 9)]
    

    You can pass vectors to select rows/columns to be deleted. First two methods are useful if you are trying to delete contiguous rows/columns. Third method is useful if You are trying to delete discrete rows/columns.

    > t1 <- array(1:20, dim=c(10,10));
    
    > t1[-c(1, 4, 6, 7, 9), -c(2, 3, 8, 9)]
    
         [,1] [,2] [,3] [,4] [,5] [,6]
    [1,]    2   12    2   12    2   12
    [2,]    3   13    3   13    3   13
    [3,]    5   15    5   15    5   15
    [4,]    8   18    8   18    8   18
    [5,]   10   20   10   20   10   20
    

提交回复
热议问题