# What formula is used for standard deviation in R?

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

• Generally, you will be able to read the function's code by simply calling it without parenthesis, as Gschneider did. – Owe Jessen Apr 6 '12 at 11:54
• @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). – Erik Apr 8 '15 at 10:56

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

• 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 :-) – Matt Krause Apr 6 '12 at 7:27
• @ Matt: Maybe they should update that help file and say something like "this returns the sqrt of var" ? – Owe Jessen Apr 6 '12 at 11:57
• @OweJessen, I think it actually says that "var returns its square!" – Matt Krause Apr 7 '12 at 5:26
• See also: stackoverflow.com/questions/9508518/… for learning why this simulation could give different results for both functions. – Tim Apr 8 '15 at 10:49
• Another simple way to test it is sd( c(-1,0,1) ) which outputs 1. – kjetil b halvorsen Apr 18 '17 at 19:59

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))
}