Using var() - command to compute the variance of all elements in a matrix

Hello there,

I am having trouble to understand the var-command and hoping for your help.
I read in the documentation that, applied to a matrix given two matrices (x and y), it calculates the covariances between the columns of x and the columns of y.

But what does R do when I apply it to one matrix only? (See code below)?

m<-matrix(1:12, nrow=4, byrow = FALSE)
var(m)

RESULT:

var(m)
[,1] [,2]
[1,] 1.666667 1.666667
[2,] 1.666667 1.666667
[3,] 1.666667 1.666667
[,3]
[1,] 1.666667
[2,] 1.666667
[3,] 1.666667

Hello @futureRpro, welcome to RStudio Community.

From the documentation:

Arguments
y
NULL (default) or a vector, matrix or data frame with compatible dimensions to x. The default is equivalent to y = x (but more efficient).

So calling var() without specifying a y argument is equivalent to passing the same argument to both x and y.

m <- matrix(1:12, nrow = 4, byrow = FALSE)
n <- matrix(1:12, nrow = 4, byrow = FALSE)

var(x = m, y = n)
#>          [,1]     [,2]     [,3]
#> [1,] 1.666667 1.666667 1.666667
#> [2,] 1.666667 1.666667 1.666667
#> [3,] 1.666667 1.666667 1.666667

Created on 2020-04-14 by the reprex package (v0.3.0)

1 Like

Hello @siddharthprabhu,

thanks very much, that helped a lot :slight_smile:

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.