Teja
Teja

Reputation: 13534

How to implement variance function in R

I am trying to calculate the variance of a column from a data frame.I know that there are inbuilt functions var() for calculating the variance but I am not sure how to write a function for variance by passing my data frame column as variable.

var(banknote$Length)*((n-1)/n)

Upvotes: 1

Views: 7343

Answers (1)

David Robinson
David Robinson

Reputation: 78610

If the vector you're going to take the variance of is 1-dimensional, as in your case, you can simply do:

myvar = function(v) {
    m = mean(v)
    mean((m - v)^2)
}

This assumes (based on your example) that you don't want to use the n/(n-1) correction.

Upvotes: 5

Related Questions