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

  • A+
Category:Languages

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     

 


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 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: