R: creating a categorical variable from a numerical variable and custom/open-ended/single-valued intervals

后端 未结 2 2006
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-05 03:54

I often find myself trying to create a categorical variable from a numerical variable + a user-provided set of ranges.

For instance, say that I have a data.frame wi

2条回答
  •  無奈伤痛
    2021-01-05 04:35

    Use cut(), already:

    df$VCAT2 <- cut(df$V, c(0,9.999,10,20,Inf), labels=F)
    

    Notice the trick I pull to define a very small bin at 10:

    • (and if you need that bin to be infinitesimally narrow, use 10 - 10*.Machine$double.eps)
    • you can manually define your desired labels '(0,10)','[10,10]',(10,20), [20,Inf]' with the cut(..., labels) argument.

提交回复
热议问题