Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 296
Kon Ath Avatar asked Nov 14 '18 19:11

Kon Ath


People also ask

How do I set multiple columns to numeric in R?

Use the lapply() Function to Convert Multiple Columns From Integer to Numeric Type in R. Base R's lapply() function allows us to apply a function to elements of a list. We will apply the as. numeric() function.

How do I convert specific columns to numeric in R?

To convert all the columns of the data frame to numeric in R, use the lapply() function to loop over the columns and convert to numeric by first converting it to character class as the columns were a factor.

How do I convert all columns to integers in R?

To convert columns of an R data frame from integer to numeric we can use lapply function. For example, if we have a data frame df that contains all integer columns then we can use the code lapply(df,as. numeric) to convert all of the columns data type into numeric data type.

How do I convert string to numeric in R?

To convert String to Integer in R programming, call strtoi() function, pass the string and base values to this function. strtoi(string, base) returns the integer value of the given string with respect to the specified base.


2 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)
like image 54
akrun Avatar answered Sep 28 '22 02:09

akrun


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

df %>% mutate_if(is.character,as.numeric)
like image 40
joran Avatar answered Sep 28 '22 01:09

joran