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

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

    You can also remove rows and columns by feeding a vector of logical boolean values to the matrix. This handles the situation where you have multiple non-contiguous rows or non-contiguous columns that need to be deleted.

    # TRUE = Keep a row/column
    # FALSE = Delete a row/column
    #
    # FALSE for rows 4, 5, and 6
    # Row:            1     2     3     4      5      6      7     8     9     10
    rows_to_keep <- c(TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, TRUE, TRUE, TRUE, TRUE)
        
    # FALSE for columns 7, 8, and 9
    # Column:         1     2     3     4     5     6     7      8      9      10
    cols_to_keep <- c(TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, TRUE) 
    

    To remove just the rows:

    t1 <- t1[rows_to_keep,]
    

    To remove just the columns:

    t1 <- t1[,cols_to_keep]
    

    To remove both the rows and columns:

    t1 <- t1[rows_to_keep, cols_to_keep]
    

    This coding technique is useful if you don't know in advance what rows or columns you need to remove. The rows_to_keep and cols_to_keep vectors can be calculated as appropriate by your code.

提交回复
热议问题