extracting column at regular intervals starting from different columns
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..
I have defined 2 more functions for David's and Clint's solution and my solution.
f3 <- function(x,M,start=1) {
x[c(rep(FALSE,start-1),TRUE,rep(FALSE,M-start))]
}
f4 <- function(x,M,start=1) {
x[c(start,seq_len((length(x)-1)/M)*M+start)]
}
z3 <- f3(a,M,start=1)
z4 <- f4(a,M,start=1)
identical(z3,z1)
identical(z3,z2)
z5 <- f3(a,M,start=4)
z6 <- f4(a,M,start=4)
identical(z5,z6)
With
N <- 444
a <- 1:N
M <- 37
I get the following timing results.
benchmark(f3(a,M,start=4), f4(a,M,start=4), replications=Nrep)
test replications elapsed relative user.self sys.self 1 f3(a, M, start = 4) 100000 1.621 1.562 1.606 0.014 2 f4(a, M, start = 4) 100000 1.038 1.000 1.035 0.002 Compared to the timings for start=1 (previous post) the solution with rep becomes slightly slower. Berend