In R, how to find the standard error of the mean? In R, how to find the standard error of the mean? r r

In R, how to find the standard error of the mean?


The standard error is just the standard deviation divided by the square root of the sample size. So you can easily make your own function:

> std <- function(x) sd(x)/sqrt(length(x))> std(c(1,2,3,4))[1] 0.6454972


The standard error (SE) is just the standard deviation of the sampling distribution. The variance of the sampling distribution is the variance of the data divided by N and the SE is the square root of that. Going from that understanding one can see that it is more efficient to use variance in the SE calculation. The sd function in R already does one square root (code for sd is in R and revealed by just typing "sd"). Therefore, the following is most efficient.

se <- function(x) sqrt(var(x)/length(x))

in order to make the function only a bit more complex and handle all of the options that you could pass to var, you could make this modification.

se <- function(x, ...) sqrt(var(x, ...)/length(x))

Using this syntax one can take advantage of things like how var deals with missing values. Anything that can be passed to var as a named argument can be used in this se call.


A version of John's answer above that removes the pesky NA's:

stderr <- function(x, na.rm=FALSE) {  if (na.rm) x <- na.omit(x)  sqrt(var(x)/length(x))}