Vous êtes sur la page 1sur 127

SciViews-R

A GUI API and a suite of applications for R

Version 0.8-9 (2005-10-10)

Philippe Grosjean (phgrosjean@sciviews.org), Eric Lecoutre (lecoutre@stat.ucl.ac.be) and


José Cláudio Faria (joseclaudio.faria@terra.com.br),
with contributions of Marta Rufino (mrufino@ipimar.ualg.pt)

1
2
PART I: INSTALLING AND USING SCIVIEWS-R.......................................................... 6

1. INTRODUCTION ....................................................................................................... 7

EXAMPLE OF A SESSION USING R WITH THE COMMAND LINE INTERFACE ........................... 7


A GRAPHICAL USER INTERFACE FOR R ................................................................................ 17
ACKNOWLEDGEMENTS .......................................................................................................... 19

2. INSTALLATION OF SCIVIEWS-R, R AND R PACKAGES ............................. 20

CONDENSED INSTALLATION INSTRUCTIONS ........................................................................ 21


DETAILED INSTALLATION OF SCIVIEWS-R .......................................................................... 21
INSTALLING R UNDER WINDOWS .......................................................................................... 27
FINALIZING SCIVIEWS-R / R INSTALLATION ....................................................................... 31
FIXING THE RSCIVIEWS SHORTCUT......................................................................................... 31
INSTALLING ADDITIONAL R PACKAGES ................................................................................... 34
MANUALLY INSTALLING ADDITIONAL R PACKAGES ............................................................... 39
STARTING AND STOPPING THE SCIVIEWS-R GUI................................................................ 42
HOW TO START RGUI IN SDI MODE ......................................................................................... 44
SAVING WORKSPACES FROM SESSION TO SESSION WITH SCIVIEWS-R.................................... 47

3. COMPANION APPLICATIONS FOR WINDOWS IN SCIVIEWS-R............... 48

OVERVIEW OF THE APPLICATIONS ....................................................................................... 48


SCIVIEWS R CONSOLE ........................................................................................................... 49
SCIVIEWS R CONSOLE BARS ................................................................................................... 51
COMMAND BAR / SCRIPT EDITOR ............................................................................................ 52
DOCK WINDOWS ...................................................................................................................... 54
ADDING CUSTOM TOOLS .......................................................................................................... 57
SCIVIEWS R REPORT ............................................................................................................. 60
TINN-R, A R CODE EDITOR .................................................................................................... 62
MAIN CHARACTERISTICS OF TINN-R ....................................................................................... 62
TIPS FOR USING TINN-R........................................................................................................... 63
USING SCIVIEWS R CONSOLE WITH R COMMANDER .......................................................... 68

4. PRESENTATION OF SOME FUNCTIONS IN THE SCIVIEWS BUNDLE .... 69

EXPORT AND COPY FUNCTIONS ............................................................................................. 69


VIEW FUNCTIONS .................................................................................................................... 71
CLIPPASTE FUNCTION ............................................................................................................ 75
REPORT FUNCTION ................................................................................................................. 76

PART II: THE SCIVIEWS GUI API .................................................................................. 77

5. CONCEPTION OF A “CODE-CENTRED” GUI.................................................. 78

THE CONSOLE IS STILL THERE… BUT IT IS SUPPORTED BY A SCRIPT EDITOR ................... 78


MENUS, TOOLBARS AND DIALOG BOXES ............................................................................... 81

3
THE OBJECT EXPLORER AND DATA EDITOR ......................................................................... 83
OTHER “EXPLORERS”............................................................................................................ 85
VIEWS AND REPORTING FEATURES ....................................................................................... 86
FACILITATED INPUT AND OUTPUT......................................................................................... 88
MANAGEMENT OF THE SYSTEM ............................................................................................ 88
OTHER ASSISTANTS ................................................................................................................ 88
SIMPLIFIED ONLINE HELP AND MANUALS............................................................................. 89
TEXT EDITOR AND IDE .......................................................................................................... 89

6. OVERVIEW OF THE SCIVIEWS R GUI API ..................................................... 90

7. SVGUI, FUNCTIONS TO INTERFACE GUI CLIENT APPLICATIONS........ 91

8. SVIO AND SVVIEWS: FORMATTED DATA EXCHANGE.............................. 92

EXTENDING EXPORT, VIEW AND REPORT FUNCTIONS........................................................ 92

9. SVMISC: MISCELLANEOUS UTILITARY FUNCTIONS ................................ 95

10. SVDIALOGS: REUSABLE DIALOG BOXES ...................................................... 96

BUILDING DIALOG BOXES ...................................................................................................... 96


THREE LEVELS OF MAKING DIALOG BOXES IN YOUR GUI....................................................... 97
APPROACH USED IN SVDIALOGS .............................................................................................. 99
TOOLKIT-INDEPENDENT API AND TOOLKIT IMPLEMENTATIONS........................................... 100
SPECIFICATION OF STANDARD DIALOG BOXES .................................................................. 106
THE MESSAGE BOX ................................................................................................................ 106
THE INPUT BOX ...................................................................................................................... 108
THE OPEN FILE(S) DIALOG BOX .............................................................................................. 109
THE SAVE FILE DIALOG BOX .................................................................................................. 111
THE CHOOSE DIRECTORY DIALOG BOX .................................................................................. 113
THE LIST SELECTION DIALOG BOX ......................................................................................... 114
THE VARIABLE SELECTION DIALOG BOX ............................................................................... 115
THE VARIABLE/ITEM SELECTION DIALOG BOX ...................................................................... 115
THE DOUBLE LIST DIALOG BOX ............................................................................................. 115
THE FORMULA DIALOG BOX .................................................................................................. 116
THE COLOUR SELECTION DIALOG BOX .................................................................................. 116
THE FONT SELECTION DIALOG BOX ....................................................................................... 116
SPECIFICATION OF STANDARD WINDOWS ........................................................................... 116
THE TEXT WINDOW ................................................................................................................ 117
THE GRID WINDOW ................................................................................................................ 117
THE VIEW WINDOW ................................................................................................................ 117
THE EXPLORER WINDOW ....................................................................................................... 118
THE OBJECT EXPLORER WINDOW........................................................................................... 120
THE PROGRESSION WINDOW .................................................................................................. 121
SPECIFICATION OF FLEXIBLE DIALOG BOXES .................................................................... 121
THE FUNCTION ASSISTANT DIALOG BOX ............................................................................... 123
THE OPTIONS DIALOG BOX..................................................................................................... 124
THE GRAPH OPTIONS DIALOG BOX ......................................................................................... 124
THE ASSISTANT DIALOG BOX ................................................................................................. 124

4
11. TCLTK2: ADDITIONAL TCL/TK FEATURES FOR R ...ERROR! BOOKMARK
NOT DEFINED.

REFERENCES .................................................................................................................... 127

5
PART I: INSTALLING AND USING SCIVIEWS-R

6
1. INTRODUCTION

R (Ihaka and Gentleman 1996, R Development Core Team 2004,


but see http://www.R-project.org) is a wonderful environment for
statistics, data analysis, modelling and other scientific calculations. It is
based on a rich and powerful language: S, as is S-PLUS, its commercial
equivalent. It is a functional language1. It is a matrix calculation
software. It is object-oriented2. It features thousands of functions,
collected in hundreds of packages that can be installed to tailor it from
general to very specific purposes. It is excellent in making complex and
high-quality plots. And, last but not least, it is free and the whole code
source is available for everybody! All these characteristics make the
success of R, and it is almost certain that this success will still grow in
the future.

Example of a session using R with the command line interface


This example shows a non trivial analysis run in R using his default
command line interface. We choose a non trivial application to
demonstrate both strengths and difficulties of R. Indeed, it is easy to
show that a menu / dialog box paradigm is much easier to use for
standard analyses, but this does not promote trials and
experimentations for more complex examination of the data, a field
where R is shinning!

There were a few discussions on the R-help mailing list


(https://stat.ethz.ch/mailman/listinfo/r-help, another excellent place
where beginner or occasional statisticians and R users get pertinent
advices from international experts) about how large is the community of
R users and how large it will grow in the future. It appears that it is
indeed both difficult to evaluate (because R is free, there is no procedure
to get it that can be easily monitored), and it is probably not the most
interesting aspect: there is no need to monitor or plan its growth,
because there is no business plan for its development! R is done by
passionate people aiming to get a complete and high-quality statistical
environment. Those passionate users/developers are indeed not much
concerned whether R is more or less used than, say S-PLUS, or SAS (at
least, I suspect that people behind S-PLUS and SAS are more concerned
about the growth of R than the contrary ;-).

However, we could analyze the amount of email exchanges on the


R-help mailing list per time unit as an indirect measurement of the
“activity” around R, … This activity is measured, as a rough proxy, by the
size of gzipped archives over the last seven years (thanks Martin

1 Most code is accessed by calling functions.


2 Put shortly, object-oriented programming is an efficient way to organize

data and code. In this paradigm, an ‘object’ contains both the data and the code
to manipulate it, and the way data is manipulated depends on the “nature” of
the object (which is called its ‘class’).

7
Maechler for this suggestion and for providing these data). We propose
to analyze these data using R itself:

> RhelpUsage <-


+ ts(c(55, 19, 19, 18, 19, 17, 35, 27, 47, 55, 32, 50, 55,
+ 41, 49, 50, 28, 53, 42, 81, 54, 99, 60, 84, 80, 76,
+ 75, 78, 61, 83, 97, 141, 122, 96, 144, 173, 153,
+ 226, 202, 131, 165, 183, 175, 168, 187, 240, 272,
+ 262, 195, 236, 244, 285, 249, 326, 345, 392, 268,
+ 455, 320, 418, 453, 468, 422, 447, 400, 323, 516,
+ 478, 327, 450, 487, 535, 658, 573, 606, 659, 543,
+ 655, 722, 677, 567, 519, 703, 886),
+ start = 1997.25, deltat = 1/12)

If this looks like some intimidating code to you, you just have to
know that we constructed a special R object ‘RhelpUsage’, of class ‘ts’ (a
regular time-series) with monthly intervals. Here is a friendlier textual
presentation of its content (the default print for this ‘ts’ object):

> RhelpUsage
Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
1997 55 19 19 18 19 17 35 27 47
1998 55 32 50 55 41 49 50 28 53 42 81 54
1999 99 60 84 80 76 75 78 61 83 97 141 122
2000 96 144 173 153 226 202 131 165 183 175 168 187
2001 240 272 262 195 236 244 285 249 326 345 392 268
2002 455 320 418 453 468 422 447 400 323 516 478 327
2003 450 487 535 658 573 606 659 543 655 722 677 567
2004 519 703 886

… and the default graphical presentation:

> plot(RhelpUsage)

8
800
600
RhelpUsage

400
200
0

1997 1998 1999 2000 2001 2002 2003 2004

Time

Although using specific objects for storing data looks intimidating


and complex at the beginning, it is a very efficient approach for two
reasons. First, data storage is optimized for such an object (for instance,
here, time is internally recorded with only three numbers: the start time,
in any time units that best fits that time series, the end time and the
frequency). This is obviously more efficient than storing the time at
which each observation is done, that is here, 84 numbers for the 84
observations in the series. Second, R “knows” about its objects and its
“behaviour” is adapted to the context. Hence, it nicely prints the time
series automatically when you type the name of the variable that holds
it. Also, the default graphical presentation is also optimized (using lines
to show continuity between values, and nicely formatting the time axis).
So, a difficulty (use of specialized objects) reveals as a very convenient
feature once you manipulate these objects.

Coming back to our analysis, we can plot also a log-transformed


series3.

3 The reason why we use a log transformation here is not important for

the sake of the demonstration. For those who want to know, it is because the
high-frequency signal appears multiplicative with the general trend (its
amplitude increases proportionally with the value of this trend). In this case, a
log transformation makes those two signals additive and stabilizes the variance
of the high-frequency signal (i.e., the residuals in the models we apply, further
in the analysis).

9
> LogRhU <- log(RhelpUsage)
> plot(LogRhU)

6
LogRhU

5
4
3

1997 1998 1999 2000 2001 2002 2003 2004

Time

At this stage, we could wonder if a monthly interval is really the


best one to maximize the signal/noise ratio in this time series. The
“turnogram” is one method that uses information theory to answer this
question (interested readers should look at Dallot and Etienne 1990, or
Grosjean and Ibanez 2004):

> library(pastecs)
Loading required package: boot
> RhU.turno <- turnogram(RhelpUsage, FUN = sum)
> summary(RhU.turno)
Simple turnogram for: RhelpUsage

options : sum / two-tailed probability


call : turnogram(series = RhelpUsage, FUN = sum)
max. info. : 35.34312 at interval 6 (P = 2.294349e-11: 0
turning points for 14 observations)
extract level: 6 ()

interval n turns info


1 1 84 49 2.8550122
2 2 42 27 -0.2299715
3 3 28 11 7.8110573
4 4 21 7 8.6546750
5 5 17 7 3.7143862
6 6 14 0 35.3431242

10
7 7 12 0 27.8354558
8 8 11 1 14.2519023
9 9 10 1 11.7938816
10 10 9 1 9.4747796
11 11 8 1 7.3105233
12 12 7 0 11.2992080
13 13 7 1 5.3219281
14 14 6 0 8.4918531
15 15 6 1 3.5376568
16 16 6 1 3.5376568

Simple turnogram for: RhelpUsage


30
20
I (bits)

10
0

1 2 5 10

interval ()
sum / two-tailed probability

This method tells us clearly that information (expressed in bits) in


this time series is the highest with an interval of six months. In other
words, the ratio signal/noise is significantly lowered with such a time
interval, compared to the original monthly time series. We could decide,
thus, to recalculate the time series with biannual sums of the activity:

> RhU6 <- extract(RhU.turno)


> plot(RhU6)

11
4000
3000
RhU6

2000
1000
0

1997 1998 1999 2000 2001 2002 2003 2004

Time

Indeed, the series looks much cleaner now, isn’t it? Notice how simple
was the analysis (once you know which function you have to call, of
course!). We just had to load a package containing additional functions
called ‘pastecs’ with the instruction library(pastecs). Then, we used a
specialized function called turnogram() on our data with an argument,
FUN = sum. We got a summary of the results simply by calling …
summary() on the object we just created… and extraction of the
optimized series was not more complex, just calling extract() on the
same object! Let’s look now at the graph of the log-transformed form of
our time series:

> LogRhU6 <- log(RhU6)


> plot(LogRhU6)

12
8.0
7.5
7.0
LogRhU6

6.5
6.0
5.5
5.0

1997 1998 1999 2000 2001 2002 2003 2004

Time

Can we fit a linear model on this? (take care! This is a time series.
There is probably some autocorrelation. So, the ANOVA on the
regression and the t-tests on parameters are not valid here!)

> LogRhU6.lm <- lm(LogRhU6 ~ time(LogRhU6))


> summary(LogRhU6.lm)

Call:
lm(formula = LogRhU6 ~ time(LogRhU6))

Residuals:
Min 1Q Median 3Q Max
-0.23652 -0.10947 0.03873 0.12922 0.20945

Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) -1.018e+03 4.095e+01 -24.85 1.09e-11 ***
time(LogRhU6) 5.121e-01 2.047e-02 25.02 1.01e-11 ***
---
Signif. codes: 0 `***' 0.001 `**' 0.01 `*' 0.05 `.' 0.1 ` ' 1

Residual standard error: 0.1544 on 12 degrees of freedom


Multiple R-Squared: 0.9812, Adjusted R-squared: 0.9796
F-statistic: 625.8 on 1 and 12 DF, p-value: 1.009e-11

> abline(coef = coef(LogRhU6.lm), col = 2)

13
8.0
7.5
7.0
LogRhU6

6.5
6.0
5.5
5.0

1997 1998 1999 2000 2001 2002 2003 2004

Time

Humm! Could we do better than this? We could use polynomials to


fit a curve on these data, but I don’t like them much. For this series, we
could prefer to fit something like a simple asymptotic growth model:

> abline(coef = coef(LogRhU6.lm), col = 2)


> df1 <- data.frame(time = as.vector(time(LogRhU6)),
+ load = as.vector(LogRhU6))
> LogRhU6.nls <- nls(load ~ SSasympOff(time, Asym, lrc, c0),
data = df1)
> summary(LogRhU6.nls)

Formula: load ~ SSasympOff(time, Asym, lrc, c0)

Parameters:
Estimate Std. Error t value Pr(>|t|)
Asym 11.1333 0.9797 11.364 2.03e-07 ***
lrc -2.1036 0.2320 -9.067 1.95e-06 ***
c0 1992.3589 0.6269 3177.920 < 2e-16 ***
---
Signif. codes: 0 `***' 0.001 `**' 0.01 `*' 0.05 `.' 0.1 ` ' 1

Residual standard error: 0.09667 on 11 degrees of freedom

Correlation of Parameter Estimates:


Asym lrc
lrc -0.9938
c0 -0.9521 0.9791

