代码之家  ›  专栏  ›  技术社区  ›  pkpto39

在字符串中用0填充

  •  1
  • pkpto39  · 技术社区  · 3 年前

    我正在整理一些数据。这应该很简单,但我正在努力想办法。我想在字符串中左键填充1-9,但如果数字大于10,我不想更改字符串。我一直在用 gsub()

    df = data.frame("col1" = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10),
                    "col2" = c("test 1", "test 2", "test 3", "test 14", "test 15", "test 16", "test 17", "test 18", "test 19", "test 20" ))
    
    > df
       col1    col2
    1     1  test 1
    2     2  test 2
    3     3  test 3
    4     4 test 14
    5     5 test 15
    6     6 test 16
    7     7 test 17
    8     8 test 18
    9     9 test 19
    10   10 test 20
    
    # This is what I've been trying without much luck
    test <- df %>% 
      mutate(col2 = gsub("test 1", "test 01", col2))
    
    # My result
    > test
       col1     col2
    1     1  test 01
    2     2   test 2
    3     3   test 3
    4     4 test 014
    5     5 test 015
    6     6 test 016
    7     7 test 017
    8     8 test 018
    9     9 test 019
    10   10  test 20
    
    
    ----------------
    > desired
       col1    col2
    1     1 test 01
    2     2 test 02
    3     3 test 03
    4     4 test 14
    5     5 test 15
    6     6 test 16
    7     7 test 17
    8     8 test 18
    9     9 test 19
    10   10 test 20
    
    
    2 回复  |  直到 3 年前
        1
  •  2
  •   akrun    3 年前

    我们可以用 parse_number ,使用 sprintf 粘贴前缀“test”时填充2位数字

    library(dplyr)    
    df %>% 
        mutate(col2 = sprintf('test %02d', readr::parse_number(col2)))
    

    -输出

    #   col1    col2
    #1     1 test 01
    #2     2 test 02
    #3     3 test 03
    #4     4 test 14
    #5     5 test 15
    #6     6 test 16
    #7     7 test 17
    #8     8 test 18
    #9     9 test 19
    #10   10 test 20
    

    或使用 sub ,捕捉数字( \\d $ )字符串后跟空格( \\s ),在替换中,添加一个空格,后跟0和backreference( \\1 )被抓获的一组人

    with(df, sub("\\s(\\d)$", " 0\\1", col2))
    #[1] "test 01" "test 02" "test 03" "test 14" "test 15" 
    #[6] "test 16" "test 17" "test 18" "test 19" "test 20"
    
        2
  •  0
  •   Chris Ruehlemann    3 年前

    另一个解决方案,使用 str_pad 消极的展望 (?!\\d) 要将填充限制为个位数:

     library(stringr)
     str_pad(sub("test (\\d)(?!\\d)","test 0\\1", df$col2, perl = T), width = 2, side = "left", pad = "0")
     [1] "test 01"      "test 02"      "test 03"      "test test 14" "test test 15" "test test 16"
     [7] "test test 17" "test test 18" "test test 19" "test test 20"