问题
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