how to filter a correlation matrix in r

To filter a correlation matrix in r, we can use the dplyr package from the tidyverse library for data wrangling.

Assuming we have a correlation matrix saved in a variable cor_mat, we can apply a filter on the strength of the correlation using the filter() function from the dplyr package.

For example, we can use the following code to filter out correlations that are less than 0.5 or greater than 0.7:

main.r
library(dplyr)

cor_mat %>%
  as.data.frame() %>%
  filter(value >= 0.5 & value <= 0.7)
88 chars
6 lines

Here, we convert the correlation matrix into a data frame using as.data.frame(), and apply the filter() function to select correlations with a strength between 0.5 and 0.7.

Note that the as.data.frame() function is used to convert the correlation matrix to a dataframe so it can be filtered using dplyr. The resulting object is a dataframe with 3 columns: rowname, colname, and value.

If we only want to extract the correlation values that match our criterion, we can use pull() function to extract the value column as a vector:

main.r
cor_mat %>%
  as.data.frame() %>%
  filter(value >= 0.5 & value <= 0.7) %>%
  pull(value)
90 chars
5 lines

This will give us a vector of correlation values that meet the filtering criterion.

gistlibby LogSnag