R Tutorial R Charts & Graphs R Statistics R References

R - Standard Deviation



The R sd() function returns standard deviation of all elements present in the argument. The syntax for using this function is given below:

Syntax

sd(x, na.rm = FALSE)

Parameters

x Required. Specify numeric vector.
na.rm Optional. Specify TRUE to remove NA or NaN values before the computation. Default is FALSE.

Return Value

Returns standard deviation of all elements present in the argument.

Example:

The example below shows the usage of sd() function.

vec <- c(10, 55, 25, -56, 30, 99)
cat("Standard deviation of all elements of vec:", sd(vec), "\n")

mat <- matrix(c(10, 55, 25, -56, 30, 99), ncol=2)
cat("\nThe matrix contains:\n")
print(mat)
cat("Standard deviation of all elements of mat:", sd(mat))
cat("\nStandard deviation of elements along first column:", sd(mat[,1]))

The output of the above code will be:

Standard deviation of all elements of vec: 51.30075 

The matrix contains:
     [,1] [,2]
[1,]   10  -56
[2,]   55   30
[3,]   25   99
Standard deviation of all elements of mat: 51.30075
Standard deviation of elements along first column: 22.91288

Using na.rm parameter

The na.rm parameter can be set TRUE to remove NA or NaN values before the computation.

Example:

Consider the example below to see the usage of na.rm parameter.

v1 <- c(10, 55, 25, -56, 30, 99, NA)
v2 <- c(10, 55, 25, -56, 30, 99, NaN)

cat("Standard deviation of all elements of v1:", sd(v1), "\n")
cat("Standard deviation after removing NA:", sd(v1, na.rm=TRUE), "\n")

cat("\nStandard deviation of all elements of v2:", sd(v2), "\n")
cat("Standard deviation after removing NaN:", sd(v2, na.rm=TRUE), "\n")

The output of the above code will be:

Standard deviation of all elements of v1: NA 
Standard deviation after removing NA: 51.30075 

Standard deviation of all elements of v2: NA 
Standard deviation after removing NaN: 51.30075 

❮ R Statistical Functions