0

我有好几个名字。我想将一个函数应用于名称的所有排列,以找出所有可能对的所有可能边的总和:

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"

如何将所有排列的所有边相加?

4

1 回答 1

5

这是你要找的吗?

> 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

更好的输出:

> 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 
于 2013-11-12T22:08:12.813 回答