2016-01-05 29 views
-14
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) 
    } 
    } 
} 

functionA Result

+1

發佈圖片而不是文字的原因是什麼? –

+0

在你的函數中,你沒有返回任何東西;只是打印結果。既然你想保存被測試的兩個組的名稱和它們各自的X平方值,你應該預先分配一個名稱向量('VS = character(choose(6,2))'),另一個給X- sq('Xsq = numeric(choose(6,2))'),並且在每次迭代中將「n」和「k」保存在相應的向量中。順便說一句,使你的函數作爲一個二進制文件應該會更方便一些(例如'myfun = function(x,y)setNames(chisq.test(x,y,...),paste(x,「VS」,y) )')並使用'combn'將你的函數應用到你的列的所有組合。 –

+0

@WernerHenze因爲它會混亂......我不知道原因是什麼....... –

回答

-2

您可以提取X方統計是這樣的:

chisq.test(c(89,37,30,28,2), c(40,20,20,15,5)) -> test 
test$statistic 

# X-squared 
#  15 

而不僅僅是找到的最大值。但如果您的示例具有可重複性,則幫助會更容易。

+0

感謝您的迴應。但我用函數A(ager)來運算結果。 「functionA(ager)$統計」不起作用。你知道如何解決它嗎? –

+0

@ZheZhang用一個最小和可重現的例子來問一個問題。 –

+0

@Pascal我編輯我的問題,但它是無序的............ –

相關問題