用 R 中的偏相关系数绘制散点图矩阵 [英] Plot scatterplot matrix with partial correlation coefficients in R

查看:209
本文介绍了用 R 中的偏相关系数绘制散点图矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 pairs 函数的修改版本来生成散点图矩阵:

I use a modified version of the pairs function to produce a scatterplot matrix:

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])

看起来像这样:

我想做的是将偏相关系数而不是成对 Pearson's r 放入下面板.

What I would like to do is to put the partial correlation coefficients instead of the pairwise Pearson's r into the lower panel.

我可以很容易地计算偏相关系数:

I can calculate the partial correlation coefficients easily:

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

但我不知道如何修改下面板函数 panel.cor 以便它显示这些值.问题似乎是下面板函数处理成对的 xy 值,而偏相关函数 pcor 需要整个数据帧(或矩阵).

But I couldn't figure out how to modify the lower panel function panel.cor so that it shows these values. The problem seems to be that the lower panel function handles the pairwise x and y values, whereas the partial correlation function pcor requires the entire data frame (or matrix).

推荐答案

看起来 pairs 并没有让这变得很容易.我能想到的最简单的事情是让 panel.cor 窥视父 data.frame 以找到当前面板的行/列索引,然后您可以使用它来索引预先计算的值.这是更新后的 panel.cor 函数

Looks like pairs doesn't make this very easy. Simplest thing I could come up with is to have panel.cor peek into the parent data.frame to find the row/col index for the current panel and then you can use that to index into pre-calculated values. Here's the updated panel.cor function

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)
}

这里使用 parent.frame(2)pairs.default 中实际获取局部变量 ij 函数.我们假设 pp 包含来自 pcor 的值.所以你会在调用 pairs.cor

Here use use parent.frame(2) to actually grab the local variables i and j from the pairs.default function. And we assume that pp contains the values from pcor. So you would define that variable before calling pairs.cor

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

结果如下

这篇关于用 R 中的偏相关系数绘制散点图矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