irene
irene

Reputation: 29

How to write a function to rename multiples columns at once?

df1 <- df %>% 
  rename(newcol1 = oldcol1) %>% 
  rename(newcol2 = oldcol2) %>% 
  rename(newcol3 = oldcol3) %>% 
  rename(newcol4 = oldcol4) %>% 
  rename(newcol5 = oldcol5) 

I am trying to write a function, which I just learned, that will do the same thing as above.

renaming = function(df, oldcol, newcol) {
rename(df, newcol = oldcol)

but then I am not sure how to do with the multiple columns.. any help would be much appreciated!

Upvotes: 0

Views: 100

Answers (2)

DanY
DanY

Reputation: 6073

Using base R

names(df) <- c("newname1", "newname2", "newname3") # for all varnames
names(df)[c(1,3,4)] <- c("newname1", "newname3", "newname4") # for varnames 1,3,4
names(df)[names(df) == "oldname"] <- "newname" # for one varname

Using data.table

setnames(dt, old=c("oldname1", "oldname2"), new=c("newname1", "newname2"))

Using dplyr/tidyverse

df %>% rename(newname1 = oldname1, newname2 = oldname2)

Upvotes: 1

Vivek Katial
Vivek Katial

Reputation: 626

You can use set_names from the tidyverse package purrr.

Reproducible example:

> df <- iris
> df1 <- df %>% 
     purrr::set_names(c("d","x","y","z","a"))

> df1
      d   x   y   z          a
1   5.1 3.5 1.4 0.2     setosa
2   4.9 3.0 1.4 0.2     setosa
3   4.7 3.2 1.3 0.2     setosa

Upvotes: 0

Related Questions