I would like to convert a string column into numeric to facilitate calculation, but I would also like to preserve the information of the values. Thus, I would like to assign the string values as labels. Not sure if people do this in R, but it was common practice in Stata, so whenever you pulled a table or plotted a graph you could see the labels instead of assigned numbers. The problem that I have is that there are more than 20 string values, and more than 10k rows. So, let’s say I have the following dataframe:
df <- data.frame(color = c("green", "green", "blue", "red", "green", "blue", "red"))
df
color
1 green
2 green
3 blue
4 red
5 green
6 blue
7 red
How can I assign one number for each color, save the string information, and assign it as value labels?
>Solution :
You might want to take a look at this
I am afraid you cannot have duplicate row names in a data.frame in R. You might want to use a factor instead if you have repeated strings. The next example produces a bar plot with the labels using this approach.
library(tidyverse)
df |>
mutate(color = factor(color)) |>
ggplot(aes(x = color)) +
geom_bar()