首页 > 解决方案 > 每组“n”行的平均数 - R

问题描述

我有一个包含三列的数据框;entity, date, value.

首先,我必须根据每个实体的“'DATE'降序”来订购“价值”。

然后,要求是根据用户定义的行数为每个实体获取2 种类型的平均值。例如,如果用户输入 3 和 6;这意味着每个实体“给我前 3 个值的平均值,然后给我接下来 6 个值的平均值”。

对于给定的数据集,结果将是一个数据框:

    Entity    Avg3 Avg6
        A     110   65 
        B     220  130

我可以使用“ aggregate”函数按实体获取“ mean”,但我无法提取每个实体的特定行数据。此外,ordering基于实体和“日期”的数据框似乎不起作用。

#order data based on date (tried adding entity here but it does not work)
df_new <- df[rev(order(as.Date(df$Date)))),]

这是输出:

structure(list(Wells = c("A", "A", "A", "A", "A", "A", "A", "A", 
"A", "A", "A", "A", "B", "B", "B", "B", "B", "B", "B", "B", "B", 
"B", "B", "B"), Date = structure(c(1577836800, 1577923200, 1578009600, 
1578096000, 1578182400, 1578268800, 1578355200, 1578441600, 1578528000, 
1578614400, 1578700800, 1578787200, 1577836800, 1577923200, 1578009600, 
1578096000, 1578182400, 1578268800, 1578355200, 1578441600, 1578528000, 
1578614400, 1578700800, 1578787200), class = c("POSIXct", "POSIXt"
), tzone = "UTC"), Index = c(10, 20, 30, 40, 50, 60, 70, 80, 
90, 100, 110, 120, 20, 40, 60, 80, 100, 120, 140, 160, 180, 200, 
220, 240)), row.names = c(NA, -24L), class = c("tbl_df", "tbl", 
"data.frame"))

标签: rdataframedplyraverage

解决方案


这是一个选项tidyverse。假设我们有动态输入('n1','n2'),arrange数据按'Wells'和desc'Date'的结束顺序,group_by'Well',用于slice_head获取第一(n1 + n2)行,然后summarise创建'Avg 'mean列分别基于 'n1'headtail'n2'

library(dplyr)
library(stringr)
n1 <- 3
n2 <- 6
df %>%
    arrange(Wells, desc(Date)) %>% 
    group_by(Wells) %>%
    slice_head(n = n1 + n2) %>%
    summarise(!! str_c('Avg', n1) := mean(head(Index, n1)), 
              !! str_c('Avg', n2)  := mean(tail(Index, n2)), .groups = 'drop')

-输出

# A tibble: 2 x 3
#  Wells  Avg3  Avg6
#  <chr> <dbl> <dbl>
#1 A       110    65
#2 B       220   130

或使用base R

df1 <- df[order(df$Wells, -as.numeric(df$Date)),]
out <- do.call(data.frame, aggregate(Index ~ Wells, 
       subset(df1, ave(seq_along(Wells), 
         Wells, FUN = seq_along) <= (n1 + n2)), FUN = function(x)
        c(Avg3 = mean(head(x, n1)), Avg6 = mean(tail(x, n2)))))

推荐阅读