Renaming variables meeting specific criteria

Hi, I have this simple df:

URN = c("aaa","bbb","ccc", "ddd","eee","fff","ggg","hhh"),
                         Name = c("xxx","xxx","yyy", "yyy","yyy","zzzz","abcde","zzzz"),
                          A1 = c("None.",NA,
                                            "No comments related to this exercise","Na",
                                            "N/A","Interesting comment","abc", "whatever is fine"),
                          A2 = c("Nothing",
                                            "I have nothing in common","NA",NA,
                                            "Another comment","....?","xxxx", "All fine"),
                          B1 = c("Service","All good",
                                            "aa","I don't know",
                                            "The final comment about that","Nothing.","na","Everything"),
                          B2 = c("aaa","Nothing",
                                              "None","My final comments are ok", "I don't know",
                                              "Nothing.","Another comment","really"),
                                                                       Q4 = c(2019,2020,2020,2019,
                                                                              2020,2021,2021,2019)
                     )

Can you help me to add "Comm" in the beginning or in the end of each variable name which is a character type and has responses longer than 15 characters (so URN and Name would be excluded from renaming)?
How would I rename just these variables? Shall I use this piece of the code somehow?

where(~is.character(.x) & any(nchar(.x) > 15)

How can I do that?

Thank you for your help.

rename_with(example_df,
            .fn=function(name){paste0("Comm_",name)},
            .cols=where(~is.character(.x) & 
                          any(nchar(.x) > 15)))

or more succinctly

rename_with(example_df,
            .fn=~paste0("Comm_",.),
            .cols=where(~is.character(.x) & 
                          any(nchar(.x) > 15)))
1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.