QuestionAnswer QuestionAnswer - 1 year ago 90
R Question

Conditional renaming of data frame columns

I have (1) a data frame with many columns (

), (2) a character vector whose elements may or may not be the names of the data frame columns (
), and (3) a character containing strings that should replace each element of the aforementioned vector if the data frame contains the specified column (

df <- data.frame(
dat = rep(1:2),
bat = seq(1:2),
cat = c("foo","bar"))

search_for_these <- c("dat", "bat", "shoe", "box")
replace_with_these <- c("cow", "bat2", "shoes", "boxes")

My goal is to replace any element of
found in
with the value found in the same index of
. The desired result is therefore:

df <- data.frame(
cow = rep(1:2),
bat2 = seq(1:2),
cat = c("foo","bar"))

I thought of using
for this but it's not clear how to actually implement this.

Answer Source

We can do this with match

i1 <- match(colnames(df), search_for_these, nomatch = 0)
colnames(df)[i1] <- replace_with_these[i1]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download