Switch Class of All Data Frame Columns to Appropriate Type in R (Example Code)
In this R tutorial you’ll learn how to convert all data frame columns to the appropriate data type.
Creation of Example Data
my_df <- data.frame(col1 = c("foo", "bar", "foo", "bar", "bar"), # Constructing a data frame col2 = c("3", "1", "6", "7", "3"), col3 = c("3.1", "1.1", "6.1", "7.1", "3.1")) my_df # col1 col2 col3 # 1 foo 3 3.1 # 2 bar 1 1.1 # 3 foo 6 6.1 # 4 bar 7 7.1 # 5 bar 3 3.1 |
my_df <- data.frame(col1 = c("foo", "bar", "foo", "bar", "bar"), # Constructing a data frame col2 = c("3", "1", "6", "7", "3"), col3 = c("3.1", "1.1", "6.1", "7.1", "3.1")) my_df # col1 col2 col3 # 1 foo 3 3.1 # 2 bar 1 1.1 # 3 foo 6 6.1 # 4 bar 7 7.1 # 5 bar 3 3.1
sapply(my_df, class) # Checking the column classes # col1 col2 col3 # "character" "character" "character" |
sapply(my_df, class) # Checking the column classes # col1 col2 col3 # "character" "character" "character"
Example: Changing Classes of Data Frame Columns Automatically
my_df_updated <- type.convert(my_df, as.is = TRUE) # Adjusting the column classes |
my_df_updated <- type.convert(my_df, as.is = TRUE) # Adjusting the column classes
sapply(my_df_updated, class) # Checking the updated column classes # col1 col2 col3 # "character" "integer" "numeric" |
sapply(my_df_updated, class) # Checking the updated column classes # col1 col2 col3 # "character" "integer" "numeric"
Further Resources & Related Articles
Have a look at the following R tutorials. They explain topics such as factors, dates, vectors, and naming data: