Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For loop in R with increments

Tags:

for-loop

r

I am trying to write a for loop which will increment its value by 2. The equivalent code is c is

for (i=0; i<=78; i=i+2)

How do I achieve the same in R?

like image 719
Probabilityman Avatar asked Apr 23 '12 19:04

Probabilityman


People also ask

Can I increment 2 in for loop?

A for loop doesn't increment anything. Your code used in the for statement does.

How do you add increments to a while loop?

First off, you will have to declare the index variable before the while loop. If you declare it inside, it will be a new variable each time it iterates. When that is done, you will need to increment the variable for each iteration, this can be done by either $i++ or $i+=1 .

Does continue increment for loop?

The continue statement in C programming works somewhat like the break statement. Instead of forcing termination, it forces the next iteration of the loop to take place, skipping any code in between. For the for loop, continue statement causes the conditional test and increment portions of the loop to execute.

How do you do a for loop in a range in R?

For loop is used to iterate the elements over the given range. We can use for loop to append, print, or perform some operation on the given range of integers. Consider the below syntax of the for loop that also contains some range in it.


2 Answers

See ?seq for more info:

for(i in seq(from=1, to=78, by=2)){
#  stuff, such as
  print(i)
}

or

for(i in seq(1, 78, 2))

p.s. Pardon my C ignorance. There, I just outed myself.

However, this is a way to do what you want in R (please see updated code)

EDIT

After learning a bit of how C works, it looks like the example posted in the question iterates over the following sequence: 0 2 4 6 8 ... 74 76 78.

To replicate that exactly in R, start at 0 instead of at 1, as above.

seq(from=0, to=78, by=2)
 [1]  0  2  4  6  8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44
[24] 46 48 50 52 54 56 58 60 62 64 66 68 70 72 74 76 78
like image 181
BenBarnes Avatar answered Oct 07 '22 20:10

BenBarnes


you can do so in following way, you can put any length upto which you want iteration in place of length(v1), and the increment value at position of 2 to your desired value

for(i in seq(1,length(v1),2))
like image 24
Shivam Paliya Avatar answered Oct 07 '22 22:10

Shivam Paliya