【问题标题】:How to run cor.test with nested loops如何使用嵌套循环运行 cor.test
【发布时间】:2019-12-03 00:44:47
【问题描述】:

我正在尝试对不同的数据框进行相关性测试,这些数据框表示为员工分配的唯一商店的数量以及同时表示不同区域的列。我的数据框按每个员工拥有的唯一商店数量划分:
unique_store_breakdown <- split(Data, as.factor(Data$unique_stores))

理想情况下我想要输出:

Region -- unique_store -- correlation    
Midwest ------- 1 --------------  .05  
Midwest ------- 2 --------------  .04  
.  
.  
Southeast ----- 1 -------------  0.75  
.  
.
cor_tests <-list() 
counter = 0 

for (i in unique(j$region)){
for (j in 1: length(unique_store_breakdown)){
  counter = counter + 1
  #Create new variables for correlation test
  x = as.numeric(j[j$region == i,]$quality)
  y = as.numeric(j[j$region == i,]$rsv)

  cor_tests[[counter]] <- cor.test(x,y)
}}
cor_tests

我可以一次运行一个数据帧,但是当我尝试添加嵌套循环(j 项)时,我收到错误“错误:$ 运算符对原子向量无效。此外,我还想如果可能,将结果输出为数据框而不是列表。

【问题讨论】:

  • j 只是您循环中的一个整数,您为什么要尝试使用其中的元素,就好像它是一个数据框一样?
  • 您要测试每个商店的qualityrsv 之间的相关性吗?
  • 是的,我希望测试每次迭代的质量和 rsv 之间的相关性

标签: r loops nested correlation data-analysis


【解决方案1】:

如果您只想为每个商店执行cor.test(),那么使用by() 应该相当简单。 by() 的输出是一个常规列表,只是打印有点特别。

# example data
set.seed(1)
dtf <- data.frame(store=rep(1:3, each=30), rsv=rnorm(90))
dtf$quality <- dtf$rsv + rnorm(90, 0, dtf$store)

# perform cor.test for every store
by(dtf, dtf$store, function(x) cor.test(x$quality, x$rsv))
# dtf$store: 1
# 
#   Pearson's product-moment correlation
# 
# data:  x$quality and x$rsv
# t = 5.5485, df = 28, p-value = 6.208e-06
# alternative hypothesis: true correlation is not equal to 0
# 95 percent confidence interval:
#  0.4915547 0.8597796
# sample estimates:
#       cor 
# 0.7236681 
# 
# ------------------------------------------------------------------------------
# dtf$store: 2
# 
#   Pearson's product-moment correlation
# 
# data:  x$quality and x$rsv
# t = 0.68014, df = 28, p-value = 0.502
# alternative hypothesis: true correlation is not equal to 0
# 95 percent confidence interval:
#  -0.2439893  0.4663368
# sample estimates:
#       cor 
# 0.1274862 
# 
# ------------------------------------------------------------------------------
# dtf$store: 3
# 
#   Pearson's product-moment correlation
# 
# data:  x$quality and x$rsv
# t = 2.2899, df = 28, p-value = 0.02977
# alternative hypothesis: true correlation is not equal to 0
# 95 percent confidence interval:
#  0.04304952 0.66261810
# sample estimates:
#      cor 
# 0.397159 
# 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    • 2014-12-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多