What is an elegant way to change the data types of data frames columns from a list of data type names?
Here's an example (change_to_data_types function is what I'm looking for):
my_df <- iris
my_types <- c("factor", "character", "double", "logical", "character")
my_df <- my_df %>% change_to_data_types(my_types)
my_types
has the same number of elements as the number of columns in my_df
and the conversion is done in the same order.
This is an example of an 'inelegant' way
my_df$Sepal.Length <- my_df$Sepal.Length %>% as.factor()
my_df$Sepal.Width <- my_df$Sepal.Width %>% as.character()
#etc...
An option would be
library(tidyverse)
my_df[] <- map2(my_df, str_c("as.", my_types), ~ get(.y)(.x))
Or in base R
my_df[] <- Map(function(x, y) get(y)(x), my_df, paste0("as.", my_types))
-checking the class again
sapply(my_df, class)
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# "factor" "character" "numeric" "logical" "character"
Having fun with match.fun:
my_df[] <- lapply(seq_along(names(my_df)),
function(i) match.fun(paste0("as.", my_types[ i ]))(my_df[[ i ]]))
sapply(my_df, class)
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# "factor" "character" "numeric" "logical" "character"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With