使用 gsub 函数从值中删除 $ 符号时出现问题
Problem in using gsub function to remove $ sign from values
我试图从列中删除“$”符号,但是,在使用 gsup
之后,我得到了 NAs introduced by coercion
,看起来我的代码引入了 NA。请看下面的例子:
structure(list(Strata.Maint.Fee = c("2.00", "0.00", "0.00",
".88", ".88", ".88", ".88", ".88", ".86", ".86",
",056.2", ",056.2")), row.names = c(NA, -12L), class = c("tbl_df",
"tbl", "data.frame"))
然后我使用这个代码:
data_Selected$new = as.numeric(gsub("\$", "", data_Selected$Strata.Maint.Fee))
结果将是:
Strata.Maint.Fee new
<chr> <dbl>
1 2.00 672
2 0.00 670
3 0.00 670
4 .88 67.9
5 .88 67.9
6 .88 67.9
7 .88 67.9
8 .88 67.9
9 .86 67.9
10 .86 67.9
11 ,056.2 NA
我猜最后一个数字中的 ,
有问题,但不明白为什么。你能建议我应该如何解决这个问题吗?
我们可以使用parse_number
。根据显示的输入,最后一个值也有一个 ,
,它不包含在 numeric
部分中。所以,要么我们使用 parse_number
library(dplyr)
data_Selected %>%
mutate(new = readr::parse_number( Strata.Maint.Fee))
或更改 gsub
以删除 $
和 ,
as.numeric(gsub("[,$]", "", data_Selected$Strata.Maint.Fee))
我试图从列中删除“$”符号,但是,在使用 gsup
之后,我得到了 NAs introduced by coercion
,看起来我的代码引入了 NA。请看下面的例子:
structure(list(Strata.Maint.Fee = c("2.00", "0.00", "0.00",
".88", ".88", ".88", ".88", ".88", ".86", ".86",
",056.2", ",056.2")), row.names = c(NA, -12L), class = c("tbl_df",
"tbl", "data.frame"))
然后我使用这个代码:
data_Selected$new = as.numeric(gsub("\$", "", data_Selected$Strata.Maint.Fee))
结果将是:
Strata.Maint.Fee new
<chr> <dbl>
1 2.00 672
2 0.00 670
3 0.00 670
4 .88 67.9
5 .88 67.9
6 .88 67.9
7 .88 67.9
8 .88 67.9
9 .86 67.9
10 .86 67.9
11 ,056.2 NA
我猜最后一个数字中的 ,
有问题,但不明白为什么。你能建议我应该如何解决这个问题吗?
我们可以使用parse_number
。根据显示的输入,最后一个值也有一个 ,
,它不包含在 numeric
部分中。所以,要么我们使用 parse_number
library(dplyr)
data_Selected %>%
mutate(new = readr::parse_number( Strata.Maint.Fee))
或更改 gsub
以删除 $
和 ,
as.numeric(gsub("[,$]", "", data_Selected$Strata.Maint.Fee))