Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rename specific variable of a data frame with setNames()?

Tags:

r

To rename a specific variable I can do for instance

names(df1)[which(names(df1)  == "C")] <- "X"
> df1
  A B X
1 1 2 3

I wonder if this is also possible with setNames(), but without repeating the names I don't want to rename as in

df1 <- setNames(df1, c("A", "B", "X"))`

I've tried setNames(df1, c(rep(NA, 2), "X")) and setNames(df1[3], "X") but this won't work. The advantage I see in setNames() is that I can set names while doing other stuff in one step.

Data

df1 <- setNames(data.frame(matrix(1:3, 1)), LETTERS[1:3])
> df1
  A B C
1 1 2 3    
like image 862
jay.sf Avatar asked Nov 06 '18 08:11

jay.sf


2 Answers

You can use replace,

setNames(df1, replace(names(df1), names(df1) == 'B', 'X'))
#  A X C
#1 1 2 3
setNames(df1, replace(names(df1), names(df1) == 'A', 'X'))
#  X B C
#1 1 2 3
setNames(df1, replace(names(df1), names(df1) == 'C', 'X'))
#  A B X
#1 1 2 3
like image 187
Sotos Avatar answered Sep 30 '22 14:09

Sotos


You can do it using setnames from library(data.table)

library(data.table)

setnames(DF, "oldName", "newName")
like image 35
Hunaidkhan Avatar answered Sep 30 '22 16:09

Hunaidkhan