简体   繁体   English

Sapply function 用于按元素计算 R 中的矩阵

[英]Sapply function for element-wise calculation a matrix in R

I have an (5x4) matrix in R , namely data defined as follows:我在R中有一个(5x4)矩阵,即data定义如下:

data <- matrix(rnorm(5*4,mean=0,sd=1), 5, 4) 

and I want to create 4 different matrices that follows this formula: Assume that data[,1] = [A1,A2,A3,A4,A5] .我想创建 4 个遵循这个公式的不同矩阵:假设data[,1] = [A1,A2,A3,A4,A5] I want to create the following matrix:我想创建以下矩阵:

        ||A1-A1|| ||A1-A2|| ||A1-A3|| ||A1-A4|| ||A1-A5|| 
        ||A2-A1|| ||A2-A2|| ||A2-A3|| ||A2-A4|| ||A2-A5||
   G1 = ||A3-A1|| ||A3-A2|| ||A3-A3|| ||A3-A4|| ||A3-A5||
        ||A4-A1|| ||A4-A2|| ||A4-A3|| ||A4-A4|| ||A4-A5||
        ||A5-A1|| ||A5-A2|| ||A5-A3|| ||A5-A4|| ||A5-A5||

where ||.||在哪里||.|| is the Euclidean norm.是欧几里得范数。 Similarly for the other columns i want to calculate at once all the G matrices ( G1 , G2 , G3 , G4 ).同样对于其他列,我想一次计算所有 G 矩阵( G1G2G3G4 )。 How can i achieve that with the sapply funciton?我怎样才能用sapply实现这一点?

We may use elementwise subtraction of column with outer我们可以使用outer列的元素减法

outer(data[,1], data[,1], `-`)

If it should be done on each column, loop over the columns (or do asplit with MARGIN = 2 to split by column), loop over the list and apply the outer如果应该在每一列上完成,循环遍历列(或使用asplit MARGIN = 2进行拆分以按列拆分),循环遍历list并应用outer

lapply(asplit(data, 2), function(x) outer(x, x, `-`))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM