Using apply functions instead of for and branching statements in R

时光总嘲笑我的痴心妄想 提交于 2019-12-25 01:41:08

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!