2

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

非常感谢。

埃兹。

4

2 回答 2

3

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

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

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

于 2015-02-22T22:38:46.400 回答
0

你能做类似的事情吗

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])
于 2015-02-22T22:01:59.447 回答