【问题标题】:How to use a list of variables with dplyr across?如何在 dplyr 中使用变量列表?
【发布时间】:2021-02-21 23:56:00
【问题描述】:

我觉得应该有一个非常简单的方法来做到这一点,但我想不通。我想在大型数据集中使用 across 和变量列表和 tidyselect 助手,但我将使用 iris 作为示例。

在 dplyr 1.0 更新之前,我可以像这样成功地使用作用域动词:

VARS <- vars(Sepal.Length, starts_with("Petal"))
iris %>% 
  mutate_at(VARS, as.character)

我认为iris %&gt;% mutate(across(!!!VARS, as.character)) 会起作用,但我得到了一个错误。我知道更新取代了vars,但我无法使用listc 保存变量。

请帮忙!寻找优雅的 tidyverse 解决方案。

【问题讨论】:

    标签: r dplyr rlang across


    【解决方案1】:

    vars 自 dplyr 1.0.0 起已被取代。您可以直接将列名用作across 中的字符串或不带引号的变量。

    library(dplyr)
    iris %>% 
      mutate(across(c(Sepal.Length, starts_with("Petal")), as.character))
    

    如果你想先保存变量,然后应用你可以做的功能。

    VARS <- c('Sepal.Length', grep('^Petal', names(iris), value = TRUE))
    
    iris %>% mutate(across(VARS, as.character)) 
    

    【讨论】:

    • 我正在专门寻找一个将列名保存为变量的答案,然后在 cross 中调用它们
    • @KateHam 查看更新的答案。这对你的目的有帮助吗?
    【解决方案2】:

    有很多选项供您选择。

    library(dplyr)
    VARS1 <- quote(c(Sepal.Length, starts_with("Petal")))
    VARS2 <- expr(c(Sepal.Length, starts_with("Petal")))
    VARS3 <- quo(c(Sepal.Length, starts_with("Petal")))
    

    输出

    > iris %>% mutate(across(!!VARS1, as.character)) %>% str()
    'data.frame':   150 obs. of  5 variables:
     $ Sepal.Length: chr  "5.1" "4.9" "4.7" "4.6" ...
     $ Sepal.Width : num  3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
     $ Petal.Length: chr  "1.4" "1.4" "1.3" "1.5" ...
     $ Petal.Width : chr  "0.2" "0.2" "0.2" "0.2" ...
     $ Species     : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...
    
    > iris %>% mutate(across(!!VARS2, as.character)) %>% str()
    'data.frame':   150 obs. of  5 variables:
     $ Sepal.Length: chr  "5.1" "4.9" "4.7" "4.6" ...
     $ Sepal.Width : num  3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
     $ Petal.Length: chr  "1.4" "1.4" "1.3" "1.5" ...
     $ Petal.Width : chr  "0.2" "0.2" "0.2" "0.2" ...
     $ Species     : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...
    
    > iris %>% mutate(across(!!VARS3, as.character)) %>% str()
    'data.frame':   150 obs. of  5 variables:
     $ Sepal.Length: chr  "5.1" "4.9" "4.7" "4.6" ...
     $ Sepal.Width : num  3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
     $ Petal.Length: chr  "1.4" "1.4" "1.3" "1.5" ...
     $ Petal.Width : chr  "0.2" "0.2" "0.2" "0.2" ...
     $ Species     : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...
    

    【讨论】:

      猜你喜欢
      • 2018-05-22
      • 1970-01-01
      • 2016-03-17
      • 1970-01-01
      • 1970-01-01
      • 2019-01-27
      • 2021-04-11
      • 1970-01-01
      相关资源
      最近更新 更多