nouse
nouse

Reputation: 3461

Change column names by looking up new names in another dataframe

I have a dataframe with a set of column names ("A", "B"):

df <- data.frame(A=c(1,2), B=c(1,3))

I want to exchange the column names with new ones, which are provided in a new dataframe:

new.names <- data.frame(Old=c("A","B"), New=c("C","D"))

I want R to browse new.names$Old for matches in colnames(df) and exchange colnames(df) with what it has found in new.names$New. It is basically a variant of excel's vlookup. Thank you.

Upvotes: 4

Views: 1129

Answers (1)

G5W
G5W

Reputation: 37641

You can do this with match

colnames(df) = new.names$New[match(colnames(df), new.names$Old)]

Upvotes: 4

Related Questions