我有一个包含多个因素和两种表型的数据框
freq sampleID status score snpsincluded
0.5 0001 case 100 all
0.2 0001 case 30 all
0.5 0002 control 110 all
0.5 0003 case 100 del
etc
我想做一个 t.test,比较每组相关因素的病例和对照。我已经尝试过以下方法:
o2 <- ddply(df, c("freq","snpsincluded"), summarise, pval=t.test(score, status)$p.value)
但它提示“分组因子必须恰好有 2 个级别”
我没有缺失值、NA,并且我已检查过:
levels(df$status)
[1] "case" "control"
我错过了一些愚蠢的事情吗? 谢谢!
最佳答案
您会收到错误,因为您会获得至少一个子组的所有分数的唯一状态值。
这会重现错误,所有分数的状态都是唯一的(等于 1)。
dx = read.table(text=' score status
1 1 1
2 2 1
3 3 1 ')
t.test(score ~ status, data = dx)
Error in t.test.formula(score ~ status, data = dx) :
grouping factor must have exactly 2 levels
这解决了问题,但使用 t.test
创建了另一个已知问题,您应该有足够的观察结果(我认为 >= 2):
dx = read.table(text=' score status
1 1 1
2 2 1
3 3 2 ')
t.test(score ~ status, data = dx)
Error in t.test.default(x = 1:2, y = 3L) : not enough 'y' observations
最终解决了所有问题:
dx = read.table(text=' score status
1 1 1
2 2 1
3 3 2
4 4 2')
t.test(score ~ status, data = dx)
Welch Two Sample t-test
data: score by status
t = -2.8284, df = 2, p-value = 0.1056
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
-5.042435 1.042435
sample estimates:
mean in group 1 mean in group 2
1.5 3.5
编辑我解释了问题但没有给出解决方案,因为您没有给出可重现的示例。
一个解决方案是只对好的组进行计算:
ddply(df, c("freq","snpsincluded"), function(x)
{
if(length(unique(x$status)==2)
pval=t.test(score~status,data=x)$p.value
})
关于ddply 内的 R ttest 给出错误 "grouping factor must have exactly 2 levels",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21148658/