【问题标题】:dplyr: apply sequential functions to variables without creating new variables in a single mutate(across(...))dplyr:将顺序函数应用于变量而不在单个 mutate(across(...)) 中创建新变量
【发布时间】:2020-10-28 01:35:14
【问题描述】:

tl;dr -- 是否可以使用 dplyr 语法在一次调用 mutate(across(...)) 时将多个函数应用于选择的变量,而无需创建额外的变量?

举例来说,假设我们要将meanfactor 应用于mpgcyl。我们可以通过重复自己来做到这一点:

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(...)) 调用中实现吗?

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    所以你想先从这些变量中取出mean,然后把它们变成factor

    这可以通过以下方式实现:

    library(dplyr)
    
    mtcars %>% mutate(across(c('mpg', 'cyl'),~factor(mean(.)))) 
    

    【讨论】:

    • 哈哈!我想我已经说服自己该解决方案将涉及棘手的语法,甚至没有考虑最简单和最明显的方法。谢谢罗纳克。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-11
    • 2018-08-13
    相关资源
    最近更新 更多