Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/83.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在R中使用stringr将一位数替换为两位数_R_Regex_Stringr - Fatal编程技术网

如何在R中使用stringr将一位数替换为两位数

如何在R中使用stringr将一位数替换为两位数,r,regex,stringr,R,Regex,Stringr,我想用s01、s02、s09和s10替换列xs1、s2、s9和s10的值。我可以很容易地为每种情况做这件事,例如s1_uu,但并非所有我的正则表达式知识都很短。 我怎样才能在不重复自己的情况下完成所有这些替换 library(tidyverse) df <- tibble( x = c('s1_', 's2_', 's9_', 's10_')) pattern <- 's1_' replacement <- 's01_' stringr::str_replace(

我想用s01、s02、s09和s10替换列xs1、s2、s9和s10的值。我可以很容易地为每种情况做这件事,例如s1_uu,但并非所有我的正则表达式知识都很短。 我怎样才能在不重复自己的情况下完成所有这些替换

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)
带有gsubfn的选项

或者使用dplyr

library(gsubfn)
df$x <- gsubfn("(\\d+)", ~sprintf('%02d', as.numeric(x)), df$x)
library(stringr)
str_replace(df$x, "\\d+", function(x) sprintf('%02d', as.numeric(x)))
#[1] "s01_" "s02_" "s09_" "s10_"
library(dplyr)
df %>%
    mutate(x = str_replace(x, "\\d+", 
          purrr::as_mapper(~ sprintf('%02d', as.numeric(.x)))))