【问题标题】:Replacing commas in thousands/millions but not smaller numbers以千/百万而不是更小的数字替换逗号
【发布时间】:2021-04-30 07:07:01
【问题描述】:

我正在阅读具有多种格式的已发表论文的数据。如果有数千或数百万,我想删除数字中的逗号,但不能更小。这是因为有些作者使用逗号来表示小数位(例如“1,1”)。

这是一个不起作用的简单示例:

library(stringr)
> text = c('1,1', '2,222', '3,333,333')
> str_replace_all(string=text, pattern='[0-9],[0-9][0-9][0-9]', replacement = '[0-9][0-9][0-9][0-9]')
[1] "1,1"                      "[0-9][0-9][0-9][0-9]"     "[0-9][0-9][0-9][0-9],333"

理想情况下,第二个数字将更改为“2222”,第三个“3333333”,第一个保留为“1,1”(我可以轻松处理小数位的逗号/句号问题)。

【问题讨论】:

    标签: r


    【解决方案1】:

    您可以使用积极的前瞻:

    gsub(",(?=\\d{3,})", "", text, perl = TRUE)
    [1] "1,1"     "2222"    "3333333"
    

    这里的前瞻(?=\\d{3,}),之后的至少3个digits;如果满足该条件,则删除 ,

    如果你更喜欢str_remove,你可以使用否定前瞻:

    library(stringr)
    str_remove_all(text, ",(?!\\d$)")
    

    这里的前瞻 (?!\\d$)disallows 删除逗号 if 在字符串的末尾 ($) 前跟一个 digit

    【讨论】:

      【解决方案2】:

      你可以这样使用: 如果字符的长度大于 4,它会将逗号更改为“”。

      text = c('1,1', '2,222', '3,333,333')
      
      for (i in 1:length(text)) {
                
                if (nchar(text[i]) > 4) {
                          textnew <- as.numeric(gsub(x = text[i], ",", ""))
                          text[i] <- textnew
                          message(i," did a thing")
                } else{
                          message(i," did nothing")
                }
      }
      
      text
      1 did nothing
      2 did a thing
      3 did a thing
      

      文本现在看起来像这样:

      [1] "1,1"     "2222"    "3333333"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-04-05
        • 1970-01-01
        • 2014-09-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多