简体   繁体   中英

Removing every 2nd and 5th column in a matrix in r

I am working on a problem set where i'm being asked to remove every 2nd and every 5th column from a very large matrix mA

mA = matrix(rnorm(10000), nrow = 100, ncol = 100)

I can easily figure out how to do one of either, but i'm having a hard time figuring out how to do both at the same time. Anyone got any ideas?

Using vector recycling you can do -

result <- mA[, c(TRUE, FALSE, TRUE, TRUE, FALSE)]

mA[,!(seq(ncol(mA)) %% 2 == 0 | seq(ncol(mA)) %% 5 == 0)]

We can also do

result <- mA[, -unique(unlist(lapply(c(2, 5), function(i) seq(1, ncol(mA), by = i))))]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM