Tenho uma longa lista de variáveis que desejo multiplicar pelas variáveis correspondentes e somar. a_1
corresponde a b_1
, a_2
a b_2
etc. A saída desejada seria calculada por(a_1*b_1 + a_2*b_2...)
library(dplyr)
(df <- tibble(
a_1 = sample(1:5),
a_2 = sample(1:5),
b_1 = sample(1:5),
b_2 = sample(1:5),
desired_output = (a_1*b_1 + a_2*b_2)
))
# A tibble: 5 × 5
a_1 a_2 b_1 b_2 desired_output
<int> <int> <int> <int> <int>
1 4 5 1 3 19
2 1 2 2 5 12
3 2 1 4 2 10
4 5 3 5 1 28
5 3 4 3 4 25
Eu tentei e falhei em escrever uma função para fazer isso (sou muito novo em tentar escrever funções!) por exemplo
df %>%
mutate(desired_output = function(df) {
for (i in 1:2) {
y1 <- get(paste0(x,'$','a_',i))
y2 <- get(paste0(x,'$','a_',i))
z <- y1*y2
}
return(z)
}