I have a dataframe containing Parts grouped by Material, Client, CompanyCode, and STOCK_UOM. For each FiscalYear there is an associated column for WAP (weighted average price). FiscalYear 2022 should have the value of WAP_2021 (and associated type) in the WaP column. FiscalYear 2023 should have the value of WAP_2022 (and associated type) in the WaP column. But where FiscalYear is 2023 there can be NA values for WAP_2022, in this case it should give the value of the previous year WaP (WAP_2021).
| Material | Client | CompanyCode | STOCK_UOM | FiscalYear | WAP_2021 | WAP_2021_Type | WAP_2022 | WAP_2022_Type |
|---|---|---|---|---|---|---|---|---|
| 1234 | Cl1 | 1010 | EA | 2022 | 13.1 | WAP 2021 | NA | NA |
| 1234 | Cl1 | 1010 | EA | 2023 | NA | NA | NA | WAP 2022 |
Desired Result:
| Material | Client | CompanyCode | STOCK_UOM | FiscalYear | WaP | WaPType |
|---|---|---|---|---|---|---|
| 1234 | Cl1 | 1010 | EA | 2022 | 13.1 | WAP 2021 |
| 1234 | Cl1 | 1010 | EA | 2023 | 13.1 | WAP 2022 |
I have added a mutate statement to handle the first part.
df %>% mutate(WaP = ifelse(FiscalYear == 2022, WAP_2021, WAP_2022),
WaPType = ifelse(FiscalYear == 2022, WAP_2021_Type, WAP_2022_Type))
Now I need to replace the NA values in this WaP column with the associated value for that Material, Client, CompanyCode, UOM from the WAP_2021 column. How do I reference certain rows based on this criteria? I would need the same group (Material, etc) but for FiscalYear 2022.