QuestionAnswer QuestionAnswer - 1 year ago 99
R Question

Conditional renaming of data frame columns

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

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

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
search_for_these
found in
colnames(df)
with the value found in the same index of
replace_with_these
. The desired result is therefore:

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


I thought of using
dplyr::contains()
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