【问题标题】:How to add a space between digits and unit of measure in r如何在r中的数字和度量单位之间添加空格
【发布时间】:2020-06-29 15:07:58
【问题描述】:

我有一个数据集,有时度量单位与数字之间没有用空格隔开,我想将其添加进去。我有一个可以在数据集中使用的度量单位列表,我想要确保每次出现时都有一个空格。 我的数据是这样的: mydata <- c("black box 125CM", "10KG white chair", "bottle of water 1000ML") 我想: result <- c("black box 125 CM", "10 KG white chair", "bottle of water 1000 ML") 可能出现的计量单位: measure <- c("ML", "MG", "F", "CM", "CPR", "FL", "CPS", "KG")

到目前为止我已经尝试过(但它不起作用):

  for (i in 1:NROW(measure)) {
    replacement <- paste0("\\s", measure[i])
    result <- gsub("(?<=[[:digit:]])"measure[i], replacement, mydata, perl = TRUE)
    }

如果是一次替换,我可以这样做:

result <- gsub("(?<=[[:digit:]])MG", " MG", mydata, perl = TRUE)

我只是不知道应该如何在 gsub 函数中编写 measure[i],我找不到正确的语法。 有什么建议么?非常感谢您。

【问题讨论】:

  • 尝试类似:gsub(paste0( "(?&lt;=[[:digit:]])(", paste(measure, collapse="|"), ")"), " \\1", mydata, perl = TRUE)

标签: r regex gsub


【解决方案1】:

Regex lookahead 可以做到这一点。

gsub(paste0("(?<=[0-9])(", paste(measure, collapse = "|"), ")"), " \\1",
     mydata, perl = TRUE)
# [1] "black box 125 CM"        "10 KG white chair"       "bottle of water 1000 ML"

【讨论】:

  • 它完全符合我的期望。谢谢!
【解决方案2】:
mydata <- c("black box 125CM", "10KG white chair", "bottle of water 1000ML")
stringr::str_replace_all(mydata, "[:digit:]([ML|MG|F|C[M|PR|PS]|FL|KG])", " \\1")

给予

[1] "black box 12 CM"        "1 KG white chair"       "bottle of water 100 ML"

注意对以C开头的三种情况的特殊处理。

顺便说一句,如果我不得不对空间如此挑剔,我也会考虑让 SI 单位的大小写正确:“KG”不是千克,而是开尔文 ⋅ 6.674×10−11 m3⋅kg−1⋅s−2,我能想象到的接近!

【讨论】:

    【解决方案3】:

    这是我想出的并为我工作的。

    mydata <- c("black box 125CM", "10KG white chair", "bottle of water 1000ML")
    
    measure <- c("ML", "MG", "F", "CM", "CPR", "FL", "CPS", "KG")
    measure <- paste(measure, collapse = "|")
    
    result <- sub(paste0("([", measure, "])"), " \\1", mydata)
    

    编辑:如果已经有空格,这也会添加空格,r2evans 解决方案会更可取。

    【讨论】:

    • 这会增加空间,即使它已经存在,不是吗?
    • 是的,这是正确的,我将编辑答案以明确这一点。在这种情况下,您的解决方案会更好。
    【解决方案4】:

    如果像示例中一样,度量总是出现在数字之后,那么这有效:

    sub("(\\d+)", "\\1 ", mydata)
    [1] "black box 125 CM"        "10 KG white chair"       "bottle of water 1000 ML"
    

    【讨论】:

      猜你喜欢
      • 2021-07-22
      • 2020-08-26
      • 2023-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-08
      • 2013-05-14
      • 2018-09-29
      相关资源
      最近更新 更多