R cor() function - Calculate correlation coefficient

R 语言实例R language example

The R cor() function is used to calculate the correlation coefficient between two or more variables.

The correlation coefficient measures the degree of linear correlation between variables, with values ranging from -1 to 1. A value of 1 indicates a perfect positive correlation, -1 indicates a perfect negative correlation, and 0 indicates no correlation.

The syntax format of the cor() function is as follows:

cor(x, y = NULL, method = c("pearson", "kendall", "spearman"))

Parameter description:

  • xInput a numeric vector or matrix.

  • yOptional, the second vector or matrix.

  • methodCorrelation coefficient type: pearson (default, linear correlation), kendall, spearman (rank correlation).

Example

# Create two sets of data
height <- c(160, 165, 170, 175, 180)  # Height cm
weight <- c(55, 60, 65, 70, 80)       # Weight kg

# Calculate correlation coefficient
r <- cor(height, weight)
print(paste("Correlation coefficient between height and weight:", round(r, 3)))

# Calculate the correlation coefficient matrix of multiple variables
sleep_hours <- c(7, 6.5, 8, 7.5, 6)
df <- data.frame(height, weight, sleep_hours)
print("Correlation coefficient matrix:")
print(round(cor(df), 3))

Executing the above code produces the following output:

[1] "身高与体重的相关系数: 0.993"
[1] "相关系数矩阵:"
             height weight sleep_hours
height        1.000  0.993      -0.784
weight        0.993  1.000      -0.729
sleep_hours  -0.784 -0.729       1.000

R 语言实例R language example

Other extensions