Francis Smart
Francis Smart

Reputation: 4055

R: Sequential Ordering With Adjacent Number

I would like to order a sequence in R with all of the numbers adjacent and ties counted the same. For example

Aorder(1,1,40,50,2,40,2)
[1] 1 1 3 4 2 3 2

In contrast to order:

order(c(1,1,40,50,2,40,2))
[1] 1 2 5 7 3 6 4

Upvotes: 0

Views: 162

Answers (2)

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193537

The rank function gets you part of the way, but doesn't do what you're asking for:

rank(x, ties.method="min")
# [1] 1 1 5 7 3 5 3

A simpler approach is to use factor and as.numeric instead:

as.numeric(factor(x, sort(unique(x))))
# [1] 1 1 3 4 2 3 2

Upvotes: 2

Roland
Roland

Reputation: 132706

This should be more efficient than using factor:

x <- c(1,1,40,50,2,40,2)

match(x, sort(unique(x)))
#[1] 1 1 3 4 2 3 2

Upvotes: 3

Related Questions