How to Find the Standard Error of the Mean in R

Standard error in R tutorial

This tutorial explains several ways to easily find the standard error of the mean in R.

What is the Standard Error of the Mean?

The standard error of the mean is an estimate of the standard deviation of the mean. The standard error is important because it is used to compute other measures like margins of error and confidence intervals. The formula to find the standard error of the mean is as follows:

standard error of the mean: s / √n

where is the sample standard deviation and is the sample size.

How to Find the Standard Error of the Mean in R

Base R does not have a built-in function to compute the standard error of the mean, but we can easily write a short function to compute the standard error of the mean ourselves.

Suppose we have the following sample:

data <- c(1, 2, 4, 7, 9, 14)

The following function can be used to compute the standard error of the mean for this sample:

#define function to compute standard error of the mean
find_stderr <- function(x) {
  sd(x)/sqrt(length(x))
}

#use function to find standard error of the mean
find_stderr(data)

#[1] 1.990254

The following function offers an equivalent way to compute the standard error of the mean:

#define function to compute standard error of the mean
find_stderr <- function(x) {
  sqrt(var(x)/length(x))
}

#use function to find standard error of the mean
find_stderr(data)

#[1] 1.990254

Unfortunately, neither of the functions we defined above are capable of handling missing values. Luckily, we can define the following new function to compute the standard error of the mean while also being able to disregard missing values:

#define new sample data that contains missing values
data <- c(1, NA, 4, 7, NA, 14)

#define function to compute standard error while disregarding missing values
find_stderr <- function(x, na.rm=FALSE) {
  if (na.rm) x <- na.omit(x)
  sqrt(var(x)/length(x))
}

#use the function to find the standard error
find_stderr(data, na.rm = TRUE)

#[1] 2.783882

Note that this function can also be used to compute the standard error of the mean even if there are no missing values present in the data:

#define data
data <- c(1, 2, 4, 7, 9, 14)

#define function to compute standard error while disregarding missing values
find_stderr <- function(x, na.rm=FALSE) {
  if (na.rm) x <- na.omit(x)
  sqrt(var(x)/length(x))
}

#use the function to find the standard error
find_stderr(data, na.rm = TRUE)

#[1] 1.990254

Further Reading:
An Easy Guide to Writing Functions in R (With Examples)
How to Explore a Dataset in R Using Descriptive Statistics

Leave a Reply

Your email address will not be published. Required fields are marked *