19
$\begingroup$

What formula is used in the standard deviation function sd in R?

$\endgroup$
  • $\begingroup$ Generally, you will be able to read the function's code by simply calling it without parenthesis, as Gschneider did. $\endgroup$ – Owe Jessen Apr 6 '12 at 11:54
  • 2
    $\begingroup$ @OweJessen While true, this is often not as helpful as one might think. Many functions in R are just wrappers that call underlying C code. For example, sd leads you to var, which leads you to .Call(C_cov, x, y, na.method, FALSE). $\endgroup$ – Erik Apr 8 '15 at 10:56
31
$\begingroup$

As pointed out by @Gschneider, it computes the sample standard deviation

$$\sqrt{\frac{\sum\limits_{i=1}^{n} (x_i - \bar{x})^2}{n-1}}$$

which you can easily check as follows:

> #generate a random vector
> x <- rnorm(n=5, mean=3, sd=1.5)
> n <- length(x)
> 
> #sd in R
> sd1 <- sd(x)
> 
> #self-written sd
> sd2 <- sqrt(sum((x - mean(x))^2) / (n - 1))
>  
> #comparison
> c(sd1, sd2)   #:-)
[1] 0.6054196 0.6054196
$\endgroup$
  • 4
    $\begingroup$ If you look at the help page (?sd), it says "Like var, this uses denominator n-1", if for some reason you don't believe ocram's simulation :-) $\endgroup$ – Matt Krause Apr 6 '12 at 7:27
  • $\begingroup$ @ Matt: Maybe they should update that help file and say something like "this returns the sqrt of var" ? $\endgroup$ – Owe Jessen Apr 6 '12 at 11:57
  • $\begingroup$ @OweJessen, I think it actually says that "var returns its square!" $\endgroup$ – Matt Krause Apr 7 '12 at 5:26
  • $\begingroup$ See also: stackoverflow.com/questions/9508518/… for learning why this simulation could give different results for both functions. $\endgroup$ – Tim Apr 8 '15 at 10:49
  • $\begingroup$ Another simple way to test it is sd( c(-1,0,1) ) which outputs 1. $\endgroup$ – kjetil b halvorsen Apr 18 '17 at 19:59
12
$\begingroup$

Yes. Technically, it computes the sample variance, and then takes the square root:

> sd
function (x, na.rm = FALSE) 
{
if (is.matrix(x)) 
    apply(x, 2, sd, na.rm = na.rm)
else if (is.vector(x)) 
    sqrt(var(x, na.rm = na.rm))
else if (is.data.frame(x)) 
    sapply(x, sd, na.rm = na.rm)
else sqrt(var(as.vector(x), na.rm = na.rm))
}
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.