r - 对具有宽数据的数据框进行卡方检验

标签 r chi-squared

我的数据如下所示:

ID  gamesAlone  gamesWithOthers  gamesRemotely  tvAlone  tvWithOthers  tvRemotely
1   1                                                    1
2                                1                       1
3                                1              1
4                                1              1
5                                1                       1
6                                1              1
7                                1              1
8               1                                        1
9   1                                                                   1

我想要可以执行以下两件事的代码:

首先,将其转换为一个整洁的列联表,如下所示:

        Alone   WithOthers   Remotely
games   2       1            6
tv      4       4            1

其次,使用卡方来查看这些事件(游戏与电视)在其社交背景中是否有所不同。

这是生成数据框的代码:

data<-data.frame(ID=c(1,2,3,4,5,6,7,8,9),
             gamesAlone=c(1,NA,NA,NA,NA,NA,NA,NA,1),
             gamesWithOthers=c(NA,NA,NA,NA,NA,NA,NA,1,NA),
             gamesRemotely=c(NA,1,1,1,1,1,1,NA,NA),
             tvAlone=c(NA,NA,1,1,NA,1,1,NA,NA),
             tvWithOthers=c(1,1,NA,NA,1,NA,NA,1,NA),
             tvRemotely=c(NA,NA,NA,NA,NA,NA,NA,NA,1))

最佳答案

省略第一列 id ([-1]),然后计算每列的总和 (colSums),同时删除 >NA 值 (na.rm=TRUE),并将所得长度为 6 的向量放入 2 行矩阵中。如果需要,您还可以相应地标记矩阵维度(dimnames 参数):

m <- matrix(
  colSums(data[-1], na.rm=T), 
  nrow=2, byrow=T, 
  dimnames = list(c("games", "tv"), c("alone", "withOthers", "remotely"))
)
m
#       alone withOthers remotely
# games     2          1        6
# tv        4          4        1
chisq.test(m)
# 
#   Pearson's Chi-squared test
# 
# data:  m
# X-squared = 6.0381, df = 2, p-value = 0.04885

关于r - 对具有宽数据的数据框进行卡方检验,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45559829/

相关文章:

r - 在 R 中为卡方检验格式化数据

r - 如何计算序列中的运行次数?

r - float 条形图

r - 如何合并数据框中具有相同前缀的行?

python - 在 scipy 中找到卡方检验的自由度?

python - 如何获得卡方值作为 scipy.optimize.curve_fit 的输出?

使用 R 在 Tableau 中复制 Excel chisq.test 函数

r - 在 R 中使用分数进行情感分析

r - 满足条件时显示图

r - 在进行卡方检验时修复 for 循环中的列