I am trying to create a new column and have values derived from another column in a dataframe using if-else or case-when but i am only getting the first condition satisfied and not going to else part thereby populating all the records with the first value.
New column:Quarter
Column from which values are to be derived:Month
unique(promax_2020_data$month)
[1] "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep"
If-else code:-
promax_2020_data$Quarter<-if (promax_2020_data$month %in% c("Jan","Feb","Mar")){
"Q1"
} else if (promax_2020_data$month %in% c("Apr","May","Jun")){
"Q2"
} else {
"Q3"
}
Warning message:
In if (promax_2020_data$month %in% c("Jan", "Feb", "Mar")) { :
the condition has length > 1 and only the first element will be used
promax_2020_data$Quarter <- {
case_when(
promax_2020_data$month=="Jan" || promax_2020_data$month=="Feb" || promax_2020_data$month=="Mar" ~ "Q1",
promax_2020_data$month=="Apr" || promax_2020_data$month=="May" || promax_2020_data$month=="Jun" ~ "Q2",
promax_2020_data$month=="Jul" || promax_2020_data$month=="Aug" || promax_2020_data$month=="Sep" ~ "Q3",
TRUE ~ "Q4"
)
}
Although using case when doesn't give any error or warning like if-else but this also populates all the records with Q1 only.