Using ifelse to transform column in R

后端 未结 4 1462
-上瘾入骨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:24

    The main problem was that you need to reference the variable in each inequality test. To make this more readable, I wrapped everything in a with(data... call. Another problem with your code was the use of && instead of &. The former is for single values only while the latter compares each element of two vectors.

    data$words<-
      with(data,
           ifelse(number >= 0 & number <= 9, "less than 10",
           ifelse(number >= 10 & number <= 20, "between 10 and 20",
           ifelse(number >= 20 & number <= 30, "between 20 and 30", "other"))))
    

    I also think this is a lot more readable than the tidyverse without introducing new syntax. It is easier to debug, too.

提交回复
热议问题