To calculate sample and population variance in R, you can use var() function and sd() function.
The following methods show how you can do it with syntax.
Method 1: Use var() Function
var(data)
Method 2: Use var() and length() Function
var(data) * (length(data) - 1) / length(data)
The following examples show how to calculate sample and population variance in R.
Using var() Function
Let’s see how to calculate sample variance using var() function:
# Create data frame
df <- data.frame(Machine_name=c("A","D","B","C","B","D","C","A"),
Pressure1=c(78.2, 81.21, 71.7, 80.21, 71.7, 81.21, 80.21, 78.2),
Temperature1=c(31, 33, 36, 37, 36, 33, 37, 31),
Status=c(TRUE,TRUE,FALSE,TRUE,FALSE,TRUE,TRUE,TRUE))
# Calculate sample variance
v <- var(df$Pressure1)
# Show sample variance
print(v)
Output:
[1] 15.65789
Here the output shows sample variance for Pressure column of dataframe.
Using var() and length() Function
Let’s calculate population variance in R using var() and length() function:
# Create data frame
df <- data.frame(Pressure=c(78, 81, 71, 80, 71, 81, 80, 78),
Temperature=c(31, 33, 36, 37, 36, 33, 37, 31))
# Calculate sample variance
v <- var(df$Pressure) * (length(df$Pressure) - 1) / length(df$Pressure)
# Print population variance
print(v)
Output:
[1] 15.25
Here the output shows population variance for Pressure column of dataframe.