Compute monthly averages from daily data

后端 未结 1 1162
深忆病人
深忆病人 2020-12-05 21:17

I have this dataframe \"df1\" as example which is actually part of a much larger one (15 years):

             X1          X2
3798 2009-12-29           0
3799         


        
相关标签:
1条回答
  • 2020-12-05 21:52

    One way, using base R would be to make sure your dates are of class Date or similar ( e.g. POSIXct) if you haven't already, and then to extract the months and years (as your data spans more than one year) and aggregate like so:

    #  Convert to date if not already
    df1$X1 <- as.Date(df1$X1)
    
    #  Get months
    df1$Month <- months(df1$X1)
    
    #  Get years
    df1$Year <- format(df1$X1,format="%y")
    
    #  Aggregate 'X2' on months and year and get mean
    aggregate( X2 ~ Month + Year , df1 , mean )
    #    Month Year        X2
    #1 December   09 0.0000000
    #2 February   10 0.1714286
    #3  January   10 1.2074074
    

    There are quite a few ways of doing this if you have a look around.

    0 讨论(0)
提交回复
热议问题