loop (calculate according to several factors of the data frame)?

HI @louna123,

could you include a (subset) of your data data frame in a format that others can copy-paste into R Studio? See e.g. FAQ: How to do a minimal reproducible example ( reprex ) for beginners

In this way you will greatly increase your chances of getting a fast and meaningful response.

Once you do that seems like a much more simple solution is to use dplyr to group_by and then aggregate, some examples can be found here https://rdrr.io/cran/dplyr/man/group_by.html