Reputation: 3471
df <- data.frame(A=1, B=2, C=3)
new.names <- data.frame(old=c("A","B","C"), new=c("X", "Y", "Z"))
How can i look up names(df)
in new.names$old
and replacing them with new.names$new
?
Desired output:
names(df)
[1] "X" "Y" "Z"
Upvotes: 2
Views: 42
Reputation: 79348
library(tidyverse)
df <- rename(df, !!invoke(set_names, unname(new.names)))
df
X Y Z
1 1 2 3
Upvotes: 1
Reputation: 334
Two ways come to mind: base R and data.table
. I changed the order of the names just to show that the look-up is working.
Instead of a data.frame with the names, I would use a named vector (using the old names as names of the components of this vector):
df <- data.frame(A=1, B=2, C=3)
new_names <- setNames(c("Y", "X", "Z"), c("B","A","C"))
names(df) <- new_names[names(df)]
data.table
More straightforward:
library(data.table)
df <- data.frame(A=1, B=2, C=3)
setnames(df, old = c("B","A","C"), new = c("Y", "X", "Z"))
# Note that setnames() doesn't return anything. You can
# run names(df) for seeing the result.s
Upvotes: 1
Reputation: 79311
In plyr
package we could use mapvalues
function
library(plyr)
df_new <- df
colnames(df_new) <- plyr::mapvalues(colnames(df),
as.character(new.names$old),
as.character(new.names$new))
Output:
> df_new
X Y Z
1 1 2 3
Upvotes: 1
Reputation: 40171
One way to do it could be:
names(df) <- new.names$new[match(new.names$old, names(df))]
X Y Z
1 1 2 3
Upvotes: 2