-1

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:

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!

TarJae
  • 72,363
  • 6
  • 19
  • 66
  • 2
    Can you please clarify _why_ you want to use `rename_with` when you already have a vector with new column names. I assume you know that `rename_with` needs a `.fn` argument: "A function used to transform the selected `.cols`". Cheers – Henrik Nov 06 '21 at 22:20
  • It is mainly for learning purposes. I am still learning. Within this process I develop an idea. Then I try to apply this idea to practice by doing some research. And if I don't find a solution like in this case it was not possible for me to grasp exactly this function need of `rename_with`, I ask a question here. Thank you for reply. – TarJae Nov 06 '21 at 22:30

1 Answers1

3

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.

MrFlick
  • 195,160
  • 17
  • 277
  • 295
  • Ok. That is what I was exactly looking for. So the vector is becoming a function by ~? – TarJae Nov 06 '21 at 22:31
  • 1
    `~` makes it a formula, which the tidyverse treats as a kind of anonymous function. Note that this isn't true for R in general. – Migwell Nov 07 '21 at 03:31
  • 1
    @Migwell Thank you very much. Now it is much more clearer for me. The `with` part in `rename_with` refers to the fact that this function needs a function that will be applied to each column of the dataframe and how a vector could fulfill this request. Now I understand why people downvoted my question. But for me it was not logical to have a function that renames column names, but is not able to rename the column names that are stored in a vector. – TarJae Nov 07 '21 at 06:31