pads numbers in file-names in R

43 Views Asked by At

i used

PadNumbers <- function(numbers) {
  assertIntegerish(numbers, min.len = 0, lower = 0)
  strnumbers <- as.character(numbers)
  numbers <- as.numeric(gsub(".*?(\\d+).*", "\\1", strnumbers))
  if (any(!is.na(numbers))) {
    maxdigits <- max(nchar(as.character(numbers)), na.rm = TRUE)
  } else {
    maxdigits <- 0
  }
  paddednumbers <- sprintf(paste0("%0", maxdigits, "d"), numbers)
  paddednumbers[is.na(numbers)] <- NA
  return(paddednumbers)
}

so that : ex01PadNumbers(c(1, 2, 30)) outputs c("01", "02", "30")

and i want to pads numbers in file-names like in

PadNumbers

so that : ex02PadFiles(c("podcast_ep1.mp3", "podcast_ep3.mp3", "podcast_ep22.mp3"))

outputs c("podcast_ep01.mp3", "podcast_ep03.mp3", "podcast_ep22.mp3")

ex02PadFiles <- function(filenames) {
  assertCharacter(filenames, any.missing = FALSE, len = length(filenames))
  if (length(filenames) == 0) {
    return(character(0))
  }
  paddednumbers <- ex01PadNumbers(as.integer(gsub("\\D", "", filenames)))
  paddedfilenames <- gsub("(\\d+)(\\.\\w+)$", "0\\1\\2", filenames)
  return(paddedfilenames)
}

but my output is: c("podcast_ep01.mp3", "podcast_ep03.mp3", "podcast_ep022.mp3") but the last element should remain since there are already two digits

i changed the code and it didnt work

1

There are 1 best solutions below

1
HoelR On
library(tidyverse)

strings <- c("podcast_ep1.mp3", "podcast_ep3.mp3", "podcast_ep22.mp3")

pad_numbers <- function(string) {
  num <- str_extract_all(string, "\\d+") %>% 
    pluck(1, 1) 
  
  str_replace(string = string, 
              pattern = num, 
              replacement = if_else(str_length(num) < 2, str_c("0", num), num))

}

map_chr(strings, pad_numbers)

[1] "podcast_ep01.mp3" "podcast_ep03.mp3" "podcast_ep22.mp3"