YouTip LogoYouTip

R Func Var

# 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 outputs:

 "Sample variance: 10"
 "Standard deviation: 3.16227766016838"
 "Standard deviation squared: 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))

Executing the above code outputs:

 "Covariance of height and weight: 62.5"
 "Covariance matrix:"
             height weight
height   62.5   62.5
weight   62.5   92.5

Image 4: R Examples R Examples

← R Func Write CsvR Func Unique β†’