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

后端 未结 4 1308
梦如初夏
梦如初夏 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 14:53

    Use select_if to select only numeric columns then use purrr:map_df to apply t.test against grp. Finally use broom:tidy to get the results in tidy format

    library(tidyverse)
    
    res <- test_data %>% 
      select_if(is.numeric) %>%
      map_df(~ broom::tidy(t.test(. ~ grp)), .id = 'var')
    res
    #> # A tibble: 3 x 11
    #>   var   estimate estimate1 estimate2 statistic p.value parameter conf.low
    #>                                  
    #> 1 a       -0.259      9.78      10.0    -0.587   0.565      16.2    -1.19
    #> 2 b        0.154     15.0       14.8     0.169   0.868      15.4    -1.78
    #> 3 c       -0.359     20.4       20.7    -0.287   0.778      16.5    -3.00
    #> # ... with 3 more variables: conf.high , method ,
    #> #   alternative 
    

    Created on 2019-03-15 by the reprex package (v0.2.1.9000)

提交回复
热议问题