Correlation Matrix Contains Only NA & 1 in R (2 Examples)
In this tutorial you’ll learn how to show correlation values instead of NA when using the cor() function in the R programming language.
Example Data
data(iris) # Load iris data set iris_num <- iris[ , 1:4] # Extract numeric columns iris_num$Sepal.Length[c(1, 7, 10)] <- NA iris_num$Sepal.Width[c(3, 55, 110)] <- NA iris_num$Petal.Length[c(4, 5, 20)] <- NA iris_num$Petal.Width[c(1, 3, 10)] <- NA head(iris_num) # Head of modified iris data set # Sepal.Length Sepal.Width Petal.Length Petal.Width # 1 NA 3.5 1.4 NA # 2 4.9 3.0 1.4 0.2 # 3 4.7 NA 1.3 NA # 4 4.6 3.1 NA 0.2 # 5 5.0 3.6 NA 0.2 # 6 5.4 3.9 1.7 0.4 |
data(iris) # Load iris data set iris_num <- iris[ , 1:4] # Extract numeric columns iris_num$Sepal.Length[c(1, 7, 10)] <- NA iris_num$Sepal.Width[c(3, 55, 110)] <- NA iris_num$Petal.Length[c(4, 5, 20)] <- NA iris_num$Petal.Width[c(1, 3, 10)] <- NA head(iris_num) # Head of modified iris data set # Sepal.Length Sepal.Width Petal.Length Petal.Width # 1 NA 3.5 1.4 NA # 2 4.9 3.0 1.4 0.2 # 3 4.7 NA 1.3 NA # 4 4.6 3.1 NA 0.2 # 5 5.0 3.6 NA 0.2 # 6 5.4 3.9 1.7 0.4
Example 1: Reproduce Correlation Matrix Showing Only NA or 1
cor(iris_num) # Using cor() function # Sepal.Length Sepal.Width Petal.Length Petal.Width # Sepal.Length 1 NA NA NA # Sepal.Width NA 1 NA NA # Petal.Length NA NA 1 NA # Petal.Width NA NA NA 1 |
cor(iris_num) # Using cor() function # Sepal.Length Sepal.Width Petal.Length Petal.Width # Sepal.Length 1 NA NA NA # Sepal.Width NA 1 NA NA # Petal.Length NA NA 1 NA # Petal.Width NA NA NA 1
Example 2: Correlation Matrix without NA Values
cor(iris_num, use = "complete.obs") # Using cor() function & use argument # Sepal.Length Sepal.Width Petal.Length Petal.Width # Sepal.Length 1.00000000 -0.09607404 0.8609699 0.8010341 # Sepal.Width -0.09607404 1.00000000 -0.4214206 -0.3611788 # Petal.Length 0.86096988 -0.42142065 1.0000000 0.9595811 # Petal.Width 0.80103407 -0.36117879 0.9595811 1.0000000 |
cor(iris_num, use = "complete.obs") # Using cor() function & use argument # Sepal.Length Sepal.Width Petal.Length Petal.Width # Sepal.Length 1.00000000 -0.09607404 0.8609699 0.8010341 # Sepal.Width -0.09607404 1.00000000 -0.4214206 -0.3611788 # Petal.Length 0.86096988 -0.42142065 1.0000000 0.9595811 # Petal.Width 0.80103407 -0.36117879 0.9595811 1.0000000