Home > Blockchain >  How to rename multiple Columns in R?
How to rename multiple Columns in R?

Time:06-15

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?

CodePudding user response:

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

CodePudding user response:

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'...

  • Related