使用R语言构建微阵列数据基因共表达网络遇报错求助
Hey there! Let's work through this heatmap.2 error you're hitting. The message 'RowSideColors' must be a character vector of length nrow(x) is telling you exactly the problem—your cond_colors vector doesn't match the number of rows in your correlation matrix cor(raw_counts). Here's how to fix it:
Let's start with dimensions to get clear:
- Your
raw_countsmatrix has ~16,000 rows (genes) and some number of columns (samples). - When you run
cor(raw_counts), you're calculating gene-to-gene correlations, so the resulting matrix has the same number of rows as your originalraw_counts—~16,000 (one row per gene). - The
RowSideColorsargument needs one color per row in the heatmap (so one color per gene here). But it sounds like yourcond_colorsis set up for your samples (one color per sample), which is way shorter than 16,000. That's why you're getting the error!
You've got two likely goals—let's cover both:
Option 1: You wanted sample group colors on the column side
If your goal was to highlight sample groups with colors next to the heatmap columns (since raw_counts columns are samples), you need to use ColSideColors instead of RowSideColors. Just make sure cond_colors length matches the number of samples first:
# Verify the length matches your sample count stopifnot(length(cond_colors) == ncol(raw_counts)) # Run the heatmap with column-side colors heatmap.2(cor(raw_counts), ColSideColors = cond_colors, trace = "none")
Option 2: You actually want row-side colors for genes
If you do want to color the gene rows (e.g., based on gene clusters, functional annotations, etc.), you need to create a color vector where every element corresponds to a gene (so length ~16,000). For example:
# Example: If you have a gene cluster annotation vector # Let's say gene_clusters is a vector with one cluster label per gene gene_colors <- dplyr::case_when( gene_clusters == "immune" ~ "darkgreen", gene_clusters == "metabolic" ~ "orange", TRUE ~ "gray" ) # Double-check the length matches your gene count stopifnot(length(gene_colors) == nrow(cor(raw_counts))) # Now run the heatmap with row-side colors heatmap.2(cor(raw_counts), RowSideColors = gene_colors, trace = "none")
Always verify lengths before running the heatmap—it'll save you from this exact issue:
# Print out key dimensions cat("Number of rows in correlation matrix:", nrow(cor(raw_counts)), "\n") cat("Length of your color vector:", length(cond_colors), "\n")
If these numbers don't match, you know exactly where to adjust!
内容的提问来源于stack exchange,提问作者Anam Farooqui

