lenpyspanacb
lenpyspanacb

Reputation: 333

Automatic iterative calculation in R

Good afternoon, friends!

I'm currently performing some financial calculations in R (code is displayed below). My goal is to get different "Results" given various (but already known) dates.

For example, these calculations are based on 31.12.19 (we can see it by selecting the column name "Main_Debt_As_Of_31.12.19" inside subset function), "2019-12-31" and "2020-12-31".

testdf <- subset(df, df$Main_Debt_As_Of_31.12.19 > 0)
testdf2 <- subset(testdf, (testdf$Earliest_Date > "2019-12-31" | is.na(testdf$Earliest_Date)))
testdf3 <- subset(testdf, testdf$Earliest_Date > "2019-12-31" & testdf$Earliest_Date <= "2020-12-31")
Result <- sum(testdf3$Main_Debt_As_Of_31.12.19, na.rm = TRUE) / sum(testdf2$Main_Debt_As_Of_31.12.19, na.rm = TRUE)

My question is: if I create a vector with column names and dates I want to use (see below), is it possible to automate my code in order not to copy and change names and dates three times manually (in real task I should change it 120 times).

vector1 <- c(Main_Debt_As_Of_31.10.19, Main_Debt_As_Of_30.11.19, Main_Debt_As_Of_31.12.19)
vector2 <- c("2019-10-31", "2019-11-30", "2019-12-31")
vector3 <- c("2020-10-31", "2020-11-30", "2020-12-31")

I just want R to use different values from my vector (or from a list), run the code with new inputs and display the result of the calculations in a new vector..

Thanks a lot!

Upvotes: 1

Views: 123

Answers (1)

Rui Barradas
Rui Barradas

Reputation: 76402

Use mapply with an auxiliary function calc.

calc <- function(col, date1, date2, data){
  i <- data[[col]] > 0
  j <- data[["Earliest_Date"]] > date1 | is.na(data[["Earliest_Date"]])
  k <- data[["Earliest_Date"]] > date1 & data[["Earliest_Date"]] <= date2
  Main_Debt2 <- data[i & j, col, drop = TRUE]
  Main_Debt3 <- data[i & k, col, drop = TRUE]
  sum(Main_Debt3, na.rm = TRUE)/sum(Main_Debt2, na.rm = TRUE)
}

vector1 <- c("Main_Debt_As_Of_31.10.19", "Main_Debt_As_Of_30.11.19", "Main_Debt_As_Of_31.12.19")
vector2 <- c("2019-10-31", "2019-11-30", "2019-12-31")
vector3 <- c("2020-10-31", "2020-11-30", "2020-12-31")

mapply(calc, vector1, vector2, vector3, MoreArgs = list(data = df))

Upvotes: 1

Related Questions