确定数据是否与 R 相关

Determine if data is related in R

我有两个数据集,我想看看它们之间是否存在关系。

第一个数据集包含为健康运动做广告所花的钱,而第二个数据集包含同一时期内的伤亡人数。我想看看花更多的钱是否意味着伤亡更少。比较两者的最佳方法是什么?

关于数据集,都包含一个日期和一个值。

让我们假设

set.seed(44) 
deaths<- 10:1 + sample.int(3, 10, replace = T)

spent<- seq(100, 550, by = 50 )

获得数据后,您要做的第一件事就是查看数据。这可以通过

相对轻松地完成
plot(spent, deaths)

产生

所以看起来我们花的钱越多,死亡人数就越少。这就说得通了。但是我们如何量化该声明。使用 cor() 将为我们提供两个变量 spentdeaths.

之间的相关性
cor(spent, deaths)
# [1] -0.9809581

所以看起来它们非常强(并且呈负相关。)另一种简单的方法(与 cor() 密切相关)是拟合线性模型。

model<- lm(deaths~spent)

summary() 调用会产生很多关于您刚刚拟合的模型的有用信息,这些信息的解释超出了本 post 的范围,但可以通过快速谷歌搜索轻松找到.

summary(model) 

#Call:
#lm(formula = deaths ~ spent)

#Residuals:
# Min       1Q   Median       3Q      Max 
#-0.89697 -0.51515 -0.05758  0.46364  1.01818 

#Coefficients:
#            Estimate Std. Error t value Pr(>|t|)    
#(Intercept) 14.151515   0.539649   26.22 4.80e-09 ***
#spent       -0.021697   0.001519  -14.29 5.62e-07 ***
#---
#Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

#Residual standard error: 0.6898 on 8 degrees of freedom
#Multiple R-squared:  0.9623,   Adjusted R-squared:  0.9576 
#F-statistic: 204.1 on 1 and 8 DF,  p-value: 5.622e-07