sum only the negative values in a row from an xts-object

风流意气都作罢 提交于 2020-01-06 07:29:11

问题


I have an xts-object and I want to sum only the negative values in the first row.

The code

sum(test[test<0])

gives me the error

Error in `[.xts`(test, test < 0) : 'i' or 'j' out of range

but

sum(test[1],na.rm=TRUE)

works, but then I have the sum of all the values, not just the negative ones:

[1] -0.9786889

Without giving an example of data yet, does anybody know why this simple code doesnt work?

The dimension of the xts-object is > dim(test) is 216 39.


回答1:


There is a chance that this is related to the open xts issue here ---> here

It appears that xts objects cannot be subset in this manner. Instead, you should use coredata(), an xts function that treats the "core data" as a matrix.

It's a little messy but:

sum(coredata(test)[1,][coredata(test)[1,] < 0]

should work. If you wanted to do this for all rows, you would need to use something like apply() or a for loop.




回答2:


Here are some possibilities:

sum(pmin(test[1], 0), na.rm = TRUE)

sum(test[1] * (test[1] < 0), na.rm = TRUE)

sum(Filter(function(x) x < 0, coredata(test[1])))


来源:https://stackoverflow.com/questions/51155822/sum-only-the-negative-values-in-a-row-from-an-xts-object

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!