as.character()1. Recode all ID variables to character
Review the data (d8)
# A tibble: 3 x 4
stu_id tch_id sch_id grade
<dbl> <dbl> <dbl> <dbl>
1 5000 200 13 6
2 5002 201 13 7
3 5003 200 13 6
View the class for each variable
dplyr::glimpse(d8)
Rows: 3
Columns: 4
$ stu_id <dbl> 5000, 5002, 5003
$ tch_id <dbl> 200, 201, 200
$ sch_id <dbl> 13, 13, 13
$ grade <dbl> 6, 7, 6
I see that my ID variables are stored as numeric but I want them to be stored as character.
Here I am going to bring in my existing data dictionary to help me choose the variables to recode.
Let’s view our data dictionary
# A tibble: 4 x 3
var_name type label
<chr> <chr> <chr>
1 stu_id character student study ID
2 tch_id character teacher study ID
3 sch_id character school study ID
4 grade numeric student grade level
I can pull a vector of all the variables that should be character type.
var_char <- dict %>%
dplyr::filter(type == "character") %>%
dplyr::pull(var_name)
And then use this vector to update the type of multiple variables.
d8 <- d8 %>%
dplyr::mutate(across(all_of(var_char), base::as.character))
Now we can check our variable types again.
dplyr::glimpse(d8)
Rows: 3
Columns: 4
$ stu_id <chr> "5000", "5002", "5003"
$ tch_id <chr> "200", "201", "200"
$ sch_id <chr> "13", "13", "13"
$ grade <dbl> 6, 7, 6
Return to Data Types