Rhodo
Rhodo

Reputation: 1334

Looping through all pairwise permutations and applying a function in R

I have a number of names. I would like to apply a function to all the permutations of names to find out the sum of all the possible sides of all the possible pairs:

shapes<- c("Square", "Triangle","Octagon","Hexagon")
sides<-c(4,3,8,6)

shapescount<-combn(shapes, 2)

shapescount

[,1]       [,2]      [,3]      [,4]       [,5]       [,6]     
[1,] "Square"   "Square"  "Square"  "Triangle" "Triangle" "Octagon"
[2,] "Triangle" "Octagon" "Hexagon" "Octagon"  "Hexagon"  "Hexagon"

How do I add up all the sides for all the permutations?

Upvotes: 0

Views: 889

Answers (1)

Jilber Urbina
Jilber Urbina

Reputation: 61154

Is this what you're looking for?

> vec <- setNames(sides, shapes)
> vec
  Square Triangle  Octagon  Hexagon 
       4        3        8        6 
> combn(vec, 2)
     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    4    4    4    3    3    8
[2,]    3    8    6    8    6    6
> colSums(combn(vec, 2))
[1]  7 12 10 11  9 14

A better output:

> Names <- combn(shapes, 2, function(x) paste0(x[1], "+", x[2]))
> setNames(colSums(combn(vec, 2)), Names)
 Square+Triangle   Square+Octagon   Square+Hexagon Triangle+Octagon Triangle+Hexagon  Octagon+Hexagon 
               7               12               10               11                9               14 

Upvotes: 5

Related Questions