Skip to content

Instantly share code, notes, and snippets.

@JohnCoene
Last active December 21, 2018 23:35
Show Gist options
  • Select an option

  • Save JohnCoene/8ae47292545d7e26570d71234ba1bdfd to your computer and use it in GitHub Desktop.

Select an option

Save JohnCoene/8ae47292545d7e26570d71234ba1bdfd to your computer and use it in GitHub Desktop.
Tidy Pascal's triangle
# 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)
@krlmlr
Copy link

krlmlr commented Dec 21, 2018

One option, not memory efficient but tidy-ish:

library(tidyverse)
x <- LETTERS[1:5]
crossing(x = x, y = x) %>%
  filter(x < y)
#> # A tibble: 10 x 2
#>    x     y    
#>    <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     E

Created on 2018-12-22 by the reprex package (v0.2.1.9000)

But this gets ugly for k > 2:

library(tidyverse)
x <- LETTERS[1:5]

tibble(x) %>% 
  crossing(y = x) %>%
  filter(x < y) %>% 
  crossing(z = x) %>% 
  filter(y < z)
#> # A tibble: 10 x 3
#>    x     y     z    
#>    <chr> <chr> <chr>
#>  1 A     B     C    
#>  2 A     B     D    
#>  3 A     B     E    
#>  4 A     C     D    
#>  5 A     C     E    
#>  6 A     D     E    
#>  7 B     C     D    
#>  8 B     C     E    
#>  9 B     D     E    
#> 10 C     D     E

Created on 2018-12-22 by the reprex package (v0.2.1.9000)

@krlmlr
Copy link

krlmlr commented Dec 21, 2018

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     E

Created 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