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

Create columns based on other columns names R

I need to operate columns based on their name condition. In the following reproducible example, per each column that ends with ‘x’, I create a column that multiplies by 2 the respective variable:

library(dplyr)
set.seed(8)
id <- seq(1,700, by = 1)
a1_x <- runif(700, 0, 10)
a1_y <- runif(700, 0, 10)
a2_x <- runif(700, 0, 10)

df <- data.frame(id, a1_x, a1_y, a2_x)

#Create variables manually: For every column that ends with X, I need to create one column that multiplies the respective column by 2
df <- df %>%
  mutate(a1_x_new = a1_x*2,
         a2_x_new = a2_x*2)

Since I’m working with several columns, I need to automate this process. Does anybody know how to achieve this? Thanks in advance!

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 :

Try this:

df %>% mutate(
    across(ends_with("x"), ~ .x*2, .names = "{.col}_new")
)

Thanks @RicardoVillalba for correction.

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