![](/img/trans.png)
[英]Creating new variables with dplyr::mutate() without conflicting names
[英]dplyr: apply sequential functions to variables without creating new variables in a single mutate(across(...))
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(...))
选择。
根据对 cross 的参考,我们可以在列表中提供多个函数或 purrr 风格的 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(...))
调用中是可能的吗?
所以你想先取这些变量的mean
,然后把它们变成factor
?
这可以通过以下方式实现:
library(dplyr)
mtcars %>% mutate(across(c('mpg', 'cyl'),~factor(mean(.))))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.