ddply 内的 R ttest 给出错误 "grouping factor must have exactly 2 levels"

标签 r plyr

我有一个包含多个因素和两种表型的数据框

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/

相关文章:

r - purrr::map中的第一个波浪号是什么意思

R Shiny 如何选择输入表单数据框列(响应式(Reactive))

RGA (CRAN) - "get_accounts"提供错误的帐户

r - 在 plyr 调用中使用 svyglm

r - R 中的条件交叉表

r - 按因子值将数据帧分成子集,发送到返回 glm 类的函数,如何重新组合?

r - 将 ggplot 省略号限制为现实/可能的值

r - 仅从 4d NetCDF 文件中提取底部温度

r - ddply 总结比例计数

用 ddply 或 ply-family 函数的创造性使用替换 R 循环