Create category based on range in R

前端 未结 1 701
北恋
北恋 2021-01-07 04:35

I would like to add a column to my dataframe that contains categorical data based on numbers in another column. I found a similar question at Create categorical variable in

1条回答
  •  一生所求
    2021-01-07 05:25

    Why didn't cut work? Did you not assign to a new column or something?

    > data=data.frame(x=c(3,4,6,12))
    > data$group = cut(data$x,c(0,5,10,15))
    > data
       x   group
    1  3   (0,5]
    2  4   (0,5]
    3  6  (5,10]
    4 12 (10,15]
    

    What you've created there is a factor object in a column of your data frame. The text displayed is the levels of the factor, and you can change them by assignment:

    levels(data$group) = c("0-5","6-10",">10")
    data
       x group
    1  3   0-5
    2  4   0-5
    3  6  6-10
    4 12   >10
    

    Read some basic R docs on factors and you'll get it.

    0 讨论(0)
提交回复
热议问题