我的第一个R函数,很low

Write my own functions to compute the variance  of a numeric vector. Variance is defined as,

 

The code is:


x <- rnorm(100)
dim(x) <- c(100,1)
my_var <- function(x) { 
  a <- x-apply(x, 2, mean) 
  apply(a*a,2,sum)/99 
} 
my_var(x)

The same as 

my_var <- function(x) { 
a <- x-mean(x)
sum(a*a)/99
}
my_var(x)

It can be solved only use one line code:


apply(x,2,var)

 

Leave a Reply

Your email address will not be published. Required fields are marked *