R语言 如何迭代数据框列名进行ANOVA?

3wabscal  于 2023-05-26  发布在  其他
关注(0)|答案(2)|浏览(169)

我有一个数据框

bbb <- as.data.frame(list(X1 = c(19, 12, 6, 17, 8, 14, 19, 22, 20, 21, 23, 19), 
                                X2 = c(12, 6, 11, 9, 9, 9, 19, 18, 21, 22, 21, 23), 
                                X3 = c(19, 12, 13, 13, 12, 5, 23, 19, 14, 19, 20, 20), 
                                X4 = c(12, 12, 12, 16, 9, 10, 21, 19, 19, 21, 16, 21), 
                                X5 = c(12, 10, 7, 6, 11, 10, 15, 20, 24, 19, 19, 24),
                                cluster = c(1,1,1,1,1,1,2,2,2,2,2,2)))

我想用方差分析从每一列得到p值。我可以一个接一个地做,但我怎么能在循环中做呢?aov不理解来自colnames(bbb)的数据

summary(aov(X1 ~ cluster, data = bbb))[[1]]$'Pr(>F)'[1]

我需要迭代我的dataframe并将p值提取到向量中

vlf7wbxs

vlf7wbxs1#

一种选择是使用purrr package(tidyverse的一部分)中的map()函数,例如:

library(purrr)

bbb <- as.data.frame(list(X1 = c(19, 12, 6, 17, 8, 14, 19, 22, 20, 21, 23, 19), 
                          X2 = c(12, 6, 11, 9, 9, 9, 19, 18, 21, 22, 21, 23), 
                          X3 = c(19, 12, 13, 13, 12, 5, 23, 19, 14, 19, 20, 20), 
                          X4 = c(12, 12, 12, 16, 9, 10, 21, 19, 19, 21, 16, 21), 
                          X5 = c(12, 10, 7, 6, 11, 10, 15, 20, 24, 19, 19, 24),
                          cluster = c(1,1,1,1,1,1,2,2,2,2,2,2)))

summary(aov(X1 ~ cluster, data = bbb))[[1]]$'Pr(>F)'[1]
#> [1] 0.004145981

map(bbb, ~summary(aov(.x ~ cluster, data = bbb))[[1]]$'Pr(>F)'[1])
#> $X1
#> [1] 0.004145981
#> 
#> $X2
#> [1] 1.614913e-06
#> 
#> $X3
#> [1] 0.01052767
#> 
#> $X4
#> [1] 0.0001252443
#> 
#> $X5
#> [1] 7.91075e-05
#> 
#> $cluster
#> [1] 4.842692e-159

创建于2023-05-25带有reprex v2.0.2
这将以列表的形式输出结果,但是您可以unlist()结果,或者根据需要将它们强制到 Dataframe 中

laawzig2

laawzig22#

# Create the dataframe
bbb <- as.data.frame(list(X1 = c(19, 12, 6, 17, 8, 14, 19, 22, 20, 21, 23, 19), 
                          X2 = c(12, 6, 11, 9, 9, 9, 19, 18, 21, 22, 21, 23), 
                          X3 = c(19, 12, 13, 13, 12, 5, 23, 19, 14, 19, 20, 20), 
                          X4 = c(12, 12, 12, 16, 9, 10, 21, 19, 19, 21, 16, 21), 
                          X5 = c(12, 10, 7, 6, 11, 10, 15, 20, 24, 19, 19, 24),
                          cluster = c(1,1,1,1,1,1,2,2,2,2,2,2)))

# Vector to store p-values
p_values <- numeric()

# Perform ANOVA and extract p-values for each column
p_values <- lapply(names(bbb)[1:5], function(col) {
  aov_result <- summary(aov(as.formula(paste(col, "~ cluster")), data = bbb))
  p_value <- aov_result[[1]]$`Pr(>F)`[1]
  return(p_value)
})

# Print the p-values
print(p_values)

相关问题