在较新版本的dplyr中,我们可以使用across
library(dplyr)
library(stringr)
iris %>%
rename(Sepal = Sepal.Width, Petal = Petal.Width) %>%
mutate(across(c('Sepal', 'Petal'), ~
./get(str_c(cur_column(), '.Length')), .names = '{.col}_test'))
-输出
# Sepal.Length Sepal Petal.Length Petal Species Sepal_test Petal_test
#1 5.1 3.5 1.4 0.2 setosa 0.6862745 0.14285714
#2 4.9 3.0 1.4 0.2 setosa 0.6122449 0.14285714
#3 4.7 3.2 1.3 0.2 setosa 0.6808511 0.15384615
#4 4.6 3.1 1.5 0.2 setosa 0.6739130 0.13333333
#5 5.0 3.6 1.4 0.2 setosa 0.7200000 0.14285714
#6 5.4 3.9 1.7 0.4 setosa 0.7222222 0.23529412
#7 4.6 3.4 1.4 0.3 setosa 0.7391304 0.21428571
#8 5.0 3.4 1.5 0.2 setosa 0.6800000 0.13333333
# ...
我们不需要重命名只是为了做除法。也可以通过保留原来的列名来实现
iris %>%
mutate(across(ends_with('Width'), ~
./get(str_replace(cur_column(), 'Width', 'Length')),
.names = '{.col}_test'))
. 返回值而不是列名。因此,paste0(., '.Length') 将使用相应的列值粘贴子字符串 .Length