我对 R
世界还很陌生。我有以下测试数据:
A<-tibble(parasite=sample(0:1,10,rep=TRUE),L1=sample(0:1,10,rep=TRUE),
L2=sample(0:1,10,rep=TRUE),L3=sample(0:1,10,rep=TRUE),
L4=sample(0:1,10,rep=TRUE))
看起来像:
parasite L1 L2 L3 L4
1 0 0 1 0 0
2 1 0 1 1 1
3 1 1 1 0 1
4 0 1 1 1 0
5 1 1 1 1 0
...10 rows total
我想做的是运行 4 个 chisq 测试:
1.寄生虫 vs L1
2.寄生虫 vs L2
3.寄生虫 vs L3
4.寄生虫 vs L4
然后,我想生成一个摘要标题,其中列出了测试的每个表的 Y 分量(L1、L2...)、chisq 值和 p 值(四舍五入到合理的范围)。喜欢:
variable chisq pvalue
L1 1.475 0.0892
L2 18.453 0.0000E8
L3 2.4781 0.0012
L4 0.6785 0.2755
我已经看到使用 map
来做类似的事情,但我无法让它工作,但由于我正在学习,任何简洁的方法都将不胜感激。
例如
map(~chisq.test(.x, data$column)) %>%
tibble(names = names(.), data = .) %>%
mutate(stats = map(data, tidy))
unnest(data,stats)
谁能告诉我如何做到这一点?
谢谢!
最佳答案
这是一种方法:将数据变成长形状,在分组数据帧上使用 do
调用 chisq.test
,然后使用 整理输出扫帚
。
library(tidyverse)
set.seed(1)
A <-tibble(parasite=sample(0:1,10,rep=TRUE),
L1=sample(0:1,10,rep=TRUE),
L2=sample(0:1,10,rep=TRUE),
L3=sample(0:1,10,rep=TRUE),
L4=sample(0:1,10,rep=TRUE))
A %>%
gather(key = variable, value = value, -parasite) %>%
group_by(variable) %>%
do(chisq.test(.$parasite, .$value) %>% broom::tidy())
#> # A tibble: 4 x 5
#> # Groups: variable [4]
#> variable statistic p.value parameter method
#> <chr> <dbl> <dbl> <int> <chr>
#> 1 L1 0. 1 1 Pearson's Chi-squared test
#> 2 L2 2.93e-32 1.000 1 Pearson's Chi-squared test with Ya…
#> 3 L3 0. 1 1 Pearson's Chi-squared test
#> 4 L4 2.34e- 1 0.628 1 Pearson's Chi-squared test with Ya…
由reprex package于2018年5月11日创建(v0.2.0)。
关于使用 purrr 在一个数据集上运行多个 chisq 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50299430/