我想在R.做fisher.test
我已经拥有列联表的数据(在单独的file.txt中).
我想要:
- 所有文件看起来像这样:
56
989
Run Code Online (Sandbox Code Playgroud)
所有文件只有两行(#1发生,#2未发生);
- 文件名称是:
Anna_50.txt
Anna_100.txt
Anna_200.txt
Ben_50.txt
Ben_100.txt
Ben_200.txt
Run Code Online (Sandbox Code Playgroud)
- 我想为Anna_50和Ben_50做Fisher测试; Anna_100和Ben_100等:
-Questions:
files <- list.files()
Run Code Online (Sandbox Code Playgroud)
如何在文件中匹配Anna_50和Ben_50;
如何创建矩阵作为输入顺序是棘手的.
table <- matrix(c(Anna_50_Occ, Ben_50_Occ, Anna_50_NonOn, Ben_50_NonO)2,2)
Run Code Online (Sandbox Code Playgroud)
如何在所有文件上运行?
期待您的回答.试图让这个尽可能清楚 - 我真的需要这个,但是如果还有一些不清楚的地方,请不要犹豫.
我有一些代码可以做到这一点.但是,由于我没有您的文件,最后一部分可能会失败.
这个想法如下.首先,你从中读取数字files.然后,您创建两个包含文件名的向量.一个用于所有Anna文件,一个用于Ben文件.然后创建一个函数,用于在其中两个对象上运行Fisher测试.通过mapply在文件名的两个向量上同时迭代来实现最终的魔力:
files <- c("Anna_50.txt", "Anna_100.txt", "Anna_200.txt", "Ben_50.txt",
"Ben_100.txt", "Ben_200.txt")
# get the numbers from the filenames
numbers <- vapply(strsplit(vapply(strsplit(files, "\\."), "[", i = 1, ""), "_"), "[", i = 2, "")
# only use those numbers that appear two times:
t.num <- table(numbers)
valid.num <- dimnames(t.num)[[1]][t.num == 2]
# make vector for Anna and Ben (that now have the same ordering)
f.anna <- paste("Anna_", valid.num, ".txt", sep = "")
f.ben <- paste("Ben_", valid.num, ".txt", sep = "")
#Now you can use mapply with a suitable function
# Did not check it as I dont have the files, but the logic should become clear:
run.fisher <- function(file1, file2) {
d1 <- scan(file1)
d2 <- scan(file2)
d.matrix <- matrix(c(d1, d2), byrow = TRUE)
fisher.test(d.matrix)
}
# now use mapply to obtain a list with all results:
mapply(run.fisher, f.anna, f.ben)
Run Code Online (Sandbox Code Playgroud)
更新:实际上你可以减少从文件名中获取数字的行:
files <- vapply(strsplit(files, "[\\._]"), "[", i = 2, "")
Run Code Online (Sandbox Code Playgroud)