gpt4 book ai didi

r - R 中的分面或分组相关和相关图

转载 作者:行者123 更新时间:2023-12-04 13:29:17 26 4
gpt4 key购买 nike

我正在尝试从数据框中按组/面绘制相关图。如果我对每个变量的数据进行子集化,我就能做到这一点。我怎样才能一次对所有变量执行此操作以根据每个变量生成刻面图?

###Load libraries
library(gdata)
library(corrplot)
library(ggplot2)
library(gtable)
library(ggpmisc)
library(grid)
library(reshape2)
library(plotly)
packageVersion('plotly')

##Subset ample data from the "iris" data set in R
B<-iris[iris$Species == "virginica", ]

##calculate correlation for numeric columns only
M<-cor(B[,1:4])
head(round(M,2))

###calculate significance
cor.mtest <- function(mat, ...) {
mat <- as.matrix(mat)
n <- ncol(mat)
p.mat<- matrix(NA, n, n)
diag(p.mat) <- 0
for (i in 1:(n - 1)) {
for (j in (i + 1):n) {
tmp <- cor.test(mat[, i], mat[, j], ...)
p.mat[i, j] <- p.mat[j, i] <- tmp$p.value
}
}
colnames(p.mat) <- rownames(p.mat) <- colnames(mat)
p.mat
}
# matrix of the p-value of the correlation
p.mat <- cor.mtest(B[,1:4])

###plot
#color ramp
col<- colorRampPalette(c("red","white","blue"))(40)
corrplot(M, type="upper",tl.col="black", tl.cex=0.7,tl.srt=45, col=col,
p.mat = p.mat, insig = "blank", sig.level = 0.01)

这很有效,因为我只从数据框中取出了一个变量“virginica”。我如何自动执行此操作以进行独特的相关性计算,然后将所有单个变量作为单个方面进行校正?

最佳答案

据我了解,您需要每个 Species 级别的校正图。所以,你可以试试:

library(Hmisc) # this package has implemented a cor function calculating both r and p.  
library(corrplot)
# split the data
B <- split(iris[,1:4], iris$Species)
# Calculate the correlation in all data.frames using lapply
M <- lapply(B, function(x) rcorr(as.matrix(x)))

# Plot three pictures
par(mfrow=c(1,3))
col<- colorRampPalette(c("red","white","blue"))(40)
lapply(M, function(x){
corrplot(x$r, type="upper",tl.col="black", tl.cex=0.7,tl.srt=45, col=col,
p.mat = x$P, insig = "blank", sig.level = 0.01)
})

enter image description here

关于r - R 中的分面或分组相关和相关图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42536187/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com