CSV column month needs to be labelled as quarters

homework

#1

This post was flagged by the community and is temporarily hidden.


#2

in R there's a built in vector of month abbreviations called month.abb. You can use that to turn your month abbreviations into month numbers, then use the ceiling function with a little division to get the q number. Then just add q to each quarter number.

You can easily wrap this in a function, but here's a step by step so you can understand the pieces:

date_abb <- c("Jan","Apr", "Mar","Dec","Feb","Jul")
date_num <- match(date_abb,month.abb)
q_number <- ceiling(date_num / 3)
q_name <- paste0('q',q_number)
q_name

#> [1] "q1" "q2" "q1" "q4" "q1" "q3"

it looks like you might have some case issues if your abbreviations come without initial caps. The easiest solution is to just force everything to lower case using tolower:

date_abb <- c("Jan","Apr", "mar","DeC","FEB","jul")
date_num <- match(tolower(date_abb),tolower(month.abb))
q_number <- ceiling(date_num / 3)
q_name <- paste0('q',q_number)
q_name

#> [1] "q1" "q2" "q1" "q4" "q1" "q3"

#3

This post was flagged by the community and is temporarily hidden.


#4

you're question has been hard to understand because you have not included a reproducible example (reprex). But your screenshot of the data gives some clues. In the future using a reprex will help you get good help faster.

I think your forestfires$month column is a factor which is causing you a world of invisible problems. When you read in your csv, turn off strings as factors with stringsAsFactors = FALSE or use read_csv from the readr package which defaults to strings not as factors.

I built a reproducible example to illustrate what should be happening:

# create example data, a critical step of a reprex
forestfires <- data.frame(month=c('jan','mar','dec','apr','aug'), stringsAsFactors = FALSE)

monthlist <- rep(c("Q1",'Q2','Q3','Q4'),each = 3)

#your months are all lower case so use tolower() to make your named vector also lowercase
names(monthlist) <- tolower(month.abb)
monthlist
#>  jan  feb  mar  apr  may  jun  jul  aug  sep  oct  nov  dec 
#> "Q1" "Q1" "Q1" "Q2" "Q2" "Q2" "Q3" "Q3" "Q3" "Q4" "Q4" "Q4"

monthlist[forestfires$month]
#>  jan  mar  dec  apr  aug 
#> "Q1" "Q1" "Q4" "Q2" "Q3"