0

I want to that the mean of one variable when two other variables are equal to a certain value. For example, I want to make a new data frame that has a variable called "mean", that gives the mean of all the values in S1 when year == 2003 and mon == 1, and then the next value of the mean of S1 values when year == 2003 and mon == 2.

YEAR   MON    S1     S
  <dbl> <dbl> <dbl> <dbl>
1  2003     1  8.2   1.03
2  2003     1  7.39  0.97
3  2003     1  7.78  0.82
4  2003     2  7     0.91
5  2003     2  5     1.93
6  2003     2  5.49  0.31
Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294

1 Answers1

0

It can be more easily done with a group by operation and should be more efficient too when compared to case_when

library(dplyr)
df1 %>%
   group_by(YEAR, MON) %>%
   summarise(mean = mean(S1, na.rm = TRUE), .groups = 'drop')
akrun
  • 874,273
  • 37
  • 540
  • 662