Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

for() loop step width

Tags:

loops

for-loop

r

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,

like image 713
Lisa Ann Avatar asked Oct 12 '12 16:10

Lisa Ann


2 Answers

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
like image 73
GSee Avatar answered Sep 28 '22 07:09

GSee


Why use for ?

 b <- a[seq(2,length(a),3)]
like image 43
Carl Witthoft Avatar answered Sep 28 '22 07:09

Carl Witthoft