R var() function - Calculate Variance
The R var() function is used to calculate the variance of a sample.
Variance is the square of the standard deviation, measuring the degree to which data deviates from the mean. The larger the variance, the more dispersed the data.
The syntax of the var() function is as follows:
var(x, y = NULL, na.rm = FALSE)
Parameter description:
xInput numeric vector.
yOptional, second vector. When provided, calculates the covariance of x and y.
na.rmBoolean, default is FALSE, sets whether to remove missing values NA.
Example
# Create dataset
data <- c(2, 4, 6, 8, 10)
# Calculate sample variance
result.var <- var(data)
print(paste("Sample variance:", result.var))
# Verify: variance = standard deviation^2
print(paste("Standard deviation:", sd(data)))
print(paste("Standard deviation squared:", sd(data)^2))
data <- c(2, 4, 6, 8, 10)
# Calculate sample variance
result.var <- var(data)
print(paste("Sample variance:", result.var))
# Verify: variance = standard deviation^2
print(paste("Standard deviation:", sd(data)))
print(paste("Standard deviation squared:", sd(data)^2))
Executing the above code produces the following output:
[1] "样本方差: 10" [1] "标准差: 3.16227766016838" [1] "标准差平方: 10"
var() can also calculate the covariance of two variables:
Example
# Two variables: height (cm) and weight (kg)
height <- c(160, 165, 170, 175, 180)
weight <- c(55, 60, 65, 70, 80)
# Calculate covariance
cov_xy <- var(height, weight)
print(paste("Covariance of height and weight:", cov_xy))
# Covariance matrix
m <- cbind(height, weight)
print("Covariance matrix:")
print(var(m))
height <- c(160, 165, 170, 175, 180)
weight <- c(55, 60, 65, 70, 80)
# Calculate covariance
cov_xy <- var(height, weight)
print(paste("Covariance of height and weight:", cov_xy))
# Covariance matrix
m <- cbind(height, weight)
print("Covariance matrix:")
print(var(m))
Executing the above code produces the following output:
[1] "身高和体重的协方差: 62.5"
[1] "协方差矩阵:"
height weight
height 62.5 62.5
weight 62.5 92.5
Other extensions
R language examples