For loop in R with increments

前端 未结 2 538
伪装坚强ぢ
伪装坚强ぢ 2021-01-01 10:06

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 achie

相关标签:
2条回答
  • 2021-01-01 10:44

    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))
    
    0 讨论(0)
  • 2021-01-01 10:52

    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
    
    0 讨论(0)
提交回复
热议问题