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