samedi 9 juillet 2016

alternative to long list of nested ifelse statement with multiple conditions

I have the following data frame

    structure(list(FY = c("2015-2016", "2015-2016", "2015-2016", 
"2015-2016"), YEARMN = structure(c(2015.25, 2015.25, 2015.25, 
2015.25), class = "yearmon"), BRAND = c("3M CAR CARE", "CAR CARE 3M", 
"CAR CARE 3M", "CAR CARE 3M"), variable = structure(c(1L, 
2L, 3L, 4L), .Label = c("IstWEEKRent", "IIndWEEKRent", "IIIrdWEEKRent", 
"IVthWEEKRent", "mymonth"), class = "factor"), value = c("0", 
"17500", "85000", "212500"), mymonth = c("Apr", "Apr", "Apr", 
"Apr")), .Names = c("FY", "YEARMN", "BRAND", "variable", "value", 
"mymonth"), row.names = c(NA, 4L), class = "data.frame")

The actual data frame looks like this:

         FY   YEARMN       BRAND      variable  value mymonth
1 2015-2016 Apr 2015 3M CAR CARE   IstWEEKRent      0     Apr
2 2015-2016 Apr 2015 CAR CARE 3M  IIndWEEKRent  17500     Apr
3 2015-2016 Apr 2015 CAR CARE 3M IIIrdWEEKRent  85000     Apr
4 2015-2016 Apr 2015 CAR CARE 3M  IVthWEEKRent 212500     Apr

The my month column has months from Apr to Mar...and every month has 4 weeks in my dataset which is given in column variable. I am trying to create a week number for the FY Apr - Mar, starting from 1 to 48. I want to give week number 1 which matches the condition

variable == "IstWeekRent" & mymonth == "Apr"

I used ifelse function to get this done...which works fine...but when I include the same into my shiny application I am getting the following error:

Error in parse(file, keep.source = FALSE, srcfile = src, encoding = enc) : 
  contextstack overflow at line 2870

My current ifelse condition statement looks like this:

trndR$weeks <- ifelse(trndR$mymonth == "Apr" & trndR$variable == "IstWEEKRent", 1,
                ifelse(trndR$mymonth == "Apr" & trndR$variable == "IIndWEEKRent", 2,
                ifelse(trndR$mymonth == "Apr" & trndR$variable == "IIIrdWEEKRent", 3,
                ifelse(trndR$mymonth == "Apr" & trndR$variable == "IVthWEEKRent", 4,
                ifelse(trndR$mymonth == "May" & trndR$variable == "IstWEEKRent", 5,
                ifelse(trndR$mymonth == "May" & trndR$variable == "IIndWEEKRent", 6,

trndR is the name of my df and the condition extends upto 48.

I figured out that I can have only upto 50 nested ifelse condition...but not quite not sure how to rectify this. I read about apply function but don't know how to use it in this case.

Aucun commentaire:

Enregistrer un commentaire