Calculate Correlation of One Data Frame Column to All Others in R (Example Code)
In this article you’ll learn how to compute the correlation of one data frame column to all the others in R.
Creation of Example Data
data(iris) # Example data iris_new <- iris[ , c(1:4)] head(iris_new) # Sepal.Length Sepal.Width Petal.Length Petal.Width # 1 5.1 3.5 1.4 0.2 # 2 4.9 3.0 1.4 0.2 # 3 4.7 3.2 1.3 0.2 # 4 4.6 3.1 1.5 0.2 # 5 5.0 3.6 1.4 0.2 # 6 5.4 3.9 1.7 0.4 |
data(iris) # Example data iris_new <- iris[ , c(1:4)] head(iris_new) # Sepal.Length Sepal.Width Petal.Length Petal.Width # 1 5.1 3.5 1.4 0.2 # 2 4.9 3.0 1.4 0.2 # 3 4.7 3.2 1.3 0.2 # 4 4.6 3.1 1.5 0.2 # 5 5.0 3.6 1.4 0.2 # 6 5.4 3.9 1.7 0.4
Example: Applying cor() Function Get Correlations of One Column with All Others
cor(iris_new[ , - 1], # Get correlation estimates iris_new$Sepal.Length) # [,1] # Sepal.Width -0.1175698 # Petal.Length 0.8717538 # Petal.Width 0.8179411 |
cor(iris_new[ , - 1], # Get correlation estimates iris_new$Sepal.Length) # [,1] # Sepal.Width -0.1175698 # Petal.Length 0.8717538 # Petal.Width 0.8179411
Related Tutorials
Please find some related R programming tutorials on topics such as ggplot2, graphics in R, variables, and lists in the following list.