You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R中维度不同的典型相关分析(CCA)遇兼容问题求助

Fixing Dimension Mismatch in R for Canonical Correlation Analysis (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:

  1. 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]]
    
  2. 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 column
    
  3. Run the CCA analysis
    Now your datasets have matching row counts (13 observations, one per row), so the cc() 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 16:12:54