Reputation: 69
I am new to R so I am struggling to figure out how to do this. I have a data frame with thousands of observations that looks like this
x total subgroup1 subgroup2
.03 1000 500 500
.04 1050 550 500
.07 1100 525 575
.08 9900 4900 5000
I am trying to come up with a weighted value for x based on the following equation.
weighted x for subgroup1 = (Σ x*subgroup1) / (Σ subgroup1)
The idea is that for each observation we multiply the x value by the subgroup 1 value and add them all together and divide it by the sum of all the subgroup values. I also want to do this for subgroup 2. I imagine I will need some type of loop function. However, I am not sure where to start in R. Any leads would be great.
Upvotes: 0
Views: 44
Reputation: 356
x <- c(0.3, 0.4, 0.7, 0.8)
subgroup1 <- c(500, 550, 525, 4900)
subgroup2 <- c(500, 500, 575, 5000)
total <- subgroup1 + subgroup2
df <-data.frame(x, total, subgroup1,
subgroup2)
x_wg_1 <-
(sum(df$x*df$subgroup1))/sum(df$subgroup1)
x_wg_1
Just some code using base R. No need for a loop. Just multiply vectors from the data frame and sum the elements. Then divide by then sum of another vector.
Upvotes: 1