将函数应用于向量中元素的每个组合 [英] Applying a function to every combination of elements in a vector
问题描述
我想将某个(自定义)函数应用于数组的所有组合.我认为最好用一个例子来解释:
I would like to apply a certain (custom) function to all combinations of an array. I think its best to explain with an example:
矩阵1:
A B C
1 2 3
矩阵2:
A B C
4 5 6
我想执行以下操作:获取矩阵2的所有组合,并分别对每个矩阵应用一个函数,如下所示:
I would like to do the following: obtain all the combinations of Matrix two and apply a function to each as follows:
矩阵3:
AB AC BC CB CA BA
4/2 4/3 5/3 6/2 6/1 5/1
应用于矩阵3的函数是矩阵2的对应元素(由矩阵3的每一列中的第一个字母表示)/矩阵2的对应元素(由矩阵3的每一列中的第二个字母表示)
Where the function applied to Matrix 3 is the corresponding element of Matrix 2 (represented by the first letter in each column of Matrix 3)/the corresponding element of Matrix 2 (represented by the second letter in each column in Matrix 3).
如果有任何不清楚的地方,请告诉我,我觉得我可能还没有完美地解释过.
Please let me know if anything is unclear, I feel that I may not have explained perfectly.
任何帮助将不胜感激!
谢谢
迈克
推荐答案
结果不完全符合您要求的格式,但是您可以使用outer
从两个输入向量创建结果矩阵:>
The result is not exactly in the format you asked for, but you can use outer
to create a matrix of results from your two input vectors :
x <- c(A=1,B=2,C=3)
y <- c(A=4,B=5,C=6)
outer(x,y, FUN="/")
会给予:
A B C
A 0.25 0.2 0.1666667
B 0.50 0.4 0.3333333
C 0.75 0.6 0.5000000
如果您真的想要一个向量作为结果,则可以使用:
If you really want a vector as result, you can use :
m <- outer(x,y, FUN="/")
v <- as.vector(m)
names(v) <- as.vector(outer(names(x),names(y),FUN="paste0"))
然后得到:
AA BA CA AB BB CB AC
0.2500000 0.5000000 0.7500000 0.2000000 0.4000000 0.6000000 0.1666667
BC CC
0.3333333 0.5000000
这篇关于将函数应用于向量中元素的每个组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!