R 按天计算平均价格
我想这是一个相当简单的任务。。。 我正在计算每天的平均价格。这里有三个不同的日子,每个日子都有价格。 这是我最初拥有的数据帧R 按天计算平均价格,r,dataframe,dplyr,mean,R,Dataframe,Dplyr,Mean,我想这是一个相当简单的任务。。。 我正在计算每天的平均价格。这里有三个不同的日子,每个日子都有价格。 这是我最初拥有的数据帧 ID Date RoomAv Price 1 2001-01-02 TRUE 110 2 2001-01-04 FALSE 120 3 2001-01-03 TRUE 130 4 2001-01-03 TRUE 140 5 2001
ID Date RoomAv Price
1 2001-01-02 TRUE 110
2 2001-01-04 FALSE 120
3 2001-01-03 TRUE 130
4 2001-01-03 TRUE 140
5 2001-01-03 TRUE 150
6 2001-01-02 FALSE 160
7 2001-01-02 TRUE 170
8 2001-01-04 TRUE 180
9 2001-01-04 FALSE 190
10 2001-01-02 TRUE 200
我需要像这样的东西
Date AveragePrice
2001-01-02 num1
2001-01-03 num2
2001-01-04 num3
这就是我试图做的
df <- DataFrame %>%
group_by(DataFrame$Date) %>%
summarize(DataFrame$price == mean(DataFrame$Price))
尚未使用data.table库,但希望了解它是如何实现的。您可以执行以下操作 使用dplyr 使用data.table 请记住,in R==用于测试某个值是否等于另一个值,如x==1。因此,您应该在summary with=中分配新变量。这是正确的版本
library(dplyr)
DataFrame %>%
group_by(Date) %>%
summarize(avrgPrice = mean(Price))
您可以使用基础R中的聚合,使其:
dfout <- aggregate(Price ~Date, df, mean)
资料
带有data.table的选项
谢谢,
实际上我发现这个方法是最短的:
dfMean <- aggregate(DataFrame$Price ~ DataFrame$Date, DataFrame, mean)
在基于dplyr的函数中,通常不需要使用dataframe_name$
library(dplyr)
DataFrame %>%
group_by(Date) %>%
summarize(avrgPrice = mean(Price))
dfout <- aggregate(Price ~Date, df, mean)
> dfout
Date Price
1 2001-01-02 160.0000
2 2001-01-03 140.0000
3 2001-01-04 163.3333
df <- structure(list(ID = 1:10, Date = c("2001-01-02", "2001-01-04",
"2001-01-03", "2001-01-03", "2001-01-03", "2001-01-02", "2001-01-02",
"2001-01-04", "2001-01-04", "2001-01-02"), RoomAv = c(TRUE, FALSE,
TRUE, TRUE, TRUE, FALSE, TRUE, TRUE, FALSE, TRUE), Price = c(110L,
120L, 130L, 140L, 150L, 160L, 170L, 180L, 190L, 200L)), class = "data.frame", row.names = c(NA,
-10L))
library(data.table)
setDT(df)[, .(Price = mean(Price), by = Date]
dfMean <- aggregate(DataFrame$Price ~ DataFrame$Date, DataFrame, mean)