R sd() Function - Calculate Standard Deviation

R 语言实例R Language Examples

The R sd() function is used to calculate the standard deviation of a sample.

The standard deviation measures the dispersion of data; the larger the value, the more spread out the data. It is the arithmetic square root of the variance.

The syntax of the sd() function is as follows:

sd(x, na.rm = FALSE)

Parameter description:

  • xInput numeric vector.

  • na.rmA boolean value, default is FALSE, specifying whether to remove missing values NA.

Example

# Two sets of data, same mean, different standard deviations
group1 <- c(85, 86, 84, 85, 86, 84, 85, 85)
group2 <- c(60, 70, 85, 90, 95, 100, 75, 105)

# Calculate mean and standard deviation
print(paste("Group 1 - Mean:", mean(group1), "Standard deviation:", sd(group1)))
print(paste("Group 2 - Mean:", mean(group2), "Standard deviation:", sd(group2)))

Executing the above code produces the following output:

[1] "第一组 - 均值: 85 标准差: 0.925820099772551"
[1] "第二组 - 均值: 85 标准差: 15.1186472433265"

Standard deviation is commonly used for probability estimation in the normal distribution. About 68% of the data falls within ±1 standard deviation of the mean:

Example

# Generate normally distributed data
set.seed(123)
scores <- rnorm(1000, mean = 70, sd = 10)

# Calculate mean and standard deviation
m <- mean(scores)
s <- sd(scores)

# Calculate the proportion within ±1 standard deviation
within_1sd <- mean(scores >= m - s & scores <= m + s)
print(paste("Mean:", round(m, 2)))
print(paste("Standard deviation:", round(s, 2)))
print(paste("Proportion within ±1 standard deviation:", round(within_1sd * 100, 1), "%"))

Executing the above code produces the following output:

[1] "均值: 69.97"
[1] "标准差: 10.03"
[1] "±1 标准差范围内的比例: 68.1 %"

R 语言实例R Language Examples

Other Extensions