0

How can I select all columns in a matrix without some subset of columns (by name)?

Here I would like to select all but foo

m = as.matrix(1:4)
dim(m) <- c(2,2)
colnames(m) = c('foo', 'bar')

     foo bar
[1,]   1   3
[2,]   2   4

m[, all-but-`foo`] # ???

In the real script my matrix has many columns and I would like to select all of them but one or two. I do not want to specify explicitly the columns I want to select, by rather those that I don't want at the output.

4

1 回答 1

4

使用%in%运算符

m[ , ! colnames(m) %in% c('foo') ]
[1] 3 4

c向向量添加任意数量的名称。在此示例中,它显示为向量,因为您只返回一列。

更好的例子

m <- matrix( 1 , nrow = 3 , ncol = 6 )
colnames( m ) <- letters[1:6]
m[ , ! colnames(m) %in% c('a','b') ]
     c d e f
[1,] 1 1 1 1
[2,] 1 1 1 1
[3,] 1 1 1 1
于 2013-08-06T13:54:56.820 回答