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
.
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.