从 4 列创建一个卡方表并将其中的 2 个值配对在一起,使一个从属和另一个独立 [英] Create a chi-square table from 4 columns and pair 2 of the values together to make one dependent and other indenpendent
问题描述
我有下面的列列表.
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,然后将它们想象成两列
What i would like to do is take the last four columns and take Yes Col_B, No Col_B, Yes Col_W, and No Col_W and then imagine them as two columns
Yes or No| B or W
7 B
9 B
3 W
2 W
现在我有两个临时列,我可以运行一个卡方来指示 Yes 或 No 是否依赖于 B 或 W
Now that i have two temporary columns I could run a chisquare to indicate if Yes or No is dependent on B or W
test <- chisq.test(table(data$YesorNo, data$BorW))
推荐答案
这是 Ricardo 的另一个版本,其中大部分名称拆分和分离是在 pivot_longer
函数中完成的:
Here is another version to Ricardo, where most of the name splitting and separation is accomplished within the pivot_longer
function:
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[ , c("B", "W")])
chi^2 检验通常每个类别至少需要 5 个成员进行分析,因此我将 Fisher's Exact 检验包括在内.
The chi^2 test generally needs at least 5 members per category for analysis, thus I have included the Fisher's Exact test as alternative.
这篇关于从 4 列创建一个卡方表并将其中的 2 个值配对在一起,使一个从属和另一个独立的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!