Benjamin Krick
Benjamin Krick

Reputation: 107

function to iterated through summation

I have two dataset.

One looks like this:

model <- data.frame(Variable = c("P_ALC", "P_ALC_BEER", "P_ALC_LIQUOR", 
"P_ALC_WINE", "P_BEAN", "P_LUNCH"), Estimate = c(0.0728768079454515, 
0.189831156431574, 0.182511704261063, 0.176711987960571, 0.0108000123096659, 
-0.00463222009211804))

The other looks like this:

data <- data.frame(P_ALC = c(0.044, 0.001, 2.295, 0.55, 0.063, 1.604, 
0.584, 0.211, 0, 0.244), P_ALC_BEER = c(0.02, 0, 0.177, 0.53, 
0.02, 0.53, 0, 0.01, 0, 0.02), P_ALC_LIQUOR = c(0.022, 0, 0, 
0, 0.022, 1.069, 0.583, 0, 0, 0.046), P_ALC_WINE = c(0, 0, 2.118, 
0.02, 0.02, 0.004, 0, 0.202, 0, 0.177), P_BEAN = c(0.18, 0.133, 
0.182, 0.128, 0.06, 0.408, 0.066, 0.18, 0.757, 0.068), P_LUNCH = c(0.137, 
0.058, 0.107, 0.249, 0.037, 0.161, 0.542, 0.033, 0.029, 0.44))

I want to do the following calculation:

score <- model[1,2] + model[2,2]*data[model[2,1]]  + model[3,2]*data[model[3,1]]+ model[4,2]*data[model[4,1]]  + model[5,2]*data[model[5,1]] + model[6,2]*data[model[6,1]]

This works fine for my toy dataset. But in actuality the model data frame is around 80 rows long so i want to write a function that will keep counting through the rows without having to copy and past.

Upvotes: 0

Views: 39

Answers (1)

akrun
akrun

Reputation: 887098

We may loop across the columns specified in 'Variable' column of 'model' except the first element, multiply with the corresponding 'Variable' value, get the rowSums and add the first element of 'Estimate'

library(dplyr)
data %>% 
   mutate(score = model$Estimate[1] + rowSums(across(all_of(model$Variable[-1]), 
      ~ . * model$Estimate[match(cur_column(), model$Variable)])))

-output

 P_ALC P_ALC_BEER P_ALC_LIQUOR P_ALC_WINE P_BEAN P_LUNCH      score
1  0.044      0.020        0.022      0.000  0.180   0.137 0.08199808
2  0.001      0.000        0.000      0.000  0.133   0.058 0.07404454
3  2.295      0.177        0.000      2.118  0.182   0.107 0.48222287
4  0.550      0.530        0.000      0.020  0.128   0.249 0.17725054
5  0.063      0.020        0.022      0.020  0.060   0.037 0.08469954
6  1.604      0.530        1.069      0.004  0.408   0.161 0.37295980
7  0.584      0.000        0.583      0.000  0.066   0.542 0.17748327
8  0.211      0.010        0.000      0.202  0.180   0.033 0.11226208
9  0.000      0.000        0.000      0.000  0.757   0.029 0.08091808
10 0.244      0.020        0.046      0.177  0.068   0.440 0.11504322

Upvotes: 4

Related Questions