[R] elements that appear only once

Peter Dalgaard p.dalgaard at biostat.ku.dk
Wed Feb 22 13:57:23 CET 2006


Robin Hankin <r.hankin at noc.soton.ac.uk> writes:

> Hi Dmitris, and list
> 
> 
> 
> On 22 Feb 2006, at 09:24, Dimitris Rizopoulos wrote:
> 
> > another approach is:
> >
> > names(which(table(a) == 1))
> >
> > but I don't know if you find this more elegant :)
> >
> 
> 
> 
> well, thank you for this (which() is good here!) but this is still  
> "inelegant" IMHO
> because it uses the names() of a table.
> 
> If I had
> 
>  > a <- as.factor(c(1,1,1,2,3,4,4,4,4,5))
>  > names(which(table(a)==1))
> [1] "2" "3" "5"
>  >
> 
> this gives a character vector.
> 
> I could coerce using  as.integer() here, but this seems so....inelegant.

You could go 

sort(unique(a))[table(a)==1]

(without the sort(), things go pearshaped, try setting

a <- factor(c(1,1,1,2,3,4,4,4,4,5),levels=5:1)

wnd you'll see).

If we assume that a is a factor, another option is

levels(a))[table(a)==1]

but that also has the problem of returning a character vector.

-- 
   O__  ---- Peter Dalgaard             Øster Farimagsgade 5, Entr.B
  c/ /'_ --- Dept. of Biostatistics     PO Box 2099, 1014 Cph. K
 (*) \(*) -- University of Copenhagen   Denmark          Ph:  (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)                  FAX: (+45) 35327907




More information about the R-help mailing list