Search code examples
rdatabasedataframeif-statementcase

Case_when or if else?


I have a dataset like this with the column "value":

enter image description here

I want to create with R the column "code", meaning that:

  • Values: between 0.0 to 0.3 --> code: 1
  • Values: between 0.40 to 0.50 --> code: 2
  • Values: >50 --> code: 3

What should I use instead of case_when (which for my knowledge works only for two conditions)?


Solution

  • Actually, the case_when() function handles multiple conditions, whereas ifelse() handles only one (unless you chain calls). You may use case_when here:

    df$code <- case_when(
        df$value >= 0.0 & df$value <= 0.3 ~ 1,
        df$value > 0.4 & df$value <= 0.5 ~ 2,
        df$value > 0.5 ~ 3
    )