给出的是带有基数据的data.table,子集的startIndex,子集的持续时间。对于每个子集,应用每个持续时间。
base <- data.table(idx=c(1,2,3,4,5,6,7,8,9,10), val=c(11,12,13,14,15,16,17,18,19,20))
startIndex <- c(2, 4, 7, 9)
duration <- c(1,2,3)是否有一些优雅的方法来获得startIndex定义的每个子集的最大值和持续时间,结果如下所示?例如,第一个子集由startIndex=2和duration=1定义,这意味着索引2和3之间的最大值为13。
Result:
idxStart idxEnd max
1: 2 3 13
2: 4 5 15
3: 7 8 18
4: 2 4 14
5: 4 6 16
6: 7 9 19
7: 2 5 15
8: 4 7 17
9: 7 10 20经常这样。
发布于 2021-04-04 19:28:58
下面是一种使用非equi的data.table方法。首先,将expand.grid用于开始索引和持续时间的组合。然后,计算每一行的结束索引。然后加入您的base,其中索引idx位于开始和结束之间,并保持最大val。
library(data.table)
dt <- data.table(expand.grid(idxStart = startIndex, Duration = duration))
dt[ , idxEnd := idxStart + Duration][
base, Max := max(val), on = .(idxStart <= idx, idxEnd >= idx), by = .EACHI]输出
idxStart Duration idxEnd Max
1: 2 1 3 13
2: 4 1 5 15
3: 7 1 8 18
4: 9 1 10 20
5: 2 2 4 14
6: 4 2 6 16
7: 7 2 9 19
8: 9 2 11 20
9: 2 3 5 15
10: 4 3 7 17
11: 7 3 10 20
12: 9 3 12 20发布于 2021-04-04 18:32:32
在这里,我想不出一个特别优雅的解决方案,但我认为映射函数应该可以完成这项工作。这是野蛮的强迫每一个组合通过,所以可能有一个更有效的解决方案,但它应该有效。
library(data.table)
base <- data.table(idx=c(1,2,3,4,5,6,7,8,9,10), val=c(11,12,13,14,15,16,17,18,19,20))
startIndex <- c(2, 4, 7, 9)
duration <- c(1,2,3)
combos <- expand.grid(startIndex = startIndex,
duration = duration) %>%
mutate(endIndex = startIndex + duration)
max_slices <- map2(combos$startIndex, combos$endIndex, function(startIndex, endIndex){
slice(base, startIndex, endIndex) %>%
select(val) %>%
max()
}) %>%
as.numeric()
result <- combos %>%
cbind(max = max_slices)结果:
startIndex duration endIndex max
1 2 1 3 13
2 4 1 5 15
3 7 1 8 18
4 9 1 10 20
5 2 2 4 14
6 4 2 6 16
7 7 2 9 19
8 9 2 11 19
9 2 3 5 15
10 4 3 7 17
11 7 3 10 20
12 9 3 12 19https://stackoverflow.com/questions/66944437
复制相似问题