lundi 16 novembre 2020

How to FOR and IF loop in R to sum values according to two factor levels and create new variable?

I want my data frame to be like

> trial_acc
   df$Condition df$id df$correct keep
1            1_1 006          1   no
2            3_3 006          1   no
3            1_3 006          5   no
4            3_1 006          3   no
5            1_1 0ui         13   yes
6            3_3 0ui         18   yes
7            1_3 0ui         16   yes
8            3_1 0ui         13   yes
9            1_1 12f         12   no
10           3_3 12f          2   no
11           1_3 12f         13   no
12           3_1 12f          7   no

I need to create a variable 'keep' where "yes" if the total of df$correct is >= 40 grouped by df$id, otherwise "no"

I tried this but it is not working

for (i in levels(trial_acc$`df$id`)) {
  if (trial_acc$`df$id` == i & sum(trial_acc$`df$correct`) >=  40){
    trial_acc$keep <- "yes"
  } else{
    trial_acc$keep <- "no"
  }
}

Aucun commentaire:

Enregistrer un commentaire