【问题标题】:Is parse_number supposed to fail when there are multiple periods in the string?当字符串中有多个句点时, parse_number 是否应该失败?
【发布时间】:2018-12-04 14:15:29
【问题描述】:

在 R 的 readr 包中,当字符串中有多个句点时,parse_number 函数会失败。这是一个错误,还是设计使然?

示例如下:

> library(readr)
> parse_number("asf125")
[1] 125
> parse_number("asf.125")
[1] 0.125
> parse_number(".asf.125")
Warning: 1 parsing failure.
row # A tibble: 1 x 4 col     row   col expected actual expected   <int> <int>    <chr>  <chr> actual 1     1    NA a number      .

[1] NA
attr(,"problems")
# A tibble: 1 x 4
    row   col expected actual
  <int> <int>    <chr>  <chr>
1     1    NA a number      .

【问题讨论】:

  • 我猜它“尝试”解析,它不可能涵盖所有边缘情况。为什么不在解析之前用正则表达式清理?因为数字只能有 1 个点 "." 和多个逗号 "," 作为千位分隔符。
  • 谢谢@zx8754。我使用正则表达式作为解决方法,但我想看看这是否是 parse_number 的预期行为。
  • 对于尝试使用正则表达式执行此操作的未来读者,它将类似于regmatches(x = ".asf.125", m = regexpr(text = ".asf.125", pattern = "[[:digit:]]+"))
  • 请添加为未来读者的答案。

标签: r readr


【解决方案1】:

这会在字符串中提取带有符号的任意浮点数:

as.numeric(stringi::stri_match_first_regex(
  c("asf125", "asf.125", ".asf.125"), 
  "[-+]?[[:digit:]]*\\.?[[:digit:]]+"
)[,1])
## [1] 125.000   0.125   0.125

这只是做正或负“整数”:

as.numeric(stringi::stri_match_first_regex(
  c("asf125", "asf.125", ".asf.125"), 
  "[-+]?[[:digit:]]+"
)[,1])
## [1] 125 125 125

依赖像readr::parse_number() 这样的通用函数似乎充满了危险。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-17
    • 2017-01-31
    • 1970-01-01
    • 1970-01-01
    • 2017-02-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多