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!
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.
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.
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.
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.
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)
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