bgbrink
bgbrink

Reputation: 663

R rounds decimal values in matrix when subsetting

I have a question about subsetting in R. Say I have the following Matrices:

     Ch1.Amplitude Ch2.Amplitude
[1,]      6968.577      9637.309
[2,]     11903.564     11385.656
[3,]     13503.292      9928.314

     Ch1.Amplitude Ch2.Amplitude
[1,]     11903.564     11385.656
[2,]      2519.582      8042.450
[3,]      9878.749      5899.139

I would like to match row 2 of the first Matrix A with row 1 in the second Matrix B. However, when I access the row with

matrixA[2, , drop=F]

This is what I get:

     Ch1.Amplitude Ch2.Amplitude
[1,]      11903.56      11385.66

As you can see, the third number after the decimal point has been chopped off! So naturally, if I use match() to find the row in Matrix B, it will return NA. However, when I query more than one row, this does not happen.

MatrixA[c(1,2),]
     Ch1.Amplitude Ch2.Amplitude
[1,]      6968.577      9637.309
[2,]     11903.564     11385.656

So I suppose it has something to do with drop=F. What is happening and how can I avoid it?

Upvotes: 0

Views: 1287

Answers (1)

zero323
zero323

Reputation: 330163

Actually, there is nothing wrong here. It is simply a formatting issue. You easily check that values are not affected:

> identical(matrixA[2, , drop=F], matrix(c(11903.564, 11385.656), nrow=1)
[1] TRUE

If want to see more decimal places you can for example use options(digits):

> options(digits=10)
> matrixA[2, , drop=F]
      [,1]      [,2]
[1,] 11903.564 11385.656

or format:

> format(matrixA[2, , drop=F], nsmall=3)
     [,1]        [,2]       
[1,] "11903.564" "11385.656"

Upvotes: 2

Related Questions