1

I have a matrix or a data-frame with specific column names. With a vector containing some of the column names, I can easily address those columns of the matrix. But is there as well a simple way to address the opposite columns, which are not listed in the vector:

mat <- matrix(c(1:12), ncol=4)
colnames(mat) <- c("a", "b", "c", "d")
not_target_col <- c("a", "b")

in this case I like to have the columns c and d. I search something like this, without making the extra step:

pos <- colnames(mat) != not_target_col
mat[,pos]

Additional explanation

I like to make it more clear: When I have a numeric vector I can get the opposite when I add *-1

not_target_col <- c(1,2)
mat[,not_target_col * -1]

There is as well a technique like this when I use a logical vector. Here I just have to add a !.

not_target_col <- c(T,T,F,F)
mat[,!not_target_col]
and-bri
  • 1,563
  • 2
  • 19
  • 34

2 Answers2

0

We can use setdiff between column names (colnames) and not_target_col to get the column names which do not match with not_target_col.

setdiff(colnames(mat), not_target_col)
#[1] "c" "d"

If we need to select those columns from the matrix

mat[, setdiff(colnames(mat), not_target_col)]

#     c  d
#[1,] 7 10
#[2,] 8 11
#[3,] 9 12
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
0

Another option is %in%

mat[, !colnames(mat) %in% not_target_col]
#     c  d
#[1,] 7 10
#[2,] 8 11
#[3,] 9 12
akrun
  • 874,273
  • 37
  • 540
  • 662