在 R 中使用 lapply 进行 t 检验时删除 NA

Remove NAs when using mapply for ttest in R

我想在 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 忽略或跳过分析对于这些列?

非常感谢。

aez.

你能做类似的事吗

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])

您可以使用 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

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

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