gpt4 book ai didi

r - R中使用for循环的卡方分析

转载 作者:行者123 更新时间:2023-12-04 10:01:47 24 4
gpt4 key购买 nike

我正在尝试对数据中的所有变量组合进行卡方分析,我的代码是:

Data <- esoph[ , 1:3]
OldStatistic <- NA
for(i in 1:(ncol(Data)-1)){
for(j in (i+1):ncol(Data)){
Statistic <- data.frame("Row"=colnames(Data)[i], "Column"=colnames(Data)[j],
"Chi.Square"=round(chisq.test(Data[ ,i], Data[ ,j])$statistic, 3),
"df"=chisq.test(Data[ ,i], Data[ ,j])$parameter,
"p.value"=round(chisq.test(Data[ ,i], Data[ ,j])$p.value, 3),
row.names=NULL)
temp <- rbind(OldStatistic, Statistic)
OldStatistic <- Statistic
Statistic <- temp
}
}

str(Data)
'data.frame': 88 obs. of 3 variables:
$ agegp: Ord.factor w/ 6 levels "25-34"<"35-44"<..: 1 1 1 1 1 1 1 1 1 1 ...
$ alcgp: Ord.factor w/ 4 levels "0-39g/day"<"40-79"<..: 1 1 1 1 2 2 2 2 3 3 ...
$ tobgp: Ord.factor w/ 4 levels "0-9g/day"<"10-19"<..: 1 2 3 4 1 2 3 4 1 2 ...


Statistic
Row Column Chi.Square df p.value
1 agegp tobgp 2.400 15 1
2 alcgp tobgp 0.619 9 1

我的代码给出了变量 1 与变量 3 以及变量 2 与变量 3 的卡方分析输出,但变量 1 与变量 2 缺少卡方分析输出。我努力尝试但无法修复代码。任何意见和建议将不胜感激。我想对所有可能的组合进行交叉制表。提前致谢。

编辑

我曾经在 SPSS 中进行过这种分析,但现在我想切换到 R。

最佳答案

您的数据样本将不胜感激,但我认为这对您有用。首先,使用 combn 创建所有列的组合.然后编写一个函数与 apply 一起使用函数来遍历组合。我喜欢用 plyr因为很容易在后端指定您想要的数据结构。另请注意,您只需要为每个列组合计算一次卡方检验,这也可以大大加快速度。

library(plyr)

combos <- combn(ncol(Dat),2)

adply(combos, 2, function(x) {
test <- chisq.test(Dat[, x[1]], Dat[, x[2]])

out <- data.frame("Row" = colnames(Dat)[x[1]]
, "Column" = colnames(Dat[x[2]])
, "Chi.Square" = round(test$statistic,3)
, "df"= test$parameter
, "p.value" = round(test$p.value, 3)
)
return(out)

})

关于r - R中使用for循环的卡方分析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7382039/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com