Drop matrix columns by matched pattern

Hi all,

This question should be straightforward.

I have a matrix. Each column name is in the format "integer_string". I would like to drop all columns where the "string" matches a pattern. I can do it with tibbles, but can't figure it out with a matrix without converting to a tibble. Can anyone offer a more concise solution that what I have so far?

# create matrix
matrix1 <- matrix(c(1,2,3,4,5,6,7,8), nrow = 2, ncol = 4)
rownames(matrix1) <- c("row1", "row2")
colnames(matrix1) <- c("1_car", "2_brush", "3_car", "4_pluto")
matrix1

 # my solution
library(dplyr)
rows <- rownames(matrix1)                 # save rownames
matrix1 <- matrix1 |> 
  as_tibble() |>                          # convert to tibble
  dplyr::select(-ends_with("car")) |>     # remove cols
  as.matrix()                             # convert back to matrix
rownames(matrix1) <- rows                 # re-add rownames
matrix1

# what I have attempted (but finds exact matches only, and returns only col names)
colnames(matrix1[ ,setdiff(colnames(matrix1), "car")])

Thanks in advance,
Kenneth

Here is one method.

matrix1 <- matrix(c(1,2,3,4,5,6,7,8), nrow = 2, ncol = 4)
rownames(matrix1) <- c("row1", "row2")
colnames(matrix1) <- c("1_car", "2_brush", "3_car", "4_pluto")
matrix1
#>      1_car 2_brush 3_car 4_pluto
#> row1     1       3     5       7
#> row2     2       4     6       8
matrix1[, !grepl("_car$", colnames(matrix1))]
#>      2_brush 4_pluto
#> row1       3       7
#> row2       4       8

Created on 2024-05-21 with reprex v2.0.2

1 Like

Thank you for your answer, it worked exactly as I wanted.
Also, it led me to an additional ability to pass multiple patterns to grepl

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.