Using ifelse to transform column in R

后端 未结 4 1465
-上瘾入骨i
-上瘾入骨i 2021-01-26 18:40

I have a dataframe with a column of numbers.

In a separate column, I want to print whether the number is \"less than 10\", \"between 10 and 20\" or \"between 20 and 30\

4条回答
  •  佛祖请我去吃肉
    2021-01-26 19:16

    You could use cut from base R, but be aware it makes the words variable a factor. You just need to set the appropriate intervals (which is why I used 30.5 etc for readibility). BTW, in your example you coded 20 should be recoded both to "between 10 and 20" and to "between 20 and 30", which won't work.

    data$words <- cut(data$number, c(0,9.5,20.5,30.5,40), c("less than 10", "between 10 and 20", "between 20 and 30", "other"))
    data
    

提交回复
热议问题