YouTip LogoYouTip

R Func Cor

# R cor() Function - Calculating Correlation Coefficient [![Image 3: R Language Examples](#) R Language Examples](#) 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 a value range of -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:** * **x** Input numeric vector or matrix. * **y** Optional, the second vector or matrix. * **method** Correlation coefficient type: pearson (default, linear correlation), kendall, spearman (rank correlation). ## Example # Create Two Datasets 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 for 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 outputs the following result: "Correlation Coefficient Between Height and Weight: 0.993" "Correlation Coefficient Matrix:" 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 [![Image 4: R Language Examples](#) R Language Examples](#)
← R Func CumsumR Func Choose β†’