【问题标题】:T-test with column number instead of column name使用列号而不是列名的 T 检验
【发布时间】:2021-06-05 11:34:57
【问题描述】:

我正在尝试使用 RStatix 的 t_test() 执行一系列 T 检验,其中因变量在每个测试中都是相同的,并且分组变量会发生变化。我在一个循环中进行这些测试,所以我想用列号而不是列名来选择分组变量。我尝试使用colnames(dataframe)[[columnnumber]] 执行此操作,但出现以下错误:“无法提取不存在的列”。如何使用列号而不是列名选择分组变量?

下面是一个带有虚构数据框的最小可复制示例;当指示分组变量的名称(性别)时,测试正常工作,但在指示列号时不能正常工作。

library(tidyverse)
library(rstatix)
dat<-data.frame(gender=rep(c("Male", "Female"), 1000),
              age=rep(c("Young","Young", "Old", "Old"),500),
              tot= round(runif(2000, min=0, max=1),0))

dat %>% t_test(tot ~ gender,detailed=T) ##Works

dat %>% t_test(tot ~ colnames(dat)[[1]],detailed=T) ##Doesn't work

【问题讨论】:

    标签: r t-test rstatix


    【解决方案1】:

    colnames(dat)[1] 是一个字符串。 t_test 需要公式对象,您需要将字符串转换为公式并将其传递给t_test。这可以使用reformulateas.formula 来完成。

    library(rstatix)
    dat %>% t_test(reformulate(colnames(dat)[1], 'tot'),detailed=T)
    
    # A tibble: 1 x 15
    #  estimate estimate1 estimate2 .y.   group1 group2    n1    n2 statistic
    #*    <dbl>     <dbl>     <dbl> <chr> <chr>  <chr>  <int> <int>     <dbl>
    #1    0.011     0.505     0.494 tot   Female Male    1000  1000     0.492
    # … with 6 more variables: p <dbl>, df <dbl>, conf.low <dbl>,
    #   conf.high <dbl>, method <chr>, alternative <chr>
    

    【讨论】:

      【解决方案2】:

      如果我们想使用tidyverse 的构造方式,那么在expr 中执行此操作

      library(rstatix)
      dat %>%
           t_test(formula = eval(rlang::expr(tot ~ !! rlang::sym(names(.)[1]))),
                      detailed = TRUE)
      # A tibble: 1 x 15
      #  estimate estimate1 estimate2 .y.   group1 group2    n1    n2 statistic     p    df conf.low conf.high method alternative
      #*    <dbl>     <dbl>     <dbl> <chr> <chr>  <chr>  <int> <int>     <dbl> <dbl> <dbl>    <dbl>     <dbl> <chr>  <chr>      
      #1    -0.02     0.497     0.517 tot   Female Male    1000  1000    -0.894 0.371 1998.  -0.0639    0.0239 T-test two.sided
      

      注意:值不同,因为数据是在没有任何 set.seed 的情况下构建的(wrt rnorm

      【讨论】:

        猜你喜欢
        • 2012-07-27
        • 2011-12-06
        • 2021-04-16
        • 2021-08-16
        • 1970-01-01
        • 2013-07-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多