-1

I am new to R programming. Actually I want to map seasons (like Winter, Summer, Monsoon, Post Monsoon) based on the months. I have tried below code. Pls guide me on same.

ifelse((air_quality$Month %in% c('12','01','02','04')),air_quality$Seasons = 'Winter',
ifelse((air_quality$Month %in% c('04','05','06')),air_quality$Seasons = 'Summer',
ifelse((air_quality$Month %in% c('07','08','09')),air_quality$Seasons = 'Monsoon','Post Monsoon')))

Thanks in advance. AP

Dee_wab
  • 1,171
  • 1
  • 10
  • 23
Anupam
  • 1
  • 1
    Please provide a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610#5963610). – kath May 09 '18 at 08:35
  • Related: [*Adding a seasons column to data table based on month dates*](https://stackoverflow.com/q/36903538/2204410) & [*Seasonal aggregate of monthly data*](https://stackoverflow.com/q/22124315/2204410) – Jaap May 09 '18 at 08:43
  • There are vast amounts of tutorials for such a simple task to be found by googling. – LAP May 09 '18 at 08:43

1 Answers1

0

It looks like "04" in your example belongs to both "winter" and "Summer". If we assume that one month belongs to only one season and the seasons are Winter, Summer, Monsoon and Postmonsoon, then one of the ways you can convert months to seasons is:

library(stringr) # to produce strings padded with zeros 
air_quality <- data.frame(Month = str_pad(sample(1:12,12, replace=FALSE),
                                          width = 2, 
                                          side = "left", pad="0"))

# Create a mapping vector and print it
( seasons <- c( rep("Winter",2), 
                rep("Summer",3), 
                rep("Monsoon",3), 
                rep("Postmonsoon",3), 
                "Winter") )
#[1] "Winter"      "Winter"      "Summer"      "Summer"      "Summer"      "Monsoon"     "Monsoon"    
#[8] "Monsoon"     "Postmonsoon" "Postmonsoon" "Postmonsoon" "Winter"     

air_quality$Seasons <- seasons[ as.numeric(air_quality$Month) ]
air_quality
#    Month     Seasons
# 1     07     Monsoon
# 2     06     Monsoon
# 3     11 Postmonsoon
# 4     01      Winter
# 5     05      Summer
# 6     09 Postmonsoon
# 7     03      Summer
# 8     08     Monsoon
# 9     10 Postmonsoon
# 10    02      Winter
# 11    04      Summer
# 12    12      Winter
Katia
  • 3,784
  • 1
  • 14
  • 27