richie20
richie20

Reputation: 35

How to subset a data frame by pairing its columns

I need to extract columns in such a way where I am selecting one and then the next one which is 288 columns away. For example:

 datanew <- data[, c(8, 296, 9, 297, 10, 298, 11, 299, 12, 300 etc)] 

I need to do this up until 288, 576.

Could anybody suggest whether there is a quicker way to do this?

Upvotes: 2

Views: 51

Answers (2)

Ben Bolker
Ben Bolker

Reputation: 226557

Something like

first_columns <- 8:288
next_columns <- first_columns+288
comb <- c(rbind(first_columns, next_columns))

This is the tricky part - since R stores matrices in column-first order, making a two-row matrix and then using c() to collapse it to a vector will make an interleaved vector of column numbers. (Checking with head(comb) shows 8 296 9 297 10 298 ... as requested.)

Then do data[, comb].

Another, somewhat more explicit way to do this:

comb <- rep(NA_real_, 2*(288-7))     ## set up vector (could also use numeric())
odds <- seq(1,length(comb), by=2)
evens <- seq(2, length(comb), by=2)
comb[odds] <- 8:288
comb[evens] <- comb[odds] + 288

Upvotes: 3

Karolis Koncevičius
Karolis Koncevičius

Reputation: 9656

You can take advantage of recycling and do something like this:

datanew <- data[, rep(8:288, each=2) + c(0, 288)]

Upvotes: 3

Related Questions