Home > front end >  Sapply function for element-wise calculation a matrix in R
Sapply function for element-wise calculation a matrix in R

Time:08-21

I have an (5x4) matrix in R, namely data defined as follows:

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]. 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). How can i achieve that with the sapply funciton?

CodePudding user response:

We may use elementwise subtraction of column with 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

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