I have multiple columns in R with different costs in dollars and the year of the transaction, like so:
dollar <- data.frame(
variable_costs = c(1200, 4000, 5000, 200),
direct_costs = c(200, 1000, 500, 2000),
total_costs = c(1400, 5000, 5500, 2200),
year = c(2014, 2014, 2015, 2017)
)
I want to annuitize this based on inflation (if year = 2014, then account for all 7 years of inflation up until 2021 (i.e. multiply value by 2.5% (2014 to 2015 inflation), then multiply that value by 3.2% (2016 to 2017 inflation), and so forth). Final columns I am looking for would look like this:
annuitized_dollar <- data.frame(
variable_costs_2021 = c(1324, 4802, 5402, 284),
direct_costs_2021 = c(244, 1233, 591, 2281),
total_costs_2021 = c(1623, 5942, 6123, 2561)
)
Would someone be able to help in creating an if/then or if/else loop for this purpose? It's not a huge dataset of ~6700 rows.
Thank you very much.
CodePudding user response:
First you should provide the values for inflation for every year.
I created some fake values:
set.seed(1)
inflation<-setNames(round(abs(rnorm(7, 0.03, sd=0.03)),3), 2014:2020)
inflation
2014 2015 2016 2017 2018 2019 2020
0.053 0.032 0.030 0.049 0.028 0.025 0.014
-First, create a vector of cummulative inflations:
library(purrr)
cummulative_inflation<-accumulate(rev(inflation 1), ~.x*.y)
2020 2019 2018 2017 2016 2015 2014
1.014000 1.039350 1.068452 1.120806 1.154430 1.191372 1.254515
Then, we can use dplyr::mutate(across(tidy_selection)
with rowwise
and use the vector of cummulative inflations subseted by the 'year' variable.
library(dplyr)
dollar %>%
rowwise %>%
mutate(across(ends_with('costs'),
~ .x * (cummulative_inflation[as.character(year)])))
# A tibble: 4 × 4
# Rowwise:
variable_costs direct_costs total_costs year
<dbl> <dbl> <dbl> <dbl>
1 1505. 251. 1756. 2014
2 5018. 1255. 6273. 2014
3 5957. 596. 6553. 2015
4 224. 2242. 2466. 2017
CodePudding user response:
here is a base R solution that might be easier to understand at the beginning
Greetings
dollar <- data.frame(
variable_costs = c(1200, 4000, 5000, 200),
direct_costs = c(200, 1000, 500, 2000),
total_costs = c(1400, 5000, 5500, 2200),
year = c(2014, 2014, 2015, 2017)
)
multi_df <- data.frame("V1"=seq(0.04, 0.16, 0.04))
multi_df$V2 <- multi_df$V1 0.005
multi_df$V3 <- multi_df$V1 (multi_df$V2 - 0.04) - 0.04
annuitized_dollar <- dollar
annuitized_dollar[, 1]<- annuitized_dollar[, 1] * ( 1 multi_df[, 1])
annuitized_dollar[, 2] <- annuitized_dollar[, 2] * ( 1 multi_df[, 2])
annuitized_dollar[, 3]<- annuitized_dollar[, 3] * ( 1 multi_df[, 3])