所以我有一些格式如下的数据:
header1 header2
"nocandy" "nocandy"
"nocandy" "nocandy"
"nocandy" "nocandy"
"nocandy" "candy"
"nocandy" "candy"
"candy" "candy"
etc...
我用导入了它,candytext <- read.table("candytest.txt", header=TRUE)
我想进行卡方检验以查看两组之间是否存在差异。当我使用该函数时table(candytest)
,会得到如下信息:
header2
header1 candy nocandy
candy 112 39
nocandy 4 82
但是,如果我跑步,summary(candytest)
我会得到如下信息:
header1 header2
candy :151 candy :116
nocandy: 86 nocandy:121
如您所见,两个表的格式不同。但是,我可以在第一个表上运行卡方测试,但不能在第二个表上运行。但是,摘要表更像是我需要使用的表格chisq.test()
。第二张表看起来像是假设数据已配对,但数据未配对。如果配对,那就可以了,我可以在的输出上使用McNemars测试table(candytest)
,但是没有配对。因此,如何创建一个像汇总表一样的2 x 2矩阵,而无需手动输入。我意识到我可以将摘要表复制到矩阵中,但是我想知道如何使用函数正确地将其转换为R。
谢谢!
在这里,我试图假设summary
每一列都是因素,而df1
使用上每一列。从帖子中,我想是这种情况。在输出上使用,将其转换为。lapply
classes
do.call(data.frame
list
data.frame
do.call(data.frame,lapply(df1, summary)) #in case a matrix output is needed, just replace `data.frame` with `cbind`
# header1 header2
#candy 1 3
#nocandy 5 3
summary(df1)
# header1 header2
#candy :1 candy :3
#nocandy:5 nocandy:3
如果您只需要从数据集中的许多列中选择列,
nm1 <- paste0("header",1:2) #names of columns to do the summary
do.call(`cbind`, lapply(df1[nm1], summary))
# header1 header2
#candy 1 3
#nocandy 5 3
您也可以summary
使用data.table
library(data.table)
DT <- setDT(df1)[, lapply(.SD, summary)] #or
#DT <- setDT(df1)[, lapply(.SD, table)]
DT
# header1 header2
#1: 1 3
#2: 5 3
chisq.test(DT)
# Pearson's Chi-squared test with Yates' continuity correction
#data: DT
#X-squared = 0.375, df = 1, p-value = 0.5403
#Warning message:
#In chisq.test(DT) : Chi-squared approximation may be incorrect
df1 <- structure(list(header1 = structure(c(2L, 2L, 2L, 2L, 2L, 1L), .Label = c("candy",
"nocandy"), class = "factor"), header2 = structure(c(2L, 2L,
2L, 1L, 1L, 1L), .Label = c("candy", "nocandy"), class = "factor")), .Names = c("header1",
"header2"), row.names = c(NA, -6L), class = "data.frame")
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句