Transcription of An introduction to R
1 An introduction to RLonghow LamUnder Construction Feb-2010 some sections are unfinished!longhowlam at gmail dot comContents1 What is R? .. The R environment .. Obtaining and installing R .. Your first R session .. The available help .. on line help .. R mailing lists and the R Journal .. The R workspace, managing objects .. R Packages .. Conflicting objects .. Editors for R scripts .. editor in RGui .. editors ..162 data data types .. and Times .. data and Infinite values .. data structures .. frames .. objects ..413 Importing Text files .. Excel files .. Databases .. The Foreign package ..464 data Vector subscripts .. Matrix subscripts .. Manipulating data frames .. data from data frames .. columns to a data frame .. data frames .. data frames .. data frames .. columns of data frames .. data .. Attributes .. Character manipulation.
2 Functionsnchar,substringandpaste.. patterns in character objects .. characters .. characters .. Creating factors from continuous data ..685 Writing introduction .. Arguments and variables .. and optional arguments .. argument .. variables .. an object .. Scoping rules .. evaluation .. Control flow .. withifandswitch.. withfor,whileandrepeat.. Debugging your R functions .. through a function ..836 Efficient Vectorized computations .. The apply and outer functions .. Using Compiled code .. Some Compiled Code examples .. arsim example .. #include < >.. R expressions in C ..987 introduction .. More plot functions .. plots .. or more variables .. Devices .. Modifying a graph .. parameters .. handy low-level functions .. the axes .. Trellis Graphics .. panel graphs .. panel functions .. plots .. The ggplot2 package.
3 With several layers .. 1348 Basic statistical functions .. summaries and tests .. distributions and random numbers .. Regression models .. objects .. Linear regression models .. objects .. functions .. (categorical) variables as regression variables .. Logistic regression .. modeling functionglm.. measures .. ability of a logistic regression .. Tree models .. example of a tree model .. classification and binning .. Survival analysis .. Cox proportional hazards model .. models for survival analysis .. Non linear regression .. models .. value decomposition .. 1779 Miscellaneous Object Oriented Programming .. style classes .. Style classes .. R Language objects .. and Expressions .. as Lists .. as lists .. Calling R from SAS .. systemandXfunctions .. SAS data sets and SAS ODS .. Defaults and preferences in R, Starting R.
4 And preferences .. R .. Creating an R package .. private package .. real R package .. Calling R from Java .. Creating fancy output and reports .. simple LATEX-table .. simple HTML report .. 206 Bibliography207 Index2084 List of The R system on Windows .. R integrated in the Eclipse development environment .. The Tinn-R and an the R Console environment .. A surface plot created with the functionpersp.. Calculation times ofarsimR(solid line) andarsimC(dashed line) forincreasing vectors .. A scatterplot with a title .. Line plot with title, can be created withtype="l"or thecurvefunction. Different uses of the functionplot.. Example distribution plot in R .. Example barplot where the first argument is a matrix .. Example graphs of multi dimensional data sets .. The different regions of a plot .. The plotting area of this graph is divided with thelayoutfunction.
5 Examples of different symbols and colors in plots .. The graph that results from the previous low-level plot functions.. Graphs resulting from previous code examples of customizing axes.. Trellis plot Price versus Weight for different types .. A trellis plot with two conditioning variables .. Histogram of mileage for different weight classes .. Trellis plot with modified panel function .. Trellis plot adding a least squares line in each panel .. A coplot with two conditioning variables .. A coplot with a smoothing line .. A histogram and a qq-plot of the model residuals to check normality ofthe residuals.. Diagnostic plots to check for linearity and for outliers.. Explorative plots giving a first impression of the relation between thebinaryyvariable andxvariables.. The ROC curve to assess the quality of a logistic regression model .. Plot of the tree: Type is predicted based on Mileage and Price.
6 Binning the age variable, two intervals in this case .. Survival curve: 10% will develop AIDS before 45 months and 20% before76 months.. Scatter plot of the martingale residuals .. Three subjects with age 10, 30 and 60 .. Scatter plot of our simulated data fornls.. Simulated data andnlspredictions .. Hill curves for two sets of parameters .. Result of the specific plot method for class bigMatrix.. Some Lissajous plots .. A small java gui that can call R functions.. 20461 What is R?While the commercial implementation of S, S-PLUS, is struggling to keep its existingusers, the open source version of S, R, has received a lot of attention in the last fiveyears. Not only because the R system is a free tool, the system has proven to be avery effective tool in data manipulation, data analysis , graphing and developing newfunctionality. The user community has grown enormously the last years, and it is anactive user community writing new R packages that are made available to you have any questions or comments on this document please do not hesitate to best explanation of R is given on the R web site Theremainder of this section and the following section are taken from the R web is a language and environment for statistical computing and graphics.
7 It is a GNUproject which is similar to the S language and environment which was developed atBell Laboratories (formerly AT&T, now Lucent Technologies) by John Chambers andcolleagues. R can be considered as a different implementation of S. There are someimportant differences, but much code written for S runs unaltered under provides a wide variety of statistical (linear and non linear modeling, classical statis-tical tests, time-series analysis , classification, clustering, ..) and graphical techniques,and is highly extensible. The S language is often the vehicle of choice for research instatistical methodology, and R provides an Open Source route to participation in of R s strengths is the ease with which well-designed publication-quality plots canbe produced, including mathematical symbols and formulae where needed. Great carehas been taken over the defaults for the minor design choices in graphics, but the userretains full is available as Free Software under the terms of the Free Software Foundation s GNUG eneral Public License in source code form.
8 It compiles and runs on a wide varietyof UNIX platforms and similar systems (including FreeBSD and Linux), Windows 1. THE R The R environmentR is an integrated suite of software facilities for data manipulation, calculation andgraphical display. It includes an effective data handling and storage facility, a suite of operators for calculations on arrays, in particular matrices, a large, coherent, integrated collection of intermediate tools for data analysis , graphical facilities for data analysis and display either on-screen or on hardcopy,and a well-developed, simple and effective programming language which includes con-ditionals, loops, user-defined recursive functions and input and output term environment is intended to characterize it as a fully planned and coherentsystem, rather than an incremental accretion of very specific and inflexible tools, as isfrequently the case with other data analysis , like S, is designed around a true computer language, and it allows users to addadditional functionality by defining new functions.
9 Much of the system is itself writtenin the R dialect of S, which makes it easy for users to follow the algorithmic choices computationally-intensive tasks, C, C++ and Fortran code can be linked and calledat run time. Advanced users can write C code to manipulate R objects users think of R as a statistics system. We prefer to think of it of an environmentwithin which statistical techniques are implemented. R can be extended (easily) viapackages. There are about eight packages supplied with the R distribution and manymore are available through the CRAN family of Internet sites covering a very wide rangeof modern has its own LaTeX-like documentation format, which is used to supply comprehensivedocumentation, both on-line in a number of formats and in Obtaining and installing RR can be downloaded from the Comprehensive R Archive Network (CRAN). You candownload the complete source code of R, but more likely as a beginning R user youwant to download the precompiled binary distribution of R.
10 Go to the R web and select a CRAN mirror site and download the base dis-tribution file, under At the time of writing the latestversion is We will mention user contributed packages in the next base file has a size of around 29MB, which you can execute to install R. Theinstallation wizard will guide you through the installation process. It may be useful to8 CHAPTER 1. YOUR FIRST R SESSION install the R reference manual as well, by default it is not installed. You can select it inthe installation Your first R sessionStart the R system, the main window (RGui) with a sub window (R Console) will appearas in figure : The R system on WindowsIn the Console window the cursor is waiting for you to type in some R commands. Forexample, use R as a simple calculator:> print("Hello world!")[1] "Hello world!"> 1 + sin(9)[1] > 234/87754[1] 1. YOUR FIRST R SESSION> (1 + )^8[1] > *log(8)/(23 + atan(9))[1] of calculations can be stored in objects using the assignment operators: An arrow (<-) formed by a smaller than character and a hyphen without a space!