Search code examples
rfunctionchi-squared

Transform the form of the function's result and get the maximum value


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')

Results:

[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

But I want the result like this to be easy to calculate the X-square.

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

Ideal result:

      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

How to transform? I transformed successfully. But I have a new question now......... How to get the maximum value of X-square?

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


Solution

  • You can extract X-square statistic this way:

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

    And than just find the maximum value. But it would be easier to help if your example were reproducible.