# Change letter to number in a variable

I have this education variable with three values - high school, collage and PhD. I want to change them to 1, 2 and 3 like this:
high school = 1
collage = 2
PhD = 3
How do I do that?

Hello @CCV,

Happy to help you with your data! Can you provide just a bit more detail and data? Creating a reprex is the easiest way for us to help (FAQ: How to do a minimal reproducible example ( reprex ) for beginners)

df
id age education
1 56 Collage
2 64 Collage
3 35 High School
4 41 Collage

I want to change letters in the education variable to numbers. Like HS is 2 and collage is 3.

Hello,

I adjusted your example so we have PhD in it as well. As you can see I simply take the `education ` column convert it into a factor and then into numeric. This gives us the correct output. Just note that this conversion will only work if you have your dataframe sorted correctly as it takes the order 1,2,3 from the appereance of values in education as College,High Scool,Phd.

Let me know if this is the solution you wanted?

``````library(dplyr)
#> Warning: package 'dplyr' was built under R version 3.6.3
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#>     filter, lag
#> The following objects are masked from 'package:base':
#>
#>     intersect, setdiff, setequal, union

df <- data.frame(
stringsAsFactors = FALSE,
id = c(1, 2, 3, 4, 5),
age = c(56, 64, 35, 41, 42),
education = c("Collage", "Collage", "High School", "Collage", "PhD")
)

df\$new <- df\$education %>% as.factor() %>% as.numeric()
#df\$new <-  as.numeric(as.factor(df\$education)) could have written it like this too

df
#>   id age   education new
#> 1  1  56     Collage   1
#> 2  2  64     Collage   1
#> 3  3  35 High School   2
#> 4  4  41     Collage   1
#> 5  5  42         PhD   3
``````

Created on 2020-09-29 by the reprex package (v0.3.0)

If you do want High School as one then you will need to sort it in such a way where it is the first item in education.

Thank you sooo much!

Most welcome If it solved your problem sufficiently feel free to mark it as the solution

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.