英文:
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?
Ideally it should look like this:
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.
英文:
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:
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.
答案1
得分: 0
我们可以使用parse_number
来提取数字并转换为数值类
library(dplyr)
library(readr)
df1 <- df1 %>%
mutate(Rain = parse_number(Rain))
或者使用正则表达式选项来删除'mm'并转换为数值
library(stringr)
df1 <- df1 %>%
mutate(Rain = as.numeric(str_remove(Rain, "mm")))
英文:
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")))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论