Skip to content
Prev 305770 / 398506 Next

extracting column and regular interval in R

On 18-09-2012, at 16:55, eliza botto wrote:

            
Indexing with 

c(1,seq_len((length(x)-1)/M)*M+1)

is also an option.
It appears to be faster than Michael's method.

N <- 444
a <- 1:N

f1 <- function(x,M) {
    x[c(TRUE,rep(FALSE,M-1))]
}

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

M <- 37 
M
z1 <- f1(a,M)
z2 <- f2(a,M)
[1] TRUE


Nrep <- 100000

library(rbenchmark)
benchmark(f1(a,M), f2(a,M), replications=Nrep)
test replications elapsed relative user.self sys.self user.child
1 f1(a, M)       100000   1.395    1.437     1.367    0.027          0
2 f2(a, M)       100000   0.971    1.000     0.959    0.011          0

For N <- 4440 the timings are
test replications elapsed relative user.self sys.self user.child
1 f1(a, M)       100000   4.636    2.483     4.569    0.065          0
2 f2(a, M)       100000   1.867    1.000     1.714    0.153          0


Berend