如何在R中通过参数创建chisq.test()

时间:2014-12-03 07:56:43

标签: r statistics

我有以下数据框:

  

DF

User    Feature1    Feature2    Num
name1   a           x1          12
name1   a           x2          3
name1   a           x3          7
name1   b           x2          3
name2   a           x2          8
name2   b           x3          7
name2   c           x2          3

...

第一行exp:user" name1"从" a"连接到" x1" 12次。

我想为每个用户在M1到M2之间创建一个chisq.test()表(考虑到连接数)。

输出表中的行数应等于数据框中的用户数。

谢谢!

1 个答案:

答案 0 :(得分:0)

数据示例的问题是,如果任何列或行总和为0,chisq.test将返回NA。

by( df[-1], df[[1]], function(d) { 
                tbl <- xtabs(Num ~ Feature1 + Feature2, data=d)
                i <- apply( tbl, 1, sum ) > 0
                j <- apply( tbl, 2, sum ) > 0
                chisq.test( tbl[i,j] )})
#-------- result ----------
df[[1]]: name1

    Pearson's Chi-squared test

data:  tbl[i, j]
X-squared = 10.7955, df = 2, p-value = 0.004527

---------------------------------------------------------------- 
df[[1]]: name2

    Pearson's Chi-squared test

data:  tbl[i, j]
X-squared = 18, df = 2, p-value = 0.0001234