我有一个时间序列数据集,比方说在一个非常简化的版本中,时间和价格列。
Time Price
15:30:01 NA
15:30:02 NA
15:30:03 36
15:30:04 38
15:30:05 37.5
15:30:06 NA
15:30:07 NA
15:30:08 37
15:30:09 37.8
15:30:10 39
15:30:11 40
15:30:12 38.5
15:30:13 38
15:30:14 38
我希望编写一个返回最佳价格的函数,如下所示:
Time Price Best Price
15:30:01 NA 36
15:30:02 NA 36
15:30:03 36 36
15:30:04 38 38
15:30:05 37.5 38
15:30:06 NA 38
15:30:07 NA 38
15:30:08 37 38
15:30:09 37.8 38
15:30:10 39 39
15:30:11 40 40
15:30:12 38.5 40
15:30:13 38 40
15:30:14 38 40
我试过了
bbo <- function(price1, price2) {
currbestprice <- price2
newbestprice <- ifelse(price1 >= currbestprice, price1, currbestprice)
currbestprice <- newbestprice
return(currbestprice)
}
我将通过 na.omit(Price)[1] 启动我的 price2 以获得第一个非 NA 值。然后我希望 currbestprice 不断更新以始终保持最新的最佳价格。 Price1 只是价格系列。
但是当我测试这个时:
p1 <- c(NA,NA,36,38,37.5,NA,NA,37,37.8,39,40,38.5,38,38)
p2 <- 36
bbo(p1,p2)
返回
NA NA 36.0 38.0 37.5 NA NA 37.0 37.8 39.0 40.0 38.5 38.0 38.0
它似乎没有更新我的 currbestprice。我被卡住了,非常感谢任何帮助。
最佳答案
另一个带有 cummax
函数的基本 R 选项:
# create a new column 'BestPrice'
df$BestPrice <- df$Price
# replace the first NA with the first non-NA value
df$BestPrice[is.na(df$BestPrice)][1] <- df$BestPrice[!is.na(df$BestPrice)][1]
# relace the remaining NA's with zero
df$BestPrice[is.na(df$BestPrice)] <- 0
# use 'cummax' to replace the values with the best price untill that point
df$BestPrice <- cummax(df$BestPrice)
给出:
> df Time Price BestPrice 1 15:30:01 NA 36 2 15:30:02 NA 36 3 15:30:03 36.0 36 4 15:30:04 38.0 38 5 15:30:05 37.5 38 6 15:30:06 NA 38 7 15:30:07 NA 38 8 15:30:08 37.0 38 9 15:30:09 37.8 38 10 15:30:10 39.0 39 11 15:30:11 40.0 40 12 15:30:12 38.5 40 13 15:30:13 38.0 40 14 15:30:14 38.0 40
另一种选择是将 na.locf
与 zoo
中的 fromLast = TRUE
参数结合使用 高潮
:
library(zoo)
df$BestPrice <- na.locf(df$Price, fromLast = TRUE)
df$BestPrice <- cummax(df$BestPrice)
关于r - 通过函数更新数据框以找到连续的最佳值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46399414/