【问题标题】:add space between 2 strings在 2 个字符串之间添加空格
【发布时间】:2021-10-13 10:12:46
【问题描述】:

我想在.number 之间添加whitespace

我的例子如下

df <- data.frame(name1 = c("Acranthera sp.01", "Aglaia spectabilis (Miq.) S.S.Jain & Bennet", "Alyxia sp.11"))

df
                                       name1
1                            Acranthera sp.01
2 Aglaia spectabilis (Miq.) S.S.Jain & Bennet
3                                Alyxia sp.11

我想要的输出

                                       name1
1                            Acranthera sp. 01
2 Aglaia spectabilis (Miq.) S.S.Jain & Bennet
3                                Alyxia sp. 11

到目前为止,我只知道使用str_pad 来添加空格。 tidyversestringr 对此有何建议?

【问题讨论】:

    标签: r tidyverse stringr


    【解决方案1】:

    在基础 R 中:

    df$name1 <- gsub("(\\.)([0-9])", "\\1 \\2", df$name1)
    

    【讨论】:

    • 非常感谢:D。记下这一点。
    【解决方案2】:
    mutate(
      df, 
      name1 = str_replace(
        name1, 
          "\\.(\\d)", # Match a literal . followed by a digit (capturing group 1)
          ". \\1"  # Replace by a ., space and the content of the first capturing group (the digit following the .)
      )
    )
    

    【讨论】:

    • 请注意 str_replace 来自 stringr
    • 这是 tidyverse 的一部分
    • 对不起,我的错我应该添加 stringr
    • @RobinGertenbach 你能解释一下regex 部分吗
    • 我详细阐述了正则表达式和替换,希望对您有所帮助