Created
June 10, 2020 04:56
-
-
Save MilesMcBain/74b71a8e9f43c61b4f6918bc0d80fa98 to your computer and use it in GitHub Desktop.
grouped case_when
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
``` 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