I want to write a function that checks if the colnames of a dataframe exist in a list. If they do, I want to replace the names with those found in the list.
df <- data.frame(a = 1, b = 2, c = 3, d = 4)
replacements <- list(a = "a1", b = "b1", c = "c1")
I have written a function to do this, but it contains loops, which I would like to avoid.
rename_cols <- function(df) {
for(i in 1:length(df)) {
for(j in 1:length(replacements)) {
if(names(df)[i] == names(replacements)[j]) {
names(df)[i] <- replacements[[j]]
}
}
}
return(df)
}
I feel like I'm overthinking this. Please help.