从向量R中的每个其他值中减去向量中的每个值 [英] subtract every value in a vector from every other value in the vector R
问题描述
说我有一个矩阵
data<-matrix(seq(1,6),ncol=2,nrow=3,byrow=TRUE)
A B
[1,] 1 2
[2,] 3 4
[3,] 5 6
从"A"列开始,我想创建一个矢量,该矢量包含"A"中每个数字与"A"中每个其他数字之间的成对差异.实际上:
Starting with column 'A' I want to create a vector of the pairwise differences between every number in 'A' and every other number in 'A'. In effect:
c(1-1, 1-3, 1-5, 3-1, 3-3, 3-5, 5-1, 5-3, 5-5)
然后,我需要对第二列做同样的事情,依此类推.最终,我需要将这些向量绑定到新的差异矩阵中.
Then I need to do the same thing with the second column and so on. Eventually I need to bind these vectors into a new matrix of differences.
我觉得这应该可以应用apply函数,或者也许是sweep(),但是我无法将其组合在一起.
I feel like this should be doable with the apply functions, or perhaps sweep(), but I just could not get it together.
谢谢您的帮助!
PS.如果答案涉及编写函数或for循环,您能给我一个中等水平的解释吗?我是第一次学习编码,但仍然无法为循环而烦恼,并且仍然难以编写自己的函数.
PS. If the answer involves writing a function or a for loop could you please give me a dummy-medium level explanation? I am learning coding for the first time and I still cannot get my head around for loops and I still struggle with the logic of writing my own functions.
推荐答案
如果我们需要对每一列上的每个成对元素进行减法运算,则用遍历
,成对组合,作为两列data.frame与 matrix
的列apply expand.grid
并使用 Reduce
If we need to do the subtraction on each pairwise elements on each column, then loop over the columns of matrix
with apply
, get the pairwise, combinations as a two column data.frame with expand.grid
and subtract the columns using Reduce
apply(data, 2, FUN = function(x) Reduce('-', expand.grid(rep(list(x), 2))))
或在循环遍历列后使用 outer
的另一种选择
apply(data, 2, FUN = function(x) outer(x, x, FUN = '-'))
这篇关于从向量R中的每个其他值中减去向量中的每个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!