且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

用 R 中的偏相关系数绘制散点图矩阵

更新时间:2023-12-01 11:10:22

看起来 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])

结果如下