Is it possible to conditionally compute the various parts of dplyr :: summaryize ()?

Can conditional statements be used in different parts of dplyr :: summary ()?

Imagine that I work with data irisand displaying a summary, and I only want to include the average value of Sepal.Length on request. So I could do something like:

data(iris)
include_length = T
if (include_length) {
  iris %>% 
    group_by(Species) %>%
    summarize(mean_sepal_width = mean(Sepal.Width), mean_sepal_length = mean(Sepal.Length))
} else {
  iris %>% 
    group_by(Species) %>%
    summarize(mean_sepal_width = mean(Sepal.Width))

}

But is there a way to implement a conditional expression in a pipeline so that it does not need to be duplicated?

+4
source share
4 answers

You can use the .dotsSE function parameter for dplyr for program programming, for example.

library(dplyr)

take_means <- function(include_length){
    iris %>% 
        group_by(Species) %>%
        summarize_(mean_sepal_width = ~mean(Sepal.Width), 
                   .dots = if(include_length){
                       list(mean_sepal_length = ~mean(Sepal.Length))
                   })
}

take_means(TRUE)
#> # A tibble: 3 × 3
#>      Species mean_sepal_width mean_sepal_length
#>       <fctr>            <dbl>             <dbl>
#> 1     setosa            3.428             5.006
#> 2 versicolor            2.770             5.936
#> 3  virginica            2.974             6.588

take_means(FALSE)
#> # A tibble: 3 × 2
#>      Species mean_sepal_width
#>       <fctr>            <dbl>
#> 1     setosa            3.428
#> 2 versicolor            2.770
#> 3  virginica            2.974
+4
source

R c(x, if (d) y) d, , . x y .

data.table, return :

library(data.table)
f = function(d) data.table(iris)[, c(
  .(mw = mean(Sepal.Width)), 
  if(d) .(ml = mean(Sepal.Length))
), by=Species]

> f(TRUE)
      Species    mw    ml
1:     setosa 3.428 5.006
2: versicolor 2.770 5.936
3:  virginica 2.974 6.588
> f(FALSE)
      Species    mw
1:     setosa 3.428
2: versicolor 2.770
3:  virginica 2.974

DT[...] .() list(). , , .

+3

magrittr.

:

library(magrittr)
library(dplyr)

data(iris)
include_length = T

iris %>%
  group_by(Species) %>%
  { if (include_length) {summarize(., mean_sepal_width = mean(Sepal.Width), mean_sepal_length = mean(Sepal.Length))} 
    else {summarize(., mean_sepal_width = mean(Sepal.Width))} 
  }
+1

:

iris %>%
    group_by(Species) %>%
    summarise(mean_sepal_length=if(include_length) mean(Sepal.Length) else NA,
              mean_sepal_width=mean(Sepal.Width))

if include_length == TRUE NA . NA -, .

0

Source: https://habr.com/ru/post/1659555/


All Articles