14
> plot(df1$time, df1$load, type = "l")
> lines(df1$time, predict(LogRhU6.nls), col = 2)

8.0
7.5
7.0
df1$load

6.5
6.0
5.5
5.0

1997 1998 1999 2000 2001 2002 2003 2004

df1$time

Again, we should not use t-tests on the parameters, keeping in


mind that we probably have autocorrelation in the series. Otherwise,
this model does not look too bad. The code we used was a little bit more
complex here, because we had to use a nonlinear regression and had to
transform the time series object into another object (a data frame).
Otherwise, we had to use summary() and plot() + lines() in a similar
way as we did before.

Now, that’s fine, but we need a refined graph, “ready for


publication”. Should we have to switch to a specialized graphing package
for that purpose? No! R is capable of drawing very nice and refined
graphs. So, with a little more work, we can get something like this
(converting the size of gzipped archives to number of messages,
according to a rough estimation of the mean size per messages done in
March 2004):

> # Plot of the dots for observations


> plot(df1$time, exp(df1$load) * 1949 / 886, xlab =
+ "time (years)", ylab = "nbr. of messages / semester",
+ main = "R-help mailing list usage (estimation)")
> # Superposition of a red curve for the model
> lines(df1$time, exp(predict(LogRhU6.nls)) * 1949 / 886,
+ col = 2)
> # Vertical grid lines

15
> abline(v = 1998:2003, col= "gray", lty = 2)
> # Horizontal grid lines
> abline(h = (1:9)*1000, col= "gray", lty = 2)

R-help mailing list usage (estimation)

8000
nbr. of messages / semester

6000
4000
2000
0

1997 1998 1999 2000 2001 2002 2003 2004

time (years)

Wow! It looks like the R-help mailing list is still in an exponential


growth phase in 2004. Is it the same for R use? Probably! This graph is
showing that point very well. So, why the use of R is growing so fast?
Perhaps because you can do things like that in a very flexible and
convenient way!

Now, the challenge to convince sceptical people: try doing the


same analysis in your favourite software. Keep also in mind traceability
and potential to easily run the same analysis on several datasets, after
collecting all the commands in a script in R. Do you have the same
facility in your favourite software? Do you have easy access to numerous
specialized analyses like the turnogram (there are almost 400 additional
packages available for free on the R distribution web site,
http:///www.cran.r-project.org, for doing almost everything you can
imagine)?

This little session in R was conducted primarily to give you a


feeling on how it can be used today: it is a command-line driven
program and users need to key in commands at a prompt. This approach
is very flexible, and R has a lot to offer to those who can manage
entering commands in its language and who know how and where to
find specialized features.

