I would like to rename many variable names using a function. For example, adding ‘demo’ to each one of the variable names for age, gender, but NOT for zipcode, addresses.
So far, I have:
demo <- function(x)
{
data$demo_x <- data$x
}
demo("age")
demo("gender")
I’ve tried paste0 function and some suggestions below. However, I only want to change some of the variables – not all the variables in my dataset.
>Solution :
Using dplyr:
library(dplyr)
data |>
rename_with(\(x) paste0("demo", x))
A benefit of using dplyr is rename_with allows you to use tidyselect syntax to only apply these name changes to a subset of columns (e.g. rename_with(\(x) paste0("demo", x), where(is.numeric)) to only rename numeric columns).
In base R:
names(data) <- paste0("demo", names(data))