【问题标题】:How to divide each column by the average three columns that precede it?如何将每列除以它前面的平均三列?
【发布时间】:2021-02-22 17:00:44
【问题描述】:

我有 2006 年到 2012 年间奥地利的失业率水平。我想将每年的失业率除以之前三年的平均值。例如,变量将显示在 2010 年:2010 年的失业率除以 2007、2008 和 2009 年的失业率平均值。有没有办法在 dplyr 中做到这一点?

我知道以下代码将每年除以变量的前三年。但我不知道如何处理之前的 3 年:

mydata %>% 
  mutate(
    unemp_3 = unemp - mean(unemp[1:3])
    )

这是我的数据:

structure(list(cntry = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L
    ), .Label = "Austria", class = "factor"), unemp = c(5.2, 4.9, 
    4.1, 5.3, 4.8, 4.6, 4.9), year = 2006:2012), row.names = c(NA, 
    -7L), groups = structure(list(cntry = structure(1L, .Label = "Austria", class = "factor"), 
        .rows = structure(list(1:7), ptype = integer(0), class = c("vctrs_list_of", 
        "vctrs_vctr", "list"))), row.names = 1L, class = c("tbl_df", 
    "tbl", "data.frame"), .drop = TRUE), class = c("grouped_df", 
    "tbl_df", "tbl", "data.frame"))

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    问题中的代码减去均值,但问题和主题表明您想要除以均值,因此我们假设除数就是您想要的。

    使用 rollapplyr 计算滚动平均值。 list(-seq(3)) 表示使用偏移量 -1、-2 和 -3,即 3 个先验值。例如,5.3 / mean(c(5.2, 4.9, 4.1)) 给出 2009 年的值。

    library(dplyr)
    library(zoo)
    
    mydata %>%
      group_by(cntry) %>%
      mutate(unemp_3 = unemp / rollapplyr(unemp, list(-seq(3)), mean, fill = NA)) %>%
      ungroup
    

    给予:

    # A tibble: 7 x 4
      cntry   unemp  year unemp_3
      <fct>   <dbl> <int>   <dbl>
    1 Austria   5.2  2006  NA    
    2 Austria   4.9  2007  NA    
    3 Austria   4.1  2008  NA    
    4 Austria   5.3  2009   1.12 
    5 Austria   4.8  2010   1.01 
    6 Austria   4.6  2011   0.972
    7 Austria   4.9  2012   1.   
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-17
      • 1970-01-01
      • 1970-01-01
      • 2021-05-18
      相关资源
      最近更新 更多