Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

paste a string to many column names using a function in R

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading