rlang:将多个带有...的组传递给gather()

2024-04-02

假设我想计算mean, min and max对于自定义函数中任意数量的组。

玩具数据如下所示:

library(tidyverse)
df <- tibble(
  Gender = c("m", "f", "f", "m", "m", 
             "f", "f", "f", "m", "f"),
  IQ = rnorm(10, 100, 15),
  Other = runif(10),
  Test = rnorm(10),
  group2 = c("A", "A", "A", "A", "A",
             "B", "B", "B", "B", "B")
)

为了实现两个组(性别,组2)的目的,我可以使用

df %>% 
  gather(Variable, Value, -c(Gender, group2)) %>% 
  group_by(Gender, group2, Variable) %>% 
  summarise(mean = mean(Value), 
            min = min(Value), 
            max = max(Value)) 

可以与新的集成curly-curly运营商来自rlang with

descriptive_by <- function(data, group1, group2) {
  data %>% 
    gather(Variable, Value, -c({{ group1 }}, {{ group2 }})) %>% 
    group_by({{ group1 }}, {{ group2 }}, Variable) %>% 
    summarise(mean = mean(Value), 
              min = min(Value), 
              max = max(Value))
}

通常,我会假设我可以用以下内容替换指定的组...,但似乎不是这样工作的

descriptive_by <- function(data, ...) {
  data %>% 
    gather(Variable, Value, -c(...)) %>% 
    group_by(..., Variable) %>% 
    summarise(mean = mean(Value), 
              min = min(Value), 
              max = max(Value))
}

因为它返回错误

map_lgl(.x, .p, ...) 中的错误:未找到对象“性别”


这是一种可能的解决方案,其中...被传递到group_by直接,并且gather只是收集数字列(因为我认为它永远不应该收集独立于输入的非数字列...).

library(tidyverse)

set.seed(1)

## data
df <- tibble(
    Gender = c("m", "f", "f", "m", "m", 
        "f", "f", "f", "m", "f"),
    IQ = rnorm(10, 100, 15),
    Other = runif(10),
    Test = rnorm(10),
    group2 = c("A", "A", "A", "A", "A",
        "B", "B", "B", "B", "B")
)

## function
descriptive_by <- function(data, ...) {

  data %>% 
      gather(Variable, Value, names(select_if(., is.numeric))) %>% 
      group_by(..., Variable) %>% 
      summarise(mean = mean(Value), 
          min = min(Value), 
          max = max(Value))
}

descriptive_by(df, Gender, group2)
#> # A tibble: 12 x 6
#> # Groups:   Gender, group2 [4]
#>    Gender group2 Variable    mean      min     max
#>    <chr>  <chr>  <chr>      <dbl>    <dbl>   <dbl>
#>  1 f      A      IQ        95.1    87.5    103.   
#>  2 f      A      Other      0.432   0.212    0.652
#>  3 f      A      Test       0.464  -0.0162   0.944
#>  4 f      B      IQ       100.     87.7    111.   
#>  5 f      B      Other      0.281   0.0134   0.386
#>  6 f      B      Test       0.599   0.0746   0.919
#>  7 m      A      IQ       106.     90.6    124.   
#>  8 m      A      Other      0.442   0.126    0.935
#>  9 m      A      Test       0.457  -0.0449   0.821
#> 10 m      B      IQ       109.    109.     109.   
#> 11 m      B      Other      0.870   0.870    0.870
#> 12 m      B      Test      -1.99   -1.99    -1.99
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

rlang:将多个带有...的组传递给gather() 的相关文章

随机推荐