R中维度不同的典型相关分析(CCA)遇兼容问题求助
Hey there! I can totally relate to this frustrating dimension error—let's break down what's going wrong and fix it step by step.
The Core Problem: Your Data Structure is Transposed
Looking at your data, it's structured with variables as rows (X1-X7, Y1-Y5) and observations as columns. But every CCA function in R expects the opposite: rows = individual observations/samples, columns = variables.
When you extracted CETNEWx <- CETNEW[1:7,] and CETNEWy <- CETNEW[8:12,], you ended up with two datasets where rows are variables, not samples. That's why the functions throw "incompatible dimensions" errors—they're trying to calculate covariance between two sets with different numbers of "samples" (7 vs 5 rows), which doesn't make sense for CCA.
Step-by-Step Fix
Let's adjust your data structure and re-run the analysis:
Transpose the numeric data
First, we'll drop the first column (variable names), transpose the remaining numeric values to swap rows and columns, then add back the variable names as column headers:# Remove the first column (variable labels) and transpose the numeric data CETNEW_transposed <- t(CETNEW[, -1]) # Assign original variable names as column names for the transposed data colnames(CETNEW_transposed) <- CETNEW[[1]]Correctly extract X and Y variable sets
Now that observations are rows and variables are columns, we can pull the X variables (first 7 columns) and Y variables (last 5 columns):CETNEWx <- CETNEW_transposed[, 1:7] # 7 X variables, one per column CETNEWy <- CETNEW_transposed[, 8:12] # 5 Y variables, one per columnRun the CCA analysis
Now your datasets have matching row counts (13 observations, one per row), so thecc()function should work without dimension errors:library(CCA) ccCETNEW <- cc(CETNEWx, CETNEWy) # View the results summary(ccCETNEW)
Why This Works (And Why SAS Worked)
SAS might have implicitly handled this transposition, or your professor likely adjusted the data structure before running CCA in SAS. R is stricter about requiring observations as rows for multivariate analyses like CCA, so we had to explicitly fix the structure.
You can verify the dimensions of your corrected datasets with dim(CETNEWx) and dim(CETNEWy)—both should return 13 7 and 13 5 respectively, which are compatible for CCA.
内容的提问来源于stack exchange,提问作者vinbaronen

