I have data that is a much larger version of the data shown below (only for example).
Code <- c("A", "A", "A", "A", "A", "B", "B", "B", "B", "B")
Date <- as.Date(c("2018-01-01", "2018-01-02", "2018-01-03", "2018-01-04", "2018-01-05", "2018-01-01", "2018-01-02", "2018-01-03", "2018-01-04", "2018-01-05"))
Max <- c(2.4, 4.2, 3.7, 10.6, 5.2, 8.7, 3.9, 4.8, 14.5, 3.2)
Mean <- c(2.2, 3.9, 3.1, 5.3, 4.3, 4.8, 3.6, 4.2, 6.0, 2.8)
Limit <- c(6.5, 6.5, 6.5, 6.5, 6.5, 10.5, 10.5, 10.5, 10.5, 10.5)
df <- data.frame(Code, Date, Max, Mean, Limit)
What I would like to do is to replace any Max values greater than the Limit with the Mean value, but only for Code == "A".
So in this example the fourth Max value (10.6) would be replaced with 5.3.
I have been really struggling to wrap my head around this but I'm sure you lot on here can help!
I have tried separating the codes A and B into their own data frames and replacing them but I can't think of a way to do this. I also tried creating a new column using mutate with an ifelse statement inside but could not work it out.
I mainly use dplyr so if you could explain it using that that would be great! Thanks a lot, let me know if you require more information and I will add it.