Exploratory Correlation Analysis in R

Make a fortune with your little hand, give it a thumbs up!

This article [1]

Correlation analysis is one of the most basic and fundamental methods of exploring the relationship between two or more variables. You've probably used R to perform a correlation analysis at some point, and it probably looked like this:

cor_results <- cor.test(my_data$x, my_data$y,
                        method = "pearson")

cor_results

The output looks like:

alt

Here's a basic R method of running a simple association for two variables of your preselection.

But what if you really don't know what you're looking for? If you are just at the stage of doing some exploratory data analysis, you may not know which variables you are interested in, or where you may want to look for associations. What might be useful in this case is the ability to select a variable of interest and then examine a dataset with many or even hundreds of variables to find a good starting point for further analysis. Thanks to the rstatix ​​package developed by kassambara, there is a quick and relatively painless way to do this.

retrieve data

For example, I will use data from the World Bank's World Development Indicators (WDI) dataset - an open access data repository on global development indicators. We can access WDI from the website linked above, but there is also an R package

install.packages("WDI")
library(WDI)

Specific data series can be imported from WDI using the WDI() function, but since we are interested in exploratory analyzes covering possible relationships between a large number of variables, I will batch download the entire database...

bulk <- WDIbulk(timeout = 600)

Suppose we are interested in trying to find out what other country characteristics might be associated with countries that trade more, relative to the size of their economies, and we are also interested in 2020 data.

