N M
N M

Reputation: 11

If Else statement for new variable

I want to code the months into quarter and use one line of code for it. I am coding fiscal quarters. So months 4-6 is 1, months 7-9 is Quarter 2, months 10-12 is Quarter 3 and months 1-3 is Quarter 4

I have tried the ifelse statement but it gives me an error for the first part

ACLED$quarter<- ifelse(ACLED$month==4 & ACLED$month==5 & ACLED$month==6, 1)
Error in ifelse(ACLED$month == 4 & ACLED$month == 5 & ACLED$month == 6,  : 
  argument "no" is missing, with no default

How do I solve this?

Upvotes: 0

Views: 276

Answers (3)

rg255
rg255

Reputation: 4169

I would advocate the more elegant case_when solution that you have already received. However, ifelse can also do the job by using multiple ifelse functions with the same logic as the answer from markhogue (+1). See the documentation on ifelse; it needs to know what to do when criteria do not match - in this case theres three occasions where that is use another ifelse, and one where it is NA. The first argument is the match criteria (if), the second is what to do if the criteria are matched (get), and the third is what to do if the criteria are not matched (else).

set.seed(1)

df<-data.frame('mon' = sample(1:12, replace = T, size = 20))

df[,'qtr'] <- 
  ifelse(df[,'mon'] >=  1 & df[,'mon'] <=  3, 4, 
  ifelse(df[,'mon'] >=  4 & df[,'mon'] <=  6, 1, 
  ifelse(df[,'mon'] >=  7 & df[,'mon'] <=  9, 2,
  ifelse(df[,'mon'] >= 10 & df[,'mon'] <= 12, 3,  NA))))

Upvotes: 0

markhogue
markhogue

Reputation: 1179

It's easy if you use the dplyr package and the case_when function:

   library(dplyr)

   foo <- sample(1:12, 100, replace = TRUE)

   qtr <- case_when(foo %in% 4:6 ~ 1,
             foo %in% 7:9 ~ 2,
             foo %in% 10:12 ~ 3,
             foo %in% 1:3 ~ 4)

Upvotes: 1

Diego
Diego

Reputation: 422

This is straight forward with dplyr's case_when. I am not sure if it meets your need of "one line of code for it" though.

month <- c(1,2,3,4,5,6,7,8,9,10,11,12)

df <- data.frame(month = month)

df2 <- 
  df %>% 
  mutate(Quarter = case_when(
    #Quarter 1.
    month  %in% c(1,2,3) ~ 
      "First", 
    #Quarter 2.
    month  %in% c(4,5,6) ~ 
      "Second", 
    #Quarter 3.
    month  %in% c(7,8,9) ~
      "Third", 
    #Quarter 4.
    month  %in% c(10,11,12) ~ 
      "Fourth")
  )

Upvotes: 0

Related Questions