Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I change values from xx mm to just xx in R?

I’m working with a dataset about weather where one row contains amount of rain in mm. Problem is it hasn’t been recorded in the same format, so while some rows contain just numbers, some contain numbers and "mm". It look something like below:

      Date         Rain
1 2014-12-08         10mm
2 2014-12-09         3
3 2014-12-10         5mm
4 2014-12-11         0
5 2014-12-12        11

Is there any way to delete the "mm" part so that I only keep the numbers?

Idealy it should look like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Date         Rain
1 2014-12-08         10
2 2014-12-09         3
3 2014-12-10         5
4 2014-12-11         0
5 2014-12-12        11

The only way I know how to do it now is one number at a time like: weather_data[weather_data=="10mm"]<-10 ; weather_data[weather_data=="5mm"]<-5 ; etc, but since it is a very large dataset containing several years, this would take a lot of time and hoped to find an easier and quicker way.

>Solution :

We could use parse_number to extract the digits and convert to numeric class

library(dplyr)
library(readr)
df1 <- df1 %>%
   mutate(Rain = parse_number(Rain))

Or use a regex option to remove the ‘mm’ and convert to numeric

library(stringr)
df1 <- df1 %>%
     mutate(Rain = as.numeric(str_remove(Rain, "mm")))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading