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