library(CHAID)
data("USvote")
functionB <- function(z,y)
{
for (i in 1:length(table(z[,y])))
{
n<-paste(names(table(z[,y]))[i])
V = paste('vote3')
Formula <- as.formula(paste(y," ~ ", paste(V)))
k = aggregate(Formula,data = z[z[,y] %in% c(names(table(z[,y]))[i]),],function(x) length(x))
print(n)
print(k)
}
}
functionB(USvote,'ager')
结果:
[1] "18-24"
vote3 ager
1 Gore 379
2 Bush 180
[1] "25-34"
vote3 ager
1 Gore 728
2 Bush 793
[1] "35-44"
vote3 ager
1 Gore 1213
2 Bush 1258
[1] "45-54"
vote3 ager
1 Gore 1168
2 Bush 1004
[1] "55-64"
vote3 ager
1 Gore 952
2 Bush 844
[1] "65+"
vote3 ager
1 Gore 1108
2 Bush 988
但是我希望像这样的结果很容易计算出X平方。
ager1 <- aggregate(ager ~ vote3, data = USvote[USvote$ager=="18-24",], function(x) length(x))
ager2 <- aggregate(ager ~ vote3, data = USvote[USvote$ager=="25-34",], function(x) length(x))
ager3 <- aggregate(ager ~ vote3, data = USvote[USvote$ager=="35-44",], function(x) length(x))
ager4 <- aggregate(ager ~ vote3, data = USvote[USvote$ager=="45-54",], function(x) length(x))
ager5 <- aggregate(ager ~ vote3, data = USvote[USvote$ager=="55-64",], function(x) length(x))
ager6 <- aggregate(ager ~ vote3, data = USvote[USvote$ager=="65+",], function(x) length(x))
ager <- cbind(ager1,ager2,ager3,ager4,ager5,ager6)
ager
ager = ager[,-c(3,5,7,9,11)]
colnames(ager) = c("", "18-24", "25-34", "35-44", "45-54", "55-64", "65+")
ager
理想的结果:
18-24 25-34 35-44 45-54 55-64 65+
1 Gore 379 728 1213 1168 952 1108
2 Bush 180 793 1258 1004 844 988
如何改造? 我成功转型了。但我现在有一个新问题......... 如何获得X平方的最大值?
functionA <- function(x)
{
for(i in 1:(ncol(x)-1))
{
for (j in (i+1):(ncol(x)))
{
n<-paste(colnames(x)[i], " vs ", colnames(x)[j], sep="")
k=chisq.test(cbind(as.numeric((x)[,i]),as.numeric((x)[,j])),correct = FALSE, simulate.p.value = TRUE, B = 9999)
s=k$statistic
print(n)
print(s)
}
}
}
答案 0 :(得分:-2)
你可以这样提取X平方统计量:
chisq.test(c(89,37,30,28,2), c(40,20,20,15,5)) -> test
test$statistic
# X-squared
# 15
而不仅仅是找到最大值。但如果您的示例可以重现,那么帮助会更容易。