簡體   English   中英

如何在 R 中使用 stringr 將一位數字替換為兩位數字

[英]How to replace one digit numbers by two digits numbers using stringr in R

我想用 s01_、 s02_s09_s10_替換列 x s1_s2_s9_s10_s01_ 我可以很容易地針對每種情況(例如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)

gsubfn的選項

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

類似於gsubfnstr_replace替換可以采用 function

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)))))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM