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 to use rename_with() in pipe to change all column names from vector

I want to apply new column names from a vector to a dataframe.

There are already good answers to this question:
Applying dplyr's rename to all columns while using pipe operator, How do I add a prefix to several variable names using dplyr?

My question is explicitly:
What is the equivalent of rename_with to 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

newcolnames <- c("one", "two", "three", "four", "five")

head(iris) %>% 
  setNames(newcolnames)

head(iris) %>% 
  `colnames<-`(newcolnames)

I tried:

head(iris) %>% 
  rename_with(iris, newcolnames)

I want to use explicitly rename_with!

>Solution :

It doesn’t seem like rename_with is the right function for this. I guess you could do

iris %>% 
  rename_with(~newcolnames)

as kind of a hack. You can also use rename

iris %>% 
  rename(!!!setNames(names(.), newcolnames))

But the setNames method just seems much more apt.

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