lundi 27 avril 2020

Alternative for giant nested ifelse statement

I have a data frame that looks like the following:

Period No.  Frequency
1           Month
2           Month
3           Month
3           Quarter
6           Quarter     
9           Quarter
1           YTD
2           YTD
3           YTD

I want to add on a column called "Period" whose values are determined by what is in the Period No. AND Frequency columns. So:

Period No.  Frequency  Period
1           Month      1
2           Month      2
3           Month      3
3           Quarter    Q1
6           Quarter    Q2 
9           Quarter    Q3
1           YTD        YTD-Jan
2           YTD        YTD-Feb
3           YTD        YTD-Mar

Right now, I'm using nested if statements to do this. For example:

data$Period <-
  ifelse(
    (data$`Period No.` == '3') & (data$Frequency == 'Q1'), 'Q1',
    ifelse(
      (data$`Period No.` == '6') & (data$Frequency == 'Q2'), 'Q2',
      ifelse(
        (data$`Period No.` == '9') & (data$Frequency == 'Q3'), 'Q3', 'ERROR'
)
)
)

If I were to do this for every month for each iteration of Frequency, I would have 30 nested ifelse statements. I'm wondering if there's a more concise method to do what I'm trying to achieve?

Aucun commentaire:

Enregistrer un commentaire