as.character()
get_help() docs
The as.character() function comes with R and is part of the Base R {base} package.
We use this function to coerce a value or variable to be a character, i.e. change the variable’s type into a character type.
as.character(value to coerce into character type)Some examples below use the carnivores dataset. Learn more about this dataset with get_help("carnivores").
# Show the carnivores dataset
carnivores## # A tibble: 9 × 4
## name genus awake brainwt
## <chr> <fct> <dbl> <dbl>
## 1 Arctic fox Vulpes 11.5 0.0445
## 2 Cheetah Acinonyx 11.9 NA
## 3 Dog Canis 13.9 0.07
## 4 Gray seal Haliochoerus 17.8 0.325
## 5 Jaguar Panthera 13.6 0.157
## 6 Lion Panthera 10.5 NA
## 7 Northern fur seal Callorhinus 15.3 NA
## 8 Red fox Vulpes 14.2 0.0504
## 9 Tiger Panthera 8.2 NA
# Convert the number 10 into character "10"
as.character(10)## [1] "10"
# Convert the logical value `TRUE` (no quotes!) into a character type
# containing the literal letters (in quotes!) "TRUE".
as.character(TRUE)## [1] "TRUE"
# Convert a the `awake` column in a tibble (data frame) to be of type character
carnivores$awake <- as.character(carnivores$awake)
# Show result of coercion:
carnivores## # A tibble: 9 × 4
## name genus awake brainwt
## <chr> <fct> <chr> <dbl>
## 1 Arctic fox Vulpes 11.5 0.0445
## 2 Cheetah Acinonyx 11.9 NA
## 3 Dog Canis 13.9 0.07
## 4 Gray seal Haliochoerus 17.8 0.325
## 5 Jaguar Panthera 13.6 0.157
## 6 Lion Panthera 10.5 NA
## 7 Northern fur seal Callorhinus 15.3 NA
## 8 Red fox Vulpes 14.2 0.0504
## 9 Tiger Panthera 8.2 NA
# Convert a the `awake` column in a tibble (data frame) to be of type character, using dplyr::mutate()
carnivores %>%
dplyr::mutate(awake = as.character(awake))## # A tibble: 9 × 4
## name genus awake brainwt
## <chr> <fct> <chr> <dbl>
## 1 Arctic fox Vulpes 11.5 0.0445
## 2 Cheetah Acinonyx 11.9 NA
## 3 Dog Canis 13.9 0.07
## 4 Gray seal Haliochoerus 17.8 0.325
## 5 Jaguar Panthera 13.6 0.157
## 6 Lion Panthera 10.5 NA
## 7 Northern fur seal Callorhinus 15.3 NA
## 8 Red fox Vulpes 14.2 0.0504
## 9 Tiger Panthera 8.2 NA