簡體   English   中英

R:構造具有數值變量之間所有成對相關性和顯着性水平的數據框

[英]R: construct data frame with all pairwise correlations & significance levels between numeric variables

為了能夠獲取數據框中所有數字變量之間的成對相關性和顯着性水平,我編寫了以下小函數:

corwithsign=function(df,type="pearson") {
  df=df[,sapply(df, is.numeric)] # only keep numeric variables in data frame
  vars=names(df)
  nvars=length(vars)
  nvals=(nvars*nvars-nvars)/2 # number of pairwise correlations between the variables
  vars1=vars2=cors=pvals=n=vector("numeric",nvals) # make empty vectors to store results
  row=1 # row of output table
  for (v1 in (1:(nvars-1))) {
    for (v2 in ((v1+1):nvars)) {
      var1=vars[[v1]]; var2=vars[[v2]]
      vars1[[row]]=var1; vars2[[row]]=var2
      out=cor.test(df[,var1],df[,var2],use="pairwise.complete.obs",method=type)
      cors[[row]]=out$estimate
      pvals[[row]]=out$p.value
      n[[row]]=out$parameter+2 # df + 2
      row=row+1
    }
  }
  data.frame(cbind(var1=vars1,var2=vars2,r=cors,p=pvals,n),row.names=NULL)
}

corwithsign(mtcars,type="pearson")
   var1 var2                   r                    p  n
1   mpg  cyl  -0.852161959426613 6.11268714258096e-10 31
2   mpg disp  -0.847551379262479  9.3803265373813e-10 31
3   mpg   hp  -0.776168371826586 1.78783525412106e-07 31
4   mpg drat   0.681171907806749 1.77623992874132e-05 31
5   mpg   wt  -0.867659376517228 1.29395870135052e-10 31
6   mpg qsec   0.418684033921778   0.0170819884965197 31
7   mpg   vs   0.664038919127593 3.41593725443623e-05 31
8   mpg   am   0.599832429454648 0.000285020743935105 31
9   mpg gear   0.480284757338842  0.00540094822470749 31
10  mpg carb  -0.550925073902459  0.00108444622049168 31
...

我只是想知道是否可能有更短,更優雅的方法來執行此操作,或者是否已經在某些軟件包中實現了這種功能? (我在Hmisc中看到了對rcorr的一些引用,但是輸出了兩個矩陣,這對我沒有好處,因為我只想輸出一個數據幀)。

有什么想法嗎?

干杯,湯姆

如上所述, psych庫具有不錯的corr.test函數,它不僅提供普通的基本cor.test

corr.test(mtcars)$ci

非常接近corwithsign功能

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM