Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non consecutive combinations of array elements in R

Tags:

r

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?

like image 628
guest2341 Avatar asked Oct 11 '20 21:10

guest2341


2 Answers

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")
like image 83
tmfmnk Avatar answered Sep 18 '22 16:09

tmfmnk


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.

like image 36
akrun Avatar answered Sep 20 '22 16:09

akrun