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?
CodePudding user response:
Try:
x <- 1:12
ifelse(x < 10, paste0("0", x), x)
# and to force a character variable, per comment from @Miff
as.character(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("d", x) #Thanks @MrFlick
CodePudding user response:
Another way:
test <- as.character(c(5, 10))
library(stringr)
ifelse(str_length(test) == 1, str_pad(test, 2, pad = "0"), test)
[1] "05" "10"