在分析数据时,可以采用统计方法.执行基本分析所需的基本工具是 :
相关分析
分析方差
假设检验
使用大型数据集时,它不涉及这些方法的问题除相关分析外,其计算量不大.在这种情况下,始终可以采样并且结果应该是稳健的.
相关分析寻求线性关系数字变量之间.这可以在不同的情况下使用.一个常见的用途是探索性数据分析,在本书的第16.0.2节中有一个这种方法的基本例子.首先,在所提到的示例中使用的相关度量基于 Pearson系数.然而,另一个有趣的相关度量不受异常值的影响.该度量称为spearman相关性.
spearman相关度量比Pearson方法对异常值的存在更稳健,并且更好地估计了线性关系数据未正常分布时的数字变量.
library(ggplot2) # Select variables that are interesting to compare pearson and spearman correlation methods. x = diamonds[, c('x', 'y', 'z', 'price')] # From the histograms we can expect differences in the correlations of both metrics. # In this case as the variables are clearly not normally distributed, the spearman correlation # is a better estimate of the linear relation among numeric variables. par(mfrow = c(2,2)) colnm = names(x) for(i in 1:4) { hist(x[[i]], col = 'deepskyblue3', main = sprintf('Histogram of %s', colnm[i])) } par(mfrow = c(1,1))
从下图中的直方图中,我们可以预期两个指标的相关性存在差异.在这种情况下,由于变量显然不是正态分布的,因此spearman相关性是对数值变量之间线性关系的更好估计.
为了计算R中的相关性,打开文件 bda/part2/statistical_methods/correlation/correlation.R 有这个代码部分.
## Correlation Matrix - Pearson and spearman cor_pearson <- cor(x, method = 'pearson') cor_spearman <- cor(x, method = 'spearman') ### Pearson Correlation print(cor_pearson) # x y z price # x 1.0000000 0.9747015 0.9707718 0.8844352 # y 0.9747015 1.0000000 0.9520057 0.8654209 # z 0.9707718 0.9520057 1.0000000 0.8612494 # price 0.8844352 0.8654209 0.8612494 1.0000000 ### Spearman Correlation print(cor_spearman) # x y z price # x 1.0000000 0.9978949 0.9873553 0.9631961 # y 0.9978949 1.0000000 0.9870675 0.9627188 # z 0.9873553 0.9870675 1.0000000 0.9572323 # price 0.9631961 0.9627188 0.9572323 1.0000000
chi-平方测试允许我们测试两个随机变量是否独立.这意味着每个变量的概率分布不会影响另一个变量.为了评估R中的测试,我们首先需要创建一个列联表,然后将表传递给 chisq.test R 函数.
例如,让我们检查变量之间是否存在关联:切割和钻石数据集中的颜色.测试正式定义为 :
H0:变量切割和钻石是独立的
H1:变量切割和钻石不是独立的
我们假设这两个变量之间存在关系,但测试可以给出一个客观的"规则",说明这个结果有多重要.
在下面的代码片段中,我们发现测试的p值是2.2e-16,这几乎是实际上是零.然后在运行测试后进行蒙特卡罗模拟,我们发现p值为0.0004998,仍然远低于阈值0.05.这个结果意味着我们拒绝零假设(H0),所以我们认为变量 cut 和 color 不是独立的.
library(ggplot2) # Use the table function to compute the contingency table tbl = table(diamonds$cut, diamonds$color) tbl # D E F G H I J # Fair 163 224 312 314 303 175 119 # Good 662 933 909 871 702 522 307 # Very Good 1513 2400 2164 2299 1824 1204 678 # Premium 1603 2337 2331 2924 2360 1428 808 # Ideal 2834 3903 3826 4884 3115 2093 896 # In order to run the test we just use the chisq.test function. chisq.test(tbl) # Pearson’s Chi-squared test # data: tbl # X-squared = 310.32, df = 24, p-value < 2.2e-16 # It is also possible to compute the p-values using a monte-carlo simulation # It's needed to add the simulate.p.value = TRUE flag and the amount of simulations chisq.test(tbl, simulate.p.value = TRUE, B = 2000) # Pearson’s Chi-squared test with simulated p-value (based on 2000 replicates) # data: tbl # X-squared = 310.32, df = NA, p-value = 0.0004998
t-test 的想法是评估名义变量的不同组之间的数值变量#分布是否存在差异.为了证明这一点,我将选择因子变量cut的公平和理想水平的水平,然后我们将比较这两个组中的数值变量的值.
data = diamonds[diamonds$cut %in% c('Fair', 'Ideal'), ] data$cut = droplevels.factor(data$cut) # Drop levels that aren’t used from the cut variable df1 = data[, c('cut', 'price')] # We can see the price means are different for each group tapply(df1$price, df1$cut, mean) # Fair Ideal # 4358.758 3457.542
使用 t.test 函数在R中实现t检验. t.test的公式接口是使用它的最简单方法,其思想是数组变量由组变量解释.
例如: t.test( numeric_variable~group_variable,data = data).在前面的示例中, numeric_variable 是价格, group_variable 是 cut .
从统计角度来看,我们正在测试两组中数值变量的分布是否存在差异.正式地,假设检验用零(H0)假设和另一种假设(H1)来描述.
H0:那里
H1公平与理想价格变量的分布存在差异小组
以下代码可以在R中实现以下代码 :
t.test(price ~ cut, data = data) # Welch Two Sample t-test # # data: price by cut # t = 9.7484, df = 1894.8, p-value < 2.2e-16 # alternative hypothesis: true difference in means is not equal to 0 # 95 percent confidence interval: # 719.9065 1082.5251 # sample estimates: # mean in group Fair mean in group Ideal # 4358.758 3457.542 # Another way to validate the previous results is to just plot the distributions using a box-plot plot(price ~ cut, data = data, ylim = c(0,12000), col = 'deepskyblue3')
我们可以通过检查p值是否低于0.05来分析测试结果.如果是这种情况,我们会保留替代假设.这意味着我们发现了削减因子的两个层次之间的价格差异.根据我们对此结果的预期水平的名称,但我们不会预期Fail组中的平均价格会高于Ideal组中的平均价格.我们可以通过比较每个因子的平均值来看到这一点.
plot 命令生成一个图表,显示价格和切割变量之间的关系.这是一个盒子图;我们在第16.0.1节中介绍了这个图,但它基本上显示了我们正在分析的两个切割级别的价格变量的分布.
方差分析(ANOVA)是用于分析差异的统计模型通过比较每组的均值和方差,在群体分布中,该模型由Ronald Fisher开发. ANOVA提供了几个组的平均值是否相等的统计检验,因此将t检验推广到两个以上的组.
ANOVA可用于比较三个或更多组因为进行多个双样本t检验会导致提交统计类型I错误的机会增加.
在提供数学解释方面,需要以下内容:了解测试.
x ij = x +(x i - x)+(x ij - x)
这导致以下模型 :
x ij =μ +α i +∈ ij
其中μ是伟大的意思,α i 是第i组意思.假设误差项∈ ij 是来自正态分布的iid.测试的零假设是 :
α 1 =α 2 = ... =α k
在计算测试统计量方面,我们需要计算两个值 :
组间差异与减号之间的平方和;
$$ SSD_B = \ _sum_ {i} ^ {k} \sum_ {j} ^ {n}(\ bar {x_ {\bar {i}}} - \ bar {x})^ 2 $ $
群组内的平方和
$$ SSD_W = \ _sum_ {i} ^ {k} \sum_ {j} ^ {n}(\ bar {x_ {\bar {ij}}} - \ bar {x_ {\ bar {i} }})^ 2 $$
其中SSD B 具有k-1的自由度,而SSD W 具有度N-k的自由.然后我们可以定义每个度量的均方差.
MS B = SSD B /(k - 1)
MS w = SSD w /(N - k)
最后,ANOVA中的检验统计量被定义为上述两个量的比率
F = MS B /MS w
遵循具有 k-1 和 N-k 自由度的F分布.如果零假设为真,则F可能接近1.否则,组间均方MSB可能较大,这导致较大的F值.
基本上,ANOVA检查总方差的两个来源,看看哪个部分贡献更多.这就是为什么它被称为方差分析,尽管意图是比较群体均值.
在计算统计量方面,在R中实际上相当简单.下面的例子将演示如何完成并绘制结果.
library(ggplot2) # We will be using the mtcars dataset head(mtcars) # mpg cyl disp hp drat wt qsec vs am gear carb # Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4 # Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4 # Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1 # Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1 # Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2 # Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1 # Let's see if there are differences between the groups of cyl in the mpg variable. data = mtcars[, c('mpg', 'cyl')] fit = lm(mpg ~ cyl, data = mtcars) anova(fit) # Analysis of Variance Table # Response: mpg # Df Sum Sq Mean Sq F value Pr(>F) # cyl 1 817.71 817.71 79.561 6.113e-10 *** # Residuals 30 308.33 10.28 # Signif. codes: 0 *** 0.001 ** 0.01 * 0.05 . # Plot the distribution plot(mpg ~ as.factor(cyl), data = mtcars, col = 'deepskyblue3')
代码将产生以下输出 :
我们在示例中得到的p值明显小于0.05,因此R返回符号'***'来表示这一点.这意味着我们拒绝零假设,并且我们发现 cyl 变量的不同组中的mpg均值之间存在差异.