sd()
sd(x, na.rm = FALSE) Returns:
numeric · Updated March 13, 2026 · Base Functions statistics standard-deviation base
The sd() function calculates the standard deviation of a numeric vector. Standard deviation is a fundamental statistical measure that quantifies the spread of data around the mean.
Syntax
sd(x, na.rm = FALSE)
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
x | numeric | REQUIRED | A numeric vector or matrix |
na.rm | logical | FALSE | If TRUE, missing values are removed before computing |
Examples
Basic usage
x <- c(2, 4, 4, 4, 5, 5, 7, 9)
sd(x)
# [1] 2
Handling missing values
x_with_na <- c(1, 2, NA, 4, 5)
sd(x_with_na)
# [1] NA
sd(x_with_na, na.rm = TRUE)
# [1] 1.825742
Standard deviation by group
Use tapply() to compute standard deviation for groups:
df <- data.frame(
group = c("A", "A", "A", "B", "B", "B"),
value = c(1, 2, 3, 10, 11, 12)
)
tapply(df$value, df$group, sd)
# A B
# 1.000000 1.000000
Common Patterns
Coefficient of variation
The coefficient of variation (CV) expresses standard deviation as a percentage of the mean:
cv <- function(x) sd(x) / mean(x) * 100
cv(c(10, 12, 14, 16, 18))
# [1] 24.27619
Variance from standard deviation
x <- c(2, 4, 4, 4, 5, 5, 7, 9)
var_x <- sd(x) ^ 2
var_x
# [1] 4