Reputation: 4114
We all know how to exclude columns from a matrix using a vector of column indices:
v=c(1,3)
a = matrix(rnorm(12),nrow=3)
a[,-v]
But when the indexing vector is empty, the return matrix is empty:
v = numeric()
a[,-v]
# returns matrix with 0 columns
How can i get the returned matrix to be the original matrix when the excluded set of column indices is empty?
There must be a fancier way than using the cumbersome if else
:
if (length(v)==0) {
b = a
} else {
b = a[,-v]
}
Upvotes: 1
Views: 61
Reputation: 887971
We could create an index with setdiff
j1 <- setdiff(seq_len(ncol(a)), v)
and then subset 'a'
a[, j1, drop = FALSE]
Upvotes: 1