[英]dplyr: apply sequential functions to variables without creating new variables in a single mutate(across(...))
tl;dr -- is it possible to use dplyr syntax to apply more than one function to a selection of variables in a single call to mutate(across(...))
, without creating extra variables? tl; dr - 是否可以使用 dplyr 语法在一次对
mutate(across(...))
调用中将多个函数应用于一组变量,而无需创建额外的变量?
By way of example, say we want to apply mean
and factor
to mpg
and cyl
.举例来说,假设我们要将
mean
和factor
应用于mpg
和cyl
。 We can do this by repeating ourselves:我们可以通过重复自己来做到这一点:
library(dplyr)
# desired output (but we repeat ourselves)
mtcars %>%
mutate(
across(c('mpg', 'cyl'),
mean
)
) %>%
mutate(
across(c('mpg', 'cyl'),
factor
)
)
I want to avoid repeating the mutate(across(...))
selection.我想避免重复
mutate(across(...))
选择。
According to the reference for across , we can supply multiple functions or purrr-style lambdas in a list.根据对 cross 的参考,我们可以在列表中提供多个函数或 purrr 风格的 lambdas。 However, I can't figure out how to mutate in place (overwrite the variable), rather than creating new variables.
但是,我无法弄清楚如何就地变异(覆盖变量),而不是创建新变量。
Of course, applying a single function at a time does not create new variables with default parameters:当然,一次应用一个函数不会创建带有默认参数的新变量:
# 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()
But passing in a list creates new variables:但是传入一个列表会创建新的变量:
# 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(.)
)
)
)
I've tried to specify the variable names directly with .names
, but this does not work:我试图直接用
.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}"
)
)
Is this possible in a single mutate(across(...))
call?这在单个
mutate(across(...))
调用中是可能的吗?
So you want to first take mean
of those variables and then turn them into factor
?所以你想先取这些变量的
mean
,然后把它们变成factor
?
This can be achieved by :这可以通过以下方式实现:
library(dplyr)
mtcars %>% mutate(across(c('mpg', 'cyl'),~factor(mean(.))))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.