gpt4 book ai didi

R:可变宽度的滚动分位数

转载 作者:行者123 更新时间:2023-12-04 11:14:41 25 4
gpt4 key购买 nike

基本上,我有以下数据

x <- structure(c(0.609973095295898, 0.731967714355078, 0.243989238118359, 
1.46393542871016, 0.609973095295898, 0.243989238118359, 0.12199461905918,
1.34194080965098, 1.82991928588769, 0.609973095295898, 2.92787085742031,
0.243989238118359, 0.12199461905918, 0.365983857177539, 0.243989238118359,
0.365983857177539, 0.243989238118359, 0.243989238118359, 0.609973095295898,
0.243989238118359, 3.41584933365703, 1.09795157153262, 2.19590314306523,
1.95191390494687, 0.975956952473437, 0.487978476236719, 0.975956952473437,
0.243989238118359, 0, 0.243989238118359, 0.731967714355078, 0.12199461905918,
0.365983857177539, 0.487978476236719, 0.365983857177539, 0.609973095295898,
0.487978476236719, 0, 0.365983857177539, 1.46393542871016, 5.00177938142637,
1.58593004776934, 0.975956952473437, 0.731967714355078, 0.12199461905918,
1.09795157153262, 0.609973095295898, 0.12199461905918, 1.09795157153262,
0), .Dim = c(50L, 1L), .indexCLASS = c("POSIXct", "POSIXt"), .indexTZ = "", tclass = c("POSIXct",
"POSIXt"), tzone = "", class = c("xts", "zoo"), index = structure(c(1519867559.7265,
1519867560.9555, 1519867561.9165, 1519867562.9545, 1519867563.9795,
1519867564.7125, 1519867565.7165, 1519867566.8635, 1519867567.9235,
1519867568.8315, 1519867569.9905, 1519867570.7575, 1519867572.3225,
1519867573.8155, 1519867574.9315, 1519867575.4905, 1519867576.2835,
1519867577.8485, 1519867578.8205, 1519867579.8385, 1519867580.7705,
1519867581.8485, 1519867582.9695, 1519867583.9445, 1519867584.7765,
1519867585.9805, 1519867586.8755, 1519867587.7145, 1519867588.6735,
1519867589.8995, 1519867590.8525, 1519867591.8665, 1519867592.7175,
1519867593.9575, 1519867594.7415, 1519867595.9385, 1519867596.8065,
1519867597.9895, 1519867598.7925, 1519867599.8625, 1519867600.9995,
1519867601.9075, 1519867602.9505, 1519867603.9515, 1519867604.9975,
1519867605.8405, 1519867606.8505, 1519867607.9255, 1519867608.9765,
1519867609.5645), tzone = "", tclass = c("POSIXct", "POSIXt")), .Dimnames = list(
NULL, "random"))

它只是一个列 xts 对象。

现在我正在尝试计算滚动分位数,使宽度的起点始终位于 第 1 行,即窗口的范围始终从 1 开始。所以,如果我正在寻找在第 35 行,那么第 35 行的滚动分位数窗口的范围将从 1 到 35。如果我正在查看第 49 行,那么第 49 行的滚动分位数窗口的范围将从 1 到 49。

rollapply(x[,"random"],width="from row 1 to current row",FUN="quantile",probs=0.95))

但我想不出如何高效地编写代码?

最佳答案

很可能您正在寻找:

lapply(seq_along(x), function(i){
quantile(x[1:i], probs = 0.95)
})

对于 x 中的每个索引 i,从 1i 的子集 x > 并返回 quantile

输出将是一个列表,您可以将其转换为向量:

unlist(lapply(seq_along(x), function(i){
quantile(x[1:i], probs=0.95)
}))

或者更好(正如@Rui Barradas 在评论中建议的那样)使用 sapply:

sapply(seq_along(x), function(i){
quantile(x[1:i], probs=0.95)
})

关于R:可变宽度的滚动分位数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50314213/

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