[R] Derive pattern from vector
Petr Savicky
savicky at cs.cas.cz
Sat Feb 11 18:18:41 CET 2012
On Sat, Feb 11, 2012 at 09:11:12AM -0800, syrvn wrote:
> Hello,
>
> consider the following vector 'chars':
>
>
> chars <- c(A, B, C, C, D, E, E, E, F, F, F)
>
>
> I need to convert 'chars' into the following pattern:
>
>
> 1, 2, 3, 3, 4, 5, 5, 5, 6, 7, 8
>
> As soon as there are duplicates they get the same number otherwise it's
> increasing numbers.
>
> However, for the char 'F' it should be always increasing numbers. Is that
> possible in R?
>
>
> I used the following code:
>
>
> chars <- c('A', 'B', 'C', 'C', 'D', 'E', 'E', 'E', 'F', 'F', 'F')
>
> chars_dup <- duplicated(chars)
>
> cumsum(!chars_dup)
>
> [1] 1 2 3 3 4 5 5 5 6 6 6
>
>
> But I do not know how to treat 'F' in the way described above.
Try this
non_dup <- !duplicated(chars) | chars == 'F'
cumsum(non_dup)
[1] 1 2 3 3 4 5 5 5 6 7 8
HTH.
Petr Savicky.
More information about the R-help
mailing list