>我有这个简单的数据帧。sum 列表示行的总和。我想使用 prop.test 来确定每列的 P 值,并将该数据显示为标记为 p 值的附加行。我可以通过以下方式使用 prop.test 来确定任何单个列的 p 值,但无法弄清楚如何使用单个函数将其应用于多个列。
Other Island N_Shelf N_Shore S_Shore Sum
Type1 10 4 1 0 3 18
Type2 19 45 1 9 11 85
这将输出岛列的 p 值
ResI2<- prop.test(x=TableAvE_Island$Island, n=TableAvE_Island$Sum)
输出:
data: TableAvE_Island$Island out of TableAvE_Island$Sum
X-squared = 4.456, df = 1, p-value = 0.03478
alternative hypothesis: two.sided
95 percent confidence interval:
-0.56027107 -0.05410802
sample estimates:
prop 1 prop 2
0.2222222 0.5294118
我尝试使用 apply 命令,但无法弄清楚它的用法,我能够找到的示例似乎不够相似。任何指示将不胜感激。
下面是broom
函数tidy
,它从测试和其他操作中获取输出并将它们格式化为"整洁"的数据帧。
对于您发布的第一个prop.test
,tidy
输出如下所示:
library(tidyverse)
broom::tidy(prop.test(TableAvE_Island$Island, TableAvE_Island$Sum))
#> estimate1 estimate2 statistic p.value parameter conf.low
#> 1 0.2222222 0.5294118 4.456017 0.03477849 1 -0.5602711
#> conf.high
#> 1 -0.05410802
#> method
#> 1 2-sample test for equality of proportions with continuity correction
#> alternative
#> 1 two.sided
为了对数据框与 Sum 中的所有变量执行此操作,我gather
将其编辑成一个长形状
table_long <- gather(TableAvE_Island, key = variable, value = val, -Sum)
head(table_long)
#> # A tibble: 6 x 3
#> Sum variable val
#> <int> <chr> <int>
#> 1 18 Other 10
#> 2 85 Other 19
#> 3 18 Island 4
#> 4 85 Island 45
#> 5 18 N_Shelf 1
#> 6 85 N_Shelf 1
然后按变量对长形数据进行分组,将其管道化为do
,这允许您在数据帧中的每个组上调用函数,使用.
作为数据子集的代表。然后我在包含prop.test
嵌套结果的列上调用tidy
。这为您提供了所有相关测试结果的数据框,其中显示了"岛"、"N_Shelf"等。
table_long %>%
group_by(variable) %>%
do(test = prop.test(x = .$val, n = .$Sum)) %>%
broom::tidy(test)
#> # A tibble: 5 x 10
#> # Groups: variable [5]
#> variable estimate1 estimate2 statistic p.value parameter conf.low
#> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 Island 0.222 0.529 4.46 0.0348 1 -0.560
#> 2 N_Shelf 0.0556 0.0118 0.0801 0.777 1 -0.0981
#> 3 N_Shore 0 0.106 0.972 0.324 1 -0.205
#> 4 Other 0.556 0.224 6.54 0.0106 1 0.0523
#> 5 S_Shore 0.167 0.129 0.00163 0.968 1 -0.183
#> # ... with 3 more variables: conf.high <dbl>, method <fct>,
#> # alternative <fct>
创建于 2018-05-10 由 reprex 软件包 (v0.2.0(.
我们可以gather
为"long"格式,然后将其存储为list
列
library(tidyverse)
res <- gather(TableAvE_Island, key, val, -Sum) %>%
group_by(key) %>%
nest() %>%
mutate(out = map(data, ~prop.test(.x$val, .x$Sum)))
res$out