I would like to calculate mean of Mean.Temp.c. before certain date, such as 1963-03-23 as showed in date2 column in this example. This is time when peak snowmelt runoff occurred in 1963 in my area. I want to know 10 day’s mean temperature before this date (ie., 1963-03-23). How to do it? I have 50 years data, and each year peak snowmelt date is different.
            Asked
            
        
        
            Active
            
        
            Viewed 56 times
        
    -3
            
            
        - 
                    3Please include sample data (preferably using `dput`) and expected output; for more details please take a look at how to provide [a reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). – Maurits Evers Feb 21 '19 at 22:34
2 Answers
0
            
            
        You can try:
library(dplyr)
df %>%
  mutate(date2 = as.Date(as.character(date2)),
         ten_day_mean = mean(Mean.Temp.c[between(date2, "1963-03-14", "1963-03-23")]))
In this case the desired mean would populate the whole column.
Or with data.table:
library(data.table)
setDT(df)[between(as.Date(as.character(date2)), "1963-03-14", "1963-03-23"), ten_day_mean := mean(Mean.Temp.c)]
In the latter case you'd get NA for those days that are not relevant for your date range.
 
    
    
        arg0naut91
        
- 14,574
- 2
- 17
- 38
0
            
            
        Supposing date2 is a Date field and your data.frame is called x:
start_date <- as.Date("1963-03-23")-10
end_date   <- as.Date("1963-03-23")
mean(x$Mean.Temp.c.[x$date2 >= start_date & x$date2 <= end_date])
Now, if you have multiple years of interest, you could wrap this code within a for loop (or [s|l]apply) taking elements from a vector of dates.
 
    
    
        ssayols
        
- 790
- 6
- 10
- 
                    Hi ssayols, this one sounds good. For each year I know start_date, then end_date can be determined. I have the entire 50 years in one dataframe and with year as one column. How do I use column Year as a by_group? both you and arg0naut's solution did not include Year. Also this is my first question, I wanted to have an sample data as a csv, but do not know how to do it, so I pasted an image file for sample data. – West Cotter Feb 22 '19 at 15:59
- 
                    Hi @WestCotter, as someone suggested before, please add a minimal example of your data using `dput` that can be used to reproduce your question. If you don't know how to start, check `?dput` and/or try `dput(head(iris))`. I'm lost now with what you have and what you're trying to achieve... – ssayols Feb 25 '19 at 09:09
- 
                    Hi ssayols, I have just added my example data in a text format, hope this will clarify my question. Thanks you and arg0naut for help. – West Cotter Feb 26 '19 at 16:57