Once we have the correct variables in place (I'll be using trade as a % of GDP here), we need to clean up the data a bit. We'll create a list of yearly series that we can filter, then apply another filtering step to ensure we only use variables with a large number of observations for analysis (arbitrary, n > 100 in the example below).

# Create a filtered set with only annual variables
filtered <- bulk$Series %>% filter(Periodicity == "Annual")

# Create a list of variables to correlate against trade levels
bulk$Data %>% 
  filter(Indicator.Code %in% c(filtered$Series.Code)) %>% 
  filter(year == 2020) %>% 
  group_by(Indicator.Code) %>%
  filter(!is.na(value)) %>% 
  count() %>% 
  arrange(n) %>% 
  filter(n>100) -> vars_list

analyze

所以现在我们有一个变量列表要运行——大约 790 个——看看哪些可能与我们的贸易水平变量相关。这将永远需要手动运行,或者从 base R 循环运行 cor.test() 。这是 rstatix 中的 cor_test() 函数闪耀的地方——它运行得非常快,相关分析的输出被转储到一个小标题中格式(使执行额外的操作和分析变得容易),并且函数是管道友好的,这意味着我们可以将过滤、变异和执行步骤组合到一个管道框架中,我们还可以将变量输入分组以进行分组输出来自 rstatix(我们稍后会看一些例子)。

因此,要运行分析:

# Because WDI contains regional data as well, we'll create a list that only has country codes, and filter our input based on that list
countries <- bulk$Country %>% filter(!Region == "") %>% as_tibble()

bulk$Data %>% 
  filter(Indicator.Code %in% c(vars_list$Indicator.Code)) %>%
  filter(year == 2020) %>%
  filter(Country.Code %in% c(countries$Country.Code)) %>% 
  select(-Indicator.Name) %>% 
  pivot_wider(names_from = Indicator.Code,
              values_from = value) %>% 
  cor_test(NE.TRD.GNFS.ZS, 
           method = "pearson",
           use = "complete.obs") -> results

results

这会使用变量配对、相关系数 (r)、t 统计量、置信水平 (p) 以及低置信度和高置信度估计来填充整齐的小标题。对于上面运行的示例,它看起来像:

alt

因为输出是一个 tibble,所以我们可以根据需要对其进行排序和分解。让我们用变量名称和描述创建一个键,将其连接到我们的输出数据中,仅过滤在 p > 0.05 水平上显着的变量对,并检查哪些变量具有最高的 r 值:

indicator_explanation <- bulk$Series %>% select(Series.Code, Indicator.Name, Short.definition) %>% as_tibble()

results %>% 
  left_join(indicator_explanation, c("var2" = "Series.Code")) %>% 
  arrange(desc(cor)) %>%
  filter(p<0.05) %>% 
  View()
alt

一些具有最高相关性的变量并不令人惊讶——例如,总体贸易在服务贸易和商品贸易的国家之间呈高水平正相关。其他情况可能更出乎意料——比如贸易水平与一个国家收到的官方发展援助(援助资金)数额之间的中等高度正相关 (r = 0.43)(上图中最下面一行)。

分组分析

那么,如果我们想更多地研究这种关系呢?例如——如果我们看看 2020 年以外的其他年份,这种关系是否仍然牢固?这是 cor_test() 的管道友好特性再次派上用场的地方。

让我们过滤我们的初始数据以仅包括我们感兴趣的两个指标,然后按年份对数据进行分组,然后再将其传输到 cor_test() 这一次:

bulk$Data %>% 
  filter(Indicator.Code %in% c("NE.TRD.GNFS.ZS""DT.ODA.ODAT.GI.ZS")) %>% 
  filter(Country.Code %in% c(countries$Country.Code)) %>% 
  select(-Indicator.Name) %>% 
  filter(year<2021) %>% 
  pivot_wider(names_from = Indicator.Code,
              values_from = value) %>%
  group_by(year) %>%
  cor_test(NE.TRD.GNFS.ZS, DT.ODA.ODAT.GI.ZS,
           method = "pearson",
           use = "complete.obs") -> results_time

这将为我们提供关于两个变量之间相关性的输出,每年都有观察结果(我将数据过滤到 2021 年之前的年份,因为 ODA 数据只运行到 2020 年)。而且由于相关数据以整齐的方式存储,我们可以轻松地运行额外的代码来可视化我们的结果:

results_time %>% 
  mutate(`Significant?` = if_else(p<0.05"Yes""No")) %>% 
  ggplot(aes(x = year, y = cor)) +
  geom_hline(yintercept = 0
             linetype = "dashed") +
  geom_line() + 
  ylab("cor (r)") +
  geom_point(aes(color = `Significant?`)) +
  theme_minimal()

在这里我们可以看到,从历史上看,这两个变量之间根本没有太大的关系(除了偶尔出现了弱负相关的几年),但在过去几年中,相关性趋于显着和正:

alt

那么这是什么意思?关于贸易与援助之间关系的任何潜在问题——我们必须做更多的研究。相关性毕竟并不意味着因果关系,但这是一个很好的假设生成器——受援国是否越来越以贸易为导向?还是援助交付模式正在转向有利于贸易更多的国家?这些都是我们探索的新途径。这些类型的快速相关分析对于趋势分析或信号发现之类的事情来说可能是一个非常有用的工具——并且采用一种对 tidyverse 友好的方式来做它真的可以避免潜在的麻烦。

就我们快速轻松地进行一些有用的探索性分析的能力而言,我们可以看到 rstatix 是一个有用的配套包。然而,rstatix 中的 cor_test() 有一些缺点

  1. 例如,与“相关”包中的许多其他方法相比,您仅限于 Pearson (r)、Spearman (ρ) 和 Kendall (τ) 相关方法。然而,这些对于临时用户来说是最常见的,对于基本分析来说应该绰绰有余。
  2. 置信区间仅在 Pearson r 的输出中报告。这意味着如果 Spearman 的 rho 或 Kendall 的 tau 需要置信区间,则需要额外的代码。
  3. 例如,不报告样本大小和自由度,如果用户的目标是根据不同的分组段开发多个输出报告,这可能会很烦人。

但这些通常不适用于临时用户。此外,除了 cor_test() 之外,rstatix 还具有用于各种其他统计测试和过程的大量其他函数,下次您需要进行一些探索性统计分析时,这些绝对值得研究——因此请向开发人员大声疾呼一。

Reference

[1]

Source: https://towardsdatascience.com/exploratory-correlational-analysis-in-r-c99449b2e3f8

This article is published by mdnice multi-platform

Guess you like

Origin blog.csdn.net/swindler_ice/article/details/130611078