corrplot允许您在R中绘制相关矩阵的方式
任何想法我如何在R中绘制关联矩阵关联方法使用的是任何用户指定的方法,例如Cramer's V
解决方案问题的答案在很大程度上取决于您所获得的数据和特定的关联方法.我假设您有一堆标称变量,并想查看它们是否在相关图上使用Cramer的V进行了相关.在这种情况下,可以采用以下方法:
下面列出了执行此操作的难看但有效的代码.我玩过
The way corrplot allows you to plot a correlation matrix in R
Any idea how i can plot a association matrix in R where the method of association is using any user specified method like Cramer's V
解决方案The answer to your question strongly depends on the data you've got and specific correlation method. I assume you have a bunch of nominal variables and want to see whether they are correlated using Cramer's V on the correlation plot. In this case, a way to do this is following:
Ugly but working code to do this is listed below. I played around outer - the clearest and most precise way to work with row and column indexes, but encountered problems with indexing columns in df using row and column index from m: for some reason it just didn't want to get variable from df.
install.packages("vcd") library(vcd) # Simulate some data or paste your own df <- data.frame(x1 = sample(letters[1:5], 20, replace = TRUE), x2 = sample(letters[1:5], 20, replace = TRUE), x3 = sample(letters[1:5], 20, replace = TRUE)) # Initialize empty matrix to store coefficients empty_m <- matrix(ncol = length(df), nrow = length(df), dimnames = list(names(df), names(df))) # Function that accepts matrix for coefficients and data and returns a correlation matrix calculate_cramer <- function(m, df) { for (r in seq(nrow(m))){ for (c in seq(ncol(m))){ m[[r, c]] <- assocstats(table(df[[r]], df[[c]]))$cramer } } return(m) } cor_matrix <- calculate_cramer(empty_m ,data) corrplot(cor_matrix)更多推荐
r中的关联矩阵
发布评论