【问题标题】:Average at 2 week and 3 week intervals以 2 周和 3 周为间隔的平均值
【发布时间】:2016-08-12 12:50:09
【问题描述】:

假设我有 4 块土地,在每块土地上,我每小时测量一次温度、湿度、土壤 pH 值等。我可以通过 dplyr 计算每周平均值

 library(dplyr)
 my.dfA = group_by(my.df, plot, weeknumber)
 my.dfB = mutate(my.dfA, mean.temp = mean(temp), mean.pH = mean(pH))

如何取两周的平均值,然后为每个地块取三周的平均值,等等?我不想要移动平均线;我想将第 13 周和第 14 周合并为一个两周的时间段,然后对第 15 周和第 16 周执行相同的操作,依此类推。

# A tibble: 6 × 5
                 Date Temperature  Plot dayofyear weekofyear
               <dttm>       <dbl> <dbl>     <dbl>      <dbl>
1 2016-04-03 15:24:00        13.0     1        94         14
2 2016-04-03 15:39:00        13.0     1        94         14
3 2016-04-03 15:53:59        13.0     1        94         14
4 2016-04-03 16:09:00        13.5     1        94         14
5 2016-04-03 16:24:00        13.0     1        94         14
6 2016-04-03 16:38:59        13.0     1        94         14

【问题讨论】:

    标签: r dplyr lubridate


    【解决方案1】:

    我们可以使用%/%创建一个分组变量

    n <- 2
    my.df %>%
         group_by(Plot,  weekGrp = (weekofyear-1)%/% n + 1) %>%
         mutate(mean.temp = mean(Temperature))
    

    将 'n' 的值更改为 3 会将 3 个相邻的 'weekofyear' 组合在一起。

    注意:在帖子的 OP 数据中未找到“pH”列。

    数据

    my.df <- structure(list(Date = c("2016-04-03 15:24:00", "2016-04-03 15:39:00", 
    "2016-04-03 15:53:59", "2016-04-03 16:09:00", "2016-04-03 16:24:00", 
    "2016-04-03 16:38:59", "2016-04-03 15:24:00", "2016-04-03 15:39:00", 
    "2016-04-03 15:53:59", "2016-04-03 16:09:00", "2016-04-03 16:24:00", 
    "2016-04-03 16:38:59"), Temperature = c(13, 13, 12, 14.5, 13, 
    13, 14, 13, 16, 13.5, 18, 19), Plot = c(1L, 1L, 1L, 1L, 1L, 1L, 
    1L, 1L, 1L, 1L, 1L, 1L), dayofyear = c(94L, 94L, 94L, 94L, 94L, 
    94L, 94L, 94L, 94L, 94L, 94L, 94L), weekofyear = c(13L, 13L, 
    13L, 14L, 14L, 14L, 15L, 15L, 15L, 15L, 16L, 16L)), .Names = c("Date", 
    "Temperature", "Plot", "dayofyear", "weekofyear"), class = "data.frame", 
    row.names = c(NA, -12L))
    

    【讨论】:

    • 谢谢@akrun。这按预期工作。从自学的角度来看,我想知道是否可以使用与日期一起使用的软件包来实现相同的目标。我想到了#lubridate,但我想我必须深入研究这些材料。再次感谢。
    • @Ani 我不确定 lubridate 中是否有类似的功能。但是,您可以查看here
    猜你喜欢
    • 2021-03-25
    • 1970-01-01
    • 1970-01-01
    • 2020-11-13
    • 2023-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-17
    相关资源
    最近更新 更多