0

我是R的新手。由于我的项目需要,我需要对十万个条目进行Chisq测试。

我自学了几天,写了一些代码来循环运行 chisq.test。代码:

the.data = read.table ("test_chisq_allelefrq.txt", header=T, sep="\t",row.names=1)
p=c()
ID=c()
for (i in 1:nrow(the.data)) {
data.row = the.data [i,]
data.matrix = matrix ( c(data.row$cohort_1_AA, data.row$cohort_1_AB,       data.row$cohort_1_BB, data.row$cohort_2_AA, data.row$cohort_2_AB, data.row$cohort_2_BB,data.row$cohort_3_AA,data.row$cohort_3_AB,data.row$cohort_3_BB), byrow=T, nrow=3)
chisq = chisq.test(data.matrix)
pvalue=chisq$p.value
p=c(p, pvalue)
No=row.names(the.data)[i]
ID=c(rsid, SNP )
}
results=data.frame(ID,p)
write.table (results,  file = "chisq-test_output.txt", append=F, quote = F, sep = "\t ",eol = "\n", na = "NA", dec = ".", row.names = F, col.names = T) 

这段代码可能有几个问题。但它有效。

但是,它运行非常缓慢。

我尝试通过使用“应用”来改进它

我打算使用两次,而不是使用“for”

datarow= apply (the.data,1,  matrix(the.data, byrow=T, nrow=3))
result=apply(datarow,1,chisq.test)

但是,有错误说矩阵不是函数。zsd chisq.test 输出是一个列表,我不能使用 write.table 来输出数据。

the.data 是这样的。

SN0001 and 9 numbers
           cohort_1_AA cohort_1_AB cohort_1_BB cohort_2_AA cohort_2_AB cohort_2_BB cohort_3_AA cohort_3_AB cohort_3_BB
SN0001     197         964        1088       877      858      168     351    435      20
....
....

我已经尝试了几天几夜。希望可以有人帮帮我。非常感谢你。

4

2 回答 2

0

一个for循环意味着一个apply,而不是两个。

像这样的东西:

result=apply(the.data, 1, function(data.row) {
   ## Your code using data.row
})

如果结果比for循环更具可读性,请使用它。否则坚持你所拥有的。 apply速度不会有明显不同(更快或更慢)。

于 2014-06-23T05:52:38.380 回答
0

要使用应用函数组,首先定义我们自己的函数然后应用它很容易。让我们这样做。

    ##first define the function to apply
    Chsq <- function(x){
   ## input is a row of your data
   ## creating a table from each row
         x <- matrix(x,byrow =TRUE,nrow=3)
    ### this will return the p value
      return(chisq.test(x)$p.value)
    }
## Now apply this function
data = read.table ("test_chisq_allelefrq.txt", header=T, sep="\t",row.names=1)
## by using as.vector convert the output into a vector
P_Values <- as.vector(apply(data,1,Chsq))
result <- cbind(rownames(data),P_Values)
write.table (results,  file = "chisq-test_output.txt", append=F, quote = F, sep = "\t ",eol = "\n", na = "NA", dec = ".", row.names = F, col.names = T) 

试试这个代码,希望它有效!:) 如果它对您有用,请接受正确的答案。谢谢

于 2014-06-23T06:26:57.583 回答