[R] extracting column at regular intervals starting from different columns

Berend Hasselman bhh at xs4all.nl
Tue Sep 18 19:40:06 CEST 2012


On 18-09-2012, at 19:21, eliza botto wrote:

> 
> Dear useRs,
> i had a matrix with 31 rows and 444 columns and i wanted to extract every 37th column of that matrix starting from 1. more precisely i wanted to select columns 1, 38,75, 112 and so on. then doing the same by starting from column number 2(2,39,76,113.......).
> i was advised to use 
>> x[c(TRUE, rep(FALSE, 36)),]
> i works if it is start from first column but as i am very new to R i wanted to know what to do to make it work if i want to start column selection from column 2 and then from column 3 and so on.
> sorry for bothering you once again..

When you use my method you could do the following

f3 <- function(x,M,start=1) {
    x[c(start,seq_len((length(x)-1)/M)*M+start)]
}

M <- 37
A <- 1:(3*M)
f3(A,M)
f3(A,M,start=1)
f3(A,M,start=2)

When start is too large you may get NA's in the result.
You may have to get rid of them.

Berend



More information about the R-help mailing list