16
If you feel comfortable with this user interface, then probably you
do not need the SciViews-R extension. You may even consider using
(X)Emacs with ESS extension (http://stat.ethz.ch/ESS/) if you want
more power to control R from a textual-based user interface. Windows
users may also be interested by
http://socserv.mcmaster.ca/jfox/Books/Companion/ESS/ which
explains how to install and configure Xemacs and ESS under Windows4.

On the contrary, if you want a graphical user interface to drive R,


either for yourself, or for your students (in your courses), or for your
collaborators, then you should give a try to SciViews-R. Other reasons
why you could be interested by SciViews-R are:

• It is bunded with an advanced script editor with syntax


highlighting, set-by-step execution, bookmarks and many more,

• There is help everywhere to write your code, especially, function


tips which display the syntax of functions whenever you use them,
and completion lists that propose context-sensitive lists of terms to
help writing your code,

• An object explorer proposes a convenient centralized place where


you can manage your variables easily, find functions or data and
look at their help or content instantly,

• Views and reporting features add rich-formatting outputs you can


quickly integrate in the reports you build from your analyses,

• Its user interface is fully customizable: you can place up to five


docked windows wherever you like, and you can fully redefine
menus and toolbars, and add custom tools to them.

A graphical user interface for R


R is often considered as a hard-to-learn and hard-to-use system
done by and for experts (at least, I know many biologists that believe so).
It is intimidating because R lacks an advanced friendly user interface for
beginners or occasional users… what we call a GUI (Graphical User
Interface). Several projects are developed to fill the gap, see
http://www.r-project.org/GUI. One of these projects is SciViews-R
(http://www.sciviews.org/SciViews-R). It aims to bring a GUI to R, but
not any kind of GUI: one that helps beginners from start, progressively
gives him good working habits and seamlessly teaches him how to write
scripts and how to programs in S language, the underlying statistical-
oriented language build in R. The language, the command line (R
console) and the script editor are still central elements in such a GUI.
We do not intend to hide this “horrible code” and replace it completely
with “sexy” dialog boxes! We prefer instead to support the user in

4 Note from Marta Rufino : it seems that Emacs could cause problems

under Windows. However, following instructions in John Fox’s page, I (Ph.G.)


was able to install and run it smoothly on my Windows XP. I have no further
experience of Emacs-ESS, beyond this quick trial.

17
writing its code, to show him by the example how to write a script for a
given analysis.

What does the beginner or occasional user need? He needs plenty


of help: syntax highlighting, code completion wizards, code tips
displaying the syntax of functions, an assistant for writing calls to
functions, a graphical object explorer, a simple but efficient script editor,
electronic reference cards and a simplified help system that presents
only the most important features of R. These are precisely the tools we
provide (or plan to provide) in SciViews-R.

However, instead of writing proprietary tools, we want to make


them available also for other R GUI projects. It means that the core of
these additional features is written in R itself, and in such a way that it is
easily reusable. All these functions are implemented into eight different
R packages:

• svGUI: the core GUI package that implements functions to


communicate with the GUI client,

• svDialogs: the dialog boxes,

• svIDE: specific features for IDE (Integrated Development


Environment) and script editors,

• svIO: import and export functions,

• svViews: implementation of the views and the reporting system,

• svSocket: a ssimple ocket connection to R, for client/server


architecture.

• svMisc: various other supporting functions used by the other


packages, and

• tcltk2: an enhanced Tcl/Tk addition to supplement the core tcltk


package.

These eight packages are collected together in the bundle


‘SciViews’ (except tcltk2, for it is is not platform-independent yet, and
only runs on Windows, currently) and constitute the SciViews GUI
API for R. It is this API that we present in this document, together with
the SciViews-R suite of applications that use it to implement a complete
GUI for R (currently, only under Windows).

All programs developed by the SciViews team are distributed


under an Open Source license (GPL 2 or above), as R itself. Our goal is
to contribute in providing a high-quality GUI for this statistical system
that can be freely used by everyone. SciViews-R is also programmed in
an expendable way, which means any programmer may implement
additional features, or even a different suite of fully-compatible
companion applications. This way, we hope to encourage
intercompatibility between the various R GUI projects. We wish others
implementations, possibly in Tcl/Tk, Gtk, Java, Aqua, … will develop.
However, we anticipate great potentials of the wxPython (wxWidgets +
Python) as a powerful platform-independent solution for these

18
companion applications. R-wxPython
(http://bioinf.wehi.edu.au/folders/james/wxPython/) uses RSPython
(http://www.omegahat.org/RSPython/), but RPy
(http://rpy.sourceforge.net/) is a possible, although unidirectional,
alternative to write a Python/wxWidgets GUI for R. We warmly
encourage any initiative in this direction and will support and help any
volunteer that would like to write a platform-independent version of
SciViews-R with these tools. Remember: your contributions are
welcome!

Indeed, all this should be regarded as a work in progress, as more


and better features will be gradually added to the system. The current
version of SciViews-R, 0.8-9 is not the final implementation. However,
we believe that the general framework is now established, after more
than three years of research and experiments in GUIs for data analysis
systems (mainly in the ecology/biology/environmental science field).
SciViews-R has already evolved much since its first trial presented at
DSC 2003 (Grosjean, 2003)!

The first part of this manual is intended for R users that


would like to use SciViews-R as an alternate (GUI) interface
for R. The second part is dedicated to developers that either
want to contribute to the SciViews R GUI API, or want to use
it for writing, or extending their own R GUI.

Acknowledgements
We would like to tank the R Core Team for providing such an
excellent piece of software as R. We are particularly grateful to Duncan
Murdoch for his efforts in implementing features for R that ease writing
of a GUI on top of it. We also thank Peter Dalgaard for the tcltk package
and James Wettenhall for his preliminary version of R-wxPython.

19
2. INSTALLATION OF SCIVIEWS-R, R AND R PACKAGES

In this chapter, we deal with the installation procedure of


SciViews-R + R + additional R packages/bundles. The installation
procedure may look complicated, because there are several steps. Please,
consider that this is not the final version of the SciViews-R installer: it is
still in development! Of course, we aim an installation as simple as
possible. SciViews-R is mainly dedicated to beginners or occasional
users, and a straightforward installation is required for them.

In the future, we will work towards a simplification of the


installation process. Currently, R and SciViews-R must be downloaded
and installed separately. Moreover, the bare installation of R is not
enough: several additional R packages/bundles must be installed.
Starting from version 0.7-2 of SciViews-R, there is a function to
automatically prompt the user with a GUI in case these packages are
missing (thanks to James Wettenhall). This works only for computers
connected to the Internet. So, the alternate method (manual installation
of these additional packages) is still valid as an alternative.

First section, ‘condensed installation instructions’ is for


experienced users that do not need all the details to install the software
properly (they probably already have installed R and know how to install
additional R packages in R). Subsequent sections are very detailed
instructions for novices.

If you have problems installing and/or running SciViews-


R, please, make sure you followed all steps explained here,
and you read the detailed instructions carefully before calling
for help. If, despite this, you still cannot install or run
SciViews-R, then, send an email to support@sciviews.org. You
should provide as much details as possible, otherwise we
cannot help you! You should at least indicate:

• Which version of Windows you use, which processor and how


many RAM memory you have (these data are available from Start
menu -> Control Panel -> System).

• Which version of R you run, and whether is correctly configured to


use Tcl/Tk. To get these data, enter the following commands at the
R prompt and copy/paste result to your email:

> R.Version()
> capabilities("tcltk")

• Which version of SciViews-R you are installing. The version


number is in the name of the installer. For instance, the installer
‘SciViews-R_0.8-9Setup.exe’ installs version 0.8-9.

• Optionally, it may help to list loaded packages at the point where


starting of SciViews R Console fails. Use the following command
and copy/paste result to your email:

> search()

20
Condensed installation instructions
TO DO…

Detailed installation of SciViews-R


SciViews-R is distributed on the SciViews web site
(http://www.sciviews.org/SciViews-R). Download the installer for
Windows 98se/2000/XP (sorry, not compatible yet with Windows 95,
or other platforms). On the web page, it is the binaries of SciViews-R
that you have to download at this stage (the whole installation procedure
is given with lots of details, to help beginners; more advanced users can
browser this section rapidly).

To run SciViews-R, you need: a recent computer (equivalent to a


Pentium III, or IV) with at least 256 Mb of RAM memory (512 Mb is
preferred to analyse large data sets), and at least 60 Mb available on the
hard disk where you install SciViews-R and R.

Once downloaded, you have a file named ‘SciViews-R_0.8-9.exe’.


To install it, you have to log on temporarily with administrative
rights (this is not necessary for using the program after its installation).
If you installed one of the previous versions of SciViews-R, you should
better uninstall it first (go to start menu -> Control Panel -> Add
or Remove Programs -> SciViews-R version 0.x-y). Then, just
follow instructions in the setup assistant. Figures 2-1 to 2-9 present the
sequence of installation of SciViews-R 0.7-0 (should be updated to
version 0.8-9). Just double-click on the downloaded file in the files
explorer, and you face the welcome screen of the setup assistant…

21
Figure 2-1: the welcome screen of the SciViews-R 0.7-0 setup assistant. If you
see this screen after launching ‘SciViews-R_0.7-0.exe’, you are certainly logged
with administrative rights on Windows 98se, 2000, or XP (otherwise, an error
message explains the origin of the problem). Click ‘Next’.

Figure 2-2: second screen of the assistant. You have to accept the license
terms (click ‘I accept the agreement’) to be allowed to continue. Click ‘Next’.

22
Figure 2-3: the setup assistant asks you where you want to install SciViews-R.
You can install it where you want, preferably on a local hard disk with enough
free space. Most of the time, the default directory is fine. Click ‘Next’.

Figure 2-4: this screen presents components to install. In 0.7-0, there is no


optional components… just click ‘Next’.

23
Figure 2-5: it is strongly advised to create shortcuts for the programs in the
start menu. The default folder ‘SciViews-R’ should be fine. Just click ‘Next’.

Figure 2-6: this screen presents various additional tasks. You can create a
desktop icon for the program, either for yourself only, or for all users of this
computer. This is a convenient shortcut to start R with the SciViews-R interface

24
rapidly. If you had to log off your account, and log on as administrator, make
sure you select ‘For all users’, otherwise this shortcut will not be available in
your own user session. The other task is to associate files with specific
extensions to SciViews-R applications… there is no reasons for not doing this.
So, leave the ‘Associate files’ option checked and click ‘Next’.

Figure 2-7: a summary of tasks that will be done if you click ‘Install’. You can
check if everything is fine, and then start the installation with ‘Install’ (or exit
it with ‘Cancel’). Note that you can fully uninstall SciViews-R at a later time by
going in Start menu -> control panel -> Add or Remove Programs ->
SciViews-R version 0.7-2.

25
Figure 2-8 : the installation of SciViews-R is in progress…

Figure 2-9 : SciViews-R is now installed. It is generally a good idea to read the
README file, which may provide latest news and information. Click ‘Finish’.

26
Installing R under Windows
Once SciViews-R is installed on your computer, it is not yet
operational: you also need to install R and a couple of additional R
packages to be able to use it. It is not important whether you install
SciViews-R before or after R, but you must make sure you install at least
R version 2.2.0 (SciViews-R is not compatible with previous version of
R)! You can download a setup for Windows of the latest R version from
http://cran.r-project.org/bin/windows/base/. The file you need is ‘R-
X.X.X-win32.exe’ where X.X.X is the version (for instance, 2.2.0). It
weights about 25Mb. You can also download it from one of the CRAN
mirror sites. If you have time, browse the README and the FAQ from
this web page. These give useful additional information about R.

When ‘R-2.2.0-win32.exe’ is downloaded on your hard disk, run it


(double-click on this file in the files explorer). The setup assistant of R is
similar to the SciViews-R one. Figures 2-10 to 2-17 detail the step-by-
step installation of R (version 2.0.0, should be updated to R
2.2.0).

Figure 2-10: the welcome screen of the R setup assistant. Click ‘Next’.

27
Figure 2-11: the license agreement. You must click ‘I accept the agreement’ to
be allowed to continue. Then, click ‘Next’.

Figure 2-12: where do you want to install R? Usually, the default directory
provided is fine. Especially if you run R with SciViews-R, it is advised (but not
required) to keep this default directory. Click ‘Next’.

28
Figure 2-13: choose components. Select as in the figure. Make sure ‘Support
Files for library(tcltk)’ is checked! Click ‘Next’.

Figure 2-14: it is advised to create a shortcut in the start menu. The ‘R’ folder
should be fine. So, you do not need to change default options. Click ‘Next’.

29
Figure 2-15: additional tasks. It does not hurt to run them all. So, unless you
know what you do, check all options and then click ‘Next’.

Figure 2-16: R is now installing. It takes a couple of minutes. Be patient…

30
Figure 2-17: R is now installed on your computer! Just click ‘Finish’.

Finalizing SciViews-R / R installation


Now that both R and SciViews-R are installed on your computer,
you have almost done with installation. However, there is an extra step:
to install a couple of additional R packages and possibly fix the shortcut
that starts R from SciViews-R. This is a critical step where you
ensure that SciViews-R will run correctly with R. So, be careful
to follow all instructions!

Fixing the RSciViews shortcut

If R was installed in ‘C:\Program Files\R\R-2.2.0’ (the default


directory where R version 2.2.0 is installed on an English system), you
do not need to change the shortcut. Just go to the next section,
‘Installing additional R packages’. If you installed R in a different
directory, you have to fix the ‘RSciViews’ shortcut in the
SciViews-R installation directory. To do so, just follow instructions
bellow:

1. Start the file explorer, and locate the SciViews-R installation


directory. By default, it is ‘C:\Program Files\SciViews’ (fig. 2-18).

31
Figure 2-18: locate the ‘RSciViews’ shortcut in the SciViews-R installation
directory with the files explorer.

2. Right-click with your mouse on the shortcut named ‘RSciViews’,


the one with an R icon surrounded by three balls of different colors
and with an arrow in its lower left side (fig. 2-19). A context menu
is displayed.

Figure 2-19: the context menu when you right-click on the ‘RSciViews’
shortcut. Select ‘Properties’.

32
3. Select ‘properties’ in this menu. The ‘RSciViews Properties’ dialog
box is displayed (fig. 2-20).

Figure 2-20: the ‘RSciViews Properties’ dialog box. You have to fix the ‘Target’
entry in the ‘Shortcut’ tab.

4. Change the ‘Target’ field in the ‘Shortcut’ tab to reflect the actual
location where you installed R. By default, this target is:
"C:\Program Files\R\R-2.2.0\bin\Rgui.exe" --sdi
RSciViews.RData.

You just need to change the first part of it (C:\Program Files\R\R-


2.2.0) to reflect the actual directory where you installed R. Note
that, if you give a wrong directory, a message box will tell you that
there is a problem when you click ‘OK’ in this dialog box.

5. Accept your changes by clicking ‘OK’. If there is no error message,


the shortcut should be fixed now, and points to the right place
(thus, SciViews-R should be able to find and run R properly).

33
Installing additional R packages

There are different procedures to install additional packages,


depending if your computer is connected to the Internet, or not. If yes,
follow these instructions; otherwise, go to ‘Manually installing
additional R packages’.

In SciViews-R, there is a sophisticated procedure to install missing


R packages, using a graphical user interface (thanks to James
Wettenhall). So, at this stage, you could simply run SciViews R
Console, and the program will prompt automatically to install these
additional packages. Here is the detailed procedure:

1. Launch SciViews R Console from its shortcut, either on the


desktop, or from the start menu. Double-click on the ‘SciViews R
Console’ icon on your desktop, or do Start menu -> App
programs -> SciViews-R -> R Console (fig. 2-21).

Figure 2-21: you can start SciViews R Console from its shortcut in the
Start menu.

2. A ‘R Console’ window should appear shortly after that. This is R


that is launched by SciViews-R. If you see this window, it means
that both R and SciViews-R are correctly installed and that
SciViews-R knows where R resides, that is, the ‘RSciViews’
shortcut possibly fixed in the previous stage is correct.

34
3. The SciViews bundle is probably missing on your computer at this
point. So, R should prompt you to install it (fig 2-22).

Figure 2-22: the message that appears the first time you start SciViews R
Console when the SciViews bundle is missing. If your computer is connected to
Internet, click ‘Yes’ and continue. Otherwise, click ‘No’ and follow instructions
in the next section to install it manually.

4. R gives you now the choice of several places from where you can
install the SciViews bundle. Since it is currently only available on
the SciViews web site, select the first entry, ‘SciViews’, exclusively
(see fig. 2-23).

Figure 2-23: select from where you want to install the ‘SciViews’ bundle.
Currently, the only valid location is the ‘SciViews’ web site (it may be installable
from other locations as well in the future). Select this entry and click ‘OK’.

5. The bundle is automatically installed from the web site (fig. 2-24).

Figure 2-24: the ‘Download progress’ dialog box while the SciViews bundle is
being downloaded. Then it is automatically installed on your computer (version
number may change: you got always the very last one from the web site).

6. At the end of the installation, you should read a message like in


fig. 2-25. R asks you if you want to delete the installation file.
Answer ‘y’(es), except if you want to install it on several other
computers. In this case, it could be faster to click ‘N’(o), and then
to save the file ‘SciViews_0.8-9.zip’ from the location given by R to
a separate directory, or even, on a CD. On the other computers
where you want to install SciViews-R, at stage (4), you could then

35
select ‘Local Zip File’ and locate the file where you saved it. This
way, you do not have to download it every time from the Internet!

Figure 2-25: here is the text that appears in the ‘R Console’ when the SciViews
bundle is correctly installed. You have the opportunity to save the installation
file to reuse it in the future (enter ‘N’), otherwise, enter ‘y’.

7. If this procedure failed at stage 5 (you read an error message), you


computer is probably not well connected to the Internet,… or it is
connected through a firewall that is not well recognized by R (the
last possibility is a failure of Internet or of the SciViews web site,
but this is less likely to happen). In such a case, proceed in the next
section, ‘Manually installing additional R packages’.

8. After a while, you will probably be prompted to install another


package: R2HTML (fig. 2-26). Proceed the same way, but you can
select either ‘SciViews’, or ‘CRAN’ this time in the list.

Figure 2-26: you are now prompted to install the ‘R2HTML’ package. Proceed
and install it the same way (click ‘Yes’), but select either ‘SciViews’, or ‘CRAN’
in the list this time.

36
9. Check that the R2HTML package is correctly installed (fig. 2-27),
and enter either ‘y’, or ‘N’, depending if you want to save the
installation file of R2HTML for reuse or not.

Figure 2-27: now, R2HTML is installed in R. Click ‘y’ to delete installation file
and continue, or ‘N’ to save it and continue.

37
10. After a while, you should see the main window of SciViews R
Console, as in fig. 2-28. The SciViews-R graphical user interface
is now installed properly on your computer!

Figure 2-28: the main SciViews R Console window that appears when
SciViews-R, R and required additional R packages are correctly installed on
your computer. Note that the ‘Dock1’ and ‘Dock2’ panels at right could be
different, or even not be displayed at this stage. This is perfectly normal.

11. If the loading of SciViews R Console failed somewhere (most of the


time, you read a message like in fig. 2-29 after roughly 30
seconds), close any opened window (especially ‘R Console’), and
try again from stage 1. On some computers, we have observed that
SciViews R Console do not start correctly the first time it is
launched, for unknown reasons. Everything should work properly
the second time you start it. Otherwise, check that you followed the
right procedure from the beginning.

38
Figure 2-29: the error message displayed when SciViews R Console cannot
connect to R. It proposes an alternate way to start it than the one explained
here. You can either retry the current procedure (close R and close this dialog
box, and then try again launching SciViews R Console from its icon in the start
menu or on the desktop), or you could try this alternate procedure (see later in
this manual: ‘starting and stopping the SciViews-R GUI’ at the end of this
chapter). Note that the message anticipates the availability of the SciViews
bundle on CRAN (http://cran.r-project.org), while it is currently only available
at http://www.sciviews.org/SciViews-R!

Since your computer is able to download additional R packages


from the Internet when they are required, you should not worry if all
additional R packages are installed or not (indeed, several ones will be
installed later, especially if you want to use R Commander wit SciViews-
R). Just follow the same procedure and try first the ‘CRAN’ entry in
the list to download and install subsequent additional R packages. You
may skip next section. However, if you want to install all these packages
manually right now, proceed to the next section.

Manually installing additional R packages

Especially if you want to run R Commander (basic statistics


accessed through menus and dialog boxes) with SciViews-R, you will
have to install several additional R packages. First of all, make sure that
the ‘tcltk’ package is properly installed. The tcltk package is provided
with the plain R distribution. Moreover, you also need Tcl/Tk files. All
this is optionally installed at the same time as R (see fig. 2-13 above). To
know if your current R installation supports Tcl/Tk, use the following
command:

> capabilities("tcltk")

It should answer TRUE. Otherwise, reinstall R and check the tcltk feature
this time in optional components. Then, you will need the following
additional R packages/bundles (table 2-1):

39
Table 2-1: additional packages required to run SciViews-R and R Commander.

Package Minimal Where can it be obtained?


/bundle version

SciViews(1) 0.8-9 http://www.sciviews.org/SciViews-R


R2HTML(1) 1.4-3 CRAN(2) or http://www.sciviews.org/SciViews-R
Hmisc(3) 2.2-3 CRAN(2)
acepack(3) 1.3-2 CRAN(2)
Rcmdr(4) 1.1-1 CRAN(2) or http://www.sciviews.org/SciViews-R
abind 1.1-0 CRAN(2)
car 1.0-13 CRAN(2)
effects 1.0-3 CRAN(2)
leaps 2.7 CRAN(2)
lmtest 0.9-6 CRAN(2)
multcomp 0.4-7 CRAN(2)
mvtnorm 0.7-0 CRAN(2)
relimp 0.8-4 CRAN(2)
rgl 0.64-13 CRAN(2)
sandwich 0.1-3 CRAN(2)
strucchange 1.2-5 CRAN(2)
zoo 0.2-0 CRAN(2)
wxPython(5) 0.2.4 http://www.sciviews.org/SciViews-R or
http://bioinf.wehi.edu.au/folders/james/wxPython/
RSPython(5) 0.5-4 http://www.sciviews.org/SciViews-R or
http://bioinf.wehi.edu.au/folders/james/wxPython/
(1) SciViews and R2HTML are always required.
(2) To download Windows binaries of R packages from CRAN manually, navigate to
http://cran.r-project.org/bin/windows/contrib/, then click an the folder that matches your
R version (for instance, folder ‘2.0’ for R 2.0.x) and download corresponding
‘package_version.zip’ files.
(3) Hmisc (which itself requires acepack) is optional and is only used to export objects in
LaTeX format (if you don’t know what LaTeX is, you probably don’t need them).
(4) Rcmdr (R Commander) offers menus and dialog boxes to access basic statistic tests. It
requires itself abind, car, effects, … It is optional.
(5) wxPython and RSPython are also optional. They provide wxWidgets/Python dialog boxes to
R. Note that you have also to install Python 2.2.x and wxPython binaries 2.5.x. see:
http://bioinf.wehi.edu.au/folders/james/wxPython/ for further instructions.

If you failed with the automatic method to install additional R


packages as explained in the previous section (for instance, if the
computer where you install SciViews-R is not connected to the Internet),
or if you prefer to install all required packages at once, follow this
procedure:

40
1. Download all windows binaries of the R packages you need (files
with names ‘package_version.zip’) in a common directory on your
hard disk, or better, on a network directory or a CD-Rom if you
want to install SciViews-R on several computers. Use table 2-1 to
determine which R packages/bundles you need.

2. Start R from its icon in the desktop, or from the Start menu ->
All programs -> R -> R x.x.x.

3. When R is loaded, go to menu Packages -> Install package(s)


from local zip files…

4. In the ‘Select files’ dialog box, navigate to the folder where you
saved your files, and select them all (fig. 2-30). Click ‘Open’.

Figure 2-30: select all the packages you downloaded in your installation
directory. R will install them all in turn.

5. R installs all these additional packages. Be patient, it takes a couple


of minutes. At the end of the installation, R indicates if he could
successfully unpack (install) them, and checks that these unpacked
versions are correct (MD5 checksums). The latest line ‘updating
HTML package descriptions’ tells that the HTML help is updated
to include help of these new packages (fig. 2-31). Look if there is no
error message. If everything is OK, you have done. All additional
packages are installed! Otherwise,…

41
Figure 2-31: the messages you should get when all the additional packages
and bundles are correctly installed in R.

6. If R failed to install one or several packages, there may be various


reasons for that: (1) you did not download the right version, (2)
you downloaded the source or a corrupted version of the package,
or (3) the download process failed and you have an incomplete
version of them. Try downloading these packages again and restart
from step (3). If it still fails, look who is the package maintainer,
and send him an email with a full description of your problem.

Starting and stopping the SciViews-R GUI


Here are the different ways you can now start and stop the
SciViews-R GUI on top of R, once it is properly installed:

1. Double-click on the ‘SciViews R Console’ icon on the desktop (if


you installed it),

2. Select Start menu -> All programs -> SciViews R -> R


Console. Note that you can can start the same way the other
application in the SciViews-R suite: ‘SciViews R Report’ and
‘Tinn-R’.

3. Start R alone (either from its desktop icon, or from the Start
menu -> All programs -> R -> R x.x.x), or in any other way
you use to start R (for instance, from a .Rdata file, look at R
documentation). In this case, RGui must be started in SDI mode
exclusively –see hereunder, ‘how to start RGui in SDI mode’–. If
you enter the following instruction:

> library(svGUI)

42
The ‘svGUI’ package is loaded and it automatically starts ‘SciViews
R Console’, providing ‘RConsole.exe’ is located in ‘C:\Program
Files\SciViews\bin’. [PhG TO DO: explain how to customize
this!!!]. This third way to start SciViews R Console is
interesting if you want to save/load workspaces from
session to session (see R documentation if you don’t know what
a workspace is [PhG… or explain this here]).

Whatever the way you start ‘SciViews R Console’, you should end
up with a window similar to this (fig. 2-31; the ‘Dock1’ panel at right is
probably not the same at this stage, or it can even not be visible… this is
normal):

Figure 2-31: The SciViews R Console window at startup.

Note that you can start the SciViews R Console from its icon, and
stop it by selecting File -> Exit SciViews only, or by clicking on the
top-left ‘x’ button to close the window without closing the R session,
once the svGUI package is loaded. You can thus switch from the plain
‘Rgui’ to ‘SciViews R Console’ back and forth several times in the same
session! This way, it is always possible to free some memory by
temporarily switching the GUI extensions off, if required. If you just
want to hide or show these extensions, but do not care about memory
usage, you can also use Misc -> Hide/Show bars, or Ctrl-H in the
SciViews R Console.

43
How to start RGui in SDI mode

SciViews R Console cannot start if RGui (the default R program


run under Windows) is started in MDI mode (fig. 2-32; Multiple
Document Interface). Unfortunately, the MDI mode is the default one
when you install R. So, you need to switch to the SDI mode (fig. 2-33;
Single Document Interface) manually. Here is the procedure to use:

Figure 2-32: RGui started in MDI mode (default mode). The main window,
called ‘RGui’ contains one or several child windows like ‘R Console’.

44
Figure 2-33: RGui started in SDI mode the large, parent window called ‘RGui’
is not there any more. Only ‘R Console’ is there, and the main menu is displayed
in this window. SciViews R Console can only be started when RGui is in this
mode.

1. Start R (RGui) from its desktop icon, or from the start menu.

2. If it is in SDI mode, you are done.

3. If it is in MDI mode, select menu entry Edit -> GUI


preferences… You should see a dialog box like in fig. 2-34.

4. Select Single or multiple windows -> SDI in this dialog box


(fig. 2-34).

45
Figure 2-34: The Rgui Configuration Editor. You have to select ‘SDI’ in the top
of this dialog box to switch RGui in SDI mode.

5. Click ‘Save’. R asks you where to save this configuration file


(called ‘Rconsole’). Do not change it, and click ‘Save’ (fig. 2-35).

6. Click ‘Cancel’ in the Rgui Configuration Editor (fig 2-34). It is not


useful to click either ‘Apply’, or ‘OK’ here, because these changes
cannot be applied directly: you have to stop and restart RGui in
order to get it in SDI mode. That is why we just save the
configuration file and cancel the configuration editor.

7. Stop RGui (File -> Exit). Click ‘No’ at the question “Save
workspace image?”.

8. Start R again from its desktop icon, or Start menu entry. You
should have RGui running in SDI mode now (fig. 2-33).

46
Figure 2-35: the file selector displayed when you click ‘Save’ in the Rgui
Configuration Editor. Do not change the default file and path proposed and just
click ‘Save’.

Saving workspaces from session to session with SciViews-R

[TO DO: explain how one can save and restore sessions in R /
SciViews-R; explain also the difference between the workspace and the
script edited in the command bar… this appears to be often confusing
for beginners!].

[TO DO: a summary and flow chart of installation procedure for


very beginners, suggested by M. R.]

47
3. COMPANION APPLICATIONS FOR WINDOWS IN SCIVIEWS-R

Two distinct parts compose SciViews-R:

1. A platform-independent layer, mainly represented by R code


collected in the SciViews bundle (note: some part of it is not
platform-independent yet, but it is planned for the future), but
also, by menus and other items written in HTML code. This layer
does not only care of providing GUI extensions to R, but it also
expands the way data and results are manipulated and explored.
For instance, import, export, copy and clippaste concern
communication between R and other software and view
implements a flexible way to have visual insights on R objects,
combining text, tables and graphs.

2. Companion applications that actually implement the GUI. They


are interchangeable. It means that other applications can replace
existing ones, possibly with a particular look and feel more
adapted to a given platform. The SciViews team currently develops
such a suite of GUI satellite applications for the Windows
platform: SciViews R Console enhances the classical Rgui with
functionalities like an object browser, a context-sensible script
editor, customizable toolbars or dockable windows displaying
menus, graph galleries, assistants, electronic reference cards, …
Tinn-R is a code editor with syntax highlighting, contextual help
and integration with R for running and debugging R scripts.
SciViews R Report is an HTML wysiwyg editor designed to
quickly write reports of your analyses made with R. All these
applications communicate with each other and with R. They
constitute a powerful, integrated and complete statistical analysis
environment, with R as the corner stone.

Overview of the applications


SciViews R Console is a GUI that supplements the classical
Rgui with various tools. It adds some functionality such as an
object browser, basic script edition and customizable toolbars and
menus. It also handles views and can communicate with R as well
as with the others applications in the suite.

SciViews R Report is a HTML text editor you can use to edit


reports. When used conjointly with the SciViews R Console, you
can append directly your graphs or your views in it. The report
function, accessible from command line or via the contextual
menu of objects in the object explorer also interacts with it.

Tinn-R is a code editor with syntax highlighting, contextual help


and functions to submit code to R in whole or line-by-line from
the editor. You can use it as a powerful replacement of the script
editor provided with SciViews R Console.

48
SciViews R Console
SciViews R Console is the main application. It consists in an
enhanced Graphical User Interface (GUI) you can use instead on top of
the basic Rgui that comes with R (providing it is running in SDI mode,
see ‘installation of SciViews-R and the SciViews bundle’). Since SciViews
R Console runs with Rgui and do not replace it, it remains 100%
compatible with the latter. No worry thus, about compatibility issues
between the two!

49
From classical Rgui (in SDI mode)…

… to SciViews R Console [TO DO: increase resolution!]

50
At any time, you can come back to the classical Rgui:

• either by quitting completely SciViews R Console, which will


restore Rgui to it’s usual state.

• Or by using Ctrl-H shortcut which toggles Show/Hide bars.

SciViews R Console bars

SciViews R Console comes


with several add-on bars you can
show or hide, depending on what
you want. In this section, we will
describe those bars. Available
toolbars are listed in the menu
Misc -> Toolbars. [note that
the ‘more bars…’ entry in not
implemented yet in SciViews-R
0.8-9]

51
Command bar / Script Editor

The command bar allows editing R code and acts as a rapid script
editor (look at Tinn-R for a fully-featured code editor). Associated
toolbar includes buttons to:

• create a new script file,

• open a script file (default .R extension, could be changed),

• save the current script file,

• run the script in part or in whole: what is submitted is either the


active line or the current selection ; a useful shortcut is F5 key for
this button. Note that, if you click Shift-F5, then you source the
whole script in the console. This is dramatically faster, but you
have no details on the operation. The script must be saved on disk
for this to be operational. Last changes in the script are
automatically committed to the file on disk when you click Shift-
F5.

• Recall history (not programmed yet in this version).

• Send a piece of code to the Report application (not done yet).

On-the-fly execution of code when you key it in the script window


is ensured by using Shift-Enter instead of Enter to go to a new line. In
this case, the corresponding command is immediately issued at the
prompt in the console.

Within the editor, the code is syntax-highlighted.


When the name of a function is written and you
enter the open bracket ‘(‘, a code tip appears with
the syntax of the function. In the current version,
it is not terribly smart yet. It cannot resolve
generic function/methods, nor a few commands
like ‘for (‘, or ‘length (‘. This will be fixed later. To
dismiss a code tip, hit ESC, or click anywhere
outside the tip in the command window.

52
For your convenience, you can drag and drop items from the
object explorer (see hereunder) to the script. If it is a function, the
opening bracket is added automatically as well as the corresponding
code tip. Double-click on an item in the object explorer has the same
effect, except that it will send the variable name either to the script or
directly to the console, depending which one currently owns the caret.
With double-click, the name of the variable is naturally send to the caret
position, while with drag and drop you can freely decide where to drop
it. You can even use drag and drop from the object explorer to any
external text editor that is drag&drop compatible!

If you only remember the beginning of a function


or variable name, just enter it and hit Ctrl-Space.
You then obtain a completion list with all variables
starting with this string (example at right). Select
in the list, or click Tab to “autocomplete” the word.
Hit Esc to cancel the completion list. Icons recall
the type of variable it is, like function, method, data
frame, vector, etc

If you call the completion list without entering the beginning of a


variable name, the list of all variables currently in the user workspace is
displayed. Methods are displayed in the list and are pasted as such
(example, plot.default). For sure, the function should paste only ‘plot’,
since it is the recommended way to call a generic function. This will be
fixed in later versions of the software.

The completion list is automatically displayed and shows


components of a list or a data frame when you follow the name of the
list/data frame variable by ‘$’. Try for instance to issue mylist <-
list(x = 1, y = 2, name = "test") at the command line, and then key
in mylist$ in the script window to see this feature in action. More
intelligent completion lists will be proposed in the future (when using
‘[[‘ for lists, when using ‘@’ with S4 objects, …).

Please, note that both code tips and completion lists are
only able to display items that are currently visible from the
user workspace. It is not context specific when you call it from within
a function you write in the script window, and it will not show items of
your script if you have not run it yet!

Right-click in the script panel calls a context menu with


additional commands: Cut, Copy, Paste, Find…, Replace…, Show
Whitespace, Make Upper/Lowercase, Undo, Redo and
Properties… From Properties…, you can customize the appearance
of the script (colour syntaxing ON/OFF, choose colours and fonts, add
line numbering, … In the ‘Keyboard’ tab of this dialog box, you will
discover that many more commands are hidden in this small script
editor, and you can freely customize shortcuts to access these
commands! For instance, you can use bookmarks (Ctrl-F2 toggles a
bookmark ON/OFF, F2 go to next bookmark, Shift-F2 go to previous
one, by default), you can define up to 10 macros (Ctrl-Shift-R by
default to record it, and then assign your favourite shortcut to it), …

[to do: some examples of using these extra features]

53
Warning! Changes you make in the Properties… dialog
box of the script panel are not saved yet between sessions.
This will be fixed in further releases.

The main goal of this command bar is the edition of small pieces of
code, when debugging but it turns to be also a simple multiline code
editor for the R console. You could either submit the whole (selected)
code or press repeatedly F5 key to submit it line by line (step-by-step
execution). For more features and comfort to edit large pieces of R code,
consider an external code editor, like Tinn-R (see later in this manual).

Dock windows

You can use as much as five dock windows simultaneously with


your SciViews R Console. They are independent components.
For each dock window, you have to choose in a combo box what
you want to display. You can change the sheet displayed in any
dock window whenever you want it the same way.

[TO DO: M.R. -> explain how do we change and customize the
dockable windows. For example, if I want to create one that is called
‘geostatistics’ and opens the library gstat and geoR, and has the graph
whatever… I do I do it ? I saw in the example that you can create other
dockwindows, but when I press customize it states that it is still not
implemented. Ph.G.: yes, good idea, we should add a section explaining
how to write such dock contents]

Available components are categorized according to the following


classification:

Libraries

Libraries are web pages that can interact with the R Console, or
the script panel. Since you use HTML code, you are only limited by your
imagination here! In this version of SciViews-R, we have only added a
few of them, to illustrate their great potentials. Here is an overview of
the few libraries that come with the program:

54
R Reference card is an electronic Colour picker allows choosing
version of Jonathan Baron’s R colours. Hexadecimal RGB
reference card. Items are classified representation code is inserted
by categories and could be clicked to within your R session [to do: link to
be inserted in your R session. ‘RColorBrewer’ + include ideas from
http://geography.uoregon.edu/dat
agraphics/color_scales.htm].

The SciViews version of the R


Commander menu, that interacts
with the Rcmdr package (>= 1.1-1).

55
Libraries are stored in the user directory. You can add your own
libraries (a document will explain how to do that in future versions; in
the meantime, just study the code of example libraries).

Scratchpads

Scratchpads are little RTF document editors you


can use in several ways: as session clipboards to
store pieces of code, text, ideas, graphs, ‘to do’
lists and so on. In the current version, many
tools are missing to open, close and edit them.
Basically, you can copy and paste text and access
basic editing features. Scratchpads also support
drag and drop from the object explorer, from the
script window, from compatible text editors, or
word processors. Documents in scratchpads are
automatically saved at regular intervals, and
they are restored from session to session.

Object Explorer

The object explorer allows browsing the R objects accessible from


the active R session. Environments are listed, beginning by the user
workspace (.GlobalEnv). Objects existing in the selected environment
are listed in the panel below.

You can filter objects depending on types (data, vectors,


functions…) or by using regular expressions. Combining both filters you
can easily find functions or variables, even from large environments, like
‘base’. To obtain information about regular expressions, you can have a
look at the help of the function grep. Here are some expressions you
could use:

Expression/pattern Objects returned…


\\. contain a dot (usually a method)
frame$ ends with ‘frame’
^f begins with ‘f’
[0-9] contains at least one figure
^.$ its name is of length 1
^…$ its name is of length 3
^.[0_9] has a figure in second position

56
The contextual menus of the object explorer are generated in pure
R code in the current R session. They adapt, thus, to the current state of
R, and custom items can be easily added, just with R functions. The list
of available views, by example, is generated on the fly, so that if you add
a view it will appear next time you right-click on an object of the given
class. [TO DO: redraw the picture: bad resolution, unreadable in PDF!]

Adding custom tools

SciViews R Console allows you to customize your environment in


several ways. Here are the steps to add a custom button to a toolbar and
use it to call a R function (steps are identical to add menus items in the
SciViews R Console menu).

57
1. Call Customize dialog box…

Go to Commands tab, category Custom

2. Drag Custom Button and drop it on a toolbar. Once the button is


positioned, click on it. The following dialog box appears:

Click on R Command button.

Enter the R code to submit with this button and press OK.

58
You can change other attributes of the button if you want (icon,
caption, description, tooltip text…).

Close the customize dialog box. A list of all custom buttons and
corresponding R commands appear. You can put it in clipboard and
paste it in a text editor to remember those commands you added to the
toolbars/menus.

Changes in toolbars/menus are automatically saved from session


to session for each user separately. The location and visibility of the
bars, including the command bar and the dock panels is also saved. If
you want to save and retrieve given configurations, you can use the
menu entries Edit -> Save/Load Settings… Customizations are saved
in binary format, in files with .RconsoleTB2 and .RConsoleTBM. They
can be reused by other users, or on other computers.

59
SciViews R Report

60
SciViews R Report is a separate, lightweight
HTML editor that communicates with SciViews R
Console to easily build nicely formatted reports
during the analysis. Interactions are the
following:

• Insert the default view associated with an


object: call the menu and select Report.

• Insert a graph from the SciViews graphic


device. Two icons are available to export it in
PNG format only, or both in PNG and PDF
formats, respectively. [todo: explain how to
report a plot from the command line]

• Invokes report R function directly from


command line:

> report(iris)

• When using SciViews viewer for a given


view, use the Report icon to append the
content of the current view to the report.

Within SciViews R Report, you benefit of all


classical formatting options. In fact, you can use
any formatting based on HTML language.

In future versions of SciViews R Report, you will


be able to transfer your HTML report to
Microsoft Word, without any lost of formatting
(the button already exists in View -> Import
in Word, but it is not programmed yet).

A reason why we programmed SciViews R


Report, instead of using a link to Microsoft
Word, is to remain independent from the office
suite of Microsoft. The main reason, however, is
to provide a lightweight editor (about 12 Mb
when loaded in memory) that does not uses to
much RAM and leave it for R. If you open a
program like Microsoft Word at the same time
as R, you will waste as much as 50 to 60 Mb!

61
Tinn-R, a R code editor
Tinn is a text editor developed with Borland Delphi 5 for
Windows. It is designed as a small, simple, but richer replacement of the
default Notepad.exe under Windows. It is distributed under a GPL
license.

The original Tinn was adapted to edit R scripts. This special


release is called Tinn-R. It is made and maintained by José Cláudio
Faria (DCET/UESC/Brasil), Philippe Grosjean (UMH/Belgium) and
collaborators. Tinn-R uses a SendKeys component kindly donated to the
project by MJT NET (http://mjtnet.com/). It is tested so far under
Windows 98, 2000 and XP.

Main characteristics of Tinn-R

1. Syntax highlight of S language,

2. Menu and toolbar with specific tools to interact with R,

3. Allows working with the following R user interfaces:

• RGui (in MDI mode),

• R Console (RGui in SDI mode),

• SciViews R Console (it is suggested to close the command editor if


you work with Tinn-R)

4. It works also with S-PLUS.

62
Tips for using Tinn-R

This is a quick tour of Tinn-R, showing its major features:

1. Define if the specific menu and


toolbar is displayed in Tinn-R (R
Resources Visibles checkbox). You
can also indicate which is you
favourite Rgui program (Rgui.exe in
the \bin subdirectory of R, or
RConsole.exe in the \bin
subdirectory of SciViews).

2. Visualization of the specific menu and toolbar:

63
3. All highlighters are user configurable:

4. Warning! Do not use accents or symbols (@, #, $, %, ^,


&) in the path or files names of your scripts. Tinn-R do not
work properly (yet) in such a case!

5. Details of the specific R menu:

64
65
6. The specific R toolbar can be placed everywhere on the screen:

7. Files with *.r, *.R, *.q and *.Q extensions are recognized as R/S-
PLUS scripts. If the file does not have one of these extensions, or if it
has not been saved yet, some R tools are disabled

66
8. To send code line by line from Tinn-R to RGui, it is
recommended to dispose the two windows (RGui and Tinn-R) side-by-
side. If you want to place Tinn-R on top of Rgui / R Console or SciViews
R Console, you have to set the ‘On Top’ option of Tinn-R for this
purpose (the button with an icon representing a pushpin):

There are far more tools and features in Tinn-R. You can discover
them by using the program and experimenting with its menus. You can
also read the Tinn-R FAQ, whose latest version is available at:
http://www.sciviews.org/tinn-R/Tinn-R_FAQ.txt.

[TO DO: indicate how to change hotkeys in Tinn-R to match those


in SciViews R Console]

67
Using SciViews R Console with R Commander
R Commander (Rcmdr) is an R package from John Fox that offers
a basic-statistics Tcl/Tk GUI for R. You can download it from CRAN
(http://cran.r-project.org), or from John Fox’s web pages
(http://socserv.socsci.mcmaster.ca/jfox/Misc/Rcmdr/). The target
audience consists mainly in student users, for teaching purpose. Under
SciViews, Rcmdr seamlessly integrates within its environment, starting
from version 0.9-12 (but SciViews-R 0.8-9 requires at least Rcmdr 1.1-1).
The main window of R Commander is not displayed there. SciViews uses
instead a dock menu. State (which data set and which model is in use) is
displayed in the status bar of SciViews R Console. Log of commands is
done directly in the script panel.

At left, a representation of the SciViews


version of the R Commander menu. Items are
accessed in tabbed sheets.

When clicking an item, the corresponding


svRcmdr menu is called, thus invoking a
Tcl/Tk window. Simply use this window to
enter the parameters of your analyses.

Note that in this version of SciViews,


dialog boxes do not always appear on
top of SciViews R Console. Just activate
them from the command bar, if
required. This will be fixed in next
release.

68
4. PRESENTATION OF SOME FUNCTIONS IN THE SCIVIEWS BUNDLE

In this section, we present some of the R functions in the SciViews


bundle that can be called directly from the command line within an R
session. This section is not an exhaustive presentation of all the
functions in this bundle. Please, refer to the online help of the respective
packages (svGUI, svMisc, svIO, svViews, svDialogs, svIDE, svSocket and
tcltk2) for further information. We focus here on the practical use of
some of these functions.

export and copy functions


Main usage syntax:

export(x, type = ,file = )


copy(x, type = )

export function provides a convenient way to export data or other


objects from R. It is a generic function, which means different methods
can be defined for different classes of objects. At the moment, we define
specific methods for matrices and data frame. Any other objects are
treated by export.default. Other methods can be easily added in the
future, using the traditional implementation of methods in the S
language.

For a given object (let’s say a data frame), we would like to make
different types of exportation available from the same function, like raw
text, HTML, LaTeX… The argument type controls this. Depending on
the object, different types of exportation may be available (including
custom ones). To know which types are available for a given object in a
given environment, use export(x, type = "typelist") as shown below:

> library(svIO)
> data(iris)
> export(iris, type = "typelist")
[1] "raw" "ascii" "html" "latex" "sascode"

The different types in the previous example correspond to:

raw: exports an internal representation of the object which could be


sourced to recreate the object in another R session. For details, see
the help page of dput function.

ascii: exports a text (ASCII) version of the object, with values separated
by tabulations. This version could be read directly by many
external applications, such as text editors, spreadsheets, or other
statistical software.

html: exports the object as HTML code (we may consider in the future to
export as XML).

69
latex:exports the object as LaTeX code. It uses the code from HMisc
package, which is thus required. Useful for pasting the object in a
LaTeX document.

sascode: export the SAS code which defines the object within SAS (only
for data frames).

As we want to output the object, we clearly have to indicate the


destination. This is done using the file argument. In any case, an empty
string for this argument redirects the output to the R Console, which
could be useful for debugging. In many cases, you will want to write to a
file on disk (provide the complete path). Depending on the type of
exportation (and so on the underlying called export function), the value
could be any type of connexion R could handle, as listed in the help page
of file function.

> x <- 1:2


> export(x, file = "", type = "latex")
% latex.default(x, file = tmpfile, ...)
\begin{table}[!tbp]
\begin{center}
\begin{tabular}{r}\hline\hline
\multicolumn{1}{c}{}
\\ \hline
$1$\\
$2$\\
\hline
\end{tabular}
\end{center}
\end{table}

> export(x, file = "", type = "ascii")


1 2

Here is an example exportation into SAS code :

> export(iris, file = "iris.sas", type = "sascode")

The result is visible at: http://www.stat.ucl.ac.be/R2HTML/iris.sas.

You may easily add your own export types, by adding a function
whose name is: export.class..type. Please, refer to the second part of
this manual for further information on how to extend features of the
SciViews bundle.

Instead of exporting the whole object, one could also export a part
of it or the result of any calculation: export also accepts expressions as
first argument. Keep in mind, however, that the expression will always
be evaluated in the user workspace, whatever the place it is called (a
restriction required by the GUI extensions of SciViews-R). Use get(x,
pos = ) to retrieve an object in a particular environment.

An expression as first argument of the export or copy function will


be evaluated in the user workspace:

70
> export(as.data.frame(apply(iris[ , 1:4], 2, mean)), file = "",
+ type = "sascode")
DATA work.asdataframeapplyiris_14_2_mean;
INFILE cards missover;
INPUT applyiris142mean ;
CARDS;
5.84333333333333
3.05733333333333
3.758
1.19933333333333
;
RUN;

This last example would benefit from some additional parameters:


the name of the SAS data set is computed from the input but this may be
override with the option sasmember:

> export(as.data.frame(apply(iris[ , 1:4], 2, mean)), file = "",


+ type = "sascode", sasmember = "iris")
DATA work.iris;
[...]

[to do: an example using the argument append, and also, an example
with HTML format]

One current use when working on projects with several


applications is the copy/paste (the clipboard metaphore). R addresses
this issue by allowing to write to the clipboard by using file =
"clipboard". Thus, export(iris, type = "sascode", file =
"clipboard") writes the generated SAS code to the clipboard.

copy is a simple wrapper of export that automatically adds this


argument, so that you may find quicker to type:
> copy(iris, type = "sascode")

Be careful: with clipboard operations, there is a limit of 32 Kb!


Export in files for larger objects.

view functions
Main usage syntax:
view(x, type = )

Data analyses require in-depth browsing of data and results.


Statistical analyses fruitfully begin with some descriptive graphs and
sometimes well-established suites of steps to check and explore them. R
allows doing this, of course, but it separates textual output (in ASCII
format at the console) from graphics (in graph devices), which is not
always easy to collate together. Moreover, ASCII formatted tables are a
nightmare to paste and convert into publication quality tables in a
report. It is where views come in help.

Views are HTML pages that include graphs, text and nicely
formatted tables. Their primary goal is to provide insight on objects.

71
Comparing two different objects is as simple as looking at two views
side-by-side. As a side effect, they are also nice chunks of results to feed
your reports!

Although the svViews package in the SciViews bundle comes with


some predefined views, they should be considered as examples of what
could be done. In fact, this feature is intended to be customized by the
statistician to fit its particular requirements with its own favourite views.

The basic mechanism is the same as for export. view is also a


generic function, admitting different methods for different classes of
objects. Its first argument can be an expression, but it will always be
evaluated in the global environment. The list of all available views for a
given object is obtained with type = "typelist":
> library(svViews)

> view(iris, type = "typelist")

[1] "summary" "print" "twovars" "missing" "sascode"

> view(sum, type = "typelist")

[1] "print" "methods"

Each object has a default view, so that one could always simply call
view(x). Let’s try the default view on the iris data frame.
> view(iris)

The view function could work jointly with an external application (the
“viewer”). If such an external application is unavailable, the viewer will
be displayed in the default web browser (see browser function). A
dedicated viewer could add some functionality. The one provided within
SciViews R Console displays tabs for all available views and allows direct
inclusion of the current view in the report (see previous section).
Further control of views parameters is another, planned, additional
feature of the dedicated viewer.

Below is an excerpt of the default view obtained with view(iris):

View of iris [summary]


Sepal.Length Sepal.Width Petal.Length Petal.Width Species
Min. :4.300 Min. :2.000 Min. :1.000 Min. :0.100 setosa :50

1st Qu.:5.100 1st Qu.:2.800 1st Qu.:1.600 1st Qu.:0.300 versicolor:50


Median :5.800 Median :3.000 Median :4.350 Median :1.300 virginica :50
Mean :5.843 Mean :3.057 Mean :3.758 Mean :1.199
3rd Qu.:6.400 3rd Qu.:3.300 3rd Qu.:5.100 3rd Qu.:1.800
Max. :7.900 Max. :4.400 Max. :6.900 Max. :2.500

72
Sepal.Length
Numeric
Range: 4.3-7.9

Scatterplot is colorized according to factor: Species

Coming back to the list of available views for data frames, we could
see that there is also a view called “twovars”. As this is not the default
view, we have to precise the type in order to call it:

> view(iris, type = "twovars")

73
This view presents graphs for all pairs of variable within the data frame
and a correlation matrix with different colors according to correlations
values.

74
Let’s recall views are HTML pages. They rely also on so-called
Cascading Style Sheets (CSS), which allow separating the content from
the formatting. You can change the colours of this correlation matrix by
editing the associated CSS file (in fact, you can even give colours only to
the correlation up to 0.9, by example). In SciViews R Console, you
switch to a different CSS file just by selecting a different entry in the
‘Style’ dropdown list that appears in the View window. We show here
the same correlation matrix, just using a different style:

clippaste function
Main usage syntax:
clippaste("name", type = ,objclass = )

The export and copy functions allow both exporting objects to the
clipboard. The function clippaste is complementary: it reads from the
clipboard and creates an R object from its content.

When using directly as the counterpart of copy, one should specify


the type argument. In any other situations, the default value (ascii)
should be suitable. The first argument is the name of the object to be
created. A third argument allows controlling the class of the object to be
created, as there is no way to know it from the clipboard’s content
(except when its content is a raw R structure). [PhG: shouldn’t the raw
format be used as default here]

> library(svIO)
> copy(iris, type = "ascii")
> clippaste("irisCP")
> irisCP[1, 1]
[1] 5.1

The main use of this function is to import quickly data from


external application such as spreadsheets, without having to use
intermediary files in suitable formats. Indeed, most applications
propose to copy data in the clipboard and can then be retrieved with
clippaste. [TO DO: a clippaste example from Excel!]

75
An import function is planned for the future, as the counterpart of
export.

report function
report in svViews, together with all guiXXX functions (not
described here, see SciViews-Internals online help) in the svGUI
package won’t work without an external application. Its purpose is to
append a suitable representation of an R object to a report edited in that
external application. On Windows platform, SciViews-R proposes the
SciViews R Report application to create reports in HTML format and
rapidly publish them on the inter/intranet, or import it to Microsoft
Word for further edition.

76
PART II: THE SCIVIEWS GUI API

77
5. CONCEPTION OF A “CODE-CENTRED” GUI

In this section, we will develop our vision of an efficient GUI for


scientific computing software, that is a “code-centred” GUI that does not
hide code, but instead, place it at the centre of the user interface and
provides tools to help writing it. It is certainly not the only valid GUI,
but it is one that proves to be efficient for several reasons:

1. It is didactic because the user learns how to write code. How


a beginner in face of a GUI that hides code completely, or presents
it as an internal complex thing, will acquire the skills to write good
scripts and automate its analyses?

2. It is also useful for teachers for a second reason: code traces


work done by students. How will a teacher judge students’
analyses based on (sometimes truncated) outputs obtained after
tens, or hundreds of mouse clicks that are lost for the eternity?

3. It is flexible. Scripts and programs have proven to be an efficient


and flexible way to run analyses. That is why experts prefer CLI
(Command Line Interface). A well-designed code-centred GUI
inherits this flexibility. On the contrary, other types of GUI,
especially those based on menus and dialog boxes exclusively, are
rather inflexible and constitute a major waste of time with
interminable mouse-clicks!

Based on a few R GUI projects, like R Commander


(http://socserv.socsci.mcmaster.ca/jfox/Misc/Rcmdr/index.html), JGR
(Java GUI for R, pronounce “jaguar”, see http://stats.math.uni-
augsburg.de/JGR/) or SciViews-R (http://www.sciviews.org/SciViews-
R), we will sketch major features of a code-centred GUI as it
progressively develops for R.

The console is still there… but it is supported by a script editor


As being a code-centred GUI, the major element to interact with
code, the console is still there and at the middle of the interface.
However, despite powerful line editing and a history recalling feature,
the console appears terribly limited: edition of one line at a time, no
syntax highlighting or other forms of unattended help in writing the
code. In the best case, we have just a different colour to separate input
and output! If this console is supplemented with a simple script editor
above or below it, it already gains some friendliness. Of course, being a
GUI, there is also a menu and a toolbar to access frequently-used
functions! Next figures present the appearance of this console-script
editor that forms the main window of a code-centred GUI.

78
Figure 5-1: The main window of R Commander (version 0.9-12). The lower
panel (1) collects inputs and outputs and is similar to a console, even if it is not
editable, if it collects only outputs from R Commander itself and if the actual R
console is not hidden (separate window). Above it (2), there is a simple script
editor. No syntax highlighting, or other help like code completion or code tips,
but the tendency is there: a script panel supplements a console! Finally, on top
(3), there is a menu and a toolbar. In R Commander, menus are particularly
rich and give access to many different dialog boxes to parameterize the
analyses.

79
Figure 5-2: The main window of JGR (version DP3). It is also centred on a
non-editable console (1), with the lower panel (2) being a multi-line code editor
with syntax highlighting and code completion. In this case, however, this panel
is not a true script editor: once a line is issued on the console, its content is
cleared from this panel. Yet, the concept is very close. It should not be difficult
to transform it into a real script editor (unless their programmers believe it is
an unnecessary duplication of the separate script edition windows of JGR). On
top, one finds the traditional menus and toolbar (3).

80
Figure 5-3: The main SciViews-R window (version 0.7-2). The console (1),
which is editable here, is supported by a script editor, called a ‘Command’
window. It permits the edition of one script at a time, with syntax colouring,
step-by-step execution, code tips and code completion (like here, a code
completion for iris list items). This panel also has its own little toolbar at left, in
supplement to the main menu and toolbar(s) at top (3). The script editor can be
docked at the bottom or at the top of the console. It can also be hidden or
separated (in this case, it floats on top of the console window).

As these figures suggest it, there seems to be a convergence


between these three different GUIs that ultimately propose a relatively
similar organisation of their main window. The user still writes code,…
but it is supported in this (difficult) task by a richer command/script
editor and various assisting tools. It is probably in tools like syntax
highlighting, code tips or code completion, that edition of code in R
acquires a new dimension, and becomes easier for the beginner. These
tools should thus not be regarded as details or gadgets, but on the
contrary, as the major features that differentiate a plain CLI from a
code-centred GUI! Other tools that potentially enrich a code-centred
GUI are presented hereunder.

Menus, toolbars and dialog boxes


As we have seen, menus and, at least, a simple toolbar are also part
of the main windows of these three GUIs. In the case of R Commander,
this menu calls different dialog boxes to parameterize analyses (the
same dialog boxes are also accessible from SciViews-R, because the
latest version of R Commander is now compatible with SciViews-R).

81
Figure 5-4: an example of an R Commander dialog box: the independent t-
test.

The idea is simple: for beginners, a dialog box presents parameters


of the analysis in a friendlier way than a plain command line editor.
Once he clicks ‘OK’ in such a dialog box, its request is translated into
one or several lines of code that are appended to the script and executed
in the console simultaneously. This way, the user sees correspondence
between its choice in the dialog box and the code and starts learning it.
With such a mechanism, menus, toolbars and dialog boxes are powerful
supporting tools in the code-centred GUI.

However, it would be relatively simple to hide the code, and still


get a fully functional GUI with menus and dialog boxes on top of R.
Doing so, one loses all the didactic aspect of these tools, and one
encloses and reinforces the beginner into its point-and-click habits!
Code generation from menus and dialog boxes is thus a major
and indispensable feature here!

One should take care that, speaking about code generation, we


consider only solutions where dialog boxes actions produce plain –GUI-
independent– R code as one would type it directly on the command line.
For instance, functions like winMenuAdd() and winMenuAddItem() in the
Windows version of R add custom menus to Rgui and allow to link these
menu items to R commands. Let’s say you write a function called
gui.t.test() that opens a dialog box and then runs the corresponding
analysis. Then, you create a ‘t-test’ menu entry with winMenuAddItem().
Which code will appear on the command line when the user clicks on
this menu?

> gui.t.test()

That’s it! The code that should appear is rather something like:

> t.test(myX, myY, alternative = “less”, conf.level = 0.90)

With winMenuAddItem(), there is no way to replace the first call,


gui.t.test(), by the substituted command, t.test(....). Thus, it does
not permit to display command the user should enter in plain S
language. One needs a different solution, like the mechanism used in R
Commander!

82
The object explorer and data editor
What makes the success of a spreadsheet-like GUI as Excel?
Everything is visible and can be handled with the mouse. Data,
calculations, graphs are all mixed in spreadsheets… and they are visible.
On the contrary, in R, data are stored in variables, themselves located in
environments… that is, abstract concepts for those who never
programmed before. They appear to be inaccessible, hidden, complex
objects in the eyes of a beginner stuck in front of a meaningless prompt!

There is no way to overcome the need to learn what a variable, an


object, or an environment is, but it is may be possible to make them a
little bit less abstract. It is the role of the object explorer, a graphical
window to visualize the content of environments that lacks to many S-
PLUS users switching to R. A good object explorer graphically depicts
environments and variables. It also allows to “handle” them (drag and
drop, right-click context menu with a few pertinent actions one can
apply on them) with the mouse. For the beginner, an object explorer
materializes environments, variables and objects. For advanced users, it
provides shortcuts for many common operations. The next three figures
present various objects explorers, from S-PLUS, JGR and SciViews-R.

Figure 5-5: The S-PLUS (version 6 for Windows) object explorer.

83
Figure 5-6: The JGR object explorer (version DP3). Presentation and concept
is a little different, but the basic idea is the same: to materialize objects and
allow their handling with the mouse (you can drag and drop items to the
command line, for instance).

Figure 5-7: the object explorer of SciViews-R (version 0.8-9) is dockable at left
or at right of the main window. The top part allows filtering variables. The
middle part presents a tree with the various environments, and the lower part is
a list of variables in the selected environment (here in .GlobalEnv). Objects can
be drag-dropped in the script. A right click on an object displays a context menu
with a few pertinent commands for this object (here, for the data frame ‘iris’).
In particular, the ‘Edit’ entry pops up a data editor.

A complement that further materializes objects is the data editor,


a spreadsheet-like editor for 2D-tables. This presentation is very close to
Excel, and it is also very convenient to key in data in a table, or to edit
individual cells in it. R has a basic data editor (see next figure). A fully
featured GUI certainly needs something more elaborate.

84
Figure 5-8: The basic data editor of R.

Other “explorers”
Besides the object explorer, one can imagine other explorers, with
the same idea to materialize, summarize and allow handling abstract
items with the mouse. A file explorer now exists in all recent graphical
platforms. SciViews-R proposes one in its dock windows. Files on disk
are thus very easily accessible from within SciViews-R! It also proposes
various other “explorers” to access code chunks or commands: dockable
“menus”, graph galleries, electronic reference cards, … (see next figure).
Such kind of explorers are only limited by the imagination: they are
indeed HTML pages with javascript code, so, one can very easily imagine
other forms of explorers, or dockable forms to support beginners in R.

85
Figure 5-9: Two docked windows in SciViews-R. The top one holds a graph
gallery, a convenient way for a beginner to explore several graphs R provides
and to use them with real data sets (note that the graph gallery is not provided
any more in SciViews-R 0.8-9). The lower one is the electronic equivalent of
Jonathan Baron’s R reference card. It can also be viewer as an explorer
dedicated to easily browse and find various R code constructs (“code chunks”).

Views and reporting features


Reporting feature is not an original concept. It already exists in S-
PLUS, and in other statistical software like Systat. It allows to output
results in a text editor that mixes formatted tables and paragraphs of
text with graphs and pictures. In SciViews-R, a separate program, called
SciViews R Report, edits them. Although most report editors we know of
edit RTF documents under Windows, we prefer an HTML editor for
SciViews because HTML is now a widely used format, it is very flexible,
and it allows publishing such reports on the intra/internet immediately
without changes. Reporting features are provided in SciViews-R thanks
to a battery of functions that convert objects into HTML equivalent,
thanks to the R2HTML package. In the future, we would like to develop
also LaTeX as an alternate format for R reports (Sweave is a different
concept, but it already allows making nicely formatted reports with R
outputs embedded).

86
Figure 5-10: The SciViews R Report application. A report is a HTML
document mixing formatted text and tables with graphs and pictures. SciViews-
R provides functions to append results easily to such a report, thanks to the
R2HTML package.

As far as we know, Views is an original concept in SciViews. It


derives from the reporting feature. The idea is to provide a comfortable
visual inspection of objects in HTML format, thus mixing formatted
tables, text and/or graphs. For a given object, the user can open a tabbed
view window (see next figure) that displays various predefined pertinent
views for it. Of course, this is very close to chunks of report outputs. So,
it is also possible to append any view to the current report. Thus, Views
are both a tool to comfortably explore objects, and it is at the same time
an easy way to prepare pieces of output for the report!

87
Figure 5-11: A view window in SciViews-R (it is the same view that is placed in
the report presented in the previous figure, but slightly reworked). The second
button of the toolbar automatically appends the current view to the report.
Behind, a series of tabs allows a fast and easy navigation between the different
views provided for this object.

We believe that the combination of Views and reporting features


in SciViews-R will bring an interesting new dimension to rapidly explore
and communicate statistical data and results. Currently, SciViews-R
only proposes a very limited set of views for objects like ‘data.frame’ or
‘lm’. Pertinent and efficient views still remain to be developed in order to
unleash all the power of this technology (are there any imaginative or
creative volunteer over there?). Views are implemented in the svViews
package. Since they are HTML documents, views can be easily
implemented in other GUIs.

Facilitated input and output


One of the first questions a beginner asks is: “how can I import my
data set in R?”

TO DO…

Management of the system


TO DO…

Other assistants
TO DO…

88
Simplified online help and manuals
There are several introductory manuals for R. However, online
help presents all available functions. In R 2.2.0, despites a
reorganization of the main packages, there are still 1040 visible
functions in the package base! Among all these functions, many are very
unlikely to be used by the beginner. The beginner is lost in the mass of
the documentation and does not know where to find the functions to
perform simple tasks.

Electronic reference cards presented above are a solution to orient


the beginner. However, shouldn’t it be nice to have the opportunity to
simplify the system by hiding advanced functions that are unlikely to be
used at the beginning? We propose to install such a simplified help (and
perhaps also, a simplified view of package content in the object explorer,
by tagging each function as basic, advanced, or expert). Hence the user
could switch to one of these levels: basic, advanced or expert, and
discover the richness of R gradually.

Text editor and IDE


TO DO…

89
6. OVERVIEW OF THE SCIVIEWS R GUI API

Now that we have sketched the framework of our code-centred


GUI, we know which features to add to R to implement it. In this
section, we will rapidly browse through the various functions that
constitute our GUI API. Deeper exploration is done by looking at the
code and examples of these functions.

[The rest of this section still needs to be written… sorry!]

90
7. SVGUI, FUNCTIONS TO INTERFACE GUI CLIENT APPLICATIONS

The svGUI package of the SciViews bundle is the one that provides
various interfaces to client GUIs. There are functions to communicate
between the GUI client and R (…), other functions to implement an
object explorer (…), …

[The rest of this section still needs to be written… sorry!]

91
8. SVIO AND SVVIEWS: FORMATTED DATA EXCHANGE

The two complementary svIO and svViews packages manage


exchange of information with external applications, preferably in rich-
formatted versions (HTML, LaTeX, RTF, …). svIO is dedicated to
import, export and copy/paste to and from the clipboard. svViews
implements views and the reporting feature of the GUI API, associated
with these views and with R graphs.

Extending Export, View and Report functions


We detail here the functioning of the view function, as an example.
Other svIO and svViews functions, like export, copy and report use
exactly the same mechanism.
view <- function(x, type = "summary",
objname = deparse(substitute(x)), ...)
UseMethod("view")

The view function is generic, which means there could be in fact a


different view function for each class. The S3 dispatching method
ensures the good view.class function will be called (we may consider
using S4 objects in future version, since it is currently advised). The
function relies also on another, more unusual, dispatching method to
handle the type argument.

If you want to add a new type for a given class, you should use the
following skeleton:
# We define a new type called "dim"
"view.data.frame..dim" <- function(expr, objname, file, CSSFile,
command, browse = TRUE, ...) {
# To simplify the function, we consider it must be
# called from view.data.frame exclusively,
# We do not perform the full calculation of arguments like
# expr and assume it is an expression. This expression must
# be evaluated in the global environment to remain compatible
# with all GUI extensions
x <- eval(expr, envir = .GlobalEnv)

# Compute the view / This part could be modified as you want


# viewHTMLinit write the header of a HTML file that will use
# a CSS file
viewHTMLinit(objname = objname, type = "dim",
file = file, CSSFile = CSSFile, command = command)
Dim <- dim(x)
HTML(paste("Dim: ", Dim[1], " x ", Dim[2], sep = ""),
file = file)

# Add browse it from here (guiViewDisplay calls the correct


# viewer component)
# The view must return the file argument
if (browse) guiViewsDisplay(file)
invisible(return(file))
}
If you need to write a view function for another class, then you
should consider another skeleton. You first have to determine the
different types you will program yourself. The skeleton to be used
ensures anyone could add other types to your view.

92
"view.myclass" <- function(x, type = "print", objname =
deparse(substitute(x)), file = guiViewsFile(), CSSFile =
guiViewsCSS(), command = "", browse = TRUE, ...) {

# Include a function for each type


# There should always be a default type (print? or whatever
# you want)
"viewDefault" <- function(x, objname, type, file, CSSFile,
command, ...){
# optionnaly use viewHTMLinit
viewHTMLinit(objname = objname, type = type, file = file,
CSSFile = CSSFile, command = command)
# write the view...
cat("\nsome text",file=file,append=TRUE)
return(file)
}

"viewOtherType2" <- function(x, objname, type, file,


CSSFile, command, ...) {
# Define what this view does, as in viewDefault
return(file)
}

# Compute the expression. We use this system to allow


# the user to pass expressions to be evaluated as argument
objname <- objname
xexp <- try(if (inherits(x, "expression")) x else NULL,
silent = TRUE)
if (inherits(xexp, "try-error") || is.null(xexp)) {
xexp <- substitute(x)
if (is.character(xexp))
xexp <- parse(text = paste("`", xexp, "`",
sep = ""))
xexp <- as.expression(xexp)
}

# Do we have to pass this to a custom function as


# 'view.myclass..type()'?
custom <- paste("view.myclass..", type, sep = "")
if (exists(custom, mode = "function")) res <- get(custom,
mode = "function")(expr = xexp, objname = objname,
file = file, CSSFile = CSSFile,
command = command, browse = browse, ...)
else {

# Process the command in the standard function


x <- eval(xexp, envir = .GlobalEnv)
typelist <- c("print", listCustom("view", "myclass"))
typelist <- unique(typelist)

# The typelist returns the list of available views,


# including user-added
res <- switch(type,
"typelist" = typelist,
"type2" = viewOtherType2(x, objname, type, file, CSSFile,
command, ...),

# Include a line for each type you have defined / Finally


#use default view
viewDefault(x, objname, type, file, CSSFile, command,
...))
}

# Handles the viewer


if (command == "") command <- guiViewsCmd(type = type,
typelist = typelist, command = match.call(), file = file)
if (browse && type != "typelist") guiViewsDisplay(res)
if (type == "typelist" || !browse) return(res) else
invisible(res)
}

93
If this mechanism looks complex, it is indeed the most flexible way
we have found to :

1. Get the function work the same way wherever it is called (from the
command line, from a Tcl/Tk dialog box, from within another
function, etc..)

2. Define easily custom views, and integrate them automatically in


the object browser and viewer tabs.

Of course, we are open to any discussion around the


practical implementation of views, exports, etc… The features
are not frozen yet. The SciViews bundle and SciViews-R are
still in development and their specifications may change, if it
is justified.

[The rest of this section still needs to be written… sorry!]

94
9. SVMISC: MISCELLANEOUS UTILITARY FUNCTIONS

svMisc collects together various GUI (and non GUI) r functions


that we feel useful in the context of the SciViews GUI API.

[The rest of this section still needs to be written… sorry!]

95
10. SVDIALOGS: REUSABLE DIALOG BOXES

Dialog boxes are major elements of any GUI (Graphical User


Interface). It is usually by means of such dialog boxes that the user
interacts with the program to parameterize an action before triggering it
by a click on the ‘OK’ button. A basic set of dialog boxes (open/save file,
message box, input box, …) is provided with any modern platform, and it
is intended to be reusable.

Despite numerous discussions, R users/developers still do no


agree today (October 2004) on which is the best graphical widgets to
use. Indeed, there are several toolkits available, all with their own
strengths and weaknesses. Tcl/Tk can be used with R since a long time
(the tcltk package is distributed since along time with R distributions,
and it runs on all supported platforms). However, it is not the only
solution. Gtk on Linux/Unix, wxWidgets (for instance, using R-
wxPython recently developed by James Wettenhall, see
http://bioinf.wehi.edu.au/folders/james/wxPython/), Aqua, Java
Swing, AWT or SWT are some examples of potential candidates as
graphical toolkits that can be used to build a GUI for R.

Given the need of standard dialog boxes for basic GUI features in
R, and the various possible toolkits, we propose here a framework for a
reusable GUI API for dialog boxes. This API is part of a larger one that
deals with many aspects of R GUIs (menus, toolbars, object explorers,
completion lists, …). It is intended to provide a common interface to
various GUIs. In this experimental svDialogs package, we focus
exclusively on dialog boxes (indeed, more generally, on “reusable
windows”).

The idea is to provide about twenty different dialog


boxes/windows that perform common tasks. Their interface is fixed and
written in R functions like guiDlgMessage(), but not their actual
graphical implementation. Indeed, there is a default Tcl/Tk
implementation provided, but it is possible to switch at will to another
one. In the current version, we experiment this with R-wxPython. A
single option parameter determines which version of the dialog box
should be used. If guiWidgets is NULL or set to "tcltk", then the default
Tcl/Tk version is used. If this parameter is set to "wxPython", then the
wxPython version of the same dialog boxes is used, and so on...

This mechanism allows redefining all these dialog boxes in other


graphical toolkits. This way, an interface that uses these dialog boxes
becomes independent from a given graphical toolkit, and it is the end
user that chooses its favourite one, by setting options(guiWidgets =
“myFavoriteWidgets”).

Building dialog boxes


In this chapter, we discuss various ways to build dialog boxes, and
we explain the approach implemented in the svDialogs package. The
next chapter will actually describe the various dialog boxes implemented
in svDialogs.

96
Three levels of making dialog boxes in your GUI

There are at least, three ways to make dialog boxes available:

1. To provide standard dialog boxes, embedded in functions


(remember R is essentially a functional language). This is done by
means of standard dialog boxes like a message box, an open/save
file dialog box, etc. In the tcltk library, functions like
tkmessageBox(), tkgetOpenFile() or tkgetSaveFile() do this.
Freedom in designing dialog boxes at this level is very limited, only
a few predefined attributes can be changed. However, it is certainly
the simplest and fastest way to add some dialog boxes to interact
with the user in an R GUI application. Here is an example of a
simple program that prompts for a R script file and source it (the
corresponding dialog box is also shown as it appears under
Windows XP):

> file <- tclvalue(tkgetOpenFile(filetypes =


+ '{"R script" {".R"}}'))
> if (file != "") source(file)

Figure 10-1: The standard open file dialog box obtained with the script.

2. The second, more flexible, level to use dialog boxes in R is to access


and manipulate the graphical toolkit directly, or by means of an
intermediary language. In the tcltk package, there are numerous
functions to interact with the Tk widgets indirectly, using the Tcl
interpreted language. Although it seems better at first sight to
avoid using an additional intermediary language, it is not so
obvious in practice. Indeed, graphical items like dialog boxes are
event-driven, while R is designed to be used sequentially.
Incompatibilities between event-driven and sequential execution
of code are partly solved thanks to separate event loops (one for
the command line, and another independent one for tcltk). It is
further eliminated using an intermediary language to “talk with”
the widgets. Here is an example of a Tcl/Tk dialog box build using

97
various commands in the tcltk package (adapted from an example
of the tcltk package):

> tt <- tktoplevel()


> label.widget <- tklabel(tt, text = "Hello, World!")
> button.widget <- tkbutton(tt, text = "Push",
+ command = function() cat("OW!\n"))
> tkpack(label.widget, button.widget)
> tkwait.window(tt)
> tkdestroy(tt)

Figure 10-2: The custom Tcl/Tk dialog box that we just constructed
with R.

Although this approach brings far more flexibility, it does not deal
easily with the graphical and aesthetic aspects of the dialog boxes.
The developer has to figure out how the dialog box will be painted
when he writes the code, and has to construct its dialog box by
trials and errors most of the time. It turns to be a painful and
irritating task for complex dialog boxes.

3. The third level for building dialog boxes, is to paint them thanks to
a dedicated program. The tcltk package does not provide such a
level yet (programs like Visual Tcl could probably be adapted to do
it). The experimental R-wxPython package does so, using a
separate application called Boa Constructor.

98
Figure 10-3 : A screenshot of Boa Constructor during the construction of a dialog box.

Basically, the dialog box is constructed in a few steps. First, paint


the dialog box (at the centre in the picture), using the graphical
widgets from the top toolbar. For instance, add a button by
selecting it in the toolbar (1) and “painting it” with the mouse on
your dialog box (2). The little squares around the active widget are
resizing handles. Then, change properties of this widget in the
inspector (3) and define which events should be triggered in the
code of your application (in the ‘Evts’ tab of the inspector). At this
stage, not a single line of code was written, but the dialog box is
already “living”, displayed exactly as it will be in your future
program! When you close the dialog box, Boa Constructor
generates automatically the code that will display this dialog box in
your application (in Python language). This code appears in the
editor window (4). The developer just has to implement a few
events triggered by the dialog box. With wxPython in R, it is
possible to used Python code, to delegate the treatment to R by
means of an RS.call('myRfunction') instruction, and then to
implement myRfunction() in pure R code, or to mix both
approaches. This method is certainly better for complex dialog
boxes than the two previous ones. However, it currently requires
an intermediary language between R and the widgets, Python in
the case of the wxPython R package with Boa Constructor.

Approach used in svDialogs

Level 2 can and is already used to build custom dialog boxes in


several R GUIs with the tcltk package (see, for instance:
http://socserv.socsci.mcmaster.ca/jfox/Misc/Rcmdr/index.html, the R
Commander package). Level 3 is still experimental at the moment with

99
R-wxPython. We believe it has great potentials. In this svDialogs
package, we focus exclusively on level 1 dialog boxes. However, our
intention is to provide far more that the four or five standard dialog
boxes (message, input, open/save, choose dir) usually proposed. We
think that, with a carefully designed set of about twenty standard,
and/or flexible dialog boxes, one can build very easily a rather complex
GUI without the need of “programmed” dialog boxes (either at level 2, or
at level 3).

Additionally, since they are standard dialog boxes by definition in


level 1, it is rather easy to implement the same ones with the various
graphical toolkit R can use. This way, a given GUI can run on different
platforms, using different widgets. Consequently, the final user has the
freedom to choose its favourite look and feel, and it is not the developer
that imposes it. The key here is to agree on a common API that behaves
similarly, no matter its actual internal implementation, for external
code. This API, plus two particular implementations (for tcltk and
wxPython) are proposed in the current version of the svDialogs package.
These two implementations demonstrate how easy it is to switch to a
different graphical widget (from Tk to wxWidgets, or back) with this
API. Other implementations are possible in the future…

Toolkit-independent API and toolkit implementations

Option to switch between graphical toolkits

The mechanism is very simple. One argument of the functions


indicates which graphical toolkit is used. By default, it is the value stored
in the option guiWidgets. Hence, the end user has only to changes this
option, and all compatible dialog boxes are displayed with the chosen
widgets (if available). For instance:

> options(guiWidgets = "wxPython")

switches to wxPython version of the dialog boxes. To get back to the


standard Tcl/Tk dialog boxes (they are considered as “standard” just
because the tcltk package is distributed together with R), one can use:

> options(guiWidgets = "tcltk")

If guiWidgets is not defined (it is NULL), then the default Tcl/Tk version
of the dialog box is also used.

The API functions and the dispatch method

There are various ways to define the API and then to dispatch to
actual implementation of the dialog box. Here are a couple of
techniques:

1. To use the classical S3 object implementation, that is, to define API


function as generic functions (let’s say guiDlgMessage()), and to
use as first argument an object of a class like tcltk, or wxPython.
Then, methods would be: guiDlgMessage.default() –for the
default Tcl/Tk dialog box, no need of a specific method here–, and
guiDlgMessage.wxPython(), etc.

100
2. To use the same mechanism, but with S4 objects. This is the way
we are supposed to program in R since version 1.7.0!

3. To use plain functions. Indeed, it is rather unintuitive and


inefficient to have to define fake objects like tcltk or wxPython that
contain nothing, just to use the classical dispatch mechanism here.
We really do not need these objects, except for switching to a given
implementation of the dialog boxes! Moreover, the simple way to
switch to a given implementation with the textual option
GUIwidgets cannot be used in this case. One has to use specific
objects for this purpose. It is rather complex when one thinks that
these dialog boxes are mainly intended for beginners that are not
supposed to understand (yet) the object-oriented features and the
associated dispatch mechanism in R!

In the current (experimental) implementation of the svDialogs


package, we explore the third approach. Here is the way it works:

3 The API function is defined as follows (a simple message box


returning the name of the button clicked by the user, i.e., "ok" or
"cancel"):

guiDlgMessage <- function(message, GUI = getOption("guiWidgets"))


{
# Check arguments [...]

# Do we need to use a different implementation than Tcl/Tk?


if (!is.null(GUI) && GUI != "tcltk") { # Custom GUI widgets
# Look for a guiDlgMessage.<GUI> function
fun <- paste("guiDlgMessage", GUI, sep = ".")
if (exists(fun, where = 1, mode = "function")) {
res <- get(fun, pos = 1, mode = "function")(message =
message)
if (!is.null(res)) return(invisible(res)) else
warning("Using default Tcl/tk dialog box instead!")
}
}

# Use the default Tcl/Tk dialog box


if (!require(tcltk))
stop("Package 'tcltk' required. Please, (re)install it!")
res <- tkmessageBox(message = message, type = "okcancel")
return(invisible(as.character(res)))
}

The GUI argument is used (by default, it is the guiWidgets option)


to possibly dispatch to a guiDlgMessage.<GUI> function. If this
function does not exist, or returns NULL, then the default Tcl/Tk
implementation (which is embedded in the API function here) is
used.

3 Any particular implementation is defined in a function with same


arguments as the API, less the last one, GUI. Its name is
<APIfunction>.<GUI>(), where <APIfunction> is the name of the
API function and <GUI> is the name of the graphical toolkit
implemented. Here is the function that implements the same
dialog box for wxPython:

101
guiDlgMessage.wxPython <- function(message) {
if (!require(wxPython)) {
warning("Package 'wxPython' required. Please, (re)install
it!")
# Allow for using default dialog box by returning NULL
return(NULL)
}

# Use the wxPython version of this dialog box


res <- wxMessageBox(message = message, type = "okcancel")
return(invisible(res))
}

We have a dispatch mechanism that is very close to the S3 object


implementation, except that it does not need fake objects as first
argument of the API function. It is the content of a textual (GUI,
character) argument that is used instead. Are there better ways
solutions? Indeed, this simple mechanism is perfectly usable but there
are perhaps a few advantages to use S4 objects instead.

S4 objects and methods provide a strongly typed interface and


additional techniques to check that the various implementations match
the defined interface. This is a good point for an API that should provide
a sealed and well-defined interface!

Moreover, the tcltk or wxPython objects could become more that


just fake objects used for dispatch. They could contain some attributes
that are reused among dialog boxes, like fonts, colours or language (for
internationalization). These attributes can (and probably have to) be
defined differently for the various graphical toolkits. We will see in the
next paragraph that svDialogs’ “styles” provide a different solution to
this problem, and does not require such objects). Another problem that
can perhaps be solved this way, it is the modal behaviour of one dialog
box relative to another one. How to define a parent attribute in the API
function in a way that can be reused easily among the various toolkits,
since they define it differently?

Given these considerations, if someone wants to implement a few


functions of the svDialogs package using S4 objects, this would help to
decide which approach is the best one.

Using styles in the dialog boxes

“Styles”, together with the choice of the graphical toolkit, further


define the look & feel of the dialog boxes. I used to consider as a
superfluous luxury to have the opportunity to choose fonts or colours in
dialog boxes… until I had to present SciViews to almost blind people
that cannot read anything else than very large fonts with highly
contrasted colours. My default Helvetica point 10 appeared far too small
for them! Then, I realized that it is indeed a required feature for them.
So, styles are now part of my specifications for dialog boxes.

The current implementation of styles is hard coded in functions


guiSetStyle.XXX() where XXX is the graphical toolkit used. It is
necessary to implement such functions separately for each toolkit
because fonts or other graphical features are not defined the same way

102
in all toolkits (and possibly in all platforms). As an illustration of this
mechanism, I implement a guiSetStyle.tlctk() function, which
operates with Tcl/Tk dialog boxes, and defines four styles: “classic”,
“SciViews”, “Rcmdr” and “large”, as examples. Of course, new styles,
and/or customization of existing ones should be possible here. It is not
the case yet (I am still experimenting with styles, so, don’t ask too much
at once)! Here is an example (using guiDlgFunction(), a function that
automatically builds a dialog box to prompt for arguments of a function,
see further in this document):

> options(guiStyle = "classic")


> guiDlgFunction("ls")

Figure 10-4: an example Tcl/Tk dialog box, using the “classic” style.

The “classic” style is used by default. It is a usual presentation of


the dialog boxes, with default fonts like Helvetica/Helv/Arial, or
Courier.

The “Rcmdr” style is closer to R Commander dialog boxes: widgets


are more packed in the dialog box, colours are used to spot items like
green for the ‘OK’ button, red for ‘Cancel’, etc…

> options(guiStyle = "Rcmdr")


> guiDlgFunction("ls")

Figure 10-5: the same Tcl/Tk dialog box, using the “Rcmdr” style.

The “SciViews” style uses different fonts, namely Tahoma, Verdana


and Lucida Console. These fonts were designed to be more readable on
screen. They are installed by default on any relatively recent Windows
system (2000/XP) and they begin to appear on other platforms (for
instance, they exist in the latest Quantix Linux distribution). Widgets

103
look simpler also, with no 3D-borders but a little bit more space around
them than in the “Rcmdr” style… just a question of taste!

> options(guiStyle = "SciViews")


> guiDlgFunction("ls")

Figure 10-6: the same Tcl/Tk dialog box, using the “SciViews” style.

The “large” style is there to make dialog boxes more readable for
people with poor vision, or for on-screen presentations. It is basically a
“classic” style, but with enlarged fonts.

> options(guiStyle = "large")


> guiDlgFunction("ls")

Figure 10-7: the same Tcl/Tk dialog box, using the “large” style.

As you notice, styles define some aspects of the dialog boxes like
fonts, fonts colours, widgets borders or spacing, but not all aspects. It is
not their purpose to redefine the whole appearance of the dialog boxes.
Features like the appearance of the title bar, the background colour, the
colour of 3D-frames and borders, etc… are defined globally on the
system by the windows manager and it is thus unnecessary to duplicate
these global options in svDialogs styles.

104
Internationalization of the dialog boxes

I am still wondering if this is really required. Indeed, R is written


in English, (almost all) the documentation is in English too, … so, what’s
the use of a few words in a different language in dialog boxes? OK, a GUI
should be there to help beginners, and it should be useful to eliminate
the “language barrier” at this stage. But, if one customizes language of
the dialog boxes, one should logically do the same for the
documentation… and R documentation system is not currently designed
to be easily internationalized (there are a few translations of “an
introduction to R” available on CRAN, but not much more)!

Here is my first attempt for internationalization:

"l" <- function(string, lang = getOption("guiLang")) {


if (is.null(lang) || lang == "english") return(string)
# Does the string stand in the string table?
if (!exists(".guiLang.english", where = 1, mode = "character",
inherits = TRUE)) return(string)
english.table <- get(".guiLang.english", pos = 1,
mode = "character", inherits = TRUE)
pos <- match(string, english.table)
if (is.na(pos)) return(string) # Not found!
# Look if there is a .guiLang.<lang> variable of mode
'character'
var <- paste(".guiLang", lang, sep=".")
if (!exists(var, where = 1, mode = "character", inherits =
TRUE))
return(string)
foreign.table <- get(var, pos = 1, mode = "character",
inherits = TRUE)
if (length(foreign.table) != length(english.table)) {
return(string)
} else {
return(foreign.table[pos])
}
}

# A few string we may want to internationalize:


.guiLang.english <- c("OK", "Cancel", "Yes", "No", "Input")
.guiLang.french <- c("OK", "Annuler", "Oui", "Non", "Entrée")

l("Cancel")
[1] "Cancel"
options(guiLang = "french")
l("Cancel")
[1] "Annuler"

This solution is simple because one only has to embed strings that
must be internationalized in the dialog box inside l()! Of course, it is
not optimal: all string definitions in English and in the foreign language
are loaded in memory in the respective .guiLang.XXX character vectors.
One can imagine doing the same thing using text files in l(). However,
would it be fast enough? If a better solution is proposed, I would happily
integrate it in svDialogs. For the moment, there is no
internationalization support in the current version of the dialog boxes.

105
Specification of standard dialog boxes
In order to make this collection of dialog boxes really useful, they
must cover a large panel of common tasks. However, to make them easy
to implement with several graphical toolkits, they must remain as simple
as possible (to cover common features of the different graphical
toolkits). There is thus a trade-off between features, and potentials to
implement them with the various widgets and on the different platforms
where R can run. Here we deal with standard dialog boxes, a few dialog
boxes designed for a very specific use, like displaying a message, asking
for a file to open or save, etc… In svDialogs, we propose also standard
windows, a few, possibly non modal windows for tasks like visualization
or edition of data sets, and flexible dialog boxes that can contain an
arbitrary number of widgets, for general purposes. These standard
windows and flexible dialog boxes will be described in the two following
sections.

Current specification of these dialog boxes and windows is still


experimental. It may be subject to changes in the future. Specification of
each dialog box is done as follows:

3 A short description of the dialog box.

3 One or several example screenshots of the dialog box (but since the
graphical toolkits have their own look and feel, it is not necessary
to conform strictly to these pictures).

3 A prototype of the API function.

3 A description of its arguments.

3 What should this function return?

Please, note that in the current (temporary) implementation of


these dialog boxes, svDialogs styles are not implemented yet. These styles
are in test only with flexible dialog boxes.

The message box

This is probably the most basic item. It displays a message and a


series of buttons, and the feedback of the user is limited to a click on one
of these buttons.

Figure 10-8: A message box with an "ok" button and an "info" icon.

106
Figure 10-9: A message box with two buttons ("okcancel") and the
"question" icon.

Figure 10-10: A message box with two buttons ("yesno") and the "error"
icon.

Figure 10-11: A message box with three buttons ("yesnocancel") and the
"warning" icon. The second button is here the default one (default = 2
argument).

Prototype:

guiDlgMessage <- function(message, title = "Message", type =


c("ok",
"okcancel", "yesno", "yesnocancel"), default = 1, icon =
c("info",
"question", "error", "warning"), parent = 0,
GUI = getOption("guiWidgets"))

Arguments:

3 message is a string (or a vector of strings) that is displayed in the


dialog box,

3 title is the caption of the dialog box (if a character vector longer
than one is provided, only the first item is used),

3 type indicates which buttons to display in the dialog box. It can be


"ok", "okcancel", "yesno" or "yesnocancel". Its meaning is
obvious (see figures),

3 default is an integer indicating which button is the default one, if


several buttons are displayed (the one that is triggered if the user
hits {return}). With 1, the first button is active, with 2, the second
button is active, etc.

107
3 icon defines the icon to display in the dialog box. It can be "info",
"question", "error" or "warning". Suggested icons (standard ones
in the Windows platform) are depicted in the screenshots.

3 parent indicates modality of this dialog box (0 means system


modal, a positive value means modal to the window with this
handle, -1 means modeless). Modal windows must be dismissed
before other tasks can be achieved and they always appear on top
of their parent window. The message box is always modal (parent
= -1 is not allowed here).

3 GUI specifies which GUI widgets should be used to implement this


dialog box.

Return value:

A string containing the name of the clicked button: "ok", "cancel",


"yes" or "no", or NULL if the dialog box could not be displayed (for
instance, neither the specific package, nor the default one –tcltk– is
installed).

The input box

This is the elementary way to enter values for arguments. The


dialog box displays a message describing what the user should enter,
and a text box to enter the value. An "ok" button should be pressed to
accept the entry, a "cancel" button allows to dismiss the input (in this
case, the function returns character(0)).

It could be useful to add other attributes, like suggested, a list of


suggested values displayed in a drop down list, more, a more button (…)
that can be clicked to call another dialog box to build the value (for
instance, the formula dialog box to build a formula, see later in this
manual), or mask, a mask to constrain user input (a regular expression).
Currently, we keep only the most basic input box specification.

Figure 10-12: An input dialog box implemented in Tcl/Tk.

Figure 10-13: The same input box in wxPython. This is a default dialog box
defined in wxWidgets and it does not provide a ‘Cancel’ button, but the user can
click on the close button (‘X’) at the top right of the dialog box to get the same
result.

108
Prototype:

guiDlgInput <- function(message = "Enter a value", title =


"Input",
default = "", parent = 0, GUI = getOption("guiWidgets"))

Arguments:

3 message is a string (or a vector of strings) that is displayed in the


dialog box (note that the current implementation of this dialog box
in wxPython does not accept a vector of strings, or '\n' in the
string!),

3 title is the caption of the dialog box (if a character vector longer
than one is provided, only the first item is used),

3 default is a string with the default value to display in the text box
(if a character vector is provided, only the first item is used),

3 parent indicates modality of this dialog box (0 means system


modal, a positive value means modal to the window with this
handle, -1 means modeless). Modal windows must be dismissed
before other tasks can be achieved and they always appear on top
of their parent window. The message box is always modal (parent
= -1 is not allowed here).

3 GUI specifies which GUI widgets should be used to implement this


dialog box.

Return value:

A string containing the value entered by the user if he clicked "ok",


or character(0) if he clicked "cancel" or the closing button (X). It
returns NULL if the dialog box could not be displayed (for instance,
neither the specific package, nor the default one –tcltk– is installed).

The open file(s) dialog box

This is the classical “open file” dialog box defined on any system. It
should be able to open several files at once (argument multi = TRUE),
and to define filters for opening only files with a given extension (for
instance, only R script files ending with a ‘.R’ extension).

109
Figure 10-14: An example of an open file dialog box, as it appears in Windows
XP.

If the user enters a non-existing filename, the function should care


for warning him that its entry is wrong, and should allow to correct its
choice. The next figure is the kind of dialog box that can be displayed in
such a case (from tcltk):

Figure 10-15: The dialog box displayed when a non-existing file is provided by
the user in the open file dialog box. Then the open dialog box is displayed again
for correction of the file name.

Prototype:

guiDlgOpen <- function(title = "Select file", defaultFile = "",


defaultDir = "", multi = FALSE, filters = c("All files",
"*.*"), parent = 0, GUI = getOption("guiWidgets"))

Arguments:

3 title is the caption of the dialog box (if a character vector is


provided, only the first item is used),

3 defaultFile is a string with the default name of the file to open (if
a character vector is provided, only the first item is used),

3 defaultDir isa string with the default directory in which the dialog
box is opened (if a character vector is provided, only the first item
is used),

110
3 multi indicates if the user can open several files at once (multi =
TRUE), or not (multi = FALSE, by default). The wxPython version of
this dialog box does not support multi = TRUE yet.

3 filters specifies the filters for files (according to their extension).


It is either a vector of two character strings if only one filter is
provided (ex: c("R scripts", "*.*")), or a matrix of n*2 character
strings specifying several filters. In this case, the first one is used
by default.

3 parent indicates modality of this dialog box (0 means system


modal, a positive value means modal to the window with this
handle, -1 means modeless). Modal windows must be dismissed
before other tasks can be achieved and they always appear on top
of their parent window. The message box is always modal (parent
= -1 is not allowed here).

3 GUI specifies which GUI widgets should be used to implement this


dialog box.

Return value:

A string containing the path of the selected file, or a vector of


strings if several files where selected. These are valid files (it has to be
tested by the dialog box), but they are not necessarily readable or
executable (attributes of the file(s) are not checked). The string contains
nothing, that is, it returns character(0) if the user clicked "cancel" or
the closing button (X). It returns NULL if the dialog box could not be
displayed (for instance, neither the specific package, nor the default one
–tcltk– is installed).

The save file dialog box

This dialog box is similar to the open file(s) one, but its purpose is
different. It is intended to provide a name of a file where data should be
written. Arguments are also a little bit different.

111
Figure 10-16: An example of a save file dialog box, as it appears in Windows
XP.

If the user enters an existing filename, it should be prompted for


confirmation to overwrite this existing file. The next figure is the kind of
dialog box that can be displayed in such a case (from tcltk):

Figure 10-17: The dialog box displayed when an existing file name is provided
by the user in the save file dialog box. It prompts for confirmation to overwrite
this file. If the user clicks "no", then the save dialog box is displayed again for
correction of the file name.

Prototype:

guiDlgSave <- function(title = "Save As", defaultFile = "",


defaultDir = "", defaultExt = "", filters = c("All files",
"*.*"),
parent = 0, GUI = getOption("guiWidgets"))

Arguments:

3 title is the caption of the dialog box (if a character vector is


provided, only the first item is used),

3 defaultFile is a string with the default name of the file to save (if a
character vector is provided, only the first item is used),

3 defaultDir isa string with the default directory in which the dialog
box is opened (if a character vector is provided, only the first item
is used),

112
3 defaultExt is a string with the default extension of the file to save
(if a character vector is provided, only the first item is used). If the
user entered a name without extension, that extension is
automatically appended to the file name,

3 filters specifies the filters for files (according to their extension).


It is either a vector of two character strings if only one filter is
provided (ex: c("R scripts", "*.*")), or a matrix of n*2 character
strings specifying several filters. In this case, the first one is used
by default. The user is supposed to give a name with an extension
that matches the chosen filter.

3 parent indicates modality of this dialog box (0 means system


modal, a positive value means modal to the window with this
handle, -1 means modeless). Modal windows must be dismissed
before other tasks can be achieved and they always appear on top
of their parent window. The message box is always modal (parent
= -1 is not allowed here).

3 GUI specifies which GUI widgets should be used to implement this


dialog box.

Return value:

A string containing the path of the file. If this file exists, the
function already took care to ask confirmation for overwriting it (see
picture). It returns character(0) if the user clicked "cancel" or the
closing button (X). It returns NULL if the dialog box could not be
displayed (for instance, neither the specific package, nor the default one
–tcltk– is installed).

The choose directory dialog box

This dialog box is specific to select a directory. The following


picture is such a dialog box, as it appears under Windows XP.

Figure 10-18: An example of a choose directory dialog box, as it appears under


Windows XP.

113
If the user specifies a non-existing directory and the argument new
= FALSE, then the function should not accept its entry and should display
a dialog box like this (from tcltk):

Figure 10-19: The dialog box displayed when a non-existing directory name is
provided by the user and the argument new = FALSE. When the user clicks
"ok", it is returned to the choose directory dialog box to change its selection.

Prototype:

guiDlgDir <- function(title = "Select a directory", dir =


getwd(),
new = TRUE, parent = 0, GUI = getOption("guiWidgets"))

Arguments:

3 title is the caption of the dialog box (if a character vector is


provided, only the first item is used),

3 dir is a string with the default name of the directory (if a character
vector is provided, only the first item is used). By default, it is the
current working directory,

3 new determines if the user must select an existing directory (new =


FALSE), or if he can create a new one (new = TRUE, by default). If new
= FALSE, and the user attempts to create a new directory, the
function should warn him and should not accept its entry (see
picture),

3 parent indicates modality of this dialog box (0 means system


modal, a positive value means modal to the window with this
handle, -1 means modeless). Modal windows must be dismissed
before other tasks can be achieved and they always appear on top
of their parent window. The message box is always modal (parent
= -1 is not allowed here).

3 GUI specifies which GUI widgets should be used to implement this


dialog box.

Return value:

A string containing the path of the directory. It returns


character(0) if the user clicked "cancel" or the closing button (X). It
returns NULL if the dialog box could not be displayed (for instance,
neither the specific package, nor the default one –tcltk– is installed).

The list selection dialog box

This dialog box displays a list and allows selection (either simple,
or multiple) in it. It also offers "ok" and "cancel" buttons.

114
Prototype:

guiDlgList <- function(list, title = "Select one item",


default = "", multi = FALSE, new = FALSE, sort = TRUE, parent =
0,
GUI = getOption("guiWidgets"))

TO DO…

The variable selection dialog box

This is similar to the list, but it automatically constructs its content


according to variables of a given class or mode in a given environment. It
is most useful to provide the ‘x’ or ‘obj’ argument of many R functions.

Prototype:

guiDlgVarSel <- function(list, classes = NULL, title =


"Select a variable", default = "", all.names = FALSE,
multi = FALSE, new = FALSE, sort = TRUE,
parent = 0, GUI = getOption("guiWidgets"))

TO DO…

The variable/item selection dialog box

This is an extension of the variable selection box. It allows to select


a variable (in a first list, or drop-down list), and then, to select items in
this variable in a second list, like myvar$x, or myvar[ , c("x", "y",
"z")].

Prototype:

guiDlgItemSel <- function(list, classes = NULL, title =


"Select items", default = "", default.items = "",
all.names = FALSE, multi = FALSE, sort = TRUE,
sort.items = FALSE, subset = FALSE, save.restore = FALSE,
parent = 0, GUI = getOption("guiWidgets"))

TO DO…

The double list dialog box

This is similar to the variable/item selection box (thus displaying


two lists), but of a more general use. There are different modes:
independent lists, linked lists, and also select/deselect in right list from
left list if argument transfer = TRUE.

Prototype:

guiDlgDoubleList <- function(list1, list2, title = "Select",


default1 = "", default2 = "", multi = c(TRUE, TRUE),
new = c(FALSE, FALSE), sort = c(TRUE, TRUE), transfer = FALSE,

115
parent = 0, GUI = getOption("guiWidgets"))

TO DO…

The formula dialog box

A dialog box that eases writing of formulas in R.

Prototype:

guiDlgFormula <- function(....)

TO DO…

The colour selection dialog box

A dialog box to select colour(s).

Prototype:

guiDlgColor <- function(....)

TO DO…

The font selection dialog box

A dialog box to select a font and its formatting, as standard font


selection dialog on many platforms.

Prototype:

guiDlgFont <- function(....)

TO DO…

Specification of standard windows


Dialog boxes are almost exclusively modal windows. It means that
the user has to accept or cancel it before being allowed to further
interact with the rest of the application. Standard windows, on the
contrary, are designed to be usually non-modal (it is also possible to use
them as modal dialog boxes for specific purposes). They are displayed
side-by-side with the main window of the application and display
additional information (like the pager or the graph device), or allow
other kind of interaction (like script or data editors).

Specification of the API is presented the same way as in the


previous section.

116
The text window

This window displays or edits text from variables or files. In read-


only mode, it is just a pager. In edit mode, it is a very simple text editor.
In my opinion, there is no reason to design a specific pager window,
since a single argument, edit = TRUE/FALSE, easily switches this window
from a text editor to a pager.

Prototype:

guiWinText <- function(text, file = NULL, title =


deparse(substitute(text)), edit = TRUE, submit = TRUE,
parent = -1, GUI = getOption("guiWidgets"))

TO DO…

The grid window

As its name suggests, it is a grid presentation of 2D-matrices or


data frames. In read-only mode is displays the content of such a 2D-
matrix in a friendly and scrollable spreadsheet-like presentation. In
editable mode, it is just like the data editor of Rgui under Windows.

Prototype:

guiWinGrid" <- function(table, title =


deparse(substitute(table)),
edit = TRUE, edit.vars = TRUE, add.vars = TRUE, add.rows =
TRUE,
parent = -1, GUI = getOption("guiWidgets"))

TO DO…

The view window

This window is specifically designed to display ‘views’, a “new”


concept introduced with the SciViews package (see
http://www.sciviews.org/SciViews-R). A view is a HTML representation
of an R object, combining formatted text, tables and graphs. Appearance
of views can easily be changed thanks to CSS files (Cascaded Style
Sheets, but it is still necessary to check its support on all platforms!). Its
main purpose is to explore in a friendlier way the content of an R
variable or object. However, it serves also as an already formatted
building block for reports (use report = TRUE argument to enable a
button or menu entry for sending this view directly to a report, see how
SciViews R Console / SciViews R Report work together for a live
example).

117
Figure 10-20: an example of a view in SciViews-R. Here the summary of a
linear regression is presented in a nicer way than the usual presentation in the
R console. The R2HTML is used here to make most of the job. The CSS file used
is “R2HTML”, but it is possible to change the look of this view very easily using
other styles.

Prototype:

GuiWinView" <- function(file, CSSfile, title = "View",


report = TRUE, parent = -1, GUI = getOption("guiWidgets"))

TO DO…

The explorer window

An “explorer window” is designed to … “explore something”. In


SciViews-R, such windows are dockable to the left or to the right of the R
console for more convenience. They are thus called “dock”. Indeed,
explorers are HTML (or HTML-like) pages that present menus, galleries
(like graphs galleries), electronic reference cards, etc… At this stage, the
best way to get an idea of what an explorer window looks like is to install
(http://www.sciviews.org/SciViews-R) and to play with SciViews-R and
its dock windows.

118
Figure 10-21: an example of an explorer window. Here, it is a version of the R
Commander menu displayed in a dock window of SciViews-R. All items of a
related topic are collected together in tabs. Here the ‘Statistics’ tab is opened,
and a part of its content is shown. Moving the mouse on top of an item displays
a tooltip with further information about it. Clicking on it opens the
corresponding dialog box, just like the corresponding menu item of R
Commander does. Using this explorer appears to be faster in practice, because
items are more easily accessible than when they are embedded is several levels
of submenus… However, choice between a classical menus or this explorer is
more a matter of taste, and should be left to the end user! This window is
implemented in HTML and javascript only.

Figure 10-22: another explorer window written in pure HTML/javascript: an


embryo of a graph gallery. The presentation is very similar to the R commander
menu, but items are replaced here by small vignettes suggesting the kind of
graph one would obtain by clicking on them.

119
Figure 10-23: a third example of an explorer window in SciViews-R. This is
the electronic version of Jonathan Baron’s R reference card available on CRAN.
The presentation is similar than the R commander menu, but the idea is
different. Here we collect together items that show to the occasional user, or to
the beginner, how to do usual tasks in R (when you click on an item, the
corresponding syntax is pasted to the console, or to your script).

Prototype:

guiWinExplore <- function(...)

TO DO…

The object explorer window

A list or tree displaying content of the environment, allowing


further interaction with these objects by means of contextual menus.
This dialog box must be implemented using API functions for the object
browser that are/will be defined elsewhere in the SciViews GUI API.
There is already a working version of such an object explorer in the
current version of SciViews-R (see http://www.sciviews.org/SciViews-
R). However, this implementation only works on Windows. It is our
intention to make it available everywhere, thanks to this object explorer
window.

120
Figure 10-24: the object explorer in SciViews-R. It is a (possibly simplified)
version of this object explorer that we want to implement here.

Prototype:

guiWinObjExp <- function(...)

TO DO…

The progression window

This is a (usually) non-modal window that displays the progression


of a long-running task.

Prototype:

guiWinProgress <- function(value, range = c(0, 100),


message = "Please wait...", title = "Progression", percent =
TRUE,
cancel = TRUE, icon = "none", parent = -1,
GUI = getOption("guiWidgets"))

TO DO…

Specification of flexible dialog boxes


Flexible dialog boxes are proposed to extend the potentials of
svDialogs in building rapidly graphical items independently from a given
graphical toolkit and without relying to the construction of dialog boxes
at level 2 or 3 (see our classification in the first section, “Building dialog
boxes”). The principle is to match automatically the various widgets
presented in that dialog box with the prototype of an R function that is
called when the user clicks ‘ok’. So, a programmer writes an R function…
and he gets instantly a dialog box to parameterize its arguments!

The second idea behind flexible dialog boxes, is to remain as close


as possible to the R language. The dialog box should explicitly suggest
the construction of R code, instead of hiding it in a GUI. What is the
most often used instruction in R? Being a functional language, it is
certainly something like: [myvar <-] myfun([arg1], [arg2], […]),

121
where everything inside square brackets is optional. Basically, one call a
function myfun(), possibly giving values for one or more of its arguments
[arg1], [arg2], … either in the form argvalue, or in the form myarg =
argvalue. Finally, the result of the function can possibly be assigned to a
variable (myvar <- ). Thus, the dialog box should reflect, and suggest
such a construction to be a didactic tool that teaches the user how to
program in R!

This is probably easier to understand with an actual example. Let’s


consider the t-test. In R, the function t.test() does the job. The
example for this function in the R documentation treats the data set
sleep:

> data(sleep)
> t.test(extra ~ group, data = sleep)

Welch Two Sample t-test

data: extra by group


t = -1.8608, df = 17.776, p-value = 0.0794
alternative hypothesis: true difference in means is not equal to
0
95 percent confidence interval:
-3.3654832 0.2054832
sample estimates:
mean in group 1 mean in group 2
0.75 2.33

Now, we want to build a GUI on top of this function. This is done


in R Commander. The corresponding dialog box is shown in the
following figure:

Figure 10-25: the t-test dialog box for independent samples in R Commander.

TO DO: use prop.test() instead as an example! There is nothing


wrong with this dialog box. It does the job because it asks for required
arguments and then it constructs the corresponding code. In R
Commander, this code is echoed in the console and/or in a script
window:

> t.test(extra~group, alternative='two.sided', conf.level=.95,


var.equal=FALSE, data=sleep)

This way, the user sees it and can learn how to write code for a t-test by
the example. This is, unfortunately, not the case with all GUIs. Some try
to hide completely “this horrible code that we don’t want to see

122
anymore”. But then, how will the beginner learn the R language if he
only uses dialog boxes and never sees a single line of R code?

Now, is it possible to write a dialog box for the t-test that will learn
even better how to write an instruction in the language than the one
provided by R Commander? May be… look at the next one.

Figure 10-26: the default flexible dialog box automatically built for the
chisq-test function.

This dialog box represents more closely the structure of the


language, that is, a call of a function and a list of arguments.
Correspondence between selections made by the user in the dialog box,
and R code is more obvious,… and thus more didactic! However, this
dialog box is less explicit. So, we add options to include explanation (a
label explains the meaning of each argument), and to replace the default
text boxes for entries with other widgets, like lists, option or radio boxes,
sliders, etc…

The function assistant dialog box

It is a versatile dialog box that can display several “areas” (textbox,


list, check or option boxes, slider, …). Each area corresponds to one
argument in a function. Given an R function, the algorithm parses it,
and a label plus a textbox with the default value of the argument is
added in each area (by default). Once issued, the syntax of the function
call is constructed from the various entries in the respective text boxes.
Providing a template (the most flexible way to do that would be to accept
either an attribute "template" of the function, or a description in an
external file), the dialog box could be further customized. For instance, it
should be possible to specify:

ƒ Which argument should have an area in the dialog box, and which
one should not,

ƒ The appearance of each area: textbox (default), list, checkbox,


option boxes, slider,

ƒ The various possibilities for some arguments (those displayed as


option boxes or lists).

123
The idea of this dialog box is to have a (semi)-automatic
construction of an appropriate dialog box to prompt for function
arguments. This can be used to build buttons or menu entries by drag
and drop from the object explorer to a toolbar, or to a menu (see
http://www.sciviews.org/SciViews-R). There is nothing new here, since
S-PLUS does this since a long time… but it is a nice feature I would like
to get in R too! Obviously, this is a piece of work, anyway…

Prototype:

guiDlgFunction <- function(fct, ....)

TO DO…

The options dialog box

A dialog box with a list or tree at left, and a textbox, list, checkbox
or option boxes at right. It allows changing various options from within
the same dialog box. Options should be specified in a list (like
options()). A second list indicates the appearance and various choices
for each particular option.

Prototype:

guiDlgOptions <- function(....)

TO DO…

The graph options dialog box

It is the same of the options dialog box, but already tailored to


change graph parameters (see ?par).

Prototype:

guiDlgGraphOptions <- function(....)

TO DO…

The assistant dialog box

It is quite similar to the function assistant dialog box, except that it


decomposes the process of filling arguments to the function in several
steps. It should be useful for functions that require lots of arguments, or
for complex tasks that should be preferably split into several simpler
ones.

Prototype:

guiDlgAssistant <- function(....)

TO DO…

124
11. SVIDE AND SVSOCKET: COMMUNICATION BETWEEN SCRIPT
EDITORS/IDE AND R

R is best managed using scripts. Eventually, you can refine your


favourite scripts to make custom R packages containing your own R
functions. A good code editor, like Tinn-R, or even a whole IDE
(Integrated Development Environment), like Eclipse could be use for
editing your R code. svIDE and svSocket provide various functions
allowing to connect such external editors to R. Hence, you can run R
code directly from your code editor and get feedback like call tip (a
tooltip displaying the syntax of R functions), or completions lists right in
it. Tinn-R is using svIDE, for instance, to get contextual call tips.

[The rest of this section still needs to be written… sorry!]

125
12. TCLTK2: ADDITIONAL TCL/TK FEATURES FOR R

The tcltk2 packages provides additional Tcl/Tk features to R that


enhance usability of the base tcltk package provided with R. It provides
tile, a themable version of basic widgets for Tcl/Tk, and some advanced
widgets like tkTable, a combobox, a tree widget, ballons (tooltips), etc…
It also wraps various Tcl features specific to Windows, like DDE
exchange, access to the registry, or management of Windows icons into
easy to use R functions.

[The rest of this section still needs to be written… sorry!]

126
REFERENCES

Dallot, S. & M. Etienne, 1990. Une méthode non paramétrique d’analyse


des series en océanographie biologique: les tournogrammes.
Biométrie et Océanographie – Société de Biométrie, 6, Lille, 26-28
mai 1986. IFREMER, Actes de colloques, 10 :13-31.

Fox, J., 2003. R Commander [online:


http://socserv.socsci.mcmaster.ca/jfox/Misc/Rcmdr/]

Grosjean, Ph., 2003. SciViews: an object-oriented abstraction layer to


design GUIs on top of various calculation kernels
[online: http://www.ci.tuwien.ac.at/Conferences/DSC-2003]

Grosjean, Ph. & F. Ibanez, 2004. PASTECS: a package for analysis of space-
time ecological series. [online: http://www.sciviews.org/pastecs]

Ihaka R. & R. Gentleman, 1996. R : a language for data analysis and


graphics. J. Comput. Graphic. Stat., 5:299-314.

R Development Core Team, 2004. R: A language and environment for


statistical computing. [online: http://www.R-project.org].

127

Vous aimerez peut-être aussi