r - 每组“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"))
解决方案
这是一个选项tidyverse
。假设我们有动态输入('n1','n2'),arrange
数据按'Wells'和desc
'Date'的结束顺序,group_by
'Well',用于slice_head
获取第一(n1 + n2
)行,然后summarise
创建'Avg 'mean
列分别基于 'n1'head
和tail
'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)))))
推荐阅读
- sql - 条件查询表达式
- java - 无法将 java.lang.Long 类型的对象转换为类型(modelclass)
- reactjs - 如何为 api 请求显示不同的微调器?
- python - 如何使用 python 客户端打开用于谷歌云存储的 XML 文件
- oracle - 如何在 Oracle 的企业管理器中更改您的主页
- java - 尝试初始化通道时出现 Hyperledger Fabric Java SDK 事件中心异常
- javascript - 如何让这个函数检查数组(table1)中的元素是否相同?它适用于数字但不适用于字符串
- android - RuntimeExecutionException:com.google.android.gms.common.api.ApiException:8
- wordpress - 在子主题中覆盖函数父主题
- javascript - 使用 foreach 将多个电子邮件从序列化数据显示到数组