Hi there,
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:
Although, the interface for rename_if is a bit weird. For the predicate argument I had to pass it a logical vector with length ncol(dat); it didn't work as expected when I used a function object in the predicate argument.
Also, not sure if this is relevant since I haven't seen your exact code, but pivot_wider does have a 'names_prefix' argument. If it would work in your actual situation to add names_prefix = "000" then that's probably the way to go.
Thanks for the suggestions, but I think maybe I should have specified more clearly the result I was looking for? The original variables are auto-numbered like this: DIAG_1, DIAG_2, DIAG_3, DIAG_4, DIAG_5, DIAG_6, DIAG_7, DIAG_8, DIAG_9, DIAG_10
What I need is the leading zero on the number... DIAG_01, DIAG_02, DIAG_03, DIAG_04, DIAG_05, DIAG_06, DIAG_07, DIAG_08, DIAG_09, DIAG_10
But yes, they are both good solutions, and I can see how they would work. Thanks very much Technocrat and Gabriel!!!
Simple approach, but obviously depends on the consistency of single numbered variables being the only ones with an underscore as second from last character.