Home > OS >  sequential column names add 0
sequential column names add 0

Time:03-25

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.

CodePudding user response:

One way to do is

    #column names 
    nam = c( 'Col_a_b1',   'Col_a_b2' ,  'Col_a_b3')
    #extract the numer
    num = parse_number(nam)
    #remove the numbers
    nam = gsub('[0-9] ', '', nam)
    #add 0
    mod_nam = paste0(nam, 0,num)
    [1] "Col_a_b01" "Col_a_b02" "Col_a_b03"

CodePudding user response:

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"

CodePudding user response:

For a given dataframe called data:

colnames(data) <- sprintf("Col_a_bd", parse_number(colnames(data)))

d 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_bd", parse_number(colnames(data)))

> data
  Col_a_b01 Col_a_b94
1     Name1         1
2     Name2         2
  • Related