gpt4 book ai didi

r - 按组计算的累计最小值和最大值

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:11:36 24 4
gpt4 key购买 nike

我正在尝试计算 R 中数据框的最小范围。数据框如下所示:

+-----+--------------+-----------+------+------+
| Key | DaysToEvent | PriceEUR | Pmin | Pmax |
+-----+--------------+-----------+------+------+
| AAA | 120 | 50 | 50 | 50 |
| AAA | 110 | 40 | 40 | 50 |
| AAA | 100 | 60 | 40 | 60 |
| BBB | ... | | | |
+-----+--------------+-----------+------+------+

因此,最低价格范围 (Pmin) 保持该键的最低价格,直至该时间点 (DaysToEvent)。

这是我的实现:

for (i in 1:nrow(data)){
currentRecord <- data[i,]

if(currentRecord$Key != currentKey) {
# New key detected - reset pmin and pmax
pmin <- 100000
pmax <- 0
currentKey <- currentRecord$Key
}

if(currentRecord$PriceEUR < pmin) {
pmin <- currentRecord$PriceEUR
}
if(currentRecord$PriceEUR > pmax) {
pmax <- currentRecord$PriceEUR
}

currentRecord$Pmin <- pmin
currentRecord$Pmax <- pmax

# This line seems to be killing my performance
# but otherwise the data variable is not updated in
# global space
data[i,] <- currentRecord
}

这行得通 - 但真的很慢,每秒只有几个。它之所以有效,是因为我已经像这样对数据框进行了排序 data = data[order(data$Key, -data$DaysToEvent), ]。这样做的原因是因为我希望得到 nlog(n) 的 Big-O 用于排序和 n for 循环。所以我以为我会飞快地浏览这些数据,但我根本不是 - 需要几个小时。

我怎样才能让它更快?

以前的方法来 self 的同事 - 这里是伪造的:

for (i in 1:nrow(data)) {
...
currentRecord$Pmin <- data[subset on the key[find the min value of the price
where DaysToEvent > currentRecord$DaysToEvent]]
...
}

也有效——但我认为这个函数的顺序要高得多。 n^2log(n) 如果我是正确的并且需要几天时间。所以我想我会在那段重要的时间里有所进步。

所以我有 tried to get my head around在各种*applyby 函数上,当然这是您真正想要使用的。

但是 - 如果我使用 by() 然后在键上拆分。让我很接近。但是,我无法解决如何获得最小/最大范围的问题。我试图在功能范式中思考,但我被困住了。感谢您的帮助。

最佳答案

[原始答案:dplyr]

您可以使用dplyr 包解决这个问题:

library(dplyr)
d %>%
group_by(Key) %>%
mutate(Pmin=cummin(PriceEUR),Pmax=cummax(PriceEUR))

# Key DaysToEvent PriceEUR Pmin Pmax
# 1 AAA 120 50 50 50
# 2 AAA 110 40 40 50
# 3 AAA 100 60 40 60
# 4 BBB 100 50 50 50

d 应该是你的数据集:

d <- data.frame(Key=c('AAA','AAA','AAA','BBB'),DaysToEvent = c(120,110,100,100),PriceEUR = c(50,40,60,50), Pmin = c(50,40,40,30), Pmax = c(50,50,60,70))

[更新:data.table]

另一种方法是使用data.table,它具有相当惊人的性能:

library(data.table)
DT <- setDT(d)
DT[,c("Pmin","Pmax") := list(cummin(PriceEUR),cummax(PriceEUR)),by=Key]

DT
# Key DaysToEvent PriceEUR Pmin Pmax
# 1: AAA 120 50 50 50
# 2: AAA 110 40 40 50
# 3: AAA 100 60 40 60
# 4: BBB 100 50 50 50

[更新 2:基础 R]

如果您出于某种原因只想使用 base R,这是另一种方法:

d$Pmin <- unlist(lapply(split(d$PriceEUR,d$Key),cummin))
d$Pmax <- unlist(lapply(split(d$PriceEUR,d$Key),cummax))

关于r - 按组计算的累计最小值和最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28590037/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com