问题
I am using R and would like to stop using branching and for statements to take advantage of the apply functions. That being said, I have this list, x:
x <- c(5,12,19,26,2,9,16,23)
I would like a corresponding list as follows:
for i in x
if (i<=7) 1
else if (i<=14) 2
else if (i<=21) 3
else if (i<=28) 4
else 5
The final new list will be: 1,2,3,4,1,2,3,4
How can I do this with one of the apply statements? Every time I try and write one I end up scratching my head for an hour and then post a question here.
Thank you.
回答1:
Simply use cut
:
x <- c(5, 12, 21, 35)
as.integer(cut(x, c(-Inf, 7, 14, 21, 28, Inf)))
#[1] 1 2 3 5
回答2:
Showing ifelse use:
ifelse(x<7,1,ifelse(x<14,2,ifelse(x<21,3,ifelse(x<28,4,5))))
[1] 1 2 3 4 1 2 3 4
来源:https://stackoverflow.com/questions/25769790/using-apply-functions-instead-of-for-and-branching-statements-in-r