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?
A for loop doesn't increment anything. Your code used in the for statement does.
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 .
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.
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.
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
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With