How can I calculate simple mean for a variable using different conditions from other variable?

14 Views Asked by At

I have different scores (Biology, Maths, Geography Chemist, Literacture, Physics, etc). The simple means is calculated according group each candidate.

id <- c(1,2,3,4,5,6,7,8,9,10)
var_1   <- c(1,2,3,7,4,0,7,7,0,1)
var_2   <- c(8,4,0,4,5,8,1,1,8,0)
var_3   <- c(4,5,6,8,6,0,1,5,8,4)
var_4   <- c(7,8,9,5,0,7,5,0,1,4)
var_5   <- c(2,3,4,2,0,1,0,8,7,1)
var_6   <- c(8,7,4,5,6,0,5,6,7,6)
var_7   <- c(1,0,9,1,5,4,0,7,4,4)
var_8   <- c(6,8,7,0,8,5,5,0,5,1)
var_9   <- c(4,4,9,7,4,7,2,8,1,0)
group   <- as.factor(c(1,2,3,5,6,4,3,1,1,2))

I'd like a script to indicate the specific condition to calculate simple means in R. If a candidate is from group X, mean = mean (Biology, Chemist, Maths); if candidadate is from group Y, mean = mean (Chemist, Literacture, Physics), etc.

Would be a bonus obtain the code to weighted mean too.

df <- df |>
  dplyr::mutate(mean1 = case_when(group == 1 ~ ('var_1' + 'var_2' + 'var_4')/3,
                             group == 2 ~ ('var_4' + 'var_1' + 'var_3')/3,
                             group == 3 ~ ('var_9' + 'var_1' + 'var_3')/3,
                             ...
                                

Didn't work. With or not quotes, simples or doble quotes.

0

There are 0 best solutions below