Convert variable class by index in R

To convert to a different variable class by index in R quickly and efficiently, we can use the mutate(across( functions from dplyr (the mutate_at function has been superseded by this):

mutate(across(4:5, as.numeric))

The example above would convert columns 4 and 5 to numeric. You can also use the “c” function if your columns are not in order. That would look like:

mutate(across(c(4, 5, 8), as.character))

This would convert columns 4, 5, and 8 to character. This is really helpful if you have complicated variable names or simply don’t want to mess with typing them all out. The tidyverse blog has an in depth description of all of the variations of the mutate function and a few more useful tips and examples on how to use them.

Example

#convert variables by index
#load packages
suppressPackageStartupMessages(library(pacman))
pacman::p_load(tidyverse, sqldf)
#create example data
ex_data <- tibble(
  id = c(1, 2, 3, 4),
  license_num = c(65, 76, 09, 29),
  month = c('1', '8', '3', '11'))
#convert columns 1 - 2 from numeric to character
conv <- ex_data %>% mutate(across(1:2, as.character))
#convert all back to numeric
conv_back <- conv %>% mutate(across(c(1, 3), as.numeric))

Leave a Comment

Your email address will not be published. Required fields are marked *