【问题标题】:Remove NAs when using mapply for ttest in R在 R 中使用 lapply 进行 t 测试时删除 NA
【发布时间】:2015-04-24 04:21:08
【问题描述】:

我想在 R 中的两个数据帧之间进行逐列测试。即ttest(df1$col1,df2$col1)ttest(df1$col2,df2$col2) 等等....这里最好的选择是使用mapplyMap功能。比如:

mapply(t.test,tnav_DJF_histo.csv[,-1],tnav_DJF.csv[,-1])

完美运行,但如果您的 df 列之一有 NA,则会失败并出现以下错误:

Error in t.test.default(dots[[1L]][[1L]], dots[[2L]][[1L]]) : 
  not enough 'y' observations

问题:如何使用na.rm 完成工作?例如,如果 tnav_DJF.csv[,-1] 中的列有 Nas,但 tnav_DJF_histo.csv[,-1] 中没有 NA,我如何告诉 mapply 忽略或跳过对这些列的分析?

非常感谢。

哎呀。

【问题讨论】:

    标签: r mapply na.rm


    【解决方案1】:

    您可以使用mapply 和匿名函数来执行此操作,如下所示:

    示例数据:

    df1 <- data.frame(a=runif(20), b=runif(20), c=rep(NA,20))
    df2 <- data.frame(a=runif(20), b=runif(20), c=c(NA,1:18,NA))
    #notice df1's third column is just NAs
    

    解决方案:

    mapply 与匿名函数一起使用,如下所示:

    #anonumous function testing for NAs
    mapply(function(x, y) {
      if(all(is.na(x)) || all(is.na(y))) NULL else t.test(x, y, na.action=na.omit)
      }, df1, df2)
    

    输出:

    $a
    
        Welch Two Sample t-test
    
    data:  x and y
    t = 1.4757, df = 37.337, p-value = 0.1484
    alternative hypothesis: true difference in means is not equal to 0
    95 percent confidence interval:
     -0.0543192  0.3458648
    sample estimates:
    mean of x mean of y 
    0.5217619 0.3759890 
    
    
    $b
    
        Welch Two Sample t-test
    
    data:  x and y
    t = 1.1689, df = 37.7, p-value = 0.2498
    alternative hypothesis: true difference in means is not equal to 0
    95 percent confidence interval:
     -0.0815067  0.3041051
    sample estimates:
    mean of x mean of y 
    0.5846343 0.4733351 
    
    
    $c
    NULL
    

    附: t.test 函数中没有要使用的 na.rm 参数。只有一个 na.action 参数,但即使您将其设置为 na.omit(我有),如果所有列元素都是 NA,您仍然会收到错误。

    P.S.2 如果 x 或 y 的某些元素是 NA 则 t.test 函数将通过省略这些元素正常运行。如果您想忽略计算 t.test 如果任何列包含单个 NA,那么您需要将上述函数中的 all 更改为 any

    【讨论】:

    • 太棒了。谢谢,@LyzanderR
    【解决方案2】:

    你可以做类似的事情

    t.test2 <- function(col1, col2){
      df <- complete.cases(cbind(col1, col2))
      if(nrow(df) < 3){return(NA)}
      t.test(df[, 1], df[, 2], na.rm = TRUE)
      }
    mapply(t.test2, csv1[, -1], csv2[, -2])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-19
      • 2018-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多