Averaging values in a data frame for a certain hour and month in R

后端 未结 2 1442
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-03 18:41

I\'ve been scouring the net but haven\'t found a solution to this quite possibly simple problem.

This is the half-hourly data using the library \'xts\',



        
2条回答
  •  感动是毒
    2021-01-03 19:26

    Try

    library(dplyr)
    res <- dat %>% 
               group_by(month=format(datetime, '%m'),
                  #year=format(datetime, '%Y'), #if you need year also
                  # as grouping variable
                  hour=format(as.POSIXct(cut(datetime, breaks='hour')), '%H')) %>%
               summarise(Meanval=mean(val, na.rm=TRUE))   
    
    
     head(res,3)
     #  month hour     Meanval
     #1    01   00 -0.02780036
     #2    01   01 -0.06589948
     #3    01   02 -0.02166218
    

    Update

    If your datetime is POSIXlt you could convert it to POSIXct.

      dat$datetime <- as.POSIXlt(dat$datetime)
    

    By running the above code, I get the error

       # Error: column 'datetime' has unsupported type
    

    You could use mutate and convert the datetime to POSIXct class by as.POSIXct

      res1 <-  dat %>% 
                   mutate(datetime= as.POSIXct(datetime)) %>%
                   group_by(month=format(datetime, '%m'),
                     #year=format(datetime, '%Y'), #if you need year also
                     # as grouping variable
                      hour=format(as.POSIXct(cut(datetime, breaks='hour')), '%H')) %>%
                   summarise(Meanval=mean(val, na.rm=TRUE))  
    

    data

    set.seed(24)
    dat <- data.frame(datetime=seq(Sys.time(), by='1 hour', length.out=2000),
        val=rnorm(2000))
    

提交回复
热议问题