Suppose you have a data frame with several character variables which you want to transform into numeric ones. You an use the function across()
.
library (dplyr)
chr_data <- tibble:: tribble (
~ year, ~ country, ~ sex, ~ age, ~ is_married, ~ has_child,
"1990" , "Italy" , "Man" , "28" , "No" , "Yes" ,
"1990" , "France" , "Woman" , "68" , "Yes" , "No" ,
"1990" , "France" , "Woman" , "22" , "No" , "No" ,
"1990" , "Italy" , "Man" , "56" , "Yes" , "Yes" ,
"2000" , "Switzerland" , "Woman" , "42" , "Yes" , "Yes" ,
"2000" , "France" , "Woman" , "13" , "No" , "No" ,
"2000" , "Italy" , "Man" , "43" , "Yes" , "No" ,
"1990" , "Switzerland" , "Woman" , "23" , "No" , "Yes" ,
"1990" , "Italy" , "Man" , "36" , "Yes" , "Yes" ,
"2000" , "Switzerland" , "Woman" , "32" , "Yes" , "No" ,
"1990" , "Switzerland" , "Man" , "23" , "No" , "No" ,
"2000" , "France" , "Man" , "63" , "Yes" , "Yes"
)
glimpse (chr_data)
Rows: 12
Columns: 6
$ year <chr> "1990", "1990", "1990", "1990", "2000", "2000", "2000", "19…
$ country <chr> "Italy", "France", "France", "Italy", "Switzerland", "Franc…
$ sex <chr> "Man", "Woman", "Woman", "Man", "Woman", "Woman", "Man", "W…
$ age <chr> "28", "68", "22", "56", "42", "13", "43", "23", "36", "32",…
$ is_married <chr> "No", "Yes", "No", "Yes", "Yes", "No", "Yes", "No", "Yes", …
$ has_child <chr> "Yes", "No", "No", "Yes", "Yes", "No", "No", "Yes", "Yes", …
# Convert year and age into
num_data <-
chr_data |>
mutate (across (c (year, age), as.numeric))
glimpse (num_data)
Rows: 12
Columns: 6
$ year <dbl> 1990, 1990, 1990, 1990, 2000, 2000, 2000, 1990, 1990, 2000,…
$ country <chr> "Italy", "France", "France", "Italy", "Switzerland", "Franc…
$ sex <chr> "Man", "Woman", "Woman", "Man", "Woman", "Woman", "Man", "W…
$ age <dbl> 28, 68, 22, 56, 42, 13, 43, 23, 36, 32, 23, 63
$ is_married <chr> "No", "Yes", "No", "Yes", "Yes", "No", "Yes", "No", "Yes", …
$ has_child <chr> "Yes", "No", "No", "Yes", "Yes", "No", "No", "Yes", "Yes", …