cmo
cmo

Reputation: 4114

r remove columns with empty vector of indeces

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

Answers (2)

user10801787
user10801787

Reputation: 17

reline the previous command and you should be good

Upvotes: 0

akrun
akrun

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

Related Questions