Skip to content
Snippets Groups Projects
FAQ 116 KiB
Newer Older
1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000
     search path.  Finally, function '.First.sys' in the *base* package
     is run.  When terminating an R session, by default a function
     '.Last' is run if found on the search path, followed by
     '.Last.sys'.  If needed, the functions '.First()' and '.Last()'
     should be defined in the appropriate startup profiles.  See the
     help pages for '.First' and '.Last' for more details.

   * In R, 'T' and 'F' are just variables being set to 'TRUE' and
     'FALSE', respectively, but are not reserved words as in S and hence
     can be overwritten by the user.  (This helps e.g. when you have
     factors with levels '"T"' or '"F"'.)  Hence, when writing code you
     should always use 'TRUE' and 'FALSE'.

   * In R, 'dyn.load()' can only load _shared objects_, as created for
     example by 'R CMD SHLIB'.

   * In R, 'attach()' currently only works for lists and data frames,
     but not for directories.  (In fact, 'attach()' also works for R
     data files created with 'save()', which is analogous to attaching
     directories in S.) Also, you cannot attach at position 1.

   * Categories do not exist in R, and never will as they are deprecated
     now in S. Use factors instead.

   * In R, 'For()' loops are not necessary and hence not supported.

   * In R, 'assign()' uses the argument 'envir=' rather than 'where=' as
     in S.

   * The random number generators are different, and the seeds have
     different length.

   * R passes integer objects to C as 'int *' rather than 'long *' as in
     S.

   * R has no single precision storage mode.  However, as of version
     0.65.1, there is a single precision interface to C/FORTRAN
     subroutines.

   * By default, 'ls()' returns the names of the objects in the current
     (under R) and global (under S) environment, respectively.  For
     example, given

          x <- 1; fun <- function() {y <- 1; ls()}

     then 'fun()' returns '"y"' in R and '"x"' (together with the rest
     of the global environment) in S.

   * R allows for zero-extent matrices (and arrays, i.e., some elements
     of the 'dim' attribute vector can be 0).  This has been determined
     a useful feature as it helps reducing the need for special-case
     tests for empty subsets.  For example, if 'x' is a matrix, 'x[,
     FALSE]' is not 'NULL' but a "matrix" with 0 columns.  Hence, such
     objects need to be tested for by checking whether their 'length()'
     is zero (which works in both R and S), and not using 'is.null()'.

   * Named vectors are considered vectors in R but not in S (e.g.,
     'is.vector(c(a = 1:3))' returns 'FALSE' in S and 'TRUE' in R).

   * Data frames are not considered as matrices in R (i.e., if 'DF' is a
     data frame, then 'is.matrix(DF)' returns 'FALSE' in R and 'TRUE' in
     S).

   * R by default uses treatment contrasts in the unordered case,
     whereas S uses the Helmert ones.  This is a deliberate difference
     reflecting the opinion that treatment contrasts are more natural.

   * In R, the argument of a replacement function which corresponds to
     the right hand side must be named 'value'.  E.g., 'f(a) <- b' is
     evaluated as 'a <- "f<-"(a, value = b)'.  S always takes the last
     argument, irrespective of its name.

   * In S, 'substitute()' searches for names for substitution in the
     given expression in three places: the actual and the default
     arguments of the matching call, and the local frame (in that
     order).  R looks in the local frame only, with the special rule to
     use a "promise" if a variable is not evaluated.  Since the local
     frame is initialized with the actual arguments or the default
     expressions, this is usually equivalent to S, until assignment
     takes place.

   * In S, the index variable in a 'for()' loop is local to the inside
     of the loop.  In R it is local to the environment where the 'for()'
     statement is executed.

   * In S, 'tapply(simplify=TRUE)' returns a vector where R returns a
     one-dimensional array (which can have named dimnames).

   * In S(-PLUS) the C locale is used, whereas in R the current
     operating system locale is used for determining which characters
     are alphanumeric and how they are sorted.  This affects the set of
     valid names for R objects (for example accented chars may be
     allowed in R) and ordering in sorts and comparisons (such as
     whether '"aA" < "Bb"' is true or false).  From version 1.2.0 the
     locale can be (re-)set in R by the 'Sys.setlocale()' function.

   * In S, 'missing(ARG)' remains 'TRUE' if ARG is subsequently
     modified; in R it doesn't.

   * From R version 1.3.0, 'data.frame' strips 'I()' when creating
     (column) names.

   * In R, the string '"NA"' is not treated as a missing value in a
     character variable.  Use 'as.character(NA)' to create a missing
     character value.

   * R disallows repeated formal arguments in function calls.

   * In S, 'dump()', 'dput()' and 'deparse()' are essentially different
     interfaces to the same code.  In R from version 2.0.0, this is only
     true if the same 'control' argument is used, but by default it is
     not.  By default 'dump()' tries to write code that will evaluate to
     reproduce the object, whereas 'dput()' and 'deparse()' default to
     options for producing deparsed code that is readable.

   * In R, indexing a vector, matrix, array or data frame with '[' using
     a character vector index looks only for exact matches (whereas '[['
     and '$' allow partial matches).  In S, '[' allows partial matches.

   * S has a two-argument version of 'atan' and no 'atan2'.  A call in S
     such as 'atan(x1, x2)' is equivalent to R's 'atan2(x1, x2)'.
     However, beware of named arguments since S's 'atan(x = a, y = b)'
     is equivalent to R's 'atan2(y = a, x = b)' with the meanings of 'x'
     and 'y' interchanged.  (R used to have undocumented support for a
     two-argument 'atan' with positional arguments, but this has been
     withdrawn to avoid further confusion.)

   * Numeric constants with no fractional and exponent (i.e., only
     integer) part are taken as integer in S-PLUS 6.x or later, but as
     double in R.

   There are also differences which are not intentional, and result from
