Last active
December 21, 2018 23:35
-
-
Save JohnCoene/8ae47292545d7e26570d71234ba1bdfd to your computer and use it in GitHub Desktop.
Tidy Pascal's triangle
This file contains hidden or 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
| # Essentially what I want is the unique combinations of a vector of factors/characters | |
| x <- LETTERS[1:5] | |
| # x is of length 5 | |
| # Therefore, according to Pascal's triangle | |
| # https://en.wikipedia.org/wiki/Pascal%27s_triangle | |
| # | |
| # (n * (n - 1)) / k | |
| k <- 2 | |
| n <- length(x) | |
| (n * (n - 1)) / k | |
| # I thus expect 10 comninations | |
| # | |
| # Here is how I do it now. | |
| # install.packages("combinat") | |
| ( comb <- combinat::combn(x, k, simplify = FALSE)) | |
| # the length (number of combinations) is actually 10 | |
| length(comn) |
Another option that avoids the filter():
library(tidyverse)
x <- LETTERS[1:5]
tibble(a = x) %>%
group_by(a) %>%
mutate(b = list(x[x > a])) %>%
ungroup() %>%
unnest()
#> # A tibble: 10 x 2
#> a b
#> <chr> <chr>
#> 1 A B
#> 2 A C
#> 3 A D
#> 4 A E
#> 5 B C
#> 6 B D
#> 7 B E
#> 8 C D
#> 9 C E
#> 10 D ECreated on 2018-12-22 by the reprex package (v0.2.1.9000)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
One option, not memory efficient but tidy-ish:
Created on 2018-12-22 by the reprex package (v0.2.1.9000)
But this gets ugly for
k > 2:Created on 2018-12-22 by the reprex package (v0.2.1.9000)