# [R] Unique Values of a Matrix

Todd DeWees T.DeWees at cpse.dundee.ac.uk
Fri Feb 26 14:50:04 CET 2010

```I found that using

Sort(unique(c(X)) also works to remove NA....  if you don't mind the unique values being sorted....

Todd DeWees, PhD
Statistician
University of Dundee
Mackenzie Building
Kirsty Semple Way
Dundee DD2 4BF
Scotland UK
PH: 01382-420119

-----Original Message-----
From: David Winsemius [mailto:dwinsemius at comcast.net]
Sent: 26 February 2010 1:49 PM
To: Henrique Dallazuanna
Cc: Todd DeWees; r-help at r-project.org
Subject: Re: [R] Unique Values of a Matrix

On Feb 26, 2010, at 8:17 AM, Henrique Dallazuanna wrote:

> Try this:
>
> unique(c(X))

I did but it returned NA as did:    unique(as.vector(X)).

To get rid of the NA's I needed to do:

X[!duplicated(as.vector(X)) & !is.na(X)]

(Logical indexing and does need as.vector() , or c() , to "straighten
out" the index expression.)

Not sure why applying the straightening to the second logical term is
not equivalent:
> X[!duplicated(X) & !is.na(as.vector(X))]
[1] 1 2 4 3 1 7 2

This also:
> unique(c(X))[!is.na(unique(c(X)))]
[1] 1 2 4 3 7

>
> On Fri, Feb 26, 2010 at 10:06 AM, Todd DeWees
> <T.DeWees at cpse.dundee.ac.uk> wrote:
>> I have a 280,000 x 11 matrix with various values and many NA
>> values.  What I would like to do is get a vector of every unique
>> value in the matrix.
>>
>> For example:
>>
>> X =     [ 1    2    NA
>>          4    3      1
>>          7  NA  2 ]
>>
>> Returns:
>> Unique_X = [ 1, 2, 3, 4, 7]
>>
>> Thanks,
>> Todd
>>
>>
>>        [[alternative HTML version deleted]]
>>
>> ______________________________________________
>> R-help at r-project.org mailing list
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> and provide commented, minimal, self-contained, reproducible code.
>>
>
>
>
> --
> Henrique Dallazuanna
> Curitiba-Paraná-Brasil
> 25° 25' 40" S 49° 16' 22" O
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help