126*_*7b9 1 r partial ggplot2 correlation
我做了部分相关分析,与ggm包
list = list(mtcars, mtcars)
list = lapply(list, function(x) x %>%
mutate(gear = as.factor(gear)))
library(ggm)
lapply(list, function(x) {
sapply(split(x, x$gear), function(x) {
pcor(u = c('mpg', 'disp', 'hp', 'vs'), S = var(x))
})
})
Run Code Online (Sandbox Code Playgroud)
pcor和包装一起
pcorr1 = list %>%
map(function(x) split(x[c('mpg', 'disp', 'hp', 'vs')], x$gear))
coeff = c("pearson", "spearman")
res = lapply(1:2, function(x) lapply(seq(coeff), function(x) {
lapply(pcorr1[[x]], function(y) pcor(y, method = coeff[[x]]))}))
Run Code Online (Sandbox Code Playgroud)
任何人都可以推荐一种如何使用 ggplot2 计算图中的这种相关性的方法吗?
谢谢
UPFATE 只是为了理解,我想知道是否可以使用相关系数作为 y 和 x 所有级别的分组变量(它应该是一种条形图)
我无法理解您的预期输出,但也许您可以使用成对图来显示变量之间的相关性并用您的ggm::pcor()值标记每个图?例如
library(tidyverse)
# install.packages("ggm")
library(ggm)
list_of_mtcars = list(mtcars, mtcars)
list_to_plot = lapply(list_of_mtcars, function(x) x %>%
mutate(gear = as.factor(gear)))
ggm_pcor_vals <- lapply(list_to_plot, function(x) {
sapply(split(x, x$gear), function(x) {
pcor(u = c('mpg', 'disp', 'hp', 'vs'), S = var(x))
})
})
pcorr1 <- list_to_plot %>%
map(function(x) split(x[c('mpg', 'disp', 'hp', 'vs')], x$gear))
coeff <- c("pearson", "spearman")
res <- lapply(1:2, function(x) lapply(seq(coeff), function(x) {
lapply(pcorr1[[x]], function(y) cor(y, method = coeff[x]))}))
library(GGally)
#> Registered S3 method overwritten by 'GGally':
#> method from
#> +.gg ggplot2
map(1:3, \(y) map(pcorr1,
\(x) ggpairs(as.data.frame(x[[y]])) +
ggtitle(paste("ggm pcor mpg vs disp given hp and vs =", round(ggm_pcor_vals[[1]][[y]], 4), "when gear =", names(x)[[y]]))))
#> [[1]]
#> [[1]][[1]]
Run Code Online (Sandbox Code Playgroud)

#>
#> [[1]][[2]]
Run Code Online (Sandbox Code Playgroud)

#>
#>
#> [[2]]
#> [[2]][[1]]
Run Code Online (Sandbox Code Playgroud)

#>
#> [[2]][[2]]
Run Code Online (Sandbox Code Playgroud)

#>
#>
#> [[3]]
#> [[3]][[1]]
Run Code Online (Sandbox Code Playgroud)

#>
#> [[3]][[2]]
Run Code Online (Sandbox Code Playgroud)

创建于 2023-09-05,使用reprex v2.0.2
或者这完全不符合标准?
注意。最好避免使用这个词list作为列表的名称,而且看起来输出中有“重复”的图map(),但我认为这是因为你有list(mtcars, mtcars)输入。
根据您的更新,听起来您想要 pcor 值的条形图?您希望条形图是什么样子?即你会如何改变这个:
#>
#> [[1]][[2]]
Run Code Online (Sandbox Code Playgroud)

创建于 2023-09-08,使用reprex v2.0.2