Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I make this R code to format integers with leading zero more succinct?

I have created a function called interval which takes two numbers as input between 1 and 12 and if the number is less than 10, it appends a 0 to the front. e.g. 4 becomes 04, but 11 stays 11.

interval <- function(month_start = 1, month_end = 12){
    month_range <- as.character(c(month_start:month_end))
    month_range_char <- month_range %>% 
      map(
        ~if(as.numeric(.x)<10){
          paste0("0",.x)
        }
        else{
          .x
        }
      )
return(month_range_char)

}

I feel like I have written a lot of code to do quite a simple thing. Is there an obvious way to improve this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Try:

x <- 1:12

ifelse(x < 10, paste0("0", x), x)

Output:

[1] "01" "02" "03" "04" "05" "06" "07" "08" "09" "10" "11" "12"

Since vectors all have to be the same type, they will all return characters so you dont need the switching back and forth between as.character and as.numeric as in your code.

Or if you want to wrap in a function:

add0 <- function(input){
  ifelse(x < 10, paste0("0", input), input)
}

Or perhaps the best way is as @MrFlick says in the comments (since not everyone reads them)

sprintf("%02d", x) #Thanks @MrFlick
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading