Convert multiple columns of a data frame from string to numeric in R

Viewed 10176

I have a data frame contain 10 columns of data (temperatures, humidity values etc.). R identifies those as strings. I used the following command to convert one of the columns to numeric format:

df$temp_out = as.numeric(df$temp_out)

The problem is that i have another 7 columns which also need to be converted. I could do it for each and everyone of these, but I need to do it in approximately 50 df, so it's kind of inconvenient. Any help is welcome!

4 Answers

We can use lapply to loop through the columns and apply as.numeric

df[cols] <- lapply(df[cols], as.numeric)

where

cols <- names(df)[4:10] # or column index (change the index if needed)

If you like to use dplyr another option is to use mutate_if():

df %>% mutate_if(is.character,as.numeric)

use tidyverse to just convert the columns that are numeric:

df <- df %>% mutate_if(is.numeric, as.numeric)

Change character dataframe column to numeric in r with multi columns

df[, 4:17] <- lapply(df[, 4:17], as.numeric)
Related