R数据帧变量之间的移动平均值

R moving average between data frame variables

我正在尝试找到解决方案,但还没有。 我的数据框结构如下:

country City 2014 2015 2016 2017 2018 2019
France  Paris 23   34   54   12   23   21
US       NYC   1    2    2    12   95  54 

我想找到每 3 年(即 2014-16 年、2015-17 年等)的移动平均线以放入临时列中。

country City 2014 2015 2016 2017 2018 2019 2014-2016  2015-2017  2016-2018  2017-2019
France  Paris 23   34   54   12   23   21    37          33.3      29.7        18.7  
US       NYC   1    2    2    12   95  54    etc           etc     etc          etc

有什么提示吗?

1) 使用最后注释中可重复显示的数据,我们将 rollmean 应用于数据转置中的每一列,然后转置回来。我们rollapply适当的粘贴命令来创建名称。

library(zoo)

DF2 <- DF[-(1:2)]
cbind(DF, setNames(as.data.frame(t(rollmean(t(DF2), 3))), 
  rollapply(names(DF2), 3, function(x) paste(range(x), collapse = "-"))))

给予:

  country  City 2014 2015 2016 2017 2018 2019 2014-2016 2015-2017 2016-2018 2017-2019
1  France Paris   23   34   54   12   23   21 37.000000 33.333333  29.66667  18.66667
2      US   NYC    1    2    2   12   95   54  1.666667  5.333333  36.33333  53.66667

2) 这也可以用 dplyr/tidyr/zoo 来表示:

library(dplyr)
library(tidyr)
library(zoo)

DF %>%
  pivot_longer(-c(country, City)) %>%
  group_by(country, City) %>%
  mutate(value = rollmean(value, 3, fill = NA),
    name = rollapply(name, 3, function(x) paste(range(x), collapse="-"), fill=NA)) %>%
  ungroup %>%
  drop_na %>%
  pivot_wider %>%
  left_join(DF, ., by = c("country", "City"))

备注

Lines <- "country City 2014 2015 2016 2017 2018 2019
France  Paris 23   34   54   12   23   21
US       NYC   1    2    2    12   95  54 "
DF <- read.table(text = Lines, header = TRUE, as.is = TRUE, check.names = FALSE)