在读取器R中使用parse_number的负货币值 [英] Negative currency values using parse_number in readr R

查看:59
本文介绍了在读取器R中使用parse_number的负货币值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在导入需要从字符串转换为数字的销售数据.

I'm importing sales data that needs to be converted from character strings to numeric.

我正在尝试在 reader 中使用 parse_number 来执行此操作,但是它将为负值引发解析错误,并将其强制为 NA .

I'm trying to use parse_number in readr to do this, but it throws a parsing error for negative values, and coerces them to NAs.

例如:

x<-c("$ 1,000.00","$ 500.00",-$ 200.00")

y<-parse_number(x)

警告:1个解析失败.行#小标题:1 x 4列,第col列,期望的实际期望的< int>< int>< chr>< chr>实际1 3 NA一个数字-

y

[1] 1000 500不适用

parse_number readr 是否具有允许我为负货币值保留-"的功能?

Does parse_number or readr have functionality that allows me to keep "-" for negative currency values?

(我不要求使用 as.numeric(gsub())解决方案.)

(I'm not asking for an as.numeric(gsub()) solution.)

推荐答案

如果您希望按照

If you want to stay with tidyverse functions as per comment here you can just use stringr functions instead of gsub. Options like this:

library(tidyverse)
x <- c("$1,000.00", "$500.00", "-$200.00")
x %>%
  str_replace("^-\\$(.*)$", "$-\\1") %>%
  parse_number()
#> [1] 1000  500 -200

x %>%
  str_remove("\\$") %>%
  parse_number()
#> [1] 1000  500 -200

reprex软件包(v0.2.0)创建于2018-05-03.

Created on 2018-05-03 by the reprex package (v0.2.0).

这篇关于在读取器R中使用parse_number的负货币值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