Ranji Raj
Ranji Raj

Reputation: 818

Custom standard deviation implementation in R

I am creating custom standard deviation for computing summary statistics in R, for both unbiased and biased estimates. For the biased estimate, I am getting different values from my function and from the in-built function.

Code:

My.Sd = function(x) {
    sqrt(sum((x - (sum(x) / length(x)))^2) / length(x))
}

#Sanity check
My.Sd(0:10)

The above yields:

> My.Sd(0:10)
[1] 3.162278

And the primitive:

> sd(0:10)
[1] 3.316625

Why is there a difference or am I computing something wrongly in My.Sd()?

Upvotes: 0

Views: 249

Answers (1)

Jilber Urbina
Jilber Urbina

Reputation: 61154

it's because sd is for sample standard deviation, you need n-1 obs, try using length(x)-1

My.Sd = function(x) {
  sqrt(sum((x - (sum(x) / length(x)))^2) / (length(x)-1))
}
> My.Sd(0:10)
[1] 3.316625
> sd(0:10)
[1] 3.316625

Upvotes: 3

Related Questions