3
# last modified 22 June 07 by J. Fox
5
selectActiveModel <- function(){
6
models <- listAllModels()
7
.activeModel <- ActiveModel()
8
if ((length(models) == 1) && !is.null(.activeModel)) {
9
Message(message=gettextRcmdr("There is only one model in memory."),
11
tkfocus(CommanderWindow())
14
if (length(models) == 0){
15
Message(message=gettextRcmdr("There are no models from which to choose."),
17
tkfocus(CommanderWindow())
20
initializeDialog(title=gettextRcmdr("Select Model"))
21
.activeDataSet <- ActiveDataSet()
22
initial <- if (is.null(.activeModel)) NULL else which(.activeModel == models) - 1
23
modelsBox <- variableListBox(top, models, title=gettextRcmdr("Models (pick one)"),
24
initialSelection=initial)
26
model <- getSelection(modelsBox)
28
if (length(model) == 0) {
29
tkfocus(CommanderWindow())
32
dataSet <- eval(parse(text=paste("as.character(", model, "$call$data)")))
33
if (length(dataSet) == 0){
34
errorCondition(message=gettextRcmdr("There is no dataset associated with this model."))
37
dataSets <- listDataSets()
38
if (!is.element(dataSet, dataSets)){
39
errorCondition(message=sprintf(gettextRcmdr("The dataset associated with this model, %s, is not in memory."), dataSet))
42
if (is.null(.activeDataSet) || (dataSet != .activeDataSet)) activeDataSet(dataSet)
44
tkfocus(CommanderWindow())
47
nameFrame <- tkframe(top)
48
tkgrid(tklabel(nameFrame, fg="blue", text=gettextRcmdr("Current Model: ")),
49
tklabel(nameFrame, text=tclvalue(getRcmdr("modelName"))), sticky="w")
50
tkgrid(nameFrame, sticky="w", columnspan="2")
51
tkgrid(getFrame(modelsBox), columnspan="2", sticky="w")
52
tkgrid(buttonsFrame, columnspan=2, sticky="w")
53
dialogSuffix(rows=3, columns=2)
56
summarizeModel <- function(){
57
.activeModel <- ActiveModel()
58
if (is.null(.activeModel) || !checkMethod("summary", .activeModel)) return()
59
doItAndPrint(paste("summary(", .activeModel, ", cor=FALSE)", sep=""))
62
plotModel <- function(){
63
.activeModel <- ActiveModel()
64
if (is.null(.activeModel) || !checkMethod("plot", .activeModel)) return()
65
command <- "oldpar <- par(oma=c(0,0,3,0), mfrow=c(2,2))"
68
doItAndPrint(paste("plot(", .activeModel, ")", sep=""))
69
command <- "par(oldpar)"
74
CRPlots <- function(){
76
.activeModel <- ActiveModel()
77
if (is.null(.activeModel) || !checkMethod("cr.plot", .activeModel)) return()
78
doItAndPrint(paste("cr.plots(", .activeModel, ", ask=FALSE)", sep=""))
82
AVPlots <- function(){
84
.activeModel <- ActiveModel()
85
if (is.null(.activeModel) || !checkMethod("av.plot", .activeModel)) return()
86
response <- tclvalue(RcmdrTkmessageBox(message=gettextRcmdr("Identify points with mouse?"),
87
icon="question", type="yesno", default="no"))
88
doItAndPrint(paste("av.plots(", .activeModel, ", ask=FALSE, identify.points=",
89
response=="yes", ")", sep=""))
93
anovaTable <- function(){
95
.activeModel <- ActiveModel()
96
if (is.null(.activeModel)) return()
97
if (!checkMethod("Anova", .activeModel)) {
98
errorCondition(message=gettextRcmdr("There is no appropriate Anova method for a model of this class."))
101
doItAndPrint(paste("Anova(", .activeModel, ")", sep=""))
106
.activeModel <- ActiveModel()
107
if (is.null(.activeModel) || !checkMethod("vif", .activeModel)) return()
108
doItAndPrint(paste("vif(", .activeModel, ")", sep=""))
111
InfluencePlot <- function(){
113
.activeModel <- ActiveModel()
114
if (is.null(.activeModel) || !checkMethod("influencePlot", .activeModel)) return()
115
response <- tclvalue(RcmdrTkmessageBox(message=gettextRcmdr("Identify points with mouse?"),
116
icon="question", type="yesno", default="no"))
117
labels <- if (response == "no") ", labels=FALSE" else ""
118
doItAndPrint(paste("influencePlot(", .activeModel, labels, ")", sep=""))
121
effectPlots <- function(){
123
.activeModel <- ActiveModel()
124
if (is.null(.activeModel) || !checkMethod("effect", .activeModel)) return()
125
doItAndPrint('trellis.device(theme="col.whitebg")')
126
command <- paste("plot(all.effects(", .activeModel, "), ask=FALSE)", sep="")
133
addObservationStatistics <- function(){
134
if (is.null(.activeModel)) return()
135
addVariable <- function(name){
136
variable <- paste(name, ".", .activeModel, sep="")
137
if (is.element(variable, .variables)) {
138
ans <- checkReplace(variable)
139
if (tclvalue(ans) == "no") return()
141
command <- paste(name, "(", .activeModel, ")", sep="")
142
justDoIt(paste(.activeDataSet, "$", variable, " <- ", command, sep=""))
143
logger(paste(.activeDataSet, "$", variable, " <- ", command, sep=""))
145
if (getRcmdr("modelWithSubset")){
147
gettextRcmdr("Observation statistics not available\nfor a model fit to a subset of the data."),
152
initializeDialog(title=gettextRcmdr("Add Observation Statistics to Data"))
153
.activeModel <- ActiveModel()
154
.activeDataSet <- ActiveDataSet()
155
.variables <- Variables()
156
obsNumberExists <- is.element("obsNumber", .variables)
157
activate <- c( checkMethod("fitted", .activeModel, default=TRUE, reportError=FALSE),
158
checkMethod("residuals", .activeModel, default=TRUE, reportError=FALSE),
159
checkMethod("rstudent", .activeModel, reportError=FALSE),
160
checkMethod("hatvalues", .activeModel, reportError=FALSE),
161
checkMethod("cooks.distance", .activeModel, reportError=FALSE))
162
checkBoxes(frame="selectFrame", boxes=c(c("fitted", "residuals", "rstudent", "hatvalues", "cookd")[activate],
164
initialValues=c(rep(1, sum(activate)), if(obsNumberExists) "0" else "1"),
165
labels=c(gettextRcmdr(c("Fitted values", "Residuals", "Studentized residuals", "Hat-values", "Cook's distances"))[activate],
166
gettextRcmdr("Observation indices")))
169
if (activate[1] && tclvalue(fittedVariable) == 1) addVariable("fitted")
170
if (activate[2] && tclvalue(residualsVariable) == 1) addVariable("residuals")
171
if (activate[3] && tclvalue(rstudentVariable) == 1) addVariable("rstudent")
172
if (activate[4] && tclvalue(hatvaluesVariable) == 1) addVariable("hatvalues")
173
if (activate[5] && tclvalue(cookdVariable) == 1) addVariable("cooks.distance")
174
if (tclvalue(obsNumbersVariable) == 1){
175
proceed <- if (obsNumberExists) tclvalue(checkReplace("obsNumber")) else "yes"
176
if (proceed == "yes") {
177
command <- paste(.activeDataSet, "$obsNumber <- 1:nrow(", .activeDataSet, ")", sep="")
182
activeDataSet(.activeDataSet, flushModel=FALSE)
183
tkfocus(CommanderWindow())
185
OKCancelHelp(helpSubject="influence.measures")
186
tkgrid(selectFrame, sticky="w")
187
tkgrid(buttonsFrame, sticky="w")
188
dialogSuffix(rows=5, columns=1)
191
residualQQPlot <- function(){
193
.activeModel <- ActiveModel()
194
if (is.null(.activeModel) || !checkMethod("qq.plot", .activeModel)) return()
195
initializeDialog(title=gettextRcmdr("Residual Quantile-Comparison Plot"))
196
selectFrame <- tkframe(top)
197
simulateVar <- tclVar("1")
198
identifyVar <- tclVar("0")
199
simulateCheckBox <- tkcheckbutton(selectFrame, variable=simulateVar)
200
identifyCheckBox <- tkcheckbutton(selectFrame, variable=identifyVar)
203
simulate <- tclvalue(simulateVar) == 1
204
identify <- if (tclvalue(identifyVar) == 1) paste("names(residuals(", .activeModel, "))",
206
command <- paste("qq.plot(", .activeModel, ", simulate=", simulate, ", labels=", identify,
208
doItAndPrint(command)
210
tkfocus(CommanderWindow())
212
OKCancelHelp(helpSubject="qq.plot.lm")
213
tkgrid(tklabel(selectFrame, text=gettextRcmdr("Simulated confidence envelope")), simulateCheckBox, sticky="w")
214
tkgrid(tklabel(selectFrame, text=gettextRcmdr("Identify points with mouse")), identifyCheckBox, sticky="w")
215
tkgrid(selectFrame, sticky="w")
216
tkgrid(buttonsFrame, sticky="w")
217
dialogSuffix(rows=2, columns=1)
220
testLinearHypothesis <- function(){
222
.activeModel <- ActiveModel()
223
if (is.null(.activeModel) || !checkMethod("linear.hypothesis", .activeModel)) return()
225
initializeDialog(title=gettextRcmdr("Test Linear Hypothesis"))
226
outerTableFrame <- tkframe(top)
227
assign(".tableFrame", tkframe(outerTableFrame), envir=env)
228
setUpTable <- function(...){
229
tkdestroy(get(".tableFrame", envir=env))
230
assign(".tableFrame", tkframe(outerTableFrame), envir=env)
231
nrows <- as.numeric(tclvalue(rowsValue))
232
col.names <- eval(parse(text=paste("names(coef(", .activeModel, "))")))
233
col.names <- substring(paste(abbreviate(col.names, 12), " "), 1, 12)
234
make.col.names <- "tklabel(.tableFrame, text='')"
236
make.col.names <- paste(make.col.names, ", ",
237
"tklabel(.tableFrame, text='", col.names[j], "')", sep="")
239
rhsText <- gettextRcmdr("Right-hand side")
240
make.col.names <- paste(make.col.names, ", tklabel(.tableFrame, text=' ')",
241
", tklabel(.tableFrame, text='", rhsText, "')", sep="")
242
eval(parse(text=paste("tkgrid(", make.col.names, ")", sep="")), envir=env)
244
varname <- paste(".tab.", i, ".1", sep="")
245
rhs.name <- paste(".rhs.", i, sep="")
246
assign(varname, tclVar("0") , envir=env)
247
assign(rhs.name, tclVar("0"), envir=env)
248
make.row <- paste("tklabel(.tableFrame, text=", i, ")")
249
make.row <- paste(make.row, ", ", "tkentry(.tableFrame, width='5', textvariable=",
250
varname, ")", sep="")
252
varname <- paste(".tab.", i, ".", j, sep="")
253
assign(varname, tclVar("0"), envir=env)
254
make.row <- paste(make.row, ", ", "tkentry(.tableFrame, width='5', textvariable=",
255
varname, ")", sep="")
257
make.row <- paste(make.row, ", tklabel(.tableFrame, text=' '),",
258
"tkentry(.tableFrame, width='5', textvariable=", rhs.name, ")", sep="")
259
eval(parse(text=paste("tkgrid(", make.row, ")", sep="")), envir=env)
261
tkgrid(get(".tableFrame", envir=env), sticky="w")
263
ncols <- eval(parse(text=paste("length(coef(", .activeModel, "))")))
264
rowsFrame <- tkframe(top)
265
rowsValue <- tclVar("1")
266
rowsSlider <- tkscale(rowsFrame, from=1, to=ncols, showvalue=FALSE, variable=rowsValue,
267
resolution=1, orient="horizontal", command=setUpTable)
268
rowsShow <- tklabel(rowsFrame, textvariable=rowsValue, width=2, justify="right")
270
nrows <- as.numeric(tclvalue(rowsValue))
272
values <- rep(NA, nrows*ncols)
273
rhs <- rep(NA, nrows)
275
rhs.name <- paste(".rhs.", i, sep="")
276
rhs[i] <- as.numeric(eval(parse(text=paste("tclvalue(", rhs.name,")", sep=""))))
279
varname <- paste(".tab.", i, ".", j, sep="")
280
values[cell] <- as.numeric(eval(parse(text=paste("tclvalue(", varname,")", sep=""))))
283
values <- na.omit(values)
285
if (length(values) != nrows*ncols){
286
Message(message=sprintf(gettextRcmdr("Number of valid entries in hypothesis matrix(%d)\nnot equal to number of rows (%d) * number of columns (%d)."),
287
length(values), nrows, ncols), type="error")
288
testLinearHypothesis()
291
if (qr(matrix(values, nrows, ncols, byrow=TRUE))$rank < nrows) {
292
Message(message=gettextRcmdr("Hypothesis matrix is not of full row rank."),
294
testLinearHypothesis()
298
if (length(rhs) != nrows){
299
errorCondition(recall=testLinearHypothesis, message=sprintf(gettextRcmdr("Number of valid entries in rhs vector (%d)\nis not equal to number of rows (%d)."), length(rhs), nrows))
302
command <- paste("matrix(c(", paste(values, collapse=","), "), ", nrows, ", ", ncols,
303
", byrow=TRUE)", sep="")
304
assign(".Hypothesis", justDoIt(command), envir=.GlobalEnv)
305
logger(paste(".Hypothesis <- ", command, sep=""))
306
command <- paste("c(", paste(rhs, collapse=","), ")", sep="")
307
assign(".RHS", justDoIt(command), envir=.GlobalEnv)
308
logger(paste(".RHS <- ", command, sep=""))
309
command <- paste("linear.hypothesis(", .activeModel, ", .Hypothesis, rhs=.RHS)", sep="")
310
doItAndPrint(command)
311
justDoIt("remove(.Hypothesis, .RHS, envir=.GlobalEnv)")
312
logger("remove(.Hypothesis, .RHS)")
313
tkfocus(CommanderWindow())
315
OKCancelHelp(helpSubject="linear.hypothesis")
316
tkgrid(tklabel(rowsFrame, text=gettextRcmdr("Number of Rows:")), rowsSlider, rowsShow, sticky="w")
317
tkgrid(rowsFrame, sticky="w")
318
tkgrid(tklabel(top, text=gettextRcmdr("Enter hypothesis matrix and right-hand side vector:"), fg="blue"), sticky="w")
319
tkgrid(outerTableFrame, sticky="w")
320
tkgrid(tklabel(top, text=""))
321
tkgrid(buttonsFrame, sticky="w")
322
dialogSuffix(rows=4, columns=1)
325
compareModels <- function(){
326
models <- listAllModels()
327
if (length(models) < 2){
328
Message(message=gettextRcmdr("There are fewer than two models."),
330
tkfocus(CommanderWindow())
333
initializeDialog(title=gettextRcmdr("Compare Models"))
334
modelsBox1 <- variableListBox(top, models, title=gettextRcmdr("First model (pick one)"))
335
modelsBox2 <- variableListBox(top, models, title=gettextRcmdr("Second model (pick one)"))
337
model1 <- getSelection(modelsBox1)
338
model2 <- getSelection(modelsBox2)
340
if (length(model1) == 0 || length(model2) == 0) {
341
errorCondition(recall=compareModels, message=gettextRcmdr("You must select two models."))
344
if (!checkMethod("anova", model1)) {
347
if (!eval(parse(text=paste("class(", model1, ")[1] == class(", model2, ")[1]",
348
sep="")), envir=.GlobalEnv)){
349
Message(message=gettextRcmdr("Models are not of the same class."),
354
doItAndPrint(paste("anova(", model1, ",", model2, ")", sep=""))
355
tkfocus(CommanderWindow())
357
OKCancelHelp(helpSubject="anova")
358
tkgrid(getFrame(modelsBox1), getFrame(modelsBox2), sticky="nw")
359
tkgrid(buttonsFrame, columnspan=2, sticky="w")
360
dialogSuffix(rows=2, columns=2)
363
BreuschPaganTest <- function(){
364
if (is.null(.activeModel)) return()
366
initializeDialog(title=gettextRcmdr("Breusch-Pagan Test"))
367
tkgrid(tklabel(top, text=gettextRcmdr("Score Test for Nonconstant Error Variance"), fg="blue"), sticky="w")
368
optionsFrame <- tkframe(top)
370
.activeModel <- ActiveModel()
371
var <- tclvalue(varVariable)
373
type <- if (var == "fitted") paste(", varformula = ~ fitted.values(",
374
.activeModel, ")", sep="")
375
else if (var == "predictors") ""
376
else paste(", varformula = ~", tclvalue(rhsVariable), sep="")
377
student <- if (tclvalue(studentVariable) == 1) "TRUE" else "FALSE"
378
model.formula <- as.character(eval(parse(text=paste("formula(", .activeModel, ")", sep=""))))
379
model.formula <- paste(model.formula[2], "~", model.formula[3])
380
command <- paste("bptest(", model.formula, type, ", studentize=", student,
381
", data=", ActiveDataSet(), ")", sep="")
382
doItAndPrint(command)
383
tkfocus(CommanderWindow())
385
OKCancelHelp(helpSubject="bptest")
386
studentVariable <- tclVar("0")
387
studentFrame <- tkframe(optionsFrame)
388
studentCheckBox <- tkcheckbutton(studentFrame, variable=studentVariable)
389
tkgrid(tklabel(studentFrame, text=gettextRcmdr("Studentized test statistic"), justify="left"),
390
studentCheckBox, sticky="w")
391
tkgrid(studentFrame, sticky="w")
392
radioButtons(optionsFrame, name="var", buttons=c("fitted", "predictors", "other"),
393
labels=gettextRcmdr(c("Fitted values", "Explanatory variables", "Other (specify)")), title=gettextRcmdr("Variance Formula"))
394
tkgrid(varFrame, sticky="w")
395
modelFormula(optionsFrame, hasLhs=FALSE)
396
tkgrid(formulaFrame, sticky="w")
397
tkgrid(outerOperatorsFrame)
398
tkgrid(getFrame(xBox), sticky="w")
399
tkgrid(optionsFrame, sticky="w")
400
tkgrid(buttonsFrame, sticky="w")
401
dialogSuffix(rows=4, columns=1)
404
DurbinWatsonTest <- function(){
405
if (is.null(.activeModel)) return()
407
initializeDialog(title=gettextRcmdr("Durbin-Waton Test"))
408
tkgrid(tklabel(top, text=gettextRcmdr("Test for First-Order Error Autocorrelation"), fg="blue"), sticky="w")
410
altHypothesis <- tclvalue(altHypothesisVariable)
412
model.formula <- as.character(eval(parse(text=paste("formula(", ActiveModel(), ")", sep=""))))
413
model.formula <- paste(model.formula[2], "~", model.formula[3])
414
command <- paste("dwtest(", model.formula, ', alternative="', altHypothesis,
415
'", data=', ActiveDataSet(), ')', sep="")
416
doItAndPrint(command)
417
tkfocus(CommanderWindow())
419
OKCancelHelp(helpSubject="dwtest")
420
radioButtons(name="altHypothesis", buttons=c("greater", "notequal", "less"), values=c("greater", "two.sided", "less"),
421
labels=c("rho > 0", "rho != 0", "rho < 0"), title=gettextRcmdr("Alternative Hypothesis"))
422
tkgrid(altHypothesisFrame, sticky="w")
423
tkgrid(buttonsFrame, sticky="w")
424
dialogSuffix(rows=3, columns=1)
427
RESETtest <- function(){
428
if (is.null(.activeModel)) return()
430
initializeDialog(title=gettextRcmdr("RESET Test"))
431
tkgrid(tklabel(top, text=gettextRcmdr("Test for Nonlinearity"), fg="blue"), sticky="w")
433
type <- tclvalue(typeVariable)
434
square <- tclvalue(squareVariable)
435
cube <- tclvalue(cubeVariable)
437
model.formula <- as.character(eval(parse(text=paste("formula(", ActiveModel(), ")", sep=""))))
438
model.formula <- paste(model.formula[2], "~", model.formula[3])
439
if (square == "0" && cube == "0"){
440
errorCondition(recall=RESETtest, message=gettextRcmdr("No powers are checked."))
443
powers <- if (square == "1" && cube == "1") "2:3"
444
else if (square == "1" && cube == "0") "2"
445
else if (square == "0" && cube == "1") "3"
446
command <- paste("resettest(", model.formula, ", power=", powers,
447
', type="', type, '", data=', ActiveDataSet(), ')', sep="")
448
doItAndPrint(command)
449
tkfocus(CommanderWindow())
451
OKCancelHelp(helpSubject="reset")
452
optionsFrame <- tkframe(top)
453
squareVariable <- tclVar("1")
454
squareCheckBox <- tkcheckbutton(optionsFrame, variable=squareVariable)
455
cubeVariable <- tclVar("1")
456
cubeCheckBox <- tkcheckbutton(optionsFrame, variable=cubeVariable)
457
typeVariable <- tclVar("regressor")
458
radioButtons(optionsFrame, name="type", buttons=c("regressor", "fitted", "princomp"),
459
labels=gettextRcmdr(c("Explanatory variables", "Fitted values", "First principal component")),
460
title=gettextRcmdr("Type of Test"))
461
tkgrid(tklabel(optionsFrame, text=gettextRcmdr("Powers to Include"), fg="blue"), sticky="w")
462
tkgrid(tklabel(optionsFrame, text=gettextRcmdr("2 (squares)")), squareCheckBox, sticky="w")
463
tkgrid(tklabel(optionsFrame, text=gettextRcmdr("3 (cubes) ")), cubeCheckBox, sticky="w")
464
tkgrid(typeFrame, sticky="w")
465
tkgrid(optionsFrame, sticky="w")
466
tkgrid(buttonsFrame, sticky="w")
467
dialogSuffix(rows=3, columns=1)
470
outlierTest <- function(){
471
if (is.null(.activeModel)) return()
473
.activeModel <- ActiveModel()
474
if (!checkMethod("outlier.test", .activeModel)) {
475
errorCondition(gettextRcmdr("There is no appropriate outlier.test method for a model of this class."))
478
doItAndPrint(paste("outlier.test(", .activeModel, ")", sep=""))
481
confidenceIntervals <- function(){
482
if (is.null(.activeModel)) return()
484
initializeDialog(title=gettextRcmdr("Confidence Intervals"))
485
tkgrid(tklabel(top, text=gettextRcmdr("Confidence Intervals for Individual Coefficients"), fg="blue"), sticky="w")
487
level <- tclvalue(confidenceLevel)
488
opts <- options(warn=-1)
489
lev <- as.numeric(level)
492
if ((is.na(lev)) || (lev < 0) || (lev > 1)) {
493
Message(gettextRcmdr("Confidence level must be a number between 0 and 1."))
494
tkfocus(CommanderWindow())
497
command <- if (glm) paste("Confint(", .activeModel, ", level=", level,
498
', type="', tclvalue(typeVariable), '")', sep="")
499
else paste("Confint(", .activeModel, ", level=", level, ")", sep="")
500
doItAndPrint(command)
501
tkfocus(CommanderWindow())
503
OKCancelHelp(helpSubject="Confint")
504
confidenceFrame <- tkframe(top)
505
confidenceLevel <- tclVar(".95")
506
confidenceField <- tkentry(confidenceFrame, width="6", textvariable=confidenceLevel)
507
radioButtons(top, name="type", buttons=c("LR", "Wald"),
508
labels=gettextRcmdr(c("Likelihood-ratio statistic", "Wald statistic")), title=gettextRcmdr("Test Based On"))
509
tkgrid(tklabel(confidenceFrame, text=gettextRcmdr("Confidence Level: ")), confidenceField, sticky="w")
510
tkgrid(confidenceFrame, sticky="w")
511
.activeModel <- ActiveModel()
512
glm <- eval(parse(text=paste("class(", .activeModel, ")")))[1] == "glm"
513
if (glm) tkgrid(typeFrame, sticky="w")
514
tkgrid(buttonsFrame, sticky="w")
515
dialogSuffix(rows=3 + glm, columns=1)
3
# last modified 26 March 2008 by J. Fox
5
selectActiveModel <- function(){
6
models <- listAllModels()
7
.activeModel <- ActiveModel()
8
if ((length(models) == 1) && !is.null(.activeModel)) {
9
Message(message=gettextRcmdr("There is only one model in memory."),
11
tkfocus(CommanderWindow())
14
if (length(models) == 0){
15
Message(message=gettextRcmdr("There are no models from which to choose."),
17
tkfocus(CommanderWindow())
20
initializeDialog(title=gettextRcmdr("Select Model"))
21
.activeDataSet <- ActiveDataSet()
22
initial <- if (is.null(.activeModel)) NULL else which(.activeModel == models) - 1
23
modelsBox <- variableListBox(top, models, title=gettextRcmdr("Models (pick one)"),
24
initialSelection=initial)
26
model <- getSelection(modelsBox)
28
if (length(model) == 0) {
29
tkfocus(CommanderWindow())
32
dataSet <- as.character(get(model)$call$data)
33
# dataSet <- eval(parse(text=paste("as.character(", model, "$call$data)")))
34
if (length(dataSet) == 0){
35
errorCondition(message=gettextRcmdr("There is no dataset associated with this model."))
38
dataSets <- listDataSets()
39
if (!is.element(dataSet, dataSets)){
40
errorCondition(message=sprintf(gettextRcmdr("The dataset associated with this model, %s, is not in memory."), dataSet))
43
if (is.null(.activeDataSet) || (dataSet != .activeDataSet)) activeDataSet(dataSet)
45
tkfocus(CommanderWindow())
48
nameFrame <- tkframe(top)
49
tkgrid(labelRcmdr(nameFrame, fg="blue", text=gettextRcmdr("Current Model: ")),
50
labelRcmdr(nameFrame, text=tclvalue(getRcmdr("modelName"))), sticky="w")
51
tkgrid(nameFrame, sticky="w", columnspan="2")
52
tkgrid(getFrame(modelsBox), columnspan="2", sticky="w")
53
tkgrid(buttonsFrame, columnspan=2, sticky="w")
54
dialogSuffix(rows=3, columns=2)
57
summarizeModel <- function(){
58
.activeModel <- ActiveModel()
59
if (is.null(.activeModel) || !checkMethod("summary", .activeModel)) return()
60
doItAndPrint(paste("summary(", .activeModel, ", cor=FALSE)", sep=""))
63
plotModel <- function(){
64
.activeModel <- ActiveModel()
65
if (is.null(.activeModel) || !checkMethod("plot", .activeModel)) return()
66
command <- "oldpar <- par(oma=c(0,0,3,0), mfrow=c(2,2))"
69
doItAndPrint(paste("plot(", .activeModel, ")", sep=""))
70
command <- "par(oldpar)"
75
CRPlots <- function(){
77
.activeModel <- ActiveModel()
78
if (is.null(.activeModel) || !checkMethod("cr.plot", .activeModel)) return()
79
doItAndPrint(paste("cr.plots(", .activeModel, ", ask=FALSE)", sep=""))
83
AVPlots <- function(){
85
.activeModel <- ActiveModel()
86
if (is.null(.activeModel) || !checkMethod("av.plot", .activeModel)) return()
87
response <- tclvalue(RcmdrTkmessageBox(message=gettextRcmdr("Identify points with mouse?"),
88
icon="question", type="yesno", default="no"))
89
doItAndPrint(paste("av.plots(", .activeModel, ", ask=FALSE, identify.points=",
90
response=="yes", ")", sep=""))
94
anovaTable <- function(){
96
.activeModel <- ActiveModel()
97
if (is.null(.activeModel)) return()
98
if (!checkMethod("Anova", .activeModel)) {
99
errorCondition(message=gettextRcmdr("There is no appropriate Anova method for a model of this class."))
102
doItAndPrint(paste("Anova(", .activeModel, ")", sep=""))
107
.activeModel <- ActiveModel()
108
if (is.null(.activeModel) || !checkMethod("vif", .activeModel)) return()
109
doItAndPrint(paste("vif(", .activeModel, ")", sep=""))
112
InfluencePlot <- function(){
114
.activeModel <- ActiveModel()
115
if (is.null(.activeModel) || !checkMethod("influencePlot", .activeModel)) return()
116
response <- tclvalue(RcmdrTkmessageBox(message=gettextRcmdr("Identify points with mouse?"),
117
icon="question", type="yesno", default="no"))
118
labels <- if (response == "no") ", labels=FALSE" else ""
119
doItAndPrint(paste("influencePlot(", .activeModel, labels, ")", sep=""))
122
effectPlots <- function(){
124
.activeModel <- ActiveModel()
125
if (is.null(.activeModel) || !checkMethod("effect", .activeModel)) return()
126
doItAndPrint('trellis.device(theme="col.whitebg")')
127
command <- paste("plot(all.effects(", .activeModel, "), ask=FALSE)", sep="")
134
addObservationStatistics <- function(){
135
if (is.null(.activeModel)) return()
136
addVariable <- function(name){
137
variable <- paste(name, ".", .activeModel, sep="")
138
if (is.element(variable, .variables)) {
139
ans <- checkReplace(variable)
140
if (tclvalue(ans) == "no") return()
142
command <- paste(name, "(", .activeModel, ")", sep="")
143
justDoIt(paste(.activeDataSet, "$", variable, " <- ", command, sep=""))
144
logger(paste(.activeDataSet, "$", variable, " <- ", command, sep=""))
146
if (getRcmdr("modelWithSubset")){
148
gettextRcmdr("Observation statistics not available\nfor a model fit to a subset of the data."),
153
initializeDialog(title=gettextRcmdr("Add Observation Statistics to Data"))
154
.activeModel <- ActiveModel()
155
.activeDataSet <- ActiveDataSet()
156
.variables <- Variables()
157
obsNumberExists <- is.element("obsNumber", .variables)
158
activate <- c( checkMethod("fitted", .activeModel, default=TRUE, reportError=FALSE),
159
checkMethod("residuals", .activeModel, default=TRUE, reportError=FALSE),
160
checkMethod("rstudent", .activeModel, reportError=FALSE),
161
checkMethod("hatvalues", .activeModel, reportError=FALSE),
162
checkMethod("cooks.distance", .activeModel, reportError=FALSE))
163
checkBoxes(frame="selectFrame", boxes=c(c("fitted", "residuals", "rstudent", "hatvalues", "cookd")[activate],
165
initialValues=c(rep(1, sum(activate)), if(obsNumberExists) "0" else "1"),
166
labels=c(gettextRcmdr(c("Fitted values", "Residuals", "Studentized residuals", "Hat-values", "Cook's distances"))[activate],
167
gettextRcmdr("Observation indices")))
170
if (activate[1] && tclvalue(fittedVariable) == 1) addVariable("fitted")
171
if (activate[2] && tclvalue(residualsVariable) == 1) addVariable("residuals")
172
if (activate[3] && tclvalue(rstudentVariable) == 1) addVariable("rstudent")
173
if (activate[4] && tclvalue(hatvaluesVariable) == 1) addVariable("hatvalues")
174
if (activate[5] && tclvalue(cookdVariable) == 1) addVariable("cooks.distance")
175
if (tclvalue(obsNumbersVariable) == 1){
176
proceed <- if (obsNumberExists) tclvalue(checkReplace("obsNumber")) else "yes"
177
if (proceed == "yes") {
178
command <- paste(.activeDataSet, "$obsNumber <- 1:nrow(", .activeDataSet, ")", sep="")
183
activeDataSet(.activeDataSet, flushModel=FALSE)
184
tkfocus(CommanderWindow())
186
OKCancelHelp(helpSubject="influence.measures")
187
tkgrid(selectFrame, sticky="w")
188
tkgrid(buttonsFrame, sticky="w")
189
dialogSuffix(rows=5, columns=1)
192
residualQQPlot <- function(){
194
.activeModel <- ActiveModel()
195
if (is.null(.activeModel) || !checkMethod("qq.plot", .activeModel)) return()
196
initializeDialog(title=gettextRcmdr("Residual Quantile-Comparison Plot"))
197
selectFrame <- tkframe(top)
198
simulateVar <- tclVar("1")
199
identifyVar <- tclVar("0")
200
simulateCheckBox <- tkcheckbutton(selectFrame, variable=simulateVar)
201
identifyCheckBox <- tkcheckbutton(selectFrame, variable=identifyVar)
204
simulate <- tclvalue(simulateVar) == 1
205
identify <- if (tclvalue(identifyVar) == 1) paste("names(residuals(", .activeModel, "))",
207
command <- paste("qq.plot(", .activeModel, ", simulate=", simulate, ", labels=", identify,
209
doItAndPrint(command)
211
tkfocus(CommanderWindow())
213
OKCancelHelp(helpSubject="qq.plot.lm")
214
tkgrid(labelRcmdr(selectFrame, text=gettextRcmdr("Simulated confidence envelope")), simulateCheckBox, sticky="w")
215
tkgrid(labelRcmdr(selectFrame, text=gettextRcmdr("Identify points with mouse")), identifyCheckBox, sticky="w")
216
tkgrid(selectFrame, sticky="w")
217
tkgrid(buttonsFrame, sticky="w")
218
dialogSuffix(rows=2, columns=1)
221
testLinearHypothesis <- function(){
223
.activeModel <- ActiveModel()
224
if (is.null(.activeModel) || !checkMethod("linear.hypothesis", .activeModel)) return()
226
initializeDialog(title=gettextRcmdr("Test Linear Hypothesis"))
227
outerTableFrame <- tkframe(top)
228
assign(".tableFrame", tkframe(outerTableFrame), envir=env)
229
setUpTable <- function(...){
230
tkdestroy(get(".tableFrame", envir=env))
231
assign(".tableFrame", tkframe(outerTableFrame), envir=env)
232
nrows <- as.numeric(tclvalue(rowsValue))
233
col.names <- names(coef(get(.activeModel)))
234
# col.names <- eval(parse(text=paste("names(coef(", .activeModel, "))")))
235
col.names <- substring(paste(abbreviate(col.names, 12), " "), 1, 12)
236
make.col.names <- "labelRcmdr(.tableFrame, text='')"
238
make.col.names <- paste(make.col.names, ", ",
239
"labelRcmdr(.tableFrame, text='", col.names[j], "')", sep="")
241
rhsText <- gettextRcmdr("Right-hand side")
242
make.col.names <- paste(make.col.names, ", labelRcmdr(.tableFrame, text=' ')",
243
", labelRcmdr(.tableFrame, text='", rhsText, "')", sep="")
244
eval(parse(text=paste("tkgrid(", make.col.names, ")", sep="")), envir=env)
246
varname <- paste(".tab.", i, ".1", sep="")
247
rhs.name <- paste(".rhs.", i, sep="")
248
assign(varname, tclVar("0") , envir=env)
249
assign(rhs.name, tclVar("0"), envir=env)
250
make.row <- paste("labelRcmdr(.tableFrame, text=", i, ")")
251
make.row <- paste(make.row, ", ", "ttkentry(.tableFrame, width='5', textvariable=",
252
varname, ")", sep="")
254
varname <- paste(".tab.", i, ".", j, sep="")
255
assign(varname, tclVar("0"), envir=env)
256
make.row <- paste(make.row, ", ", "ttkentry(.tableFrame, width='5', textvariable=",
257
varname, ")", sep="")
259
make.row <- paste(make.row, ", labelRcmdr(.tableFrame, text=' '),",
260
"ttkentry(.tableFrame, width='5', textvariable=", rhs.name, ")", sep="")
261
eval(parse(text=paste("tkgrid(", make.row, ")", sep="")), envir=env)
263
tkgrid(get(".tableFrame", envir=env), sticky="w")
265
ncols <- length(coef(get(.activeModel)))
266
# ncols <- eval(parse(text=paste("length(coef(", .activeModel, "))")))
267
rowsFrame <- tkframe(top)
268
rowsValue <- tclVar("1")
269
rowsSlider <- tkscale(rowsFrame, from=1, to=ncols, showvalue=FALSE, variable=rowsValue,
270
resolution=1, orient="horizontal", command=setUpTable)
271
rowsShow <- labelRcmdr(rowsFrame, textvariable=rowsValue, width=2, justify="right")
273
nrows <- as.numeric(tclvalue(rowsValue))
275
values <- rep(NA, nrows*ncols)
276
rhs <- rep(NA, nrows)
278
rhs.name <- paste(".rhs.", i, sep="")
279
rhs[i] <- as.numeric(eval(parse(text=paste("tclvalue(", rhs.name,")", sep=""))))
282
varname <- paste(".tab.", i, ".", j, sep="")
283
values[cell] <- as.numeric(eval(parse(text=paste("tclvalue(", varname,")", sep=""))))
286
values <- na.omit(values)
288
if (length(values) != nrows*ncols){
289
Message(message=sprintf(gettextRcmdr("Number of valid entries in hypothesis matrix(%d)\nnot equal to number of rows (%d) * number of columns (%d)."),
290
length(values), nrows, ncols), type="error")
291
testLinearHypothesis()
294
if (qr(matrix(values, nrows, ncols, byrow=TRUE))$rank < nrows) {
295
Message(message=gettextRcmdr("Hypothesis matrix is not of full row rank."),
297
testLinearHypothesis()
301
if (length(rhs) != nrows){
302
errorCondition(recall=testLinearHypothesis, message=sprintf(gettextRcmdr("Number of valid entries in rhs vector (%d)\nis not equal to number of rows (%d)."), length(rhs), nrows))
305
command <- paste("matrix(c(", paste(values, collapse=","), "), ", nrows, ", ", ncols,
306
", byrow=TRUE)", sep="")
307
assign(".Hypothesis", justDoIt(command), envir=.GlobalEnv)
308
logger(paste(".Hypothesis <- ", command, sep=""))
309
command <- paste("c(", paste(rhs, collapse=","), ")", sep="")
310
assign(".RHS", justDoIt(command), envir=.GlobalEnv)
311
logger(paste(".RHS <- ", command, sep=""))
312
command <- paste("linear.hypothesis(", .activeModel, ", .Hypothesis, rhs=.RHS)", sep="")
313
doItAndPrint(command)
314
justDoIt("remove(.Hypothesis, .RHS, envir=.GlobalEnv)")
315
logger("remove(.Hypothesis, .RHS)")
316
tkfocus(CommanderWindow())
318
OKCancelHelp(helpSubject="linear.hypothesis")
319
tkgrid(labelRcmdr(rowsFrame, text=gettextRcmdr("Number of Rows:")), rowsSlider, rowsShow, sticky="w")
320
tkgrid(rowsFrame, sticky="w")
321
tkgrid(labelRcmdr(top, text=gettextRcmdr("Enter hypothesis matrix and right-hand side vector:"), fg="blue"), sticky="w")
322
tkgrid(outerTableFrame, sticky="w")
323
tkgrid(labelRcmdr(top, text=""))
324
tkgrid(buttonsFrame, sticky="w")
325
dialogSuffix(rows=4, columns=1)
328
compareModels <- function(){
329
models <- listAllModels()
330
if (length(models) < 2){
331
Message(message=gettextRcmdr("There are fewer than two models."),
333
tkfocus(CommanderWindow())
336
initializeDialog(title=gettextRcmdr("Compare Models"))
337
modelsBox1 <- variableListBox(top, models, title=gettextRcmdr("First model (pick one)"))
338
modelsBox2 <- variableListBox(top, models, title=gettextRcmdr("Second model (pick one)"))
340
model1 <- getSelection(modelsBox1)
341
model2 <- getSelection(modelsBox2)
343
if (length(model1) == 0 || length(model2) == 0) {
344
errorCondition(recall=compareModels, message=gettextRcmdr("You must select two models."))
347
if (!checkMethod("anova", model1)) {
350
if (!class(get(model1, envir=.GlobalEnv))[1] == class(get(model2, envir=.GlobalEnv))[1]){
351
# if (!eval(parse(text=paste("class(", model1, ")[1] == class(", model2, ")[1]",
352
# sep="")), envir=.GlobalEnv)){
353
Message(message=gettextRcmdr("Models are not of the same class."),
358
doItAndPrint(paste("anova(", model1, ",", model2, ")", sep=""))
359
tkfocus(CommanderWindow())
361
OKCancelHelp(helpSubject="anova")
362
tkgrid(getFrame(modelsBox1), getFrame(modelsBox2), sticky="nw")
363
tkgrid(buttonsFrame, columnspan=2, sticky="w")
364
dialogSuffix(rows=2, columns=2)
367
BreuschPaganTest <- function(){
368
if (is.null(.activeModel)) return()
370
initializeDialog(title=gettextRcmdr("Breusch-Pagan Test"))
371
tkgrid(labelRcmdr(top, text=gettextRcmdr("Score Test for Nonconstant Error Variance"), fg="blue"), sticky="w")
372
optionsFrame <- tkframe(top)
374
.activeModel <- ActiveModel()
375
var <- tclvalue(varVariable)
377
type <- if (var == "fitted") paste(", varformula = ~ fitted.values(",
378
.activeModel, ")", sep="")
379
else if (var == "predictors") ""
380
else paste(", varformula = ~", tclvalue(rhsVariable), sep="")
381
student <- if (tclvalue(studentVariable) == 1) "TRUE" else "FALSE"
382
model.formula <- as.character(formula(get(.activeModel)))
383
# model.formula <- as.character(eval(parse(text=paste("formula(", .activeModel, ")", sep=""))))
384
model.formula <- paste(model.formula[2], "~", model.formula[3])
385
command <- paste("bptest(", model.formula, type, ", studentize=", student,
386
", data=", ActiveDataSet(), ")", sep="")
387
doItAndPrint(command)
388
tkfocus(CommanderWindow())
390
OKCancelHelp(helpSubject="bptest")
391
studentVariable <- tclVar("0")
392
studentFrame <- tkframe(optionsFrame)
393
studentCheckBox <- tkcheckbutton(studentFrame, variable=studentVariable)
394
tkgrid(labelRcmdr(studentFrame, text=gettextRcmdr("Studentized test statistic"), justify="left"),
395
studentCheckBox, sticky="w")
396
tkgrid(studentFrame, sticky="w")
397
radioButtons(optionsFrame, name="var", buttons=c("fitted", "predictors", "other"),
398
labels=gettextRcmdr(c("Fitted values", "Explanatory variables", "Other (specify)")), title=gettextRcmdr("Variance Formula"))
399
tkgrid(varFrame, sticky="w")
400
modelFormula(optionsFrame, hasLhs=FALSE)
401
tkgrid(formulaFrame, sticky="w")
402
tkgrid(outerOperatorsFrame)
403
tkgrid(getFrame(xBox), sticky="w")
404
tkgrid(optionsFrame, sticky="w")
405
tkgrid(buttonsFrame, sticky="w")
406
dialogSuffix(rows=4, columns=1)
409
DurbinWatsonTest <- function(){
410
if (is.null(.activeModel)) return()
412
initializeDialog(title=gettextRcmdr("Durbin-Waton Test"))
413
tkgrid(labelRcmdr(top, text=gettextRcmdr("Test for First-Order Error Autocorrelation"), fg="blue"), sticky="w")
415
altHypothesis <- tclvalue(altHypothesisVariable)
417
model.formula <- as.character(formula(get(ActiveModel())))
418
# model.formula <- as.character(eval(parse(text=paste("formula(", ActiveModel(), ")", sep=""))))
419
model.formula <- paste(model.formula[2], "~", model.formula[3])
420
command <- paste("dwtest(", model.formula, ', alternative="', altHypothesis,
421
'", data=', ActiveDataSet(), ')', sep="")
422
doItAndPrint(command)
423
tkfocus(CommanderWindow())
425
OKCancelHelp(helpSubject="dwtest")
426
radioButtons(name="altHypothesis", buttons=c("greater", "notequal", "less"), values=c("greater", "two.sided", "less"),
427
labels=c("rho > 0", "rho != 0", "rho < 0"), title=gettextRcmdr("Alternative Hypothesis"))
428
tkgrid(altHypothesisFrame, sticky="w")
429
tkgrid(buttonsFrame, sticky="w")
430
dialogSuffix(rows=3, columns=1)
433
RESETtest <- function(){
434
if (is.null(.activeModel)) return()
436
initializeDialog(title=gettextRcmdr("RESET Test"))
437
tkgrid(labelRcmdr(top, text=gettextRcmdr("Test for Nonlinearity"), fg="blue"), sticky="w")
439
type <- tclvalue(typeVariable)
440
square <- tclvalue(squareVariable)
441
cube <- tclvalue(cubeVariable)
443
model.formula <- as.character(formula(get(ActiveModel())))
444
# model.formula <- as.character(eval(parse(text=paste("formula(", ActiveModel(), ")", sep=""))))
445
model.formula <- paste(model.formula[2], "~", model.formula[3])
446
if (square == "0" && cube == "0"){
447
errorCondition(recall=RESETtest, message=gettextRcmdr("No powers are checked."))
450
powers <- if (square == "1" && cube == "1") "2:3"
451
else if (square == "1" && cube == "0") "2"
452
else if (square == "0" && cube == "1") "3"
453
command <- paste("resettest(", model.formula, ", power=", powers,
454
', type="', type, '", data=', ActiveDataSet(), ')', sep="")
455
doItAndPrint(command)
456
tkfocus(CommanderWindow())
458
OKCancelHelp(helpSubject="reset")
459
optionsFrame <- tkframe(top)
460
squareVariable <- tclVar("1")
461
squareCheckBox <- tkcheckbutton(optionsFrame, variable=squareVariable)
462
cubeVariable <- tclVar("1")
463
cubeCheckBox <- tkcheckbutton(optionsFrame, variable=cubeVariable)
464
typeVariable <- tclVar("regressor")
465
radioButtons(optionsFrame, name="type", buttons=c("regressor", "fitted", "princomp"),
466
labels=gettextRcmdr(c("Explanatory variables", "Fitted values", "First principal component")),
467
title=gettextRcmdr("Type of Test"))
468
tkgrid(labelRcmdr(optionsFrame, text=gettextRcmdr("Powers to Include"), fg="blue"), sticky="w")
469
tkgrid(labelRcmdr(optionsFrame, text=gettextRcmdr("2 (squares)")), squareCheckBox, sticky="w")
470
tkgrid(labelRcmdr(optionsFrame, text=gettextRcmdr("3 (cubes) ")), cubeCheckBox, sticky="w")
471
tkgrid(typeFrame, sticky="w")
472
tkgrid(optionsFrame, sticky="w")
473
tkgrid(buttonsFrame, sticky="w")
474
dialogSuffix(rows=3, columns=1)
477
outlierTest <- function(){
478
if (is.null(.activeModel)) return()
480
.activeModel <- ActiveModel()
481
if (!checkMethod("outlier.test", .activeModel)) {
482
errorCondition(gettextRcmdr("There is no appropriate outlier.test method for a model of this class."))
485
doItAndPrint(paste("outlier.test(", .activeModel, ")", sep=""))
488
confidenceIntervals <- function(){
489
if (is.null(.activeModel)) return()
491
initializeDialog(title=gettextRcmdr("Confidence Intervals"))
492
tkgrid(labelRcmdr(top, text=gettextRcmdr("Confidence Intervals for Individual Coefficients"), fg="blue"), sticky="w")
494
level <- tclvalue(confidenceLevel)
495
opts <- options(warn=-1)
496
lev <- as.numeric(level)
499
if ((is.na(lev)) || (lev < 0) || (lev > 1)) {
500
Message(gettextRcmdr("Confidence level must be a number between 0 and 1."))
501
tkfocus(CommanderWindow())
504
command <- if (glm) paste("Confint(", .activeModel, ", level=", level,
505
', type="', tclvalue(typeVariable), '")', sep="")
506
else paste("Confint(", .activeModel, ", level=", level, ")", sep="")
507
doItAndPrint(command)
508
tkfocus(CommanderWindow())
510
OKCancelHelp(helpSubject="Confint")
511
confidenceFrame <- tkframe(top)
512
confidenceLevel <- tclVar(".95")
513
confidenceField <- ttkentry(confidenceFrame, width="6", textvariable=confidenceLevel)
514
radioButtons(top, name="type", buttons=c("LR", "Wald"),
515
labels=gettextRcmdr(c("Likelihood-ratio statistic", "Wald statistic")), title=gettextRcmdr("Test Based On"))
516
tkgrid(labelRcmdr(confidenceFrame, text=gettextRcmdr("Confidence Level: ")), confidenceField, sticky="w")
517
tkgrid(confidenceFrame, sticky="w")
518
.activeModel <- ActiveModel()
519
glm <- class(get(.activeModel))[1] == "glm"
520
# glm <- eval(parse(text=paste("class(", .activeModel, ")")))[1] == "glm"
521
if (glm) tkgrid(typeFrame, sticky="w")
522
tkgrid(buttonsFrame, sticky="w")
523
dialogSuffix(rows=3 + glm, columns=1)