user46257
user46257

Reputation: 129

Easy way to make a numeric vector ordinal in R?

I have a simple question. I have a vector of years, spanning 1945:2000, with many repeated years. I want to make this an ordinal vector, so that 1945 is changed to 1, 1946 to 2, etc...

Obviously in this case the easiest way is just to subtract 1944 from the vector. But I have to do this with other numberic vectors that are not evenly spaced.

Is there an R function that does this?

Upvotes: 2

Views: 963

Answers (1)

David Robinson
David Robinson

Reputation: 78610

You can do:

as.numeric(factor(x))

For example:

x <- sample(1945:2010, 40)
ordinal_x <- as.numeric(as.factor(x))

plot(x, ordinal_x)

enter image description here

Notice that ordinal_x skips the gaps in x.

Upvotes: 3

Related Questions