I want to multiply two columns with each other by using dplyr's mutate
function.
But instead of writing a new line for each mutate conditions I would like to use the names of the columns stored in the vectors var1
and var2
. For example in the end I want to have a additional column in my existing bankdata
with the name result1
which contains the result by multiplying the columns cash and loans with each other. This shall be continued until 3 new columns have been created.
Reproducible code:
bankname <- c("Bank A", "Bank B", "Bank C", "Bank D", "Bank E")
bankid <- c(1, 2, 3, 4, 5)
year <- c(1881, 1881, 1881, 1881, 1881)
totass <- c(244789, 195755, 107736, 170600, 32000000)
cash <- c(7250, 10243, 13357, 35000, 351266)
bond <- c(20218, 185151, 177612, 20000, 314012)
loans <- c(29513, 2800, NA, 5000, NA)
bankdata <- data.frame(bankname, bankid, year, totass, cash, bond, loans)
Vectors var1 and var2 contain the column names I want to multiply (cash*loans, bond*cash, loans*bankid
) and output is the name of the new column:
var1 <- c("cash", "bond", "loans")
var2 <- c("loans","cash", "bankid")
output <- c("result1", "result2", "result3")
I would like to do something similar like this:
bankdata %>%
mutate_at(.funs = funs(output = var1*var2), vars(var1, var2))
bankdata %>%
mutate_at(.funs = funs(result1 = cash*., result2 = bond*., result3 = loans*.), vars(var2))