[R] elements that appear only once

Prof Brian Ripley ripley at stats.ox.ac.uk
Wed Feb 22 13:39:23 CET 2006


On Wed, 22 Feb 2006, Robin Hankin wrote:

> 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 :)

Since the names of the table are the levels of the factor, I would use

levels(a)[table(a) %in% 1]

Well, almost.  If you have NA or NaN as a factor level then all these 
solutions need to be more complicated.

> 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.

But a has a character vector of levels, and there is nothing there to tell 
R that you wanted integers and not decimal-digit character strings.


-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595




More information about the R-help mailing list