[英]Create columns based on other columns names R
我需要根据它们的名称条件来操作列。 在以下可重现的示例中,对于每个以“x”结尾的列,我创建了一个将相应变量乘以 2 的列:
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)
由于我正在处理多个列,因此我需要自动执行此过程。 有谁知道如何实现这一目标? 提前致谢!
尝试这个:
df %>% mutate(
across(ends_with("x"), ~ .x*2, .names = "{.col}_new")
)
感谢@RicardoVillalba 的更正。
您可以使用transmute
和across
为那些以“x”结尾的列名称生成新列。 然后,使用rename_with
将“_new”后缀和bind_cols
回原始数据框。
library(dplyr)
df <- df %>%
transmute(across(ends_with("x"), ~ . * 2)) %>%
rename_with(., ~ paste0(.x, "_new")) %>%
bind_cols(df, .)
结果:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.