Converting multiple columns to double type in R using dplyr

Viewed 536

I have a data frame with a lot of columns containing decimal values in string format and I am trying to find a way to convert all the columns containing numerical values into double type. For example by specifying the range of columns to convert, df[2:4] in this case.

From this:

df <- data_frame(cat = c('A', 'B', 'C'), 
             X11 = c('0.1', '0.3', '0.5'), 
             Y2 = c('0.2', '0.2', '0.7'), 
             P3 = c('0.14', '0.31', '0.35'),
             type = c('H', 'I', 'J'))

To this:

df <- data_frame(cat = c('A', 'B', 'C'), 
             X11 = c(0.1, 0.3, 0.5), 
             Y2 = c(0.2, 0.2, 0.7), 
             P3 = c(0.14, 0.31, 0.35),
             type = c('H', 'I', 'J'))

I have been trying to get it to work with the different dplyr mutate functions but I cannot figure out how to do it.

I would be super grateful if I could get some advice on this one.

1 Answers

It would be better to do this with type.convert from base R which automatically correct the type based on the value in each column

df1 <- type.convert(df, as.is = TRUE)

In dplyr, it can be done with across and specify the range of columns with either numeric index

df %>%
   mutate(across(2:4, as.numeric))

Or the column names range

df %>%
   mutate(across(X11:P3, as.numeric))
Related