x / x.expected中的错误:不符合规范的数组

时间:2018-10-19 04:29:49

标签: r

# rm(list=ls(all=T))

# Create matrix and specify dimensions, and name each 
variable
Sdata =  

matrix(c(417.38,91.62,231.54,222.46,209.84,278.16,315.12,492.88) 
, nrow = 2, ncol = 4)
rownames(Sdata)= c("No myocardial infraction", "Myocardial 
Infraction")
colnames(Sdata)= c("No vessel disease", "Sinlge-vessel 
disease","Double-vessel disease","Triple-vessel disease")

Sdata
# specify g-test parameters
g.test.contingency = function(x, print = T) {
  row.sum = apply(x,1,sum)
  col.sum = apply(x,1,sum)
  #sum of all the elements (n)
  n = sum(x)
  x.expected = row.sum %o% col.sum / n
  g = 2*sum(x*log(x/x.expected))
  degf = (nrow(x) - 1) * (ncol(x)-1)
  p.g = 1 - pchisq(g,degf)
  if (print) {
  cat("G-Test for Contingency Tables\n\n")
  cat("Data:\n")
  print(x)
  cat("\n")
  cat("The test statistic is ", signif(g,6),".\n")
  cat("There are ", degf, "degrees of freedom.\n")
  cat("The p-value is ",p.g,".\n\n\n")
}
  return(invisible(list(expected = x.expected,test.stat = g, 
p.value = p.g)))
    }

g.test.contingency(Sdata)

这是我编写的R代码,但是由于您可以在底部看到错误,所以我无法让R运行偶发性分析。有谁知道如何解决这一问题?

1 个答案:

答案 0 :(得分:1)

有错误/错字:col.sum = apply(x,2,sum)