簡體   English   中英

在R中具有部分相關系數的散點圖散點圖矩陣

[英]Plot scatterplot matrix with partial correlation coefficients in R

我使用pairs函數的修改版本來生成散點圖矩陣:

pairs.cor <- function (x,y,smooth=TRUE, digits=2,  ...)
{
  panel.cor <- function(x, y, ...)
  {
    usr <- par("usr"); on.exit(par(usr))
    par(usr = c(0, 1, 0, 1))
    r.obj = cor.test(x, y,use="pairwise",...)
    r = as.numeric(r.obj$estimate)
    p = r.obj$p.value
    mystars <- ifelse(p < .05, "* ", " ")
    txt <- format(c(r, 0.123456789), digits=digits)[1]
    txt <- paste(txt, mystars, sep="")
    text(0.5, 0.5, txt)
  }
panel.hist <- function(x)
  {
    usr <- par("usr"); on.exit(par(usr))
    par(usr = c(usr[1:2], 0, 1.5) )
    h <- hist(x, plot = FALSE)
    breaks <- h$breaks; nB <- length(breaks)
    y <- h$counts; y <- y/max(y)
    rect(breaks[-nB], 0, breaks[-1], y, col="cyan")
  }
pairs(x,diag.panel=panel.hist,lower.panel=panel.cor,upper.panel=panel.smooth, ...)
} 

pairs.cor(iris[,1:4])

看起來像這樣:

在此處輸入圖片說明

我想做的是將部分相關系數而不是成對的皮爾遜r放到下面的面板中。

我可以很容易地計算出偏相關系數:

library(ppcor)
pcor(iris[,1:4])$estimate

但是我不知道如何修改下部面板功能panel.cor以便顯示這些值。 問題似乎在於下部面板函數處理成對的xy值,而部分相關函數pcor需要整個數據幀(或矩陣)。

看起來像這樣pairs並不容易。 我能想到的最簡單的事情是讓panel.cor窺視父data.frame來查找當前面板的行/列索引,然后可以使用它來索引預先計算的值。 這是更新的panel.cor函數

panel.cor <- function(x, y, ...) {
    env <- parent.frame(2)
    i <- env$i
    j <- env$j
    usr <- par("usr"); on.exit(par(usr))
    par(usr = c(0, 1, 0, 1))
    r = as.numeric(pp[i,j])
    txt <- format(c(r, 0.123456789), digits=digits)[1]
    text(0.5, 0.5, txt)
}

在這里,使用use parent.frame(2)來真正地獲取pairs.default函數中的局部變量ij 並且我們假定pp包含pcor中的值。 因此,您將在調用pairs.cor之前定義該變量。

pp <- ppcor::pcor(iris[,1:4])$estimate
pairs.cor(iris[,1:4])

這給出了以下結果

在此處輸入圖片說明

暫無
暫無

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

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