sequential column names add 0

I have a dataset with column names

 Col_a_b1   Col_a_b2   Col_a_b3  Col_a_b4   Col_a_b5   Col_a_b6   Col_a_b7   Col_a_b8   Col_a_b9  Col_a_b10   Col_a_b11 ...  Col_a_b94

How do I add 0s to column names 1 to 10 , expected column names

 Col_a_b01   Col_a_b02   Col_a_b03  Col_a_b04   Col_a_b05   Col_a_b06   Col_a_b07   Col_a_b08   Col_a_b09  Col_a_b10   Col_a_b11 ...  Col_a_b94

Any suggestions much appreciated. Thanks.

3 answers

  • answered 2022-03-25 05:32 Nad Pat

    One way to do is

        #column names 
        nam = c( 'Col_a_b1',   'Col_a_b2' ,  'Col_a_b3')
        #extract the number
        num = parse_number(nam)
        #convert to two digits.  
        num = sub('(^[0-9]$)','0\\1', num)
        #remove the numbers
        nam = gsub('[0-9]+', '', nam)
        #add 0
        mod_nam = paste0(nam, num)
        [1] "Col_a_b01" "Col_a_b02" "Col_a_b03"
    

  • answered 2022-03-25 06:02 Gnueghoidune

    For a given dataframe called data:

    colnames(data) <- sprintf("Col_a_b%02d", parse_number(colnames(data)))
    

    %02d means a decimal integer, left padded, with zeros up to 2 digits.

    Example

    # Sample data
    data = structure(list(Col_a_b1 = c("Name1", "Name2"), Col_a_b94 = c(1, 
    2)), class = "data.frame", row.names = c(NA, -2L))
    
    > data
      Col_a_b1 Col_a_b94
    1    Name1         1
    2    Name2         2
    
    colnames(data) <- sprintf("Col_a_b%02d", parse_number(colnames(data)))
    
    > data
      Col_a_b01 Col_a_b94
    1     Name1         1
    2     Name2         2
    

  • answered 2022-03-25 08:31 PaulS

    With a tidyverse approach:

    library(tidyverse)
    
    names <- c("Col_a_b1", "Col_a_b2", "Col_a_b3", "Col_a_b4", "Col_a_b5", "Col_a_b6", "Col_a_b7", "Col_a_b8", "Col_a_b9", "Col_a_b10", "Col_a_b11")
    
    names %>% 
      str_split("(?<=Col_a_b)(?=\\d+)") %>% 
      map_chr(~ str_c(.x[1], str_pad(.x[2], width = 2, pad = "0")))
    
    #>  [1] "Col_a_b01" "Col_a_b02" "Col_a_b03" "Col_a_b04" "Col_a_b05" "Col_a_b06"
    #>  [7] "Col_a_b07" "Col_a_b08" "Col_a_b09" "Col_a_b10" "Col_a_b11"
    

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum