R diff() 和 0 值

发布于 2025-01-03 00:44:30 字数 844 浏览 1 评论 0原文

我想使用 diff(log(myvar)) 来计算一些时间序列日志返回。在这种情况下,myvar 中的某些值设置为 0,并且 diff() 返回 Inf,因为它应该在数学上。

当滞后对的任一数据点为 0 时,如何强制 diff() 发生异常并返回 0?例如,

diff(log(c(0,1,2,3,4)))

将返回

0 0.6931472 0.4054651 0.2876821

强制第一个计算值为 0 而不是 Inf

更新 我实际上在使用 is.infinite() 时遇到了问题。考虑以下情况:

> v = diff(log(c(1, 0, 0, 2, 3)))
> v 
[1]      -Inf       NaN       Inf 0.4054651
> is.infinite(v) 
[1]  TRUE FALSE  TRUE FALSE

这里有 3 种不同的情况:-Inf、Inf 和 NaN。目标是将所有基本报价为 0 的回报设置为 0,因此我必须添加 v[is.nan(v)] = 0

为什么我要将收益设置为 0 而不是 NA?嗯,这更多的是一个逻辑问题,而不是一个编程问题,但我的想法是,在我的例子中,0 意味着参考价格没有改变(并不是说它是未知的)。

I want to use diff(log(myvar)) to calculate some time-series log returns. Some of the values in myvar are set to 0 and diff() returns Inf in this case, as it should mathematically.

How can I force diff() to make an exception and return 0 when either data point of the lagged pair is 0? For example

diff(log(c(0,1,2,3,4)))

Would return

0 0.6931472 0.4054651 0.2876821

Forcing the very first calculated value to be 0 rather than Inf.

UPDATE
I actually had a problem using is.infinite(). Consider the following case:

> v = diff(log(c(1, 0, 0, 2, 3)))
> v 
[1]      -Inf       NaN       Inf 0.4054651
> is.infinite(v) 
[1]  TRUE FALSE  TRUE FALSE

Here we have 3 different cases, -Inf, Inf and NaN. The goal is set 0 to all returns whose base quotation is 0 so I had to add v[is.nan(v)] = 0.

Why would I want to set returns to 0 rather than NA? Well this is more of a logical problem rather than a programming question, but the idea is that in my case 0 means that the reference price hasn't changed (and not that it is unknown).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

江湖正好 2025-01-10 00:44:30

你也可以这样做:

d[is.infinite(d)] <- 0

You could also do this:

d[is.infinite(d)] <- 0
万水千山粽是情ミ 2025-01-10 00:44:30

有什么原因吗

d <- diff(log(x))
d[abs(d)==Inf] <- 0

这个愚蠢的解决方案不起作用 ? (假设您的数据一开始只有非有限值,我认为获得 Inf-Inf 的唯一方法是具有零值.. .)

Is there a reason the boneheaded solution of

d <- diff(log(x))
d[abs(d)==Inf] <- 0

doesn't work? (Assuming you only have non-finite values in your data to begin with, I think the only way you can get Inf or -Inf is to have a zero value ...)

岛歌少女 2025-01-10 00:44:30

还应该添加

d[is.nan(d)] = 0

0/0 情况。

Should also add

d[is.nan(d)] = 0

for 0/0 case.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文