我想编写一个简单的函数,该函数将利用调用中通过省略号传递的 quosures mutate_at
。
# Packages
sapply(
X = c("dplyr", "rlang"),
FUN = require,
character.only = TRUE
)
# Data
set.seed(1)
cbind(as.data.frame(replicate(3, replicate(
10, paste0(sample(letters, 5), collapse = "")
))), c(1:10)) %>% setNames(nm = paste(replicate(4, "col"), LETTERS[1:4], sep = "_")) -> dta
# Mutate
mutate_some <- function(df, ...) {
mut_vars <- quos(...)
df %>%
mutate(.vars = !!!mut_vars,
.funs = funs(toupper(.)))
}
# test
dta %>% mutate_some(col_A, col_C)
问题
代码产生:
>> dta %>% mutate_some(col_A, col_C)
col_A col_B col_C col_D .vars1 .vars2 .funs
1 gjnue mvkfb rigwn 1 gjnue rigwn ~toupper(.)
2 xzpob chmpi fdlvn 2 xzpob fdlvn ~toupper(.)
3 feqix xhlyo zsijd 3 feqix zsijd ~toupper(.)
4 mrxiy glsbt arcko 4 mrxiy arcko ~toupper(.)
5 yfpcz iuzhk zmldq 5 yfpcz zmldq ~toupper(.)
6 kajuh xvjry lmefn 6 kajuh lmefn ~toupper(.)
7 moles lrjhq obazu 7 moles obazu ~toupper(.)
8 rtcqj frczd pomwl 8 rtcqj pomwl ~toupper(.)
9 vqsml gbpur rpfxq 9 vqsml rpfxq ~toupper(.)
10 ualqp uljsn lerct 10 ualqp lerct ~toupper(.)
期望的结果
结果应该等同于:
dta %>% mutate_at(.funs = funs(toupper(.)), .vars = c("col_A", "col_C"))
col_A col_B col_C col_D
1 GJNUE mvkfb RIGWN 1
2 XZPOB chmpi FDLVN 2
3 FEQIX xhlyo ZSIJD 3
4 MRXIY glsbt ARCKO 4
5 YFPCZ iuzhk ZMLDQ 5
6 KAJUH xvjry LMEFN 6
7 MOLES lrjhq OBAZU 7
8 RTCQJ frczd POMWL 8
9 VQSML gbpur RPFXQ 9
10 UALQP uljsn LERCT 10
假设:
该
mutate_some
函数必须采用 ellipsis 参数,该参数在mut_vars <- quos(...)
.特别是,我正在寻找一种类似于
rlang::do_something_(mut_vars)
. 此功能是较长管道的一部分,我需要保留mut_vars
,quos()
因为我稍后会使用它。我不想更改列名(如上面所需的结果)。