[R] elements that appear only once

Robin Hankin r.hankin at noc.soton.ac.uk
Wed Feb 22 12:14:44 CET 2006


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.

best wishes


Robin



>
> Best,
> Dimitris
>



>
>
>> Hi.
>>
>> I have a factor and I want to extract just those elements that
>> appear
>> exactly once.
>> How to do this?
>>
>> Toy example follows.
>>
>>> a <- as.factor(c(rep("oak",5) ,rep("ash",1),rep("elm",1),rep
>> ("beech",4)))
>>> a
>> [1] oak   oak   oak   oak   oak   ash   elm   beech beech beech
>> beech
>> Levels: ash beech elm oak
>>> table(a)
>> a
>>   ash beech   elm   oak
>>     1     4     1     5
>>>
>>
>> So I would want "ash" and "elm", because there is only one ash and
>> only one elm in my wood.
>>
>> My Best Effort:
>>
>>
>>> names(table(a)[table(a)==1])
>> [1] "ash" "elm"
>>>
>>
>> This doesn't seem particularly elegant to me; there must be a better
>> way!
>>
>> anyone?
>>
>>

--
Robin Hankin
Uncertainty Analyst
National Oceanography Centre, Southampton
European Way, Southampton SO14 3ZH, UK
  tel  023-8059-7743




More information about the R-help mailing list