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

Chi-squared test on a data frame with wide data

我有这样的数据:

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

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

首先,将其转换为一个整洁的偶然事件 table,如下所示:

        Alone   WithOthers   Remotely
games   2       1            6
tv      4       4            1

其次,使用卡方检验这些活动(游戏 v 电视)在其社会背景方面是否不同。

这是生成数据框的代码:

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))

这将使您进入您提供的表格中的意外事件 table。建议:将您的数据框称为 data1 而不是 data 以避免混淆。

library(dplyr)
library(tidyr)
data1_table <- data1 %>% 
  gather(key, value, -ID) %>% 
  mutate(activity = ifelse(grepl("^tv", key), substring(key, 1, 2), substring(key, 1, 5)), 
         context = ifelse(grepl("^tv", key), substring(key, 3), substring(key, 6))) %>% 
  group_by(activity, context) %>% 
  summarise(n = sum(value, na.rm = TRUE)) %>% 
  ungroup() %>% 
  spread(context, n)

# A tibble: 2 x 4
  activity Alone Remotely WithOthers
*    <chr> <dbl>    <dbl>      <dbl>
1    games     2        6          1
2       tv     4        1          4

对于卡方:这取决于您要比较的内容,我假设您的真实数据具有更高的计数。您可以像这样将所有内容输入 chisq.test,但我认为这不是很有用:

data1_table %>%
  select(2:4) %>%
  chisq.test()

省略第一列id[-1]),然后在去掉NA的同时取每一列的总和(colSums 个值(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