#### [SOLVED] reverse loop interation in R like in Python

By Jose

here is my python loop code with output

``````peaks =range(2,10)
for i in range(len(peaks) - 1, -1, -1):
print(i)

# 7,6,5,4,3,2,1,0
``````

but i do not know how to do this with R

#### @Federico Cattai 2019-10-09 14:16:45

in R

``````peaks <- c(2:10)
l <- length(peaks)
result <- l - peaks
result[result > 0]
``````

returns

``````7 6 5 4 3 2 1
``````

if you nedd a for loop, you can use this:

``````for(p in peaks){ifelse(l-p >= 0, print(l-p), NA)}
``````

#### @Jose 2019-10-09 14:17:55

thanks , can you please do this with For loop , that is what i want

#### @Jose 2019-10-09 14:30:15

kindly check the comment of above ans as well

#### @Jose 2019-10-09 14:34:38

and there is 7 6 5 4 3 2 1 0

#### @Igor F. 2019-10-09 14:12:27

I agree with Sosel. Nevertheless, here is working code:

``````peaks = 2:9
for(i in rev(0:(length(peaks)-1))) print(i)
``````

#### @Jose 2019-10-09 14:14:39

thanks man , but here we take peaks =(2:9) , actually it (2:10) , how can we solve it

#### @Igor F. 2019-10-09 14:18:32

@Jose: In R, unlike Python, `2:n` means all the numbers from `2` to `n`, including both 2 and n.

#### @Jose 2019-10-09 14:26:34

gotcha , but here we set it manually , in my case it varies every time, how can i do that?

#### @Jose 2019-10-09 14:27:18

that range is coming directly, i just have to pass peak

### [SOLVED] Accessing the index in 'for' loops?

• 2009-02-06 22:47:54
• Joan Venge
• 1903776 View
• 3269 Score
• Tags:   python loops list