r - how to run chisq.test in loops using apply -
r - how to run chisq.test in loops using apply -
i newbie of r. due need of project, need chisq test hundred one thousand entries.
i learned myself few days , write code runing chisq.test in loops. codes:
the.data = read.table ("test_chisq_allelefrq.txt", header=t, sep="\t",row.names=1) p=c() id=c() (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)
this code might have several problems. works.
however, runs slow.
i seek improve using "apply"
i plan utilize apply twice instead of using "for"
datarow= apply (the.data,1, matrix(the.data, byrow=t, nrow=3)) result=apply(datarow,1,chisq.test)
however, there error saying matrix not function. zsd chisq.test output list, cannot utilize write.table output data.
the.data this.
sn0001 , 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 .... ....
i have been trying days , nights. hope can help me. give thanks much.
to utilize apply grouping of functions easy first define our own function , apply it. lets that.
##first define function apply chsq <- function(x){ ## input row of info ## creating table each row x <- matrix(x,byrow =true,nrow=3) ### homecoming p value return(chisq.test(x)$p.value) } ## apply function info = read.table ("test_chisq_allelefrq.txt", header=t, sep="\t",row.names=1) ## using as.vector convert output 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)
try code works !! :) take reply right if works you. thanks
r loops matrix apply chi-squared
Comments
Post a Comment