How would you replace character strings with numeric values?
For example, suppose I have a vector like so,
n <- c(rep("Sam", 3), "Harry", rep("Sparky", 2), rep("Ted", 4), "Red")
>n
[1] "Sam" "Sam" "Sam" "Harry" "Sparky" "Sparky" "Ted" "Ted" "Ted"
[10] "Ted" "Red"
I would like to get an output like this,
[1] 1 1 1 2 3 3 4 4 4 4 5
Where
Sam
is indexed by 1
Harry
is indexed by 2
Sparky
by 3
Ted
by 4
Red
by 5
.Here a solution using factor
approach preserving desired order:
n <- factor(n, levels = unique(n))
> as.numeric(n)
[1] 1 1 1 2 3 3 4 4 4 4 5
We can use match
match(n, unique(n))
#[1] 1 1 1 2 3 3 4 4 4 4 5
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With