如何计算一组中的最大值并最小化另一组并取时间的平均值

How to compute max in one group and min another group and take the average with respect to time

我有一个数据集,其中包含时间、价格和买卖代码。对于每个时间段,我都试图计算最高买入价和最低卖出价,然后取平均值。如果其中一个在特定时间不存在,那么它将只是存在的那个。例如,如果只有买入价,则平均值就是当时的买入价。对于此数据,1 是买入,0 是卖出。数据集如下所示:

data <- data.frame(buy_sell = c(0,0,0,0,0,0,1,1,1,1,1,1)
                   ,price = c(71,65,66,77,89,80,55,45,23,46,50,45)
                   ,time = c(1,1,1,2,2,1,2,1,2,1,2,3))

data$av_price <- ifelse(data$time == 1,55.5,ifelse(data$time == 2,66,45))
data

我试图在 dyplr 中执行此操作,但是当您按分组依据时,它会为两个组计算每个,因此您不能取两个的平均值。我的方法是这样的。

data <- data %>% group_by(time,buy_sell) %>%
                   mutate(max_buy = max(price),min_sell = min(price))
data

有人可以帮助我构建代码以提供所需的结果吗?

您可以使用一对 intermediate/staging 列来完成此操作。类似于以下内容:

output <- data %>%
  mutate(buy_price = ifelse(buy_sell == 1, price, NA),
         sellprice = ifelse(buy_sell == 0, price, NA)) %>%
  group_by(time,buy_sell) %>%
  mutate(max_buy = max(buy_price, na.rm = TRUE),
         min_sell = min(sell_price, na.rm = TRUE))