I have a mixed class dataframe (numeric and factor) where I am trying to convert the entire data frame to numeric. The following illustrates the type of data I am working with as well as the problem I am encountering:
> a = as.factor(c(0.01,0.02,0.03,0.04)) > b = c(2,4,5,7) > df1 = data.frame(a,b) > class(df1$a) [1] "factor" > class(df1$b) [1] "numeric"
When I try and convert the entire data frame to numeric, it alters the numeric values. For example:
> df2 = as.data.frame(sapply(df1, as.numeric)) > class(df2$a) [1] "numeric" > df2 a b 1 1 2 2 2 4 3 3 5 4 4 7
Previous posts on this site suggest using as.numeric(as.character(df1$a))
, which works great for one column. However, I need to apply this approach to a dataframe that may contain hundreds of columns.
What are my options for converting an entire dataframe from factor to numeric, while preserving the numeric decimal values?
The following is the output I would like to produce where a
and b
are numeric:
a b 1 0.01 2 2 0.02 4 3 0.03 5 4 0.04 7
I have read the following related posts, although none of them apply directly to this case:
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.
Convert Column to int (Integer)Use pandas DataFrame. astype() function to convert column to int (integer), you can apply this on a specific column or on an entire DataFrame. To cast the data type to 64-bit signed integer, you can use numpy. int64 , numpy.
Convert all columns of a data frame 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.
Using dplyr
(a bit like sapply..)
df2 <- mutate_all(df1, function(x) as.numeric(as.character(x)))
which gives:
glimpse(df2) Observations: 4 Variables: 2 $ a <dbl> 0.01, 0.02, 0.03, 0.04 $ b <dbl> 2, 4, 5, 7
from your df1 which was:
glimpse(df1) Observations: 4 Variables: 2 $ a <fctr> 0.01, 0.02, 0.03, 0.04 $ b <dbl> 2, 4, 5, 7
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