-1

I'm trying to manually compute variance within matrices in R and I'm having some issues in that I'm getting the incorrect number of dimensions.

I have x, a 12x250 matrix, Temp.means, a 12x1 matrix, and I'm feeding it unto a function with a for look inside.

I would basically like the variance of x so I'm using the apply function to try to apply my variance function to my code... but something is working wrong.

Here is my code:

Variance.fun <- function(x,Temp.means) {
for (i in 1:250) {
     vari <- (matrix(x[i,]-Temp.means)^2)/250
 }
 }
haramassive
  • 163
  • 1
  • 8
  • Please make this question *reproducible*. This includes sample data (e.g., `dput(head(x))`), literal text of warnings/errors, and the expected output. Refs: https://stackoverflow.com/questions/5963269, https://stackoverflow.com/help/mcve, and https://stackoverflow.com/tags/r/info. – r2evans Oct 25 '18 at 17:09
  • if you just need the variance of each row, why not `apply(my_matrix, 1, var)`? – Matt Tyers Oct 25 '18 at 17:51
  • The variance of x is generally understood to be a 12 by 12 matrix. Does the function `var(x)` have the output you want? If not, maybe you can explain how what you need is different. – Robert Dodier Oct 25 '18 at 18:00

1 Answers1

0

If by "variance" you mean row differences from a "standard row" (as suggested by your for-loop) then one way to get that would be to use apply

res <- apply( x, 1, "-", Temp.means)

That could be made into a function:

 row.variation.from.std <- function (mat, std){
                            apply( mat, 1, "-", std) }

I suspect your use of the word "variance" is misleading some potential responders who assumed you meant the concept as the word is defined in statistical practice.

IRTFM
  • 258,963
  • 21
  • 364
  • 487