如何在R中将值从xx毫米更改为仅为xx?

huangapple go评论72阅读模式
英文:

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 &lt;- df1 %&gt;%
   mutate(Rain = parse_number(Rain))

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

library(stringr)
df1 &lt;- df1 %&gt;%
     mutate(Rain = as.numeric(str_remove(Rain, &quot;mm&quot;)))

huangapple
  • 本文由 发表于 2023年2月7日 01:25:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/75364596.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定