Home > OS >  Using ifelse in R to create a new variable with more than 3 conditions
Using ifelse in R to create a new variable with more than 3 conditions

Time:12-23

I am using the following code to assign each month a season:

> data$SEASON = ifelse(data$Month > 8, "Fall", 
>                             ifelse(data$Month > 10, "Winter",
>                             ifelse(data$Month < 6, "Spring","Summer")))

While Summer (months 6-9), Spring (months 4-5) and Fall (months 9-10) appear to get assigned correctly, WINTER does not, and I can't understand why.

My data looks like this:

Year    Month   Day 
  2018    1       1 
  2018    1       2 
  2018    2       3 
  2018    3       3 
  2018    9       1
  2018    8       4
  2018    7       5
  2018    6       2
  2018    5       4 
  2018    6       7  
  2018    10      4
  2018    11      5
  2018    12      8  
  2018    3       9
  2018    4       10 

and I want it to look like this

Year    Month   Day   SEASON
2018    1       1     Winter 
2018    1       2     Winter 
2018    5       3     Spring
2018    6       3     Summer
2018    9       1     Fall
.... etc 

Currently, the code runs with no error and a new column is generated, but there is no WINTER season in the new column. Months 1-5 show up as Spring, and Months 9-12 show us as FALL. SUMMER is the only season that shows up correctly. I want months 1,2, 3, 11 and 12 to show up as WINTER. Any help would be appreciated - Thanks!

CodePudding user response:

We can use case_when() from the dplyr package:

data$SEASON <- case_when(
    data$Month <= 3 ~ "Winter", 
    data$Month <= 6 ~ "Spring",
    data$Month <= 9 ~ "Summer",
    TRUE ~ "Fall"
)

CodePudding user response:

library(tidyverse)

df %>%
  mutate(season = case_when(
    between(Month, 3, 5) ~ "Spring",
    between(Month, 6, 8) ~ "Summer",
    between(Month, 9, 11) ~ "Fall",
    TRUE ~ "Winter"
  ))

# A tibble: 15 × 4
    Year Month   Day season
   <dbl> <dbl> <dbl> <chr> 
 1  2018     1     1 Winter
 2  2018     1     2 Winter
 3  2018     2     3 Winter
 4  2018     3     3 Spring
 5  2018     9     1 Fall  
 6  2018     8     4 Summer
 7  2018     7     5 Summer
 8  2018     6     2 Summer
 9  2018     5     4 Spring
10  2018     6     7 Summer
11  2018    10     4 Fall  
12  2018    11     5 Winter
13  2018    12     8 Winter
14  2018     3     9 Spring
15  2018     4    10 Spring
  • Related