TransWikia.com

Non consecutive combinations of array elements in R

Stack Overflow Asked by guest2341 on January 13, 2021

I want to generate all the possible combinations of nonadjacent elements in an array.

For example:

array_a <- c("A","B","C")

possible combinations would be : AC and CA

How can I implement this in R?

4 Answers

Another base R option using expand.grid + subset

inds <- subset(expand.grid(seq_along(array_a), seq_along(array_a)), abs(Var1 - Var2) > 1)
paste0(array_a[inds$Var1],array_a[inds$Var2])

Answered by ThomasIsCoding on January 13, 2021

The @tmfmnk solution is so cool. Still I want to add sth from me. I use the arrangements package for permutations without repetition.

array_a <- c("A", "B", "C", "D", "E")
#vec to rm from permutations neighbors
vec = paste0(array_a[-1], head(array_a, -1))
cc = apply(arrangements::permutations(array_a, 2, replace = F), 1, function(x) paste0(x, collapse = ""))
> setdiff(cc, c(vec, stringi::stri_reverse(vec)))                             
  [1] "AC" "AD" "AE" "BD" "BE" "CA" "CE" "DA" "DB" "EA" "EB" "EC"

Answered by polkas on January 13, 2021

If nonadjacent elements are defined as elements with distance greater than one in absolute values, then one option could be:

mat <- which(as.matrix(dist(seq_along(array_a))) > 1, arr.ind = TRUE)
paste0(array_a[mat[, 1]], array_a[mat[, 2]])

 [1] "CA" "DA" "EA" "DB" "EB" "AC" "EC" "AD" "BD" "AE" "BE" "CE"

Sample data:

array_a <- c("A", "B", "C", "D", "E")

Answered by tmfmnk on January 13, 2021

We can use outer

c(outer(array_a, array_a, FUN = paste, sep=""))

Or if we want to omit alternate elements

outer(array_a[c(TRUE, FALSE)], array_a[c(TRUE, FALSE)], FUN = paste, sep="")

Or using crossing

library(dplyr)
library(tidyr)
crossing(v1 = array_a[c(TRUE, FALSE)], 
         v2 = array_a[c(TRUE, FALSE)]) %>%
     filter(v1 != v2) %>% 
     unite(v1, v1, v2, sep="") %>% 
     pull(v1)
#[1] "AC" "CA"

NOTE: It is not clear about the assumptions for non-adjacent elements. We answered it based on a different assumption.

Answered by akrun on January 13, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP