gpt4 book ai didi

r - 查找匹配条件的相邻行

转载 作者:行者123 更新时间:2023-12-01 03:18:43 25 4
gpt4 key购买 nike

我在 R 中有一个金融时间序列(目前是一个 xts 对象,但我现在也在研究 tibble)。

如何找到与条件匹配的 2 个相邻行的概率?

例如,我想知道连续 2 天高于平均值/中值的概率。我知道我可以 lag前几天的值(value)进入下一行,这将使我能够获得此统计信息,但这似乎非常麻烦且不灵活。

有没有更好的方法来完成这项工作?

xts 样本数据:

foo <- xts(x = c(1,1,5,1,5,5,1), seq(as.Date("2016-01-01"), length = 7, by = "days"))

连续 2 天高于 median 的概率是多少?值(value)?

最佳答案

您可以创建一个新列,调出高于中位数的列,然后仅取连续和更高的列

> foo <- as_tibble(data.table(x = c(1,1,5,1,5,5,1), seq(as.Date("2016-01-01"), length = 7, by = "days")))

步骤 1

创建列以查找高于中位数的列
> foo$higher_than_median <- foo$x > median(foo$x)

步骤 2

使用 diff 比较该列,

仅当两者连续升高或降低时才采用。 c(0, diff(foo$higher_than_median) == 0
然后添加它们必须都更高的条件 foo$higher_than_median == TRUE
完整表达:
foo$both_higher <- c(0, diff(foo$higher_than_median)) == 0 & $higher_than_median == TRUE

步骤 3

要找到概率取平均值 foo$both_higher
mean(foo$both_higher)
[1] 0.1428571

关于r - 查找匹配条件的相邻行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47450028/

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