R: t-test over all columns

后端 未结 5 757
醉话见心
醉话见心 2020-11-28 14:22

I tried to do t-test to all columns (two at a time) of my data frame, and extract only the p-value. Here is what I have come up with:

for (i in c(5:525) ) {
         


        
5条回答
  •  [愿得一人]
    2020-11-28 14:29

    Assuming your data frame looks something like this:

    df = data.frame(a=runif(100),
                    b=runif(100),
                    c=runif(100),
                    d=runif(100),
                    e=runif(100),
                    f=runif(100))
    

    the the following

    tests = lapply(seq(1,length(df),by=2),function(x){t.test(df[,x],df[,x+1])})
    

    will give you tests for each set of columns. Note that this will only give you a t.test for a & b, c & d, and e & f. if you wanted a & b, b & c, c & d, d & e, and e & f, then you would have to do:

    tests = lapply(seq(1,(length(df)-1)),function(x){t.test(df[,x],df[,x+1])})      
    

    finally if let's say you only want the P values from your tests then you can do this:

    pvals = sapply(tests, function(x){x$p.value})
    

    If you are not sure how to work with an object, try typing summary(tests), and str(tests[[1]]) - in this case test is a list of htest objects, and you want to know the structure of the htest object, not necessarily the list.

    Hope this helped!

提交回复
热议问题