使用 apply 和 t-test 时出错

Error when using apply and t-test

我找不到我代码中的错误,and/or我逻辑中的缺陷。我有一个由 0 和 1 组成的矩阵 X 和一个连续值的向量 y,我想在 R 中进行 2 个样本 t 检验,其中 [=12 的行=]表示y的不同组别。

例如:

x = matrix(rbinom(60,1,.5),ncol=10)
y = abs(rnorm(ncol(x)))

apply(x,1,function(x,y=y)t.test(y[x==1],y[x==0]))

因此,使用此代码我希望得到 6 个 t 检验,其中 X 的每一行对应于 y 的两组。但是,当我 运行 我的代码时出现此错误:

 Error in t.test(y[x == 1], y[x == 0]) : 
  promise already under evaluation: recursive default argument reference or earlier problems? 

谁能解释错误并修改我的代码以获得我想要的。

问题来自您在函数参数中重复使用变量名。这应该有效:

apply(x,1,function(x.f,y.f=y)t.test(y.f[x.f==1],y.f[x.f==0]))

怎么样

apply(x,1,function(x,z)t.test(y[x==1],y[x==0]),y)

如果你想在函数中使用第二个参数,你也应该把它传递给apply

以下作品:

> apply(x,1,function(a)t.test(y[a==1],y[a==0]))    
[[1]]

您应该为 data.frames 中的数据和向量提供更好的名称,以便 x 和 y 等可以用作通用变量。也不需要将 y 发送到函数,因为它对所有测试都是相同的。

输出:

        Welch Two Sample t-test

data:  y[a == 1] and y[a == 0]
t = 0.43835, df = 5.377, p-value = 0.6782
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
 -0.6356057  0.9036413
sample estimates:
mean of x mean of y 
0.5807408 0.4467230 


[[2]]

        Welch Two Sample t-test

data:  y[a == 1] and y[a == 0]
t = -0.80208, df = 5.5382, p-value = 0.4555
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
 -1.0985419  0.5644195
sample estimates:
mean of x mean of y 
0.4337110 0.7007722 


[[3]]

        Welch Two Sample t-test

data:  y[a == 1] and y[a == 0]
t = 0.58194, df = 7.3884, p-value = 0.5779
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
 -0.5584942  0.9283034
sample estimates:
mean of x mean of y 
0.6329878 0.4480832 


[[4]]

        Welch Two Sample t-test

data:  y[a == 1] and y[a == 0]
t = 1.1148, df = 4.8236, p-value = 0.3174
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
 -0.4919082  1.2308641
sample estimates:
mean of x mean of y 
0.7622223 0.3927443 


[[5]]

        Welch Two Sample t-test

data:  y[a == 1] and y[a == 0]
t = 0.23436, df = 5.5539, p-value = 0.8231
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
 -0.7818960  0.9439901
sample estimates:
mean of x mean of y 
0.5729543 0.4919073 


[[6]]

        Welch Two Sample t-test

data:  y[a == 1] and y[a == 0]
t = -1.015, df = 7.9168, p-value = 0.3401
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
 -1.0152988  0.3954558
sample estimates:
mean of x mean of y 
0.3855747 0.6954962 

仅对于 p 值:

> apply(x,1,function(a)t.test(y[a==1],y[a==0])$p.value)
[1] 0.6781895 0.4555338 0.5779255 0.3173567 0.8231019 0.3400979