【发布时间】:2020-10-28 01:35:14
【问题描述】:
tl;dr -- 是否可以使用 dplyr 语法在一次调用 mutate(across(...)) 时将多个函数应用于选择的变量,而无需创建额外的变量?
举例来说,假设我们要将mean 和factor 应用于mpg 和cyl。我们可以通过重复自己来做到这一点:
library(dplyr)
# desired output (but we repeat ourselves)
mtcars %>%
mutate(
across(c('mpg', 'cyl'),
mean
)
) %>%
mutate(
across(c('mpg', 'cyl'),
factor
)
)
我想避免重复 mutate(across(...)) 选择。
根据reference for across,我们可以在一个列表中提供多个函数或purrr-style lambdas。但是,我不知道如何就地变异(覆盖变量),而不是创建新变量。
当然,一次应用一个函数不会创建具有默认参数的新变量:
# single mean function mutates in place
mtcars %>%
mutate(
across(c('mpg', 'cyl'),
~mean(.)
)
)
# single factor function mutates in place
mtcars %>%
mutate(
across(c('mpg', 'cyl'),
~factor(.)
)
) %>%
glimpse()
但是传入一个列表会创建新的变量:
# this creates new vars
mtcars %>%
mutate(
across(c('mpg', 'cyl'),
.fns = list(
mean, factor
)
)
)
# as does this
mtcars %>%
mutate(
across(c('mpg', 'cyl'),
.fns = list(
~mean(.), ~factor(.)
)
)
)
我试过直接用.names指定变量名,
但这不起作用:
# trying to specify that we want to preserve
# the original names with {col} leads to a
# duplicated names error
mtcars %>%
mutate(
across(c('mpg', 'cyl'),
.fns = list(
mean, factor
),
.names = "{col}"
)
)
# the same occurs with purrr-style lambda syntax
mtcars %>%
mutate(
across(c('mpg', 'cyl'),
.fns = list(
~mean(.), ~factor(.)
),
.names = "{col}"
)
)
这可以在单个mutate(across(...)) 调用中实现吗?
【问题讨论】: