[R] which element is duplicated?

Michael Sumner md@umner @ending from gm@il@com
Tue Nov 13 02:46:15 CET 2018


what about   as.integer(factor(v, levels = unique(v)))

I recall very clearly when I realized the power of this feature of
factor(), but I've not seen it discussed much.

Cheers, Mike.

On Tue, 13 Nov 2018 at 12:08 Duncan Murdoch <murdoch.duncan using gmail.com>
wrote:

> The duplicated() function gives TRUE if an item in a vector (or row in a
> matrix, etc.) is a duplicate of an earlier item.  But what I would like
> to know is which item does it duplicate?
>
> For example,
>
> v <- c("a", "b", "b", "a")
> duplicated(v)
>
> returns
>
> [1] FALSE FALSE  TRUE  TRUE
>
> What I want is a fast way to calculate
>
>   [1] NA NA 2 1
>
> or (equally useful to me)
>
>   [1] 1 2 2 1
>
> The result should have the property that if result[i] == j, then v[i] ==
> v[j], at least for i != j.
>
> Does this already exist somewhere, or is it easy to write?
>
> Duncan Murdoch
>
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
-- 
Dr. Michael Sumner
Software and Database Engineer
Australian Antarctic Division
203 Channel Highway
Kingston Tasmania 7050 Australia

	[[alternative HTML version deleted]]



More information about the R-help mailing list