# selection from loop

Good afternoon Guys, i'm using R, i'm trying to build a function to extract the maximum from a range of 10 elements which varying with a loop iteration but i don't know how to.

This is roughly what i would like to obtain:

``````A <- \$vector with 100 random numbers*

for i in 1:length(A)
maxx(i) = max (A[i]:A[i+9]) \$ max of the range between A(i) and A(i+9)
}

maxx \$list with length A, filled with all the maximums just calculated
``````

Andrea Alternatively use the function which.max() ?

1 Like

It could be but how can I create a vector with the selection of the elements to evaluate the max??

Thank You @nirgrahamuk

Your problem is in this part `A[i]:A[i+9]`

if `A[i ] == 2` AND `A[i + 9] == 6` you will get the max of the range `2:6`

Instead try `A[i:(i+9)]`

``````A <- sample(0:9, 100, T)

a <- integer(length(A) - 9)

for (i in seq_along(a)) a[i] <- max(A[i:(i+9)])
``````
1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.