简体   繁体   中英

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!

Try this:

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

Thanks @RicardoVillalba for correction.

You could use transmute and across to generate the new columns for those column names ending in "x". Then, use rename_with to add the "_new" suffix and bind_cols back to the original data frame.

library(dplyr)

df <- df %>% 
  transmute(across(ends_with("x"), ~ . * 2)) %>% 
  rename_with(., ~ paste0(.x, "_new")) %>% 
  bind_cols(df, .)

Result:

head(df)

  id     a1_x      a1_y     a2_x  a1_x_new  a2_x_new
1  1 4.662952 0.4152313 8.706219  9.325905 17.412438
2  2 2.078233 1.4834044 3.317145  4.156466  6.634290
3  3 7.996580 1.4035441 4.834126 15.993159  9.668252
4  4 6.518713 7.0844794 8.457379 13.037426 16.914759
5  5 3.215092 3.5578827 8.196574  6.430184 16.393149
6  6 7.189275 5.2277208 3.712805 14.378550  7.425611

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM