I am trying to rename columns programmatically. I have several numbered columns of two types (DIAG_ and OPER_) which are created from a pivot_wider call. They need to have leading zeroes for later use, but don't when they are reshaped.
I have been trying this approach, but it doesn't do what is intended:
dat <- tibble(DIAG_1 = runif(10), DIAG_2 = runif(10), DIAG_3 = runif(10), DIAG_4 = runif(10), OPER_1 = runif(10), OPER_2 = runif(10), OPER_3 = runif(10), OPER_4 = runif(10)) prefixes <- c('DIAG_', 'OPER_') prefixes %>% map(grep, x=names(dat)) %>% map2(prefixes, ~function(x, y) names(dat)[x] <- paste0(y, str_pad(1:length(x), width = 2, pad = '0')))
Any help on how to add leading zeroes to various auto-numbered columns would be gratefully accepted!