[R] division giving spurious NA

Rui Barradas ruipbarradas at sapo.pt
Mon Nov 5 11:25:02 CET 2012


Hello,

Your behavior is due to the fact that R uses _column_ vectors. The first 
column of x[1:2,] is divided by the first two elements of x[3,], then 
the second column of x[1:2,] by the next two elements of x[3,] and one 
of them is NA. Then the 3rd and 4th columns of x[1:2,], each by two 
elements of x[3,].
To see this think of x[3,] as a matrix with the same number of rows as 
x[1:2,]:

matrix(x[3,], nrow=2)
          [,1]     [,2]
[1,] 3.425393       NA
[2,] 2.534523 3.247219

And superimpose this on x[1:2,] to get the divisions that take place.
To get the rows of x[1:2,] divided by the vector x[3,], use transposes:

t(t(x[1:2,])/x[3,])
           [,1]      [,2] [,3]      [,4]
[1,] 0.7572935 0.3341405   NA 0.6912376
[2,] 0.3548600 0.3248356   NA 0.9782823


Hope this helps,

Rui Barradas
Em 05-11-2012 09:57, Christian Hoffmann escreveu:
> Hi,
>
> I stumbled acros the following disturbing computation:
>
> x <- matrix(c( 
> 2.594028,0.8468867,NA,2.244600,1.215535,0.8233032,NA,3.176697,3.425393,2.5345225,NA,3.247219),nrow=3,byrow=TRUE)
> x  # having NA in column3 only
>
> x[1:2,]/x[3,]
> ##           [,1]     [,2] [,3]      [,4]
> [1,] 0.7572935       NA   NA        NA
> [2,] 0.4795913 0.253541   NA 0.9782823
>
> where do the two Nas in columns 2 and 4 come from?
>
> TIA
>
> Christian
>




More information about the R-help mailing list