简体   繁体   中英

R - meet the condition then continue loop, otherwise repeat

I now have a vector x, and I want to create another vector y. Its role is to divide x into many groups by comparing the x value with a specific value(eg 30).

here is the vector x:

x <- c(1,2,5,34,21,6,0,56,77,21,3,0)

If describe this problem with loops and conditional statements, I think that is:

when the conditions are satisfied, then continue the loop, otherwise repeat the it.

For example, in the vecor x, 1, 2, and 5 is less than 30, so "1" is repeated for three times in y; 34 is greater than 30, so the loop continue to the value of 2, and 21 is less than 30, so "2" is repeated for 1 time, and so on.

The final value of y should be like this:

y <- c(1,1,1,2,2,2,2,3,4,4,4,4)

Maybe my expression is not very clear, because I am a Non-Native English speaker, and I'm a little confused right now, I hope someone can help me.

We can use cumsum here and increment the count every time we find a value greater than 30.

cumsum(x > 30) + 1
#[1] 1 1 1 2 2 2 2 3 4 4 4 4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM