我有一个数据框,看起来像这样:
Spec. Month SampleMethod Prey1 Prey2
AR April Opp 37.2 23.2
AR April Clu 40.1 19.2
AR April Hom 2.4 70.1
MR April Opp 34.2 27.2
MR April Clu 48.1 13.2
MR April Hom 10.4 5.4
AR May Opp 32.2 21.2
AR May Clu 42.1 11.2
AR May Hom 8.9 71.1我想要做的是在每个月对每个物种的SampleMethod的每种组合运行费舍尔精确测试(例如"Clu“与"Opp";"Opp“vs."Hom";"Hom“与"Clu")。我知道如何做到这一点,通过选择每一对,并使每对新的数据帧,然后运行费舍尔的测试。然而,我想在这一个数据帧中以一种有效的方式做到这一点。例如,如何指定我想要从物种"AR“的”四月“中选择"Opp”样本方法,并将其与来自规范的“四月”月份的"Clu“SampleMethod进行比较。"AR“。我基本上是在尝试这样做,然后在这两个选定的行上运行Fisher's精确测试。然后,我必须在6个不同的月内为7个不同的物种重复这一点,所以任何关于如何做到这一点的帮助都将是很大的。
发布于 2015-12-23 07:20:50
通过使用嵌套的sapply函数,我们将对Spec.和Month的每个组合以及每个子集内的SampleMethod的每个成对组合的数据子集执行费舍尔精确测试。
下面的代码返回列表中的所有结果,其中包含Spec.和Month的每种组合的元素,以及每对SampleMethod的子元素。正是这些子元素包含了测试的输出。
FT.list = sapply(split(DF, list(DF$Spec., DF$Month)), function(dat) {
# If there are at least two rows in a data subset, then proceed with Fisher Test
if(nrow(dat)>=2) {
# Get all pairwise combinations of SampleMethod
SMs = combn(unique(dat$SampleMethod), 2, simplify=FALSE)
# Name each element of SMs so that sapply will return the names in each list element
names(SMs) = lapply(SMs, paste, collapse=", ")
# For each pair of SampleMethod, run Fisher's Exact Test
sapply(SMs, function(methods) {
dat = dat[dat$SampleMethod %in% methods, ]
fisher.test(dat[, grep("Prey", names(dat))])
}, simplify=FALSE)
}
}) https://stackoverflow.com/questions/34425778
复制相似问题