我有这个数据框:
pb2 <- read.table(header=T, text="
PT1 PT2
1 0 13
2 4636 4623
3 2 11
4 4634 4625
5 3 11
6 4633 4625
7 2 17
8 4634 4619
9 6 25
10 4630 4611")
我想运行几个卡方检验并按如下方式提取 p 值,但显然以更有效的方式,例如使用循环:
tests <- list()
tests[[1]] <- chisq.test(pb2[c(1,2),], correct=F,simulate.p.value =T,B = 10000)
tests[[2]] <- chisq.test(pb2[c(3,4),], correct=F,simulate.p.value =T,B = 10000)
tests[[3]] <- chisq.test(pb2[c(5,6),], correct=F,simulate.p.value =T,B = 10000)
tests[[4]] <- chisq.test(pb2[c(7,8),], correct=F,simulate.p.value =T,B = 10000)
tests[[5]] <- chisq.test(pb2[c(9,10),], correct=F,simulate.p.value =T,B = 10000)
pb3 <- sapply(tests, function(x) {
c(p.value = x$p.value)
})
pb4<-as.data.frame(pb3)
如果您能向我展示如何为此过程创建一个循环,我真的很感激。
最佳答案
您可以将数据框拆分为每两行,然后使用 lapply
循环遍历数据框列表并执行 chi-square.test
:
lapply(split(pb2, (1:nrow(pb2) - 1)%/%2),
function(data) chisq.test(data, correct = F, simulate.p.value = T, B = 10000)$p.value)
# $`0`
# [1] 0.00029997
# $`1`
# [1] 0.01989801
# $`2`
# [1] 0.05649435
# $`3`
# [1] 0.00089991
# $`4`
# [1] 0.00149985
关于r - 如何编写一个循环来运行两列数据框的卡方?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38926463/