Reputation: 71
I would like to rename multiple columns in a data frame with a function.
Data frame
nameAXX = c("car1", "car2", "car2", "car2", "car3", "car1")
brand = c("b1", "b2", "b2", "b2", "b3", "b1")
productionAXX = c(10, 10, 10, 40, 10, 5)
df = data.frame(brand, nameAXX, productionAXX)
The loop itself works but not if I wrap it in a function and call it.
replaceColNamePattern <- function(df, pattern, replace){
for (name in colnames(df)){
if (regexpr(pattern, name) > 0){
names(df)[names(df)==name] <- gsub(pattern, replace, name)
}
}
}
Call function
replaceColNamePattern(adf, "AXX", "")
Is it not possible to rename the column within a function?
Upvotes: 1
Views: 1909
Reputation: 20369
Besides the excellent answers of akrun et. alii, the reason why your code is not working as intended is because you change the name of df
in the scope of the function (and only there). You would need to return df
and assign it back to the original variable:
replaceColNamePattern2 <- function(df, pattern, replace){
names(df) <- gsub(pattern, replace, names(df))
df
}
(df <- replaceColNamePattern2(df, "AXX", ""))
# brand name production
# 1 b1 car1 10
# 2 b2 car2 10
# 3 b2 car2 10
# 4 b2 car2 40
# 5 b3 car3 10
# 6 b1 car1 5
Upvotes: 2