【问题标题】:How to replace one digit numbers by two digits numbers using stringr in R如何在R中使用stringr将一位数字替换为两位数字
【发布时间】:2020-11-12 22:39:08
【问题描述】:

我想用s01_s02_s09_s10_ 替换列x 的值s1_s2_s9_s10_。我可以轻松地为每种情况(例如s1_)做到这一点,但并非对所有情况都适用(我的正则表达式知识很短)。 我怎样才能在不重复自己的情况下完成所有这些替换?

library(tidyverse)

df <- tibble( x = c('s1_', 's2_', 's9_', 's10_'))

pattern <- 's1_'  
replacement <-  's01_'  
stringr::str_replace(df$x, pattern, replacement)      
#> [1] "s01_" "s2_"  "s9_"  "s10_"
Created on 2020-11-12 by the reprex package (v0.3.0)

【问题讨论】:

    标签: r regex stringr


    【解决方案1】:

    gsubfn 的选项

    library(gsubfn)
    df$x <- gsubfn("(\\d+)", ~sprintf('%02d', as.numeric(x)), df$x)
    

    类似于gsubfnstr_replace替换可以带函数

    library(stringr)
    str_replace(df$x, "\\d+", function(x) sprintf('%02d', as.numeric(x)))
    #[1] "s01_" "s02_" "s09_" "s10_"
    

    或者dplyr

    library(dplyr)
    df %>%
        mutate(x = str_replace(x, "\\d+", 
              purrr::as_mapper(~ sprintf('%02d', as.numeric(.x)))))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-26
      • 2019-11-18
      • 2012-06-06
      • 2017-04-19
      • 1970-01-01
      相关资源
      最近更新 更多