mardi 27 février 2018

Applying If Then logic to a dataframe R

I think I may have bit off more than I can chew. I am trying to apply a logical equation to a set of data based on a few factors to develop a final estimate for each year. I got all my data in the same place but now am struggling to manipulate it appropriately.

Long short of it I have a data frame that looks like this:

YEAR    ID    V1   V2   V3   Delta1   Delta2
1990    A     3    NA   NA   NA       NA
1991    A     5    2    NA   2        NA
1992    A     7    4    6    2        2
1990    B     3    1    NA   NA       NA
1991    B     5    2    NA   2        1
1992    B     7    1    NA   2        -1
etc

I want to apply the following logic to calculate a new column for each row:

For each ID in 1990

if there is a V3 value that will be selected    
else if    
if there is a V2 value that will be selected for the new column    
else
they are assigned the value of V1 (V1 is always populated).

For each proceeding year an ID is assigned a value based on

if there is a V3 value it equals V3 * Delta1
else if
the ID has never had a V3 value the calculated value will equal V2
else if
it has had a V3 but just not this year it equals the years previous calculated value for that ID * Delta2
else
the calculated value simply equals the previous years calculated value * Delta1

I know how to apply if else logic but I am lost in how to do so iteratively through years for each ID against the data frame. Any help would be appreciated, thank you.

Aucun commentaire:

Enregistrer un commentaire