R语言Psych包pairs.panels加权相关矩阵绘图报错求助
Hey there! I see exactly what's causing that error when you try to add weights to your pairs.panels plot. Let's break it down and fix it quickly.
The Root Cause
The wt parameter in pairs.panels expects a matrix or data frame (a 2-dimensional structure), but you're passing a 1-dimensional vector (iris[,4]). When the function tries to index this vector like a data frame/matrix (wt[, c(1:2)]), it throws the "incorrect number of dimensions" error because vectors don't have columns to index.
The Fixes
You just need to convert your weight vector into a 2-dimensional structure. Here are two simple ways to do this:
Option 1: Convert to a Data Frame
Wrap your weight vector in data.frame():
require(psych) # Weighted correlations (fixed with data frame weights) pairs.panels(iris[ ,1:3], gap = 0, pch = 21, ellipses = TRUE, show.points = TRUE, smoother = TRUE, rug = FALSE, main = '~ Weighted Correlations', cor = TRUE, wt = data.frame(iris[ ,4]) )
Option 2: Convert to a Matrix
Use as.matrix() to turn the vector into a single-column matrix:
# Weighted correlations (fixed with matrix weights) pairs.panels(iris[ ,1:3], gap = 0, pch = 21, ellipses = TRUE, show.points = TRUE, smoother = TRUE, rug = FALSE, main = '~ Weighted Correlations', cor = TRUE, wt = as.matrix(iris[ ,4]) )
Quick Check
If you want to confirm the difference, run these lines in your console:
# 1-dimensional vector (causes error) str(iris[,4]) # 2-dimensional data frame (works) str(data.frame(iris[,4])) # 2-dimensional matrix (works) str(as.matrix(iris[,4]))
Either fix should make your weighted correlation plot run without errors!
内容的提问来源于stack exchange,提问作者Markm0705

