mardi 12 juin 2018

Loop within a function in R

I want to create a function that holds an ifelse statement like follows:

ArrearsL1M<-function(input1, input2, input3, input4){
  output=0
  output=ifelse((df[[input1]] %in% c(1,2,3,4,5)),1,
                ifelse((df[[input2]] %in% c(1,2,3,4,5)),1,
                       ifelse((df[[input3]] %in% c(1,2,3,4,5)),1,
                              ifelse((df[[input4]] %in% c(1,2,3,4,5)), 1, 0))))
  return(output)

Then I'd have this:

df$Arrears_L1M<-ArrearsL1M("col_201823","col_201822","col_201821","col_201820")

So the code will check the previous 4 weeks of data starting with the most recent (i.e. 2018 week 23, week 22, week 21 and week 20)

The starting week can change and I want to make this work so that the I enter the first week and it runs the function for the past 4 weeks.

I'll want to run this for 52 weeks of data (i.e. a year ) at some point so I'm trying to make it easier to change if the starting week changes.

For the above example, I'd want to enter col_201823 and it'd run the function for the past 4 weeks.

I'm not sure where to start with this so can't show you anything I've already tried.

Aucun commentaire:

Enregistrer un commentaire