从 4 列创建一个卡方表并将其中的 2 个值配对在一起,使一个从属和另一个独立

问题描述

我有下面的列列表。

col 1|col 2|col 3|col 4|col 5|Yes Col_B|No Col_B|Yes Col_W|No Col_W
 1      1      3     3     5          7        9        3         2

我想做的是取最后四列并取 Yes Col_B、No Col_B、Yes Col_W 和 No Col_W,然后将它们想象成两列

Yes or No| B or W
       7       B
       9       B
       3       W
       2       W

现在我有两个临时列,我可以运行一个卡方来指示 Yes 或 No 是否依赖于 B 或 W

 test <- chisq.test(table(data$YesorNo,data$BorW)) 

解决方法

首先我们使用 pivot_longer 中的 tidyr,并将其设置为为每一列创建一个组(行):

newdf = tidyr::pivot_longer(df[,6:9],cols=everything())

给出:

  name      value
1 Yes Col_B     7
2 No Col_B      9
3 Yes Col_W     3
4 No Col_W      2

现在我们需要将 name 列分成两部分,一列表示是或否,一列表示 B 或 W。我们通过在这些名称(正则表达式)中找到模式来做到这一点:

模式是(是或否)(Col_)(B 或 W),我们将其写为 "(Yes|No) Col_(B|W)"。然后我们运行一个循环来为第一组创建一列 - 其中组由方括号设置 -(由 "\\1" 给出),另一列用于第二组("\\2"),并使用 {{ 1}} 来做到这一点。

paste0("\\",i)

输出:

newdf = cbind(NA,NA,newdf) #Creating 2 empty columns

for(i in c(1,2)){
  newdf[,i] = gsub("(Yes|No) Col_(B|W)",paste0("\\",i),newdf$name)}

newdf$name = NULL #Getting rid of the name column
colnames(newdf) = c("Yes or No","B or W","Value")
,

这是 Ricardo 的另一个版本,其中大部分名称拆分和分离是在 pivot_longer 函数中完成的:

df<-data.frame(`Yes Col_B`=7,`No Col_B`=9,`Yes Col_W`=3,`No Col_W`=2) 

library(tidyr)
library(dplyr)

answer <- pivot_longer(df,contains("Col_"),names_sep = "_",names_to=c("Yes_No",".value")) %>% 
               mutate(Yes_No=str_replace(Yes_No,"\\.Col",""))

answer
## A tibble: 2 x 3
#  Yes_No     B     W
#  <chr>  <dbl> <dbl>
#1 Yes        7     3
#2 No         9     8

chisq.test(answer[,c("B","W")])
#since counts are less than 5 suggest the Fisher's Exact Test
fisher.test(answer[,"W")])

chi^2 检验通常每个类别至少需要 5 个成员进行分析,因此我将 Fisher's Exact 检验包括在内。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...