我正在从单个价格向量计算每小时平均价格。我想将此小时值与平均每日价值进行比较 - 并删除每日平均值超过2倍的所有值。我没有问题计算不同的值,但我不知道如何将每小时值与每日值进行比较?
快速数据示例:
df <- data.frame(dates = rep(seq(from = as.POSIXct("2013-01-01 00:00:00", tz = "UTC"),
to = as.POSIXct("2013-01-30 23:00:00", tz = "UTC"), by = "hour" ), 12),
price = runif(8640, min = -25, max = 225) )
require(dplyr)
results <- group_by(df, dates)
results <- summarise(results,
average = mean(price))
day_results <- mutate(df, days = format(df$dates, "%Y-%m-%d"))
day_results <- group_by(day_results, days)
day_results <- summarise(day_results,
average_d = mean(price))
我很遗憾如何将average
的24个值与average_d
的单个每日值进行比较。
我想清楚自己要做什么吗?
答案 0 :(得分:2)
这很简单:
> df %>% group_by(dates) %>% filter(price>2*mean(price))
Source: local data frame [811 x 2]
Groups: dates
dates price
1 2013-01-01 02:00:00 182.4726
2 2013-01-01 07:00:00 155.5009
3 2013-01-01 20:00:00 139.6948
4 2013-01-01 22:00:00 132.3332
5 2013-01-02 06:00:00 222.0633
6 2013-01-03 01:00:00 217.6383
7 2013-01-03 15:00:00 224.7268
8 2013-01-03 18:00:00 215.8826
即按日期对数据进行分组,然后仅筛选价格超过该组平均值两倍的那些数据?或者如果您想在输出中保持平均价格,请执行:
> df %>% group_by(dates) %>% mutate(average=mean(price)) %>% filter(price > 2*average) %>% arrange(dates)
Source: local data frame [811 x 3]
Groups: dates
dates price average
1 2013-01-01 00:00:00 140.5748 70.12211
2 2013-01-01 00:00:00 201.6484 70.12211
3 2013-01-01 01:00:00 223.9240 89.91996
4 2013-01-01 01:00:00 196.5975 89.91996
5 2013-01-01 01:00:00 203.6165 89.91996
6 2013-01-01 02:00:00 182.4726 70.85858
7 2013-01-01 02:00:00 193.0930 70.85858
8 2013-01-01 02:00:00 177.7848 70.85858
9 2013-01-01 03:00:00 202.9842 92.84580
10 2013-01-01 03:00:00 217.1840 92.84580
它还使用arrange
按日期排序输出。