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
You can do it using setnames from library(data.table)
library(data.table)
setnames(DF, "oldName", "newName")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With