简体   繁体   中英

Subsetting an “xts” (matrix) with NAs

Consider the following xts objects, x,y:

x=xts(matrix(1:12, ncol=3), Sys.Date()+1:4  )
x[1,]=NA   
y=x

As all elements are positive:

>     coredata(x)[x>0]
[1] NA  2  3  4 NA  6  7  8 NA 10 11 12
>     coredata(y)[T]
[1] NA  2  3  4 NA  6  7  8 NA 10 11 12

To further confirm similiarities we can check:

>     str(coredata(x)[x>0])  
int [1:12] NA 2 3 4 NA 6 7 8 NA 10 ...
>     class(coredata(x)[x>0])  
[1] "integer"
>     str(coredata(y)[T])  
int [1:12] NA 2 3 4 NA 6 7 8 NA 10 ...
>     class(coredata(y)[T])  
[1] "integer"

Anyway, when it comes to assignment there is a different behaviour

>     coredata(x)[x>0]=0
>     coredata(y)[T]=0
>     x;y
           [,1] [,2] [,3]
2014-01-15   NA   NA   NA
2014-01-16    0    0    0
2014-01-17    0    0    0
2014-01-18    0    0    0

           [,1] [,2] [,3]
2014-01-15    0    0    0
2014-01-16    0    0    0
2014-01-17    0    0    0
2014-01-18    0    0    0

Can you explain why there is a different behaviour?

From help("[") :

NAs in indexing

When extracting, a numerical, logical or character NA index picks an unknown element and so returns NA in the corresponding element of a logical, integer, numeric, complex or character result, and NULL for a list. (It returns 00 for a raw result.)

When replacing (that is using indexing on the lhs of an assignment) NA does not select any element to be replaced. As there is ambiguity as to whether an element of the rhs should be used or not, this is only allowed if the rhs value is of length one (so the two interpretations would have the same outcome).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM