如何在R中使用stringr将一位数替换为两位数
我想用s01、s02、s09和s10替换列xs1、s2、s9和s10的值。我可以很容易地为每种情况做这件事,例如s1_uu,但并非所有我的正则表达式知识都很短。 我怎样才能在不重复自己的情况下完成所有这些替换如何在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(
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)))))