【问题标题】:Using str_extract to extract dollar amounts使用 str_extract 提取美元金额
【发布时间】:2019-06-11 17:16:58
【问题描述】:

我有一列文本,想只提取字符串中包含的美元金额,使用美元符号作为字符串的开头。我可以匹配美元符号,但不知道如何在后面直接取数字(并删除逗号)。

我尝试在 str_extract 中使用美元符号作为锚点,但没有得到全部金额。

input <- (c("the sum of $175,000,000 and the sum", "the sum of $20,000,000 and the sum", "the sum of $100,000,000 and the sum"))

df<-as.data.frame(input)

df %>% 
    mutate(amount = str_extract(input,"^\\$"))

在变异之前运行它看起来像:

input
the sum of $175,000,000 and the sum
the sum of $20,000,000 and the sum
the sum of $100,000,000 and the sum

我希望它看起来像:

input                                         amount
the sum of $175,000,000 and the sum        175000000
the sum of $20,000,000 and the sum          20000000
the sum of $100,000,000 and the sum        100000000

【问题讨论】:

  • 你肯定永远不会有任何十进制值吗?这会影响您是否应该删除 .

标签: r stringr


【解决方案1】:

使用来自readr 的辅助函数parse_number 你可以这样做

df %>% 
  mutate(amount = parse_number(str_match(input,"\\$([0-9,.]+)")[,2]))

基本上我们使用str_match 去除“$”,然后将其余部分通过parse_number 使其变为数字。这也适用于“$11.11”等值

您也可以使用基本函数 as.numeric() 而不是 parse_number 但如果您使用其他 tidyverse 包,我会建议您这样做。

【讨论】:

  • 当我使用这个时,我得到以下错误:错误:列amount必须是长度1(组大小),而不是3。输入的实际列比简单的例子长得多我在这里...这可能与列中的其他数字有关吗?
  • @skl 我希望您在没有 [,2] 部分的情况下得到该错误。 str_match() 返回一个矩阵,但我们想要第二列。这对我有用。有一个更具代表性的例子来触发错误以确定发生了什么会很有帮助。
【解决方案2】:

这是一种方法:

library(stringr)

input <- (c("the sum of $175,000,000 and the sum", "the sum of $20,000,000 and the sum", "the sum of $100,000,000 and the sum"))

df<-as.data.frame(input)

#extract the $, the digits and commas
#then remove the $ and commas
df %>% mutate(amount = str_remove_all(str_extract(input,"\\$[0-9,]+"), "[\\$,]"))

【讨论】:

  • 当我使用它时,我得到以下错误:错误:列数量必须是长度 1(组大小),而不是 3。输入的实际列比我的简单示例长得多这里...这可能与列中的其他数字有关吗?
  • 在您的示例中,输入是作为向量提供的。如果您的实际数据结构不同,则可能会导致您遇到的错误。您的数据的实际样本可以避免这些类型的问题。
【解决方案3】:

使用base R

gsub(",", "", sub(".*[$]([0-9,]+)\\s*.*", "\\1", input))
#[1] "175000000" "20000000"  "100000000"

【讨论】:

    猜你喜欢
    • 2020-10-09
    • 2019-01-25
    • 2020-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-16
    • 1970-01-01
    • 2018-02-13
    相关资源
    最近更新 更多