for() loop step width

29,455

Solution 1

Use 3 as the value for by in seq

for (i in seq(2, length(a), by=3)) {}

> seq(2, 11, 3)
[1]  2  5  8 11

Solution 2

Why use for ?

 b <- a[seq(2,length(a),3)]
Share:
29,455
Lisa Ann
Author by

Lisa Ann

Updated on October 06, 2022

Comments

  • Lisa Ann
    Lisa Ann over 1 year

    Let I have an array like

    a <- seq(1, 100, 1)
    

    and I want to select just the elements that occur each 3 steps with a for() loop starting from the second one, e.g. 2, 5, 8, 11 and so on.

    How should I use for() in this case?

    b <- NULL
    # for(i in 1:length(a)) { # Is there any additional argument?
       # b[i] <- a[...] # Or I can just multiply 'i' by some integer?
    # }
    

    Thanks,

  • Lisa Ann
    Lisa Ann over 11 years
    I'm a bit confused by different languages, I was trying something like for(i in 1:length(a) ; i + 3) {} and such things :)
  • Lisa Ann
    Lisa Ann over 11 years
    My fault, in the original issue that I wanted to solve I had no other choice than using for(); in the SO example I did not reproduce my original issue, but I specififed I wanted to use for().
  • John
    John over 11 years
    If you really have to use for() then you still need to make the amount of code in the loop as small as possible. The selection of the sequence in the for() example is actually outside the loop. You should be thinking like this as much as possible in order to optimize your R code.
  • John
    John over 11 years
    If you're thinking like that at all you're going to end up with very inefficient R code, even if you figure out how to do it in R. Consider posting a larger portion of your problem in another question, especially if the code seems to run slow.