Reputation: 183
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!
Upvotes: 7
Views: 15022
Reputation: 49
use tidyverse to just convert the columns that are numeric:
df <- df %>% mutate_if(is.numeric, as.numeric)
Upvotes: 4
Reputation: 173517
If you like to use dplyr another option is to use mutate_if()
:
df %>% mutate_if(is.character,as.numeric)
Upvotes: 5
Reputation: 886938
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)
Upvotes: 12