使用 stringr 和管道而不是 gsub 简化列编辑

Simplifying column edit using stringr and pipes instead of gsub

我正在尝试从列中删除 $ 符号和 , 并且到目前为止一直使用 gsub 这样做,但我想知道是否有办法在管道内使用 stringr 来完成此操作。

示例代码:

DataFrame <- structure(list(Date = structure(c(18485, 18459, 18471, 18459, 
18459, 18459, 18499, 18513, 18513, 18513), class = "Date"), Payment = c(",000.00", 
",000.00", "0.00", "0.00", ",000.00", ",000.00", 
",000.00", "0.00", ",000.00", ",290.00")), row.names = c(NA, 
-10L), class = c("tbl_df", "tbl", "data.frame"))

当前使用 gsub 的方法:

DataFrame$Payment <-gsub("\$","",DataFrame$Payment)
DataFrame$Payment <-gsub("\,","",DataFrame$Payment)
DataFrame$Payment <- as.numeric(DataFrame$Payment)

感谢指点!

实际上 gsub 带有字符 class 已经很简洁了:

DataFrame$Payment <- as.numeric(gsub("[$,]", "", DataFrame$Payment))

几乎任何东西都可以在 mutate:

中移动
DataFrame %>% 
    mutate(Payment = as.numeric(gsub('\$|\,', '', Payment)))

如果你想使用stringr,那么试试这个:

DataFrame %>% 
    mutate(Payment = as.numeric(stringr::str_remove_all(Payment, '\$|\,')))