missing or incorrect code in R. The developers would appreciate hearing
about any deficiencies you may find (in a written report fully
documenting the difference as you see it).  Of course, it would be
useful if you were to implement the change yourself and make sure it
works.

3.4 Is there anything R can do that S-PLUS cannot?
==================================================

Since almost anything you can do in R has source code that you could
port to S-PLUS with little effort there will never be much you can do in
R that you couldn't do in S-PLUS if you wanted to.  (Note that using
lexical scoping may simplify matters considerably, though.)

   R offers several graphics features that S-PLUS does not, such as
finer handling of line types, more convenient color handling (via
palettes), gamma correction for color, and, most importantly,
mathematical annotation in plot texts, via input expressions reminiscent
of TeX constructs.  See the help page for 'plotmath', which features an
impressive on-line example.  More details can be found in Paul Murrell
and Ross Ihaka (2000), "An Approach to Providing Mathematical Annotation
in Plots", _Journal of Computational and Graphical Statistics_, *9*,
582-599 (doi: 10.1080/10618600.2000.10474900
(https://doi.org/10.1080/10618600.2000.10474900)).

3.5 What is R-plus?
===================

For a very long time, there was no such thing.

   Revolution Analytics has released REvolution R, now available as
Microsoft R (see
<https://blog.revolutionanalytics.com/2016/01/microsoft-r-open.html> for
more information).

   See also
<https://en.wikipedia.org/wiki/R_programming_language#Commercialized_versions_of_R>
for pointers to commercialized versions of R.

4 R Web Interfaces
******************

Please refer to the CRAN task view on "Web Technologies and Services"
(<https://CRAN.R-project.org/view=WebTechnologies>), specifically
section "Web and Server Frameworks", for up-to-date information on R web
interface packages.

   Early references on R web interfaces include Jeff Banfield (1999),
"Rweb: Web-based Statistical Analysis" (doi: 10.18637/jss.v004.i01
(https://doi.org/10.18637/jss.v004.i01)), David Firth (2003), "CGIwithR:
Facilities for processing web forms using R" (doi: 10.18637/jss.v008.i10
(https://doi.org/10.18637/jss.v008.i10)), and Angelo Mineo and Alfredo
Pontillo (2006), "Using R via PHP for Teaching Purposes: R-php"
(doi: 10.18637/jss.v017.i04 (https://doi.org/10.18637/jss.v017.i04)).

5 R Add-On Packages
*******************

5.1 Which add-on packages exist for R?
======================================

5.1.1 Add-on packages in R
--------------------------

The R distribution comes with the following packages:

*base*
     Base R functions (and datasets before R 2.0.0).
*compiler*
     R byte code compiler (added in R 2.13.0).
*datasets*
     Base R datasets (added in R 2.0.0).
*grDevices*
     Graphics devices for base and grid graphics (added in R 2.0.0).
*graphics*
     R functions for base graphics.
*grid*
     A rewrite of the graphics layout capabilities, plus some support
     for interaction.
*methods*
     Formally defined methods and classes for R objects, plus other
     programming tools, as described in the Green Book.
*parallel*
     Support for parallel computation, including by forking and by
     sockets, and random-number generation (added in R 2.14.0).
*splines*
     Regression spline functions and classes.
*stats*
     R statistical functions.
*stats4*
     Statistical functions using S4 classes.
*tcltk*
     Interface and language bindings to Tcl/Tk GUI elements.
*tools*
     Tools for package development and administration.
*utils*
     R utility functions.
   These "base packages" were substantially reorganized in R 1.9.0.  The
former *base* was split into the four packages *base*, *graphics*,
*stats*, and *utils*.  Packages *ctest*, *eda*, *modreg*, *mva*, *nls*,
*stepfun* and *ts* were merged into *stats*, package *lqs* returned to
the recommended package *MASS*
(https://CRAN.R-project.org/package=MASS), and package *mle* moved to
*stats4*.

5.1.2 Add-on packages from CRAN
-------------------------------

The CRAN 'src/contrib' area contains a wealth of add-on packages,
including the following _recommended_ packages which are to be included
in all binary distributions of R.

*KernSmooth*
     Functions for kernel smoothing (and density estimation)
     corresponding to the book "Kernel Smoothing" by M. P. Wand and M.
     C. Jones, 1995.
*MASS*
     Functions and datasets from the main package of Venables and
     Ripley, "Modern Applied Statistics with S". (Contained in the 'VR'
     bundle for R versions prior to 2.10.0.)
*Matrix*
     A Matrix package.  (Recommended for R 2.9.0 or later.)
*boot*
     Functions and datasets for bootstrapping from the book "Bootstrap
     Methods and Their Applications" by A. C. Davison and D. V. Hinkley,
     1997, Cambridge University Press.
*class*
     Functions for classification (k-nearest neighbor and LVQ).
     (Contained in the 'VR' bundle for R versions prior to 2.10.0.)
*cluster*
     Functions for cluster analysis.
*codetools*
     Code analysis tools.  (Recommended for R 2.5.0 or later.)
*foreign*
     Functions for reading and writing data stored by statistical
     software like Minitab, S, SAS, SPSS, Stata, Systat, etc.
*lattice*
     Lattice graphics, an implementation of Trellis Graphics functions.
*mgcv*
     Routines for GAMs and other generalized ridge regression problems
     with multiple smoothing parameter selection by GCV or UBRE.
*nlme*
     Fit and compare Gaussian linear and nonlinear mixed-effects models.
*nnet*
     Software for single hidden layer perceptrons ("feed-forward neural
     networks"), and for multinomial log-linear models.  (Contained in
     the 'VR' bundle for R versions prior to 2.10.0.)
*rpart*
     Recursive PARTitioning and regression trees.
*spatial*
     Functions for kriging and point pattern analysis from "Modern
     Applied Statistics with S" by W. Venables and B. Ripley.
     (Contained in the 'VR' bundle for R versions prior to 2.10.0.)
*survival*
     Functions for survival analysis, including penalized likelihood.
   See the CRAN contributed packages page for more information.

   Many of these packages are categorized into CRAN Task Views
(https://CRAN.R-project.org/web/views/), allowing to browse packages by
topic and providing tools to automatically install all packages for
special areas of interest.

5.1.3 Add-on packages from Bioconductor
---------------------------------------

Bioconductor (https://www.bioconductor.org/) is an open source and open
development software project for the analysis and comprehension of
genomic data.  Most Bioconductor components are distributed as R add-on
packages.  Initially most of the Bioconductor software packages
(https://bioconductor.org/packages/release/BiocViews.html#___Software)
focused primarily on DNA microarray data analysis.  As the project has
matured, the functional scope of the software packages broadened to
include the analysis of all types of genomic data, such as SAGE,
sequence, or SNP data.  In addition, there are metadata (annotation, CDF
and probe) and experiment data packages.  See
<https://master.bioconductor.org/install/> for available packages and a
complete taxonomy via BioC Views.

5.1.4 Other add-on packages
---------------------------

Many more packages are available from places other than the three
default repositories discussed above (CRAN, Bioconductor and Omegahat).
In particular, R-Forge provides a CRAN style repository at
<https://R-Forge.R-project.org/>.

   More code has been posted to the R-help mailing list, and can be
obtained from the mailing list archive.

5.2 How can add-on packages be installed?
=========================================

(Unix-like only.)  The add-on packages on CRAN come as gzipped tar files
named 'PKG_VERSION.tar.gz', which may in fact be "bundles" containing
more than one package.  Let PATH be the path to such a package file.
Provided that 'tar' and 'gzip' are available on your system, type

     $ R CMD INSTALL PATH/PKG_VERSION.tar.gz

at the shell prompt to install to the library tree rooted at the first
directory in your library search path (see the help page for
'.libPaths()' for details on how the search path is determined).

   To install to another tree (e.g., your private one), use

     $ R CMD INSTALL -l LIB PATH/PKG_VERSION.tar.gz

where LIB gives the path to the library tree to install to.

   Even more conveniently, you can install and automatically update
packages from within R if you have access to repositories such as CRAN.
See the help page for 'available.packages()' for more information.

5.3 How can add-on packages be used?
====================================

To find out which additional packages are available on your system, type

     library()

at the R prompt.

   This produces something like

          Packages in `/home/me/lib/R':

          mystuff       My own R functions, nicely packaged but not documented

          Packages in `/usr/local/lib/R/library':

          KernSmooth    Functions for kernel smoothing for Wand & Jones (1995)
          MASS          Main Package of Venables and Ripley's MASS
          Matrix        Sparse and Dense Matrix Classes and Methods
          base          The R Base package
          boot          Bootstrap R (S-Plus) Functions (Canty)
          class         Functions for Classification
          cluster       Functions for clustering (by Rousseeuw et al.)
          codetools     Code Analysis Tools for R
          datasets      The R Datasets Package
          foreign       Read Data Stored by Minitab, S, SAS, SPSS, Stata, Systat,
                        dBase, ...
          grDevices     The R Graphics Devices and Support for Colours and Fonts
          graphics      The R Graphics Package
          grid          The Grid Graphics Package
          lattice       Lattice Graphics
          methods       Formal Methods and Classes
          mgcv          GAMs with GCV/AIC/REML smoothness estimation and GAMMs
                        by PQL
          nlme          Linear and Nonlinear Mixed Effects Models
          nnet          Feed-forward Neural Networks and Multinomial Log-Linear
                        Models
          rpart         Recursive Partitioning
          spatial       Functions for Kriging and Point Pattern Analysis
          splines       Regression Spline Functions and Classes
          stats         The R Stats Package
          stats4        Statistical functions using S4 Classes
          survival      Survival analysis, including penalised likelihood
          tcltk         Tcl/Tk Interface
          tools         Tools for Package Development
          utils         The R Utils Package

   You can "load" the installed package PKG by

     library(PKG)

   You can then find out which functions it provides by typing one of

     library(help = PKG)
     help(package = PKG)

   You can unload the loaded package PKG by

     detach("package:PKG", unload = TRUE)

(where 'unload = TRUE' is needed only for packages with a namespace, see
'?unload').

5.4 How can add-on packages be removed?
=======================================

Use

     $ R CMD REMOVE PKG_1 ... PKG_N

to remove the packages PKG_1, ..., PKG_N from the library tree rooted at
the first directory given in 'R_LIBS' if this is set and non-null, and
from the default library otherwise.  (Versions of R prior to 1.3.0
removed from the default library by default.)

   To remove from library LIB, do

     $ R CMD REMOVE -l LIB PKG_1 ... PKG_N

5.5 How can I create an R package?
==================================

A package consists of a subdirectory containing a file 'DESCRIPTION' and
the subdirectories 'R', 'data', 'demo', 'exec', 'inst', 'man', 'po',
'src', and 'tests' (some of which can be missing).  The package
subdirectory may also contain files 'INDEX', 'NAMESPACE', 'configure',
'cleanup', 'LICENSE', 'LICENCE', 'COPYING' and 'NEWS'.

   See section "Creating R packages" in 'Writing R Extensions', for
details.  This manual is included in the R distribution, *note What
documentation exists for R?::, and gives information on package
structure, the configure and cleanup mechanisms, and on automated
package checking and building.

   R version 1.3.0 has added the function 'package.skeleton()' which
will set up directories, save data and code, and create skeleton help
files for a set of R functions and datasets.

   *Note What is CRAN?::, for information on uploading a package to
CRAN.

5.6 How can I contribute to R?
==============================

R is in active development and there is always a risk of bugs creeping
in.  Also, the developers do not have access to all possible machines
capable of running R. So, simply using it and communicating problems is
certainly of great value.

   The R Developer Page (https://developer.R-project.org/) acts as an
intermediate repository for more or less finalized ideas and plans for
the R statistical system.  It contains (pointers to) TODO lists, RFCs,
various other writeups, ideas lists, and SVN miscellanea.

6 R and Emacs
*************

6.1 Is there Emacs support for R?
=================================

There is an Emacs package called ESS ("Emacs Speaks Statistics") which
provides a standard interface between statistical programs and
statistical processes.  It is intended to provide assistance for
interactive statistical programming and data analysis.  Languages
supported include: S dialects (R, S 3/4, and S-PLUS
3.x/4.x/5.x/6.x/7.x), LispStat dialects (XLispStat, ViSta), SAS, Stata,
and BUGS.

   ESS grew out of the need for bug fixes and extensions to S-mode 4.8
(which was a GNU Emacs interface to S/S-PLUS version 3 only).  The
current set of developers desired support for XEmacs, R, S4, and MS
Windows.  In addition, with new modes being developed for R, Stata, and
SAS, it was felt that a unifying interface and framework for the user
interface would benefit both the user and the developer, by helping both
groups conform to standard Emacs usage.  The end result is an increase
in efficiency for statistical programming and data analysis, over the
usual tools.

   R support contains code for editing R source code (syntactic
indentation and highlighting of source code, partial evaluations of
code, loading and error-checking of code, and source code revision
maintenance) and documentation (syntactic indentation and highlighting
of source code, sending examples to running ESS process, and
previewing), interacting with an inferior R process from within Emacs
(command-line editing, searchable command history, command-line
completion of R object and file names, quick access to object and search
lists, transcript recording, and an interface to the help system), and
transcript manipulation (recording and saving transcript files,
manipulating and editing saved transcripts, and re-evaluating commands
from transcript files).

   The latest stable version of ESS is available via CRAN or the ESS web
page (https://ESS.R-project.org/).

   ESS comes with detailed installation instructions.

   For help with ESS, send email to <ESS-help@r-project.org>.

   Please send bug reports and suggestions on ESS to
<ESS-bugs@r-project.org>.  The easiest way to do this from is within
Emacs by typing 'M-x ess-submit-bug-report' or using the [ESS] or [iESS]
pulldown menus.

6.2 Should I run R from within Emacs?
=====================================

Yes, instead of just running it in a console, _definitely_.  As an
alternative to other IDE's such as Rstudio, _possibly_, notably if you
are interested to use Emacs for other computer interaction.  You'd be
using ESS, Emacs Speaks Statistics, see previous FAQ.

   Inferior R mode provides a readline/history mechanism, object name
completion, and syntax-based highlighting of the interaction buffer
using Font Lock mode, as well as a very convenient interface to the R
help system.

   Of course, it also integrates nicely with the mechanisms for editing
R source using Emacs.  One can write code in one Emacs buffer and send
whole or parts of it for execution to R; this is helpful for both data
analysis and programming.  One can also seamlessly integrate with a
revision control system, in order to maintain a log of changes in your
programs and data, as well as to allow for the retrieval of past
versions of the code.

   In addition, it allows you to keep a record of your session, which
can also be used for error recovery through the use of the transcript
mode.

   To specify command line arguments for the inferior R process, use
'C-u M-x R' for starting R.

6.3 Debugging R from within Emacs
=================================

To debug R "from within Emacs", there are several possibilities.  To use
the Emacs GUD (Grand Unified Debugger) library with the recommended
debugger GDB, type 'M-x gdb' and give the path to the R _binary_ as
argument.  At the 'gdb' prompt, set 'R_HOME' and other environment
variables as needed (using e.g. 'set env R_HOME /path/to/R/', but see
also below), and start the binary with the desired arguments (e.g., 'run
--quiet').

   If you have ESS, you can do 'C-u M-x R <RET> - d <SPC> g d b <RET>'
to start an inferior R process with arguments '-d gdb'.

   A third option is to start an inferior R process via ESS ('M-x R')
and then start GUD ('M-x gdb') giving the R binary (using its full path
name) as the program to debug.  Use the program 'ps' to find the process
number of the currently running R process then use the 'attach' command
in gdb to attach it to that process.  One advantage of this method is
that you have separate '*R*' and '*gud-gdb*' windows.  Within the '*R*'
window you have all the ESS facilities, such as object-name completion,
that we know and love.

   When using GUD mode for debugging from within Emacs, you may find it
most convenient to use the directory with your code in it as the current
working directory and then make a symbolic link from that directory to
the R binary.  That way '.gdbinit' can stay in the directory with the
code and be used to set up the environment and the search paths for the
source, e.g. as follows:

     set env R_HOME /opt/R
     set env R_PAPERSIZE letter
     set env R_PRINTCMD lpr
     dir /opt/R/src/appl
     dir /opt/R/src/main
     dir /opt/R/src/nmath
     dir /opt/R/src/unix

7 R Miscellanea
***************

7.1 How can I set components of a list to NULL?
===============================================

You can use

     x[i] <- list(NULL)

to set component 'i' of the list 'x' to 'NULL', similarly for named
components.  Do not set 'x[i]' or 'x[[i]]' to 'NULL', because this will
remove the corresponding component from the list.

   For dropping the row names of a matrix 'x', it may be easier to use
'rownames(x) <- NULL', similarly for column names.

7.2 How can I save my workspace?
================================

'save.image()' saves the objects in the user's '.GlobalEnv' to the file
'.RData' in the R startup directory.  (This is also what happens after
'q("yes")'.)  Using 'save.image(FILE)' one can save the image under a
different name.

7.3 How can I clean up my workspace?
====================================

To remove all objects in the currently active environment (typically
'.GlobalEnv'), you can do

     rm(list = ls(all = TRUE))

(Without 'all = TRUE', only the objects with names not starting with a
'.' are removed.)

7.4 How can I get eval() and D() to work?
=========================================

Strange things will happen if you use 'eval(print(x), envir = e)' or
'D(x^2, "x")'.  The first one will either tell you that "'x'" is not
found, or print the value of the wrong 'x'.  The other one will likely
return zero if 'x' exists, and an error otherwise.

   This is because in both cases, the first argument is evaluated in the
calling environment first.  The result (which should be an object of
mode '"expression"' or '"call"') is then evaluated or differentiated.
What you (most likely) really want is obtained by "quoting" the first
argument upon surrounding it with 'expression()'.  For example,

     R> D(expression(x^2), "x")
     2 * x

   Although this behavior may initially seem to be rather strange, it is
perfectly logical.  The "intuitive" behavior could easily be
implemented, but problems would arise whenever the expression is
contained in a variable, passed as a parameter, or is the result of a
function call.  Consider for instance the semantics in cases like

     D2 <- function(e, n) D(D(e, n), n)

or

     g <- function(y) eval(substitute(y), sys.frame(sys.parent(n = 2)))
     g(a * b)

   See the help page for 'deriv()' for more examples.

7.5 Why do my matrices lose dimensions?
=======================================

When a matrix with a single row or column is created by a subscripting
operation, e.g., 'row <- mat[2, ]', it is by default turned into a
vector.  In a similar way if an array with dimension, say, 2 x 3 x 1 x 4
is created by subscripting it will be coerced into a 2 x 3 x 4 array,
losing the unnecessary dimension.  After much discussion this has been
determined to be a _feature_.

   To prevent this happening, add the option 'drop = FALSE' to the
subscripting.  For example,

     rowmatrix <- mat[2, , drop = FALSE]  # creates a row matrix
     colmatrix <- mat[, 2, drop = FALSE]  # creates a column matrix
     a <- b[1, 1, 1, drop = FALSE]        # creates a 1 x 1 x 1 array

   The 'drop = FALSE' option should be used defensively when
programming.  For example, the statement

     somerows <- mat[index, ]

will return a vector rather than a matrix if 'index' happens to have
length 1, causing errors later in the code.  It should probably be
rewritten as

     somerows <- mat[index, , drop = FALSE]

7.6 How does autoloading work?
==============================

R has a special environment called '.AutoloadEnv'.  Using
'autoload(NAME, PKG)', where NAME and PKG are strings giving the names
of an object and the package containing it, stores some information in
this environment.  When R tries to evaluate NAME, it loads the
corresponding package PKG and reevaluates NAME in the new package's
environment.

   Using this mechanism makes R behave as if the package was loaded, but
does not occupy memory (yet).

   See the help page for 'autoload()' for a very nice example.

7.7 How should I set options?
=============================

The function 'options()' allows setting and examining a variety of
global "options" which affect the way in which R computes and displays
its results.  The variable '.Options' holds the current values of these
options, but should never directly be assigned to unless you want to
drive yourself crazy--simply pretend that it is a "read-only" variable.

   For example, given

     test1 <- function(x = pi, dig = 3) {
       oo <- options(digits = dig); on.exit(options(oo));
       cat(.Options$digits, x, "\n")
     }
     test2 <- function(x = pi, dig = 3) {
       .Options$digits <- dig
       cat(.Options$digits, x, "\n")
     }

we obtain:

     R> test1()
     3 3.14
     R> test2()
     3 3.141593

   What is really used is the _global_ value of '.Options', and using
'options(OPT = VAL)' correctly updates it.  Local copies of '.Options',
either in '.GlobalEnv' or in a function environment (frame), are just
silently disregarded.

7.8 How do file names work in Windows?
======================================

As R uses C-style string handling, '\' is treated as an escape
character, so that for example one can enter a newline as '\n'.  When
you really need a '\', you have to escape it with another '\'.

   Thus, in filenames use something like '"c:\\data\\money.dat"'.  You
can also replace '\' by '/' ('"c:/data/money.dat"').

7.9 Why does plotting give a color allocation error?
====================================================

On an X11 device, plotting sometimes, e.g., when running
'demo("image")', results in "Error: color allocation error".  This is an
X problem, and only indirectly related to R. It occurs when applications
started prior to R have used all the available colors.  (How many colors
are available depends on the X configuration; sometimes only 256 colors
can be used.)

   One application which is notorious for "eating" colors is Netscape.
If the problem occurs when Netscape is running, try (re)starting it with
either the '-no-install' (to use the default colormap) or the '-install'
(to install a private colormap) option.

   You could also set the 'colortype' of 'X11()' to '"pseudo.cube"'
rather than the default '"pseudo"'.  See the help page for 'X11()' for
more information.

7.10 How do I convert factors to numeric?
=========================================

It may happen that when reading numeric data into R (usually, when
reading in a file), they come in as factors.  If 'f' is such a factor
object, you can use

     as.numeric(as.character(f))

to get the numbers back.  More efficient, but harder to remember, is

     as.numeric(levels(f))[as.integer(f)]

   In any case, do not call 'as.numeric()' or their likes directly for
the task at hand (as 'as.numeric()' or 'unclass()' give the internal
codes).

7.11 Are Trellis displays implemented in R?
===========================================

The recommended package *lattice*
(https://CRAN.R-project.org/package=lattice) (which is based on base
package *grid*) provides graphical functionality that is compatible with
most Trellis commands.

   You could also look at 'coplot()' and 'dotchart()' which might do at
least some of what you want.  Note also that the R version of 'pairs()'
is fairly general and provides most of the functionality of 'splom()',
and that R's default plot method has an argument 'asp' allowing to
specify (and fix against device resizing) the aspect ratio of the plot.

   (Because the word "Trellis" has been claimed as a trademark we do not
use it in R. The name "lattice" has been chosen for the R equivalent.)

7.12 What are the enclosing and parent environments?
====================================================

Inside a function you may want to access variables in two additional
environments: the one that the function was defined in ("enclosing"),
and the one it was invoked in ("parent").

   If you create a function at the command line or load it in a package
its enclosing environment is the global workspace.  If you define a
function 'f()' inside another function 'g()' its enclosing environment
is the environment inside 'g()'.  The enclosing environment for a
function is fixed when the function is created.  You can find out the
enclosing environment for a function 'f()' using 'environment(f)'.

   The "parent" environment, on the other hand, is defined when you
invoke a function.  If you invoke 'lm()' at the command line its parent
environment is the global workspace, if you invoke it inside a function
'f()' then its parent environment is the environment inside 'f()'.  You
can find out the parent environment for an invocation of a function by
using 'parent.frame()' or 'sys.frame(sys.parent())'.

   So for most user-visible functions the enclosing environment will be
the global workspace, since that is where most functions are defined.
The parent environment will be wherever the function happens to be
called from.  If a function 'f()' is defined inside another function
'g()' it will probably be used inside 'g()' as well, so its parent
environment and enclosing environment will probably be the same.

   Parent environments are important because things like model formulas
need to be evaluated in the environment the function was called from,
since that's where all the variables will be available.  This relies on
the parent environment being potentially different with each invocation.

   Enclosing environments are important because a function can use
variables in the enclosing environment to share information with other
functions or with other invocations of itself (see the section on
lexical scoping).  This relies on the enclosing environment being the
same each time the function is invoked.  (In C this would be done with
static variables.)

   Scoping _is_ hard.  Looking at examples helps.  It is particularly
instructive to look at examples that work differently in R and S and try
to see why they differ.  One way to describe the scoping differences
between R and S is to say that in S the enclosing environment is
_always_ the global workspace, but in R the enclosing environment is
wherever the function was created.

7.13 How can I substitute into a plot label?
============================================

Often, it is desired to use the value of an R object in a plot label,
e.g., a title.  This is easily accomplished using 'paste()' if the label
is a simple character string, but not always obvious in case the label
is an expression (for refined mathematical annotation).  In such a case,
either use 'parse()' on your pasted character string or use
'substitute()' on an expression.  For example, if 'ahat' is an estimator
of your parameter a of interest, use

     title(substitute(hat(a) == ahat, list(ahat = ahat)))

(note that it is '==' and not '=').  Sometimes 'bquote()' gives a more
compact form, e.g.,

     title(bquote(hat(a) = .(ahat)))

where subexpressions enclosed in '.()' are replaced by their values.

   There are more examples in the mailing list archives.

7.14 What are valid names?
==========================

When creating data frames using 'data.frame()' or 'read.table()', R by
default ensures that the variable names are syntactically valid.  (The
argument 'check.names' to these functions controls whether variable
names are checked and adjusted by 'make.names()' if needed.)

   To understand what names are "valid", one needs to take into account
that the term "name" is used in several different (but related) ways in
the language:

  1. A _syntactic name_ is a string the parser interprets as this type
     of expression.  It consists of letters, numbers, and the dot and
     (for versions of R at least 1.9.0) underscore characters, and
     starts with either a letter or a dot not followed by a number.
     Reserved words are not syntactic names.
  2. An _object name_ is a string associated with an object that is
     assigned in an expression either by having the object name on the
     left of an assignment operation or as an argument to the 'assign()'
     function.  It is usually a syntactic name as well, but can be any
     non-empty string if it is quoted (and it is always quoted in the
     call to 'assign()').

  3. An _argument name_ is what appears to the left of the equals sign
     when supplying an argument in a function call (for example,
     'f(trim=.5)').  Argument names are also usually syntactic names,
     but again can be anything if they are quoted.

  4. An _element name_ is a string that identifies a piece of an object
     (a component of a list, for example.)  When it is used on the right
     of the '$' operator, it must be a syntactic name, or quoted.
     Otherwise, element names can be any strings.  (When an object is
     used as a database, as in a call to 'eval()' or 'attach()', the
     element names become object names.)

  5. Finally, a _file name_ is a string identifying a file in the
     operating system for reading, writing, etc.  It really has nothing
     much to do with names in the language, but it is traditional to
     call these strings file "names".

7.15 Are GAMs implemented in R?
===============================

Package *gam* (https://CRAN.R-project.org/package=gam) from CRAN
implements all the Generalized Additive Models (GAM) functionality as
described in the GAM chapter of the White Book.  In particular, it
implements backfitting with both local regression and smoothing splines,
and is extendable.  There is a 'gam()' function for GAMs in package
*mgcv* (https://CRAN.R-project.org/package=mgcv), but it is not an exact
clone of what is described in the White Book (no 'lo()' for example).
Package *gss* (https://CRAN.R-project.org/package=gss) can fit
spline-based GAMs too.  And if you can accept regression splines you can
use 'glm()'.  For Gaussian GAMs you can use 'bruto()' from package *mda*
(https://CRAN.R-project.org/package=mda).

7.16 Why is the output not printed when I source() a file?
==========================================================

Most R commands do not generate any output.  The command

     1+1

computes the value 2 and returns it; the command

     summary(glm(y~x+z, family=binomial))

fits a logistic regression model, computes some summary information and
returns an object of class '"summary.glm"' (*note How should I write
summary methods?::).

   If you type '1+1' or 'summary(glm(y~x+z, family=binomial))' at the
command line the returned value is automatically printed (unless it is
'invisible()'), but in other circumstances, such as in a 'source()'d
file or inside a function it isn't printed unless you specifically print
it.

   To print the value use

     print(1+1)

or

     print(summary(glm(y~x+z, family=binomial)))

instead, or use 'source(FILE, echo=TRUE)'.

7.17 Why does outer() behave strangely with my function?
========================================================

As the help for 'outer()' indicates, it does not work on arbitrary
functions the way the 'apply()' family does.  It requires functions that
are vectorized to work elementwise on arrays.  As you can see by looking
at the code, 'outer(x, y, FUN)' creates two large vectors containing
every possible combination of elements of 'x' and 'y' and then passes
this to 'FUN' all at once.  Your function probably cannot handle two
large vectors as parameters.

   If you have a function that cannot handle two vectors but can handle
two scalars, then you can still use 'outer()' but you will need to wrap
your function up first, to simulate vectorized behavior.  Suppose your
function is

     foo <- function(x, y, happy) {
       stopifnot(length(x) == 1, length(y) == 1) # scalars only!
       (x + y) * happy
     }

If you define the general function

     wrapper <- function(x, y, my.fun, ...) {
       sapply(seq_along(x), FUN = function(i) my.fun(x[i], y[i], ...))
     }

then you can use 'outer()' by writing, e.g.,

     outer(1:4, 1:2, FUN = wrapper, my.fun = foo, happy = 10)

   Scalar functions can also be vectorized using 'Vectorize()'.

7.18 Why does the output from anova() depend on the order of factors in the model?
==================================================================================

In a model such as '~A+B+A:B', R will report the difference in sums of
squares between the models '~1', '~A', '~A+B' and '~A+B+A:B'.  If the
model were '~B+A+A:B', R would report differences between '~1', '~B',
'~A+B', and '~A+B+A:B' .  In the first case the sum of squares for 'A'
is comparing '~1' and '~A', in the second case it is comparing '~B' and
'~B+A'.  In a non-orthogonal design (i.e., most unbalanced designs)
these comparisons are (conceptually and numerically) different.

   Some packages report instead the sums of squares based on comparing
the full model to the models with each factor removed one at a time (the
famous 'Type III sums of squares' from SAS, for example).  These do not
depend on the order of factors in the model.  The question of which set
of sums of squares is the Right Thing provokes low-level holy wars on
R-help from time to time.

   There is no need to be agitated about the particular sums of squares
that R reports.  You can compute your favorite sums of squares quite
easily.  Any two models can be compared with 'anova(MODEL1, MODEL2)',
and 'drop1(MODEL1)' will show the sums of squares resulting from
dropping single terms.

7.19 How do I produce PNG graphics in batch mode?
=================================================

Under a Unix-like, if your installation supports the 'type="cairo"'
option to the 'png()' device there should be no problems, and the
default settings should just work.  This option is not available for