Standard Error in R: How to Calculate Standard Error

R does not come with a standard error function. You need to either create a standard error function or use a package like plotrix to calculate.

Standard Error in R

The standard error in R is just the standard deviation divided by the square root of the sample size. The variance of the sampling distribution is the variance of the data divided by N, and the SE is the square root of that.

The formula for finding standard error in R is the following.

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

The standard error can be calculated by dividing the standard deviation of our input by the square root of the length of our input. Let’s take an example.

std <- function(a) sd(a) / sqrt(length(a))

op <- std(c(11, 21, 19, 46))

print(op)

Output

[1] 7.564996

And we get the Standard Error of the vector.

If you want to remove NA values, then you can use the following function.

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

op <- std(c(11, 21, 19, 46))

print(op)

Output

[1] 7.564996

Let’s take another example in which we will use the set.seed() function and then use the rnorm() function to generate 10 random numbers.

set.seed(1)

data <- rnorm(10)

print(data)

se <- sd(data) / sqrt(10)

cat("The Standard Error is: ", se)

Output

[1] -0.6264538 0.1836433 -0.8356286 1.5952808 0.3295078 -0.8204684
[7] 0.4874291 0.7383247 0.5757814 -0.3053884

The Standard Error is: 0.246843

std.error Function in plotrix

To use the std.error() function in R, install the plotrix package. The plotrix add-on package includes the std.error() function, which can also calculate the standard error of the mean.

The std.error() function calculates the standard error of the mean. The std.error() function  will accept a numeric vector.

Syntax

std.error(x,na.rm)

Arguments

x: It is a vector of numerical observations.
na.rm: It is a dummy argument to match other functions.

Example

library("plotrix")

op <- std.error(c(11, 21, 19, 46))

print(op)

Output

[1] 7.564996

That is it for Standard Error in R tutorial.

Leave a Comment