R diff() 和 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你也可以这样做:
You could also do this:
有什么原因吗
这个愚蠢的解决方案不起作用 ? (假设您的数据一开始只有非有限值,我认为获得
Inf
或-Inf
的唯一方法是具有零值.. .)Is there a reason the boneheaded solution of
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 ...)还应该添加
0/0 情况。
Should also add
for 0/0 case.