R: t test over multiple columns using t.test function

后端 未结 4 1275
梦如初夏
梦如初夏 2021-01-19 14:29

I tried to perform independent t-test for many columns of a dataframe. For example, i created a data frame

set seed(333)
a <- rnorm(20, 10, 1)
b <- rno         


        
4条回答
  •  臣服心动
    2021-01-19 15:16

    As you asked for a for loop:

      a <- rnorm(20, 10, 1)
      b <- rnorm(20, 15, 2)
      c <- rnorm(20, 20, 3)
      grp <- rep(c('m', 'y'),10)
      test_data <- data.frame(a, b, c, grp)  
    
      meanM=NULL
      meanY=NULL
      p.value=NULL
    
      for (i in 1:(ncol(test_data)-1)){
        meanM=as.data.frame(rbind(meanM, t.test(test_data[,i] ~ grp)$estimate[1]))
        meanY=as.data.frame(rbind(meanY, t.test(test_data[,i] ~ grp)$estimate[2]))
        p.value=as.data.frame(rbind(p.value, t.test(test_data[,i] ~ grp)$p.value))
       }
    
      cbind(meanM, meanY, p.value)
    

    It works, but I am a beginner in R. So maybe there is a more efficient solution

提交回复
热议问题