1

My goal is to get a concise way to rename multiple columns in a data frame. Let's consider a small data frame df as below:

df <- data.frame(a=1, b=2, c=3)
df 

Let's say we want to change the names from a, b, and c to Y, W, and Z respectively. Defining a character vector containing old names and new names.

df names <- c(Y = "a", Z ="b", E = "c")

I would use this to rename the columns,

rename(df, !!!names)
df

suggestions?

Jaweed
  • 11
  • 2
  • 1
    `rename(df, !!!names)` works fine for me. You could check you have attached `dplyr` package. – Darren Tsai Jun 15 '22 at 01:56
  • 2
    @DarrenTsai - my eyesight must be getting worse or i'm just having a bad day. I could have sworn the original question had only two `!!`'s in it. – thelatemail Jun 15 '22 at 02:55

2 Answers2

2

One more !:

df <- data.frame(a=1, b=2, c=3)
df_names <- c(Y = "a", Z ="b", E = "c")
library(dplyr)
df %>% rename(!!!df_names)
##  Y Z E
##1 1 2 3

A non-tidy way might be through match:

names(df) <- names(df_names)[match(names(df), df_names)]
df
##  Y Z E
##1 1 2 3
thelatemail
  • 91,185
  • 12
  • 128
  • 188
0

You could try:

sample(LETTERS[which(LETTERS %in% names(df) == FALSE)], size= length(names(df)), replace = FALSE)
[1] "S" "D" "N"

Here, you don't really care what the new names are as you're using sample. Otherwise a straight forward names(df) < c('name1', 'name2'...

Chris
  • 1,647
  • 1
  • 18
  • 25