rifset
rifset

Reputation: 213

Create unique pairwise vector over a list using lapply

I have a list of string vectors and I want to make a vector containing combinations of unique pairwise from it. The order of the name does not matter as long as the combination is unique. Here's the sample data

studentGroup <- list(
  Group1 = c("Samuel", "Reed", "Lucas"),
  Group2 = c("Ami", "Vincent", "Dina", "George"),
  Group3 = c("Connor", "Steven", "Lois", "Moran", "Zane", "Molina")
)

I have followed this post, but since my vector is a string, neither dist() nor outer() worked. So the remaining option is just combn(). The desired output is like this

> studentGroupTest
[[1]]
[1] "Samuel & Reed"  "Samuel & Lucas" "Reed & Lucas"  

[[2]]
[1] "Ami & Vincent"    "Ami & Dina"       "Ami & George"     "Vincent & Dina"   "Vincent & George"
[6] "Dina & George"   

[[3]]
 [1] "Connor & Steven" "Connor & Lois"   "Connor & Moran"  "Connor & Zane"   "Connor & Molina" "Steven & Lois"  
 [7] "Steven & Moran"  "Steven & Zane"   "Steven & Molina" "Lois & Moran"    "Lois & Zane"     "Lois & Molina"  
[13] "Moran & Zane"    "Moran & Molina"  "Zane & Molina"  

My code

studentGroupTest <- vector(mode = "list", length = length(studentGroup))
for (i in 1:length(studentGroup)) {
  combined_group <- as.data.frame(combn(studentGroup[[i]], 2))
  combined_student <- NULL
  for (j in 1:ncol(combined_group)) {
    combined_student <- append(combined_student, paste(combined_group[1,j], "&", combined_group[2,j]))
  }
  studentGroupTest[[i]] <- combined_student
}

As you can see, my code is a little "bulky" and isn't straightforward. I wonder if I can get an lapply solution to my problem? Thanks in advance!

Upvotes: 2

Views: 55

Answers (1)

akrun
akrun

Reputation: 887851

We can loop over the list, use combn to get pairwise combinations selecting 2 at a time and paste them

lapply(studentGroup, function(x) combn(x, m = 2,
      FUN = function(y) paste(y, collapse = ' & ')))

-output

$Group1
[1] "Samuel & Reed"  "Samuel & Lucas" "Reed & Lucas"  

$Group2
[1] "Ami & Vincent"    "Ami & Dina"       "Ami & George"     "Vincent & Dina"   "Vincent & George" "Dina & George"   

$Group3
 [1] "Connor & Steven" "Connor & Lois"   "Connor & Moran"  "Connor & Zane"   "Connor & Molina" "Steven & Lois"   "Steven & Moran"  "Steven & Zane"  
 [9] "Steven & Molina" "Lois & Moran"    "Lois & Zane"     "Lois & Molina"   "Moran & Zane"    "Moran & Molina"  "Zane & Molina"  

Upvotes: 1

Related Questions