我有很多名字。我想将一个函数应用于所有名称的排列,以找出所有可能对的所有可能边的总和:
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"
如何为所有排列添加所有边?
答案 0 :(得分: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