【问题标题】:Using R to turn hourly data into monthly data by summing certain values and taking the average of other values使用R通过对某些值求和并取其他值的平均值将每小时数据转换为每月数据
【发布时间】:2023-02-22 09:30:08
【问题描述】:

我想通过将 SUM 列中的数据 SUM 和 AVG 列中的 AVG 数据相结合,同时保持 UnitID 和 State

       Date     UnitID    Time    AVG        SUM    State          
1     1/1/22       1        1      22         34       VA
2     1/1/22       1        2      24         32       VA
3     1/1/22       2        1      26         36       NY
4     1/1/22       2        1      27         37       NC
5     2/3/22       4        2      28         38       SC
6     2/3/22       4        3      22         34       SC

例如,我想要 UnitID == 1 和 UnitID == 2 的结果:

       Date     UnitID       AVG        SUM    State          
1       Jan       1          23         66       VA
2       Jan       2          26.5       73       NY
.        .        .           .          .        .
.        .        .           .          .        .

【问题讨论】:

    标签: r data-wrangling


    【解决方案1】:

    我可能会建议为此使用 {tidyverse} - 特别是 group_by()summarise() 函数,例如:

    library(tidyverse)  
    dat <- structure(list(Date = c("1/1/22", "1/1/22", "1/1/22", "1/1/22", 
                                   "2/3/22", "2/3/22"),
                          UnitID = c(1, 1, 2, 2, 4, 4),
                          Time = c(1, 2, 1, 1, 2, 3),
                          AVG = c(22, 24, 26, 27, 28, 22),
                          SUM = c(34, 32, 36, 37, 38, 34),
                          State = c("VA", "VA", "NY", "NC", "SC", "SC")),
                     class = c("tbl_df", "tbl", "data.frame"),
                     row.names = c(NA, -6L))
    month_dat <- dat |> 
      mutate(Date = lubridate::mdy(Date)) |> 
      mutate(Date = lubridate::month(Date, label = TRUE)) |> # convert to date object and get month
      group_by(Date, UnitID, State) |> # group by categories
      summarise(AVG = mean(AVG),
                SUM = sum(SUM)) # calculate sum and avg
    

    如果您的 Date 列已经是 Date 对象,您可能不需要 mdy() 函数,或者您可能需要使用 dmy() 代替 - 我假设日期的格式为月/日/年。假设说 NC 的值应该是 NY,这应该可以满足您的需求。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-20
      • 2017-11-12
      • 1970-01-01
      • 2023-03-06
      • 2018-08-01
      • 2017-02-22
      • 2022-06-30
      • 1970-01-01
      相关资源
      最近更新 更多