Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to turn a string column into numeric and save string values as labels not to lose information in R?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading