为R tidyverse环境中2个列表元素的所有组合计算多个t检验

我正在寻找一种方法,可以在R tidyverse环境中为2个列表元素的所有组合计算多个t检验。

我想基于yl和vs的每种组合,根据传输率测试Miles /(US)加仑的均值。我的工作示例是以下代码:

mtcars %>%
  filter(cyl==8 & vs == 0) %>%
  mutate(am = as.factor(am)) %>%

  # independent t-test
  t.test(mpg ~ am,data = .,paired = FALSE)%>%
  broom::tidy() %>%

  mutate(cyl = 8) %>%
  mutate(vs  = 0)   %>%
  select(cyl,vs,everything())

我写了这段代码:

cyl_list <- list(unique(mtcars$cyl)) # 6 4 8
vs_list  <- list(unique(mtcars$vs))  # 0 1


complete_t_test <- function(cyl_par,vs_par){

  mtcars %>%
    filter(cyl=={cyl_par} & vs == {vs_par}) %>%
    mutate(am = as.factor(am)) %>%

    # independent t-test
    t.test(mpg ~ am,paired = FALSE) %>%
    broom::tidy() %>%

    mutate(cyl = {cyl_par}) %>%
    mutate(vs  = {vs_par})   %>%
    select(cyl,everything())}

我在想类似purrr::map2(cyl_list,vs_list,complete_t_test)的东西  但这没用。

xiaoylcs721521 回答:为R tidyverse环境中2个列表元素的所有组合计算多个t检验

列表列可能是一个可行的解决方案(请参见R for Data Science,chapter 25书)。我使用nest()创建一个列表列,然后进行t检验,然后再次unnest()来查看结果。

注意:您的示例对mtcars数据中的几种组合都失败了,因此,仅当有适当数据可用时,我才使用possibly()进行t检验。

library("tidyverse")

f1 <- possibly(~t.test(mpg ~ am,data = .x),otherwise = NULL)

mtcars %>% 
    group_by(cyl,vs) %>% 
    nest() %>%                                 # create list columns
    mutate(res = map(data,~f1(.x))) %>%       # do t-tests
    mutate(res = map(res,broom::tidy)) %>%    # tidy()
    unnest(res) %>%                            # unnest list columns
    select(1:8)                                # show some columns for stackoverflow
#> # A tibble: 2 x 8
#> # Groups:   cyl,vs [2]
#>     cyl    vs           data estimate estimate1 estimate2 statistic p.value
#>   <dbl> <dbl> <list<df[,9]>>    <dbl>     <dbl>     <dbl>     <dbl>   <dbl>
#> 1     4     1       [10 x 9]   -5.47       22.9      28.4    -2.76   0.0254
#> 2     8     0       [14 x 9]   -0.350      15.0      15.4    -0.391  0.704

reprex package(v0.3.0)于2019-11-04创建

,

写一个函数来计算一个组合之间的t.test。使用cross_df创建所有组合,并将功能complete_t_test应用于每个组合。

library(tidyverse)

complete_t_test <- function(cyl_par,vs_par) {
   tryCatch({
      mtcars %>%
       filter(cyl== cyl_par & vs == vs_par) %>%
       t.test(mpg ~ am,data = .,paired = FALSE) %>%
       broom::tidy()
   },error = function(e) return(NA))
}

cyl_list <- unique(mtcars$cyl)
vs_list  <- unique(mtcars$vs)

cross_df(list(a = cyl_list,b = vs_list)) %>%
   mutate(t_test = map2(a,b,complete_t_test))

#     a     b   t_test           
#   <dbl> <dbl> <list>           
#1     6     0 <lgl [1]>        
#2     4     0 <lgl [1]>        
#3     8     0 <tibble [1 × 10]>
#4     6     1 <lgl [1]>        
#5     4     1 <tibble [1 × 10]>
#6     8     1 <lgl [1]>       
本文链接:https://www.f2er.com/3168152.html

大家都在问