lundi 19 septembre 2016

R lookup with Arithmetic

I am hoping you smart folks can help me out, please. I would like to create a variable that calculates the change in a value from the prior period, while ensuring a few conditions are met. The data frame contains 75,330 records of property management data for approximately 100 different nonprofit organizations submitted over approximately 70 reporting periods. There are 18 variables in total; but, it follows this general structure:

PropertyID    Months    PeriodID    NCF    ...
abc           3         18          2200   ...
abc           6         19          4600   ...
abc           9         20          6700   ...
abc           12        21          8000   ...
cab           3         18          4000   ...
cab           9         20          12000  ...

As you can see, the data are reported cumulatively (3 months this quarter, 6 months next quarter, etc.), and I am trying to calculate the change from the prior-quarter so all of the records represent just three-months of property management history. Between these 100 organizations there are 11 different fiscal year-end's, so I need to aggregate 12-months of reporting history for each property coinciding with the organization's fiscal year-end. Unfortunately, the reporting follows calendar-year's.

I am able to do it in DAX, but I need to find a way to do it in R. For example, here's the DAX Calculated Column for NCF:

enter image description here

Here's what the code does (assume next list item is "else"):

  1. If NCF is NA, NA;
  2. If Months = 3, return current period NCF;
  3. Find previous period NCF ([PeriodID]-1), and if it's NA, NA;
  4. Calculate the difference between current period NCF and previous period NCF.

I'm really not sure where to begin so I would love your feedback, and please let me know if more information is necessary.

Aucun commentaire:

Enregistrer un commentaire