[R] A matrix problem

(Ted Harding) Ted.Harding at manchester.ac.uk
Wed Sep 16 16:13:43 CEST 2009


On 16-Sep-09 13:40:03, Bogaso wrote:
> Hi all,
> I have following ch. matrix :
> 
>> mat
>      [,1]                [,2]                  [,3]                [,4]
> [1,] "NA"                "0.0671746073115122"  "1.15281464953731" 
> "0.822277316923348"  
> [2,] "0.113184828073156" "-0.0133150789005112" "0.640912657072027"
> "-0.0667317787225847"
> [3,] "-1.40593584523871" "1.10755549414758"    "0.493828059815449"
> "-1.09233516877992"  
> [4,] "0.577643850085066" "1.10279525071026"    "1.16725625310315" 
> "0.367724768195794"  
> [5,] "0.746100264271392" "-0.335556133578362"  "NA"               
> "0.328559028366446"  
> 
> Now I want to convert it to a numeric matrix. So
> I used following code:
> 
>> as.numeric(mat)
>  [1]          NA  0.11318483 -1.40593585  0.57764385  0.74610026 
> 0.06717461
> -0.01331508  1.10755549  1.10279525 -0.33555613
> [11]  1.15281465  0.64091266  0.49382806  1.16725625          NA 
> 0.82227732
> -0.06673178 -1.09233517  0.36772477  0.32855903
> Warning message:
> NAs introduced by coercion 
> 
> What I noticed is that :
> 1. Original matrix converted to vector
> 2. A waring message is there.
> 
> I do not want such things to happen. Is there any direct way to
> convert my original ch. matrix to a numeric matrix ?
> Thanks

matn<-as.numeric(mat); dim(matn)<-dim(mat)

This does the job (without requiring you to use a specific indication
of dimension, e.g. ncol=4), but the warning message will still be
there unless, as David Winsemius said, you also use options(warn = -1).
However, a warning message such as this does not mean that anything has
gone wrong -- it is simply a notification that something which was not
the character representation of a number was converted into NA.
So you can ignore it. (It would lead to exactly the same result if,
instead of "NA" in mat[1,1] and mat[5,3], you had some other string
such as "tiger" -- try it! You would still get the warning, and this
time there might even be some point to it ... ).

Ted.

--------------------------------------------------------------------
E-Mail: (Ted Harding) <Ted.Harding at manchester.ac.uk>
Fax-to-email: +44 (0)870 094 0861
Date: 16-Sep-09                                       Time: 15:13:39
------------------------------ XFMail ------------------------------




More information about the R-help mailing list