Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MilesMcBain/74b71a8e9f43c61b4f6918bc0d80fa98 to your computer and use it in GitHub Desktop.
Save MilesMcBain/74b71a8e9f43c61b4f6918bc0d80fa98 to your computer and use it in GitHub Desktop.
grouped case_when
``` r
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
library(tibble)
tribble( ~a, ~b, ~c,
"A", 1, "X",
"A", 2, "X",
"B", 1, "Y",
"B", 2, "Y") %>%
group_by(a) %>%
summarise(case_when(
c == "X" ~ sum(b),
c == "Y" ~ sum(b) * -1,
TRUE ~ NA_real_
))
#> `summarise()` regrouping output by 'a' (override with `.groups` argument)
#> # A tibble: 4 x 2
#> # Groups: a [2]
#> a `case_when(c == "X" ~ sum(b), c == "Y" ~ sum(b) * -1, TRUE ~ NA_real_)`
#> <chr> <dbl>
#> 1 A 3
#> 2 A 3
#> 3 B -3
#> 4 B -3
```
<sup>Created on 2020-06-10 by the [reprex package](https://reprex.tidyverse.org) (v0.3.0)</sup>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment