【问题标题】:Annual group means with uneven groups in dplyr?年度组意味着dplyr中的组不均匀?
【发布时间】:2016-03-11 09:34:01
【问题描述】:

假设我有以下数据:

library(dplyr)
year <- rep(c(1,2,2,3,4,4,5),3)
group <- c(rep(1,7),rep(2,7),rep(3,7))
v1 <- rep(c(0,1,2,3,4,5,6),3)
v2 <- rep(c(1,2,3,4,5,6,7),3)
df <- data.frame(year,group,v1,v2)

我想为每个变量滚动年度组均值,以便最终得到将所有前几年都考虑在内的唯一组年均值。

我知道这会给我年度组意味着:

gm <- df %>% 
    group_by(group, year) %>% 
    summarise_each(funs(mean))

但这并没有考虑到所有以前的年份。我需要每个组年包括所有以前的组年,并且(重要的是)每个组年的长度是参差不齐的,所以我不能只取年度平均值然后group_by() 每个组并在年度平均值上进行滚动平均值.

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    我们可以试试

    library(dplyr)
    Un1 <- unique(df$year)
    lapply(seq_along(Un1), function(i) 
            df[df$year %in% Un1[seq(i)],] %>% 
            group_by(group) %>% 
            summarise_each(funs(mean), v1:v2)) %>% 
            setNames(., Un1) %>%
            bind_rows(., .id='year')
    

    【讨论】:

    • 这太好了,谢谢!我刚刚在一年中添加了mutate(year = i)
    • @cigrainger 您可以使用bind_rows 中的.id 来获取“年份”列。
    • 太好了,谢谢。我认为这可以通过在group_by 之后使用filter(year %in% Un1[seq(i)]) 而不是[ 来加速(对我来说是一个问题)。这样它就不会每次都搜索所有行。
    • @cigrainger 我专门用它来扩展数据集。使用dplyr 框架,您可能需要使用do 来实现它,但这又会很慢。
    猜你喜欢
    • 1970-01-01
    • 2021-05-31
    • 1970-01-01
    • 2012-05-13
    • 2015-12-05
    • 1970-01-01
    • 2015-11-07
    • 2021-09-27
    • 1970-01-01
    相关资源
    最近更新 更多