'Why do I get the message "'names' attribute must be the same length as vector" when I run a for loop with ANOVA (R)?
I'm trying to create a for loop that runs ANOVA. I have a list of dataframes for which I need to run ANOVA, and I want to create a list with the resulting p-values. However, when I run the for loop, I get the following message:
'names' attribute [5] must be the same length as the vector [3]
This is the code I used:
##split my dataframe into a list of dataframes based on what gene the data represents
gene_data_list <- split(df_test, f = df_test$Gene)
##create an empty list to collect p-values
p_values <- list()
##run ANOVA on the list of dataframes
for(i in 1:length(gene_data_list)) {
anova <- aov(value ~ variable, data = gene_data_list[[i]])
summary <- anova_summary(anova)
append(p_values, summary$p)
}
When I run the same code on gene_data_list[[1]] outside the loop, it runs fine.
I've attached a link to the dataframe I've been using:
https://easyupload.io/z5avik
Solution 1:[1]
You can do all this with slightly simpler coding using lapply instead of a for loop:
df_test <- read.csv("Test_dataset.csv")
gene_data_list <- split(df_test, f = df_test$Gene)
# Run ANOVAs
gene_anova <- lapply(gene_data_list, function(x) aov(value ~ variable, data = x))
# Get summaries
summary_list <- lapply(gene_anova, rstatix::anova_summary)
# Create single table
results_table <- do.call(rbind, summary_list)
Output:
head(results_table)
# Effect DFn DFd F p p<.05 ges
# 1 1 2 24 1.3570e+00 0.276 1 0.10200
# AAGAB 1 2 15 1.9334e+27 0.000 2 1.00000
# AAK1 1 2 42 4.0000e-03 0.997 1 0.00017
# AAMDC 1 2 6 4.4182e+29 0.000 2 1.00000
# AATF 1 2 24 8.5433e+28 0.000 2 1.00000
# ABCA2 1 2 33 1.0470e+00 0.362 1 0.06000
Note that if you just wanted a list of p values, you could do
p_list <- lapply(gene_anova, function(x) rstatix::anova_summary(x)$p)
Which gives you a list with each position as the p value
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
