[英]R - for each observation in a column, find the closest one in another column
我正在嘗試過濾我的數據框以僅保留滿足以下條件的行:
對於每一天和每個 price_1,只保留 price_2 與 price_1 最接近的行,如果兩行等距,取 2 個價格和波動率的平均值。 例如 :
Date price_2 price_1 Volat
2011-07-15 215 200.0 5
2011-07-15 217 200.0 6
2011-07-15 235 200.0 5.5
2011-07-15 240 200.0 5.3
2011-07-15 200 201.5 6.2
2011-07-16 203 205.0 6.4
2011-07-16 207 205.0 5.1
Expected output:
Date price_2 price_1 Volat
2011-07-15 215 200.0 5
2011-07-15 200 201.5 6.2
2011-07-16 205 205.0 5.75
我是這樣開始的,但我不知道如何繼續:
group_by(Date) %>%
which(df,abs(df$price_1-df$price_2)==min(abs(df$price_1-df$price_2)))
非常感謝!
基礎 R 解決方案:
price_summary <-
data.frame(do.call("rbind", lapply(split(
df, paste(df$Date, df$price_1, sep = " - ")
),
function(x) {
data.frame(
Date = unique(x$Date),
price_1 = unique(x$price_1),
price_2 = mean(x$price_2[which.min(abs(x$price_2 - x$price_1))]),
Volat = mean(x$Volat),
stringsAsFactors = FALSE
)
})),
row.names = NULL)
數據:
df <- structure(
list(
Date = structure(c(
15170, 15170, 15170, 15170,
15170, 15171, 15171
), class = "Date"),
price_2 = c(215L, 217L,
235L, 240L, 200L, 203L, 207L),
price_1 = c(200, 200, 200, 200,
201.5, 205, 205),
Volat = c(5, 6, 5.5, 5.3, 6.2, 6.4, 5.1)
),
row.names = c(NA,-7L),
class = "data.frame"
)
一種dplyr
選項可能是:
df %>%
group_by(Date, price_1) %>%
mutate(diff = abs(price_2 - price_1)) %>%
filter(diff == min(diff)) %>%
summarise_at(vars(price_2, Volat), mean)
Date price_1 price_2 Volat
<chr> <dbl> <dbl> <dbl>
1 2011-07-15 200 215 5
2 2011-07-15 202. 200 6.2
3 2011-07-16 205 205 5.75
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.