R语言barplot报错:'height'必须为向量或矩阵(新增分组后)
Hey there! Let's dig into why that barplot error showed up after adding the L1 Spanish group. The error 'height' must be a vector or a matrix tells us exactly what's wrong: the coh object you're passing to barplot() no longer has the structure it needs, which changed when you added the new group.
Common Causes & Fixes
1. First, Check Your coh Object's Structure
Run these commands in your R console to see what you're working with:
class(coh) str(coh)
Before adding the L1 Spanish group, coh was likely a matrix or named vector—exactly what barplot() expects. After adding the new data, it might have become a data frame, list, or some other incompatible structure.
2. Ensure Your Data Is Aggregated & Formatted Correctly
Barplots for grouped percentage data typically work best with wide-format matrices (rows = categories like aspectNames, columns = groups like L1 Spanish). If your data is in long format (like the sample you shared), you'll need to reshape it:
Here's a step-by-step example using tidyverse tools (adjust to match your actual data frame name):
library(dplyr) library(tidyr) # 1. Calculate percentages per group summary_df <- your_data_frame %>% group_by(`L1 SCond`, aspectNames) %>% summarise(percent_source = mean(isSource) * 100, .groups = "drop") # 2. Reshape to wide format (columns = language groups) wide_df <- summary_df %>% pivot_wider(names_from = `L1 SCond`, values_from = percent_source) # 3. Convert to matrix (with aspectNames as row names) coh <- wide_df %>% column_to_rownames("aspectNames") %>% as.matrix()
3. Test with Your Sample Data
Let's use the snippet you provided to verify this works:
# Simulate your sample data sample_df <- data.frame( `L1 SCond` = rep("L1 Spanish", 3), isSource = c(1, 1, 0), aspectNames = c("Imperfective", "Imperfective", "Perfective") ) # Apply the steps above sample_summary <- sample_df %>% group_by(`L1 SCond`, aspectNames) %>% summarise(percent_source = mean(isSource)*100, .groups = "drop") sample_coh <- sample_summary %>% pivot_wider(names_from = `L1 SCond`, values_from = percent_source) %>% column_to_rownames("aspectNames") %>% as.matrix() # Now run barplot—no error! barplot(sample_coh, ylim = c(0, 100), ylab = "% Source")
4. Double-Check Your Original Script's Data Prep
Since your script worked before, look for where coh was originally created (e.g., using table(), prop.table(), or aggregation functions). Make sure this step now includes the L1 Spanish group—sometimes when adding new data, filters or grouping logic might accidentally exclude it, leading to unexpected structures.
Quick Recap
The key fix is ensuring coh is a matrix (or vector) when you pass it to barplot(). Most often, this means reshaping your aggregated long-format data into a wide-format matrix that matches the structure your original script used.
内容的提问来源于stack exchange,提问作者fuskerqq

