PageRenderTime 25ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/R/ologit-regression.R

http://github.com/andrewheiss/RcmdrPlugin.MPAStats
R | 197 lines | 175 code | 5 blank | 17 comment | 49 complexity | 64d9af8d95699f4f3bfb8353899dd027 MD5 | raw file
  1. # Modified on November 27, 2013 by Jordan Gressel
  2. ologitWords <- function(x){
  3. wrapper <- function(text){
  4. text2 <- strwrap(text)
  5. for(i in 1:length(text2)){
  6. cat(text2[i],"\n",sep="")
  7. }
  8. cat("\n")
  9. }
  10. yname <- rownames(attr(x$terms,"factors"))[1]
  11. alpha <-.05
  12. long <- nrow(x$coefficients)- length(x$beta)
  13. rev.coef <- x$coefficients[-c(1:long),]
  14. names <- rownames(rev.coef)
  15. # Identify coefficients which are factors and print the output
  16. # Put factor variable names into a list
  17. counter <- 1
  18. varnames <- NA
  19. for(i in 2:length(attr(x$terms,"dataClasses"))){
  20. if(attr(x$terms,"dataClasses")[i]=="factor"){
  21. varnames[counter] <- attr(attr(x$terms,"dataClasses")[i],"names")
  22. counter=counter+1
  23. }
  24. }
  25. # text is the test assumption
  26. text <- paste("Test Information: This test determines for each independent variable in the model whether that variable is a predicts a significant amount of the variance in ",yname,", all other variables held constant.
  27. \n The test assumes proportional odds (the relationship between any pair of groups is the same as any other pair).
  28. \n \n",sep="")
  29. wrapper(text)
  30. # Interpretations of coefficients that are factors
  31. if(is.na(varnames[1]) == "FALSE"){
  32. counter <- 1
  33. factor.coef <- NA
  34. for(i in 1:length(varnames)){
  35. for(j in 1:length(attr(rev.coef,"dimnames")[[1]])){
  36. if(substr(attr(rev.coef,"dimnames")[[1]][j],1,nchar(varnames[i]))==varnames[i]){
  37. factor.coef[counter] <- j
  38. counter <- counter+1
  39. pval <- rev.coef[j,4]
  40. factorname <- substring(names[j],nchar(varnames[i])+4,nchar(names[j])-1)
  41. beta <- rev.coef[j,1]
  42. if(beta >= 0){
  43. sign <- "positive"
  44. moreless <- "more" #alt. updown <- "increases"
  45. }
  46. else if(beta < 0){
  47. sign <- "negative"
  48. moreless <- "less" #alt. updown <- "decreases"
  49. }
  50. if(pval >= alpha){
  51. text1 <- paste("Test Results: ",factorname," has no statistical relationship with ",yname," (alpha=.05). \n \n")
  52. wrapper(text1)
  53. }
  54. else if(pval < alpha){
  55. text1 <- paste("Test Results: Controlling for all other variables in the model, ",varnames[i]," has a statistically significant ",sign," relationship with ",yname,". On average, for a one unit increase in ",factorname,",",yname," is ",round(exp(beta),3),moreless," likely to increase to a higher level. (z=",round(rev.coef[j,3],3),", p=",round(rev.coef[j,4],3),"). \n \n",sep="")
  56. wrapper(text1)
  57. }
  58. }
  59. }
  60. }
  61. }
  62. # Non-factor interpretations
  63. if(exists("factor.coef")){
  64. factor.coef <- factor.coef
  65. }
  66. if(exists("factor.coef") == "FALSE"){
  67. factor.coef <- nrow(rev.coef)+1
  68. }
  69. for(i in seq(1,nrow(rev.coef))[-factor.coef]){
  70. pval <- rev.coef[i,4]
  71. xname <- names[i]
  72. beta <- rev.coef[i,1]
  73. if(beta >= 0){
  74. sign <- "positive"
  75. updown <- "increases"
  76. }
  77. else if(beta < 0){
  78. sign <- "negative"
  79. updown <- "decreases"
  80. }
  81. if(pval >= alpha){
  82. text2 <- paste("Test Results: ",xname," has no statistical relationship with ",yname," (alpha=.05). \n \n",sep="")
  83. wrapper(text2)
  84. }
  85. else if(pval < alpha){
  86. text2 <- paste("Test Results: Controlling for all other variables in the model, ",xname," has a statistically significant ",sign," relationship with ",yname,". For a one unit increase in ",xname,", the likelihood of increasing to a higher level of ",yname," ",updown," by a factor of ",round(exp(beta),3),". (z=",round(rev.coef[i,3],3),", p=",round(rev.coef[i,4],3),"). \n \n",sep="")
  87. wrapper(text2)
  88. }
  89. }
  90. }
  91. # Modified ordinalRegressionModel.ordinal function from Rcmdr: R Commander
  92. ordinalRegressionModelOrdinal2 <- function(){
  93. defaults <- list(initial.type="logit")
  94. dialog.values <- getDialog("ordinalRegressionModelOrdinal2", defaults)
  95. initializeDialog(title=gettextRcmdr("Ordinal Logisitic Regression Model"))
  96. .activeModel <- ActiveModel()
  97. .activeDataSet <- ActiveDataSet()
  98. currentModel <- if (!is.null(.activeModel))
  99. class(get(.activeModel, envir=.GlobalEnv))[1] == "sclm"
  100. else FALSE
  101. if (currentModel) {
  102. currentFields <- formulaFields(get(.activeModel, envir=.GlobalEnv))
  103. if (currentFields$data != .activeDataSet) currentModel <- FALSE
  104. }
  105. if (isTRUE(getRcmdr("reset.model"))) {
  106. currentModel <- FALSE
  107. putRcmdr("reset.model", FALSE)
  108. }
  109. UpdateModelNumber()
  110. modelName <- tclVar(paste("OrdinalLogit.", getRcmdr("modelNumber"), sep=""))
  111. modelFrame <- tkframe(top)
  112. model <- ttkentry(modelFrame, width="20", textvariable=modelName)
  113. radioButtons(name="modelType",
  114. buttons=c("logit", "probit"), initialValue=dialog.values$initial.type,
  115. labels=gettextRcmdr(c("Proportional-odds logit", "Ordered probit")),
  116. title=gettextRcmdr("Type of Model"))
  117. onOK <- function(){
  118. modelValue <- trim.blanks(tclvalue(modelName))
  119. closeDialog()
  120. if (!is.valid.name(modelValue)){
  121. errorCondition(recall=proportionalOddsModel, message=sprintf(gettextRcmdr('"%s" is not a valid name.'), modelValue), model=TRUE)
  122. return()
  123. }
  124. subset <- tclvalue(subsetVariable)
  125. if (trim.blanks(subset) == gettextRcmdr("<all valid cases>") || trim.blanks(subset) == ""){
  126. subset <- ""
  127. putRcmdr("modelWithSubset", FALSE)
  128. }
  129. else{
  130. subset <- paste(", subset=", subset, sep="")
  131. putRcmdr("modelWithSubset", TRUE)
  132. }
  133. check.empty <- gsub(" ", "", tclvalue(lhsVariable))
  134. if ("" == check.empty) {
  135. errorCondition(recall=proportionalOddsModel, message=gettextRcmdr("Left-hand side of model empty."), model=TRUE)
  136. return()
  137. }
  138. check.empty <- gsub(" ", "", tclvalue(rhsVariable))
  139. if ("" == check.empty) {
  140. errorCondition(recall=proportionalOddsModel, message=gettextRcmdr("Right-hand side of model empty."), model=TRUE)
  141. return()
  142. }
  143. if (!is.factor(eval(parse(text=tclvalue(lhsVariable)), envir=get(.activeDataSet, envir=.GlobalEnv)))){
  144. # if (!is.factor(eval(parse(text=tclvalue(lhsVariable)), envir=eval(parse(text=.activeDataSet), envir=.GlobalEnv)))){
  145. errorCondition(recall=proportionalOddsModel, message=gettextRcmdr("Response variable must be a factor"))
  146. return()
  147. }
  148. if (is.element(modelValue, listProportionalOddsModels())) {
  149. if ("no" == tclvalue(checkReplace(modelValue, type=gettextRcmdr("Model")))){
  150. UpdateModelNumber(-1)
  151. proportionalOddsModel()
  152. return()
  153. }
  154. }
  155. putDialog("ordinalRegressionModelOrdinal2", list(initial.type = tclvalue(modelTypeVariable)))
  156. formula <- paste(tclvalue(lhsVariable), tclvalue(rhsVariable), sep=" ~ ")
  157. command <- paste("clm(", formula, ', link="', tclvalue(modelTypeVariable),
  158. '", data=', .activeDataSet, subset, ")", sep="")
  159. # logger(paste(modelValue, " <- ", command, sep=""))
  160. ### assign(modelValue, justDoIt(with(environment(),command)), envir=SUB)
  161. doItAndPrint(paste(modelValue,"<-",command))
  162. ### doItAndPrint(paste("with(SUB,mod <- summary(", modelValue, "))", sep=""))
  163. doItAndPrint(paste("mod <- summary(", modelValue, ")", sep=""))
  164. # Inserted Code:
  165. ### doItAndPrint("with(SUB,mod)")
  166. doItAndPrint("mod")
  167. ### doItAndPrint("with(SUB,ologitWords(mod))")
  168. doItAndPrint("ologitWords(mod)")
  169. # End Insertion
  170. ### activeModel(with(SUB,modelValue))
  171. activeModel(modelValue)
  172. tkfocus(CommanderWindow())
  173. }
  174. OKCancelHelp(helpSubject="clm", model=TRUE, reset = "resetclm")
  175. tkgrid(labelRcmdr(modelFrame, text=gettextRcmdr("Enter name for model:")), model, sticky="w")
  176. tkgrid(modelFrame, sticky="w")
  177. modelFormula()
  178. subsetBox(model=TRUE)
  179. tkgrid(getFrame(xBox), sticky="w")
  180. tkgrid(outerOperatorsFrame, sticky="w")
  181. tkgrid(formulaFrame, sticky="w")
  182. tkgrid(subsetFrame, sticky="w")
  183. tkgrid(modelTypeFrame, sticky="w")
  184. tkgrid(buttonsFrame, sticky="w")
  185. dialogSuffix(rows=7, columns=1, focus=lhsEntry, preventDoubleClick=TRUE)
  186. }
  187. # Reset the clm model dialog
  188. resetclm <- function() {
  189. putRcmdr("reset.model", TRUE)
  190. putDialog("ordinalRegressionModelOrdinal2", NULL)
  191. ordinalRegressionModelOrdinal2()
  192. }