code
stringlengths
2.5k
150k
kind
stringclasses
1 value
r None `NextMethod` Call an Inherited Method -------------------------------------- ### Description A call to `callNextMethod` can only appear inside a method definition. It then results in a call to the first inherited method after the current method, with the arguments to the current method passed down to the next method. The value of that method call is the value of `callNextMethod`. ### Usage ``` callNextMethod(...) ``` ### Arguments | | | | --- | --- | | `...` | Optionally, the arguments to the function in its next call (but note that the dispatch is as in the detailed description below; the arguments have no effect on selecting the next method.) If no arguments are included in the call to `callNextMethod`, the effect is to call the method with the current arguments. See the detailed description for what this really means. Calling with no arguments is often the natural way to use `callNextMethod`; see the examples. | ### Details The ‘next’ method (i.e., the first inherited method) is defined to be that method which *would* have been called if the current method did not exist. This is more-or-less literally what happens: The current method (to be precise, the method with signature given by the `defined` slot of the method from which `callNextMethod` is called) is deleted from a copy of the methods for the current generic, and `[selectMethod](getmethod)` is called to find the next method (the result is cached in the method object where the call occurred, so the search typically happens only once per session per combination of argument classes). The next method is defined from the *signature* of the current method, not from the actual classes of the arguments. In particular, modifying any of the arguments has no effect on the selection. As a result, the selected next method can be called with invalid arguments if the calling function assigns objects of a different class before the `callNextMethod()` call. Be careful of any assignments to such arguments. It is possible for the selection of the next method to be ambiguous, even though the original set of methods was consistent. See the section “Ambiguous Selection”. The statement that the method is called with the current arguments is more precisely as follows. Arguments that were missing in the current call are still missing (remember that `"missing"` is a valid class in a method signature). For a formal argument, say `x`, that appears in the original call, there is a corresponding argument in the next method call equivalent to `x = x`. In effect, this means that the next method sees the same actual arguments, but arguments are evaluated only once. ### Value The value returned by the selected method. ### Ambiguous Selection There are two fairly common situations in which the choice of a next method is ambiguous, even when the original set of methods uniquely defines all method selection unambiguously. In these situations, `callNextMethod()` should be replaced, either by a call to a specific function or by recalling the generic with different arguments. The most likely situation arises with methods for binary operators, typically through one of the group generic functions. See the example for class `"rnum"` below. Examples of this sort usually require three methods: two for the case that the first or the second argument comes from the class, and a third for the case that both arguments come from the class. If that last method uses `callNextMethod`, the other two methods are equally valid. The ambiguity is exactly the same that required defining the two-argument method in the first place. In fact, the two possibilities are equally valid conceptually as well as formally. As in the example below, the logic of the application usually requires selecting a computation explicitly or else calling the generic function with modified arguments to select an appropriate method. The other likely source of ambiguity arises from a class that inherits directly from more than one other class (a “mixin” in standard terminology). If the generic has methods corresponding to both superclasses, a method for the current class is again needed to resolve ambiguity. Using `callNextMethod` will again reimpose the ambiguity. Again, some explicit choice has to be made in the calling method instead. These ambiguities are not the result of bad design, but they do require workarounds. Other ambiguities usually reflect inconsistencies in the tree of inheritances, such as a class appearing in more than one place among the superclasses. Such cases should be rare, but with the independent definition of classes in multiple packages, they can't be ruled out. ### References Chambers, John M. (2016) *Extending R*, Chapman & Hall. (Chapters 9 and 10.) ### See Also `[callGeneric](callgeneric)` to call the generic function with the current dispatch rules (typically for a group generic function); [Methods\_Details](methods_details) for the general behavior of method dispatch. ### Examples ``` ## callNextMethod() used for the Math, Math2 group generic functions ## A class to automatically round numeric results to "d" digits rnum <- setClass("rnum", slots = c(d = "integer"), contains = "numeric") ## Math functions operate on the rounded numbers, return a plain ## vector. The next method will always be the default, usually a primitive. setMethod("Math", "rnum", function(x) callNextMethod(round(as.numeric(x), x@d))) setMethod("Math2", "rnum", function(x, digits) callNextMethod(round(as.numeric(x), x@d), digits)) ## Examples of callNextMethod with two arguments in the signature. ## For arithmetic and one rnum with anything, callNextMethod with no arguments ## round the full accuracy result, and return as plain vector setMethod("Arith", c(e1 ="rnum"), function(e1, e2) as.numeric(round(callNextMethod(), e1@d))) setMethod("Arith", c(e2 ="rnum"), function(e1, e2) as.numeric(round(callNextMethod(), e2@d))) ## A method for BOTH arguments from "rnum" would be ambiguous ## for callNextMethod(): the two methods above are equally valid. ## The method chooses the smaller number of digits, ## and then calls the generic function, postponing the method selection ## until it's not ambiguous. setMethod("Arith", c(e1 ="rnum", e2 = "rnum"), function(e1, e2) { if(e1@d <= e2@d) callGeneric(e1, as.numeric(e2)) else callGeneric(as.numeric(e1), e2) }) ## For comparisons, callNextMethod with the rounded arguments setMethod("Compare", c(e1 = "rnum"), function(e1, e2) callNextMethod(round(e1, e1@d), round(e2, e1@d))) setMethod("Compare", c(e2 = "rnum"), function(e1, e2) callNextMethod(round(e1, e2@d), round(e2, e2@d))) ## similarly to the Arith case, the method for two "rnum" objects ## can not unambiguously use callNextMethod(). Instead, we rely on ## The rnum() method inhertited from Math2 to return plain vectors. setMethod("Compare", c(e1 ="rnum", e2 = "rnum"), function(e1, e2) { d <- min(e1@d, e2@d) callGeneric(round(e1, d), round(e2, d)) }) set.seed(867) x1 <- rnum(10*runif(5), d=1L) x2 <- rnum(10*runif(5), d=2L) x1+1 x2*2 x1-x2 ## Simple examples to illustrate callNextMethod with and without arguments B0 <- setClass("B0", slots = c(s0 = "numeric")) ## and a function to illustrate callNextMethod f <- function(x, text = "default") { str(x) # print a summary paste(text, ":", class(x)) } setGeneric("f") setMethod("f", "B0", function(x, text = "B0") { cat("B0 method called with s0 =", x@s0, "\n") callNextMethod() }) b0 <- B0(s0 = 1) ## call f() with 2 arguments: callNextMethod passes both to the default method f(b0, "first test") ## call f() with 1 argument: the default "B0" is not passed by callNextMethod f(b0) ## Now, a class that extends B0, with no methods for f() B1 <- setClass("B1", slots = c(s1 = "character"), contains = "B0") b1 <- B1(s0 = 2, s1 = "Testing B1") ## the two cases work as before, by inheriting the "B0" method f(b1, b1@s1) f(b1) B2 <- setClass("B2", contains = "B1") ## And, a method for "B2" that calls with explicit arguments. ## Note that the method selection in callNextMethod ## uses the class of the *argument* to consistently select the "B0" method setMethod("f", "B2", function(x, text = "B1 method") { y <- B1(s0 = -x@s0, s1 ="Modified x") callNextMethod(y, text) }) b2 <- B2(s1 = "Testing B2", s0 = 10) f(b2, b2@s1) f(b2) ## Be careful: the argument passed must be legal for the method selected ## Although the argument here is numeric, it's still the "B0" method that's called setMethod("f", "B2", function(x, text = "B1 method") { callNextMethod(x@s0, text) }) ## Now the call will cause an error: tryCatch(f(b2), error = function(e) cat(e$message,"\n")) ``` r None `className` Class names including the corresponding package ------------------------------------------------------------ ### Description The function `className()` generates a valid references to a class, including the name of the package containing the class definition. The object returned, from class `"className"`, is the unambiguous way to refer to a class, for example when calling `[setMethod](setmethod)`, just in case multiple definitions of the class exist. Function `"multipleClasses"` returns information about multiple definitions of classes with the same name from different packages. ### Usage ``` className(class, package) multipleClasses(details = FALSE) ``` ### Arguments | | | | --- | --- | | `class, package` | The character string name of a class and, optionally, of the package to which it belongs. If argument `package` is missing and the `class` argument has a package slot, that is used (in particular, passing in an object from class `"className"` returns itself in this case, but changes the package slot if the second argument is supplied). If there is no package argument or slot, a definition for the class must exist and will be used to define the package. If there are multiple definitions, one will be chosen and a warning printed giving the other possibilities. | | `details` | If `FALSE`, the default, `multipleClasses()` returns a character vector of those classes currently known with multiple definitions. If `TRUE`, a named list of those class definitions is returned. Each element of the list is itself a list of the corresponding class definitions, with the package names as the names of the list. Note that identical class definitions will not be considered “multiple” definitions (see the discussion of the details below). | ### Details The table of class definitions used internally can maintain multiple definitions for classes with the same name but coming from different packages. If identical class definitions are encountered, only one class definition is kept; this occurs most often with S3 classes that have been specified in calls to `[setOldClass](setoldclass)`. For true classes, multiple class definitions are unavoidable in general if two packages happen to have used the same name, independently. Overriding a class definition in another package with the same name deliberately is usually a bad idea. Although **R** attempts to keep and use the two definitions (as of version 2.14.0), ambiguities are always possible. It is more sensible to define a new class that extends an existing class but has a different name. ### Value A call to `className()` returns an object from class `"className"`. A call to `multipleClasses()` returns either a character vector or a named list of class definitions. In either case, testing the length of the returned value for being greater than `0` is a check for the existence of multiply defined classes. ### Objects from the Class The class `"className"` extends `"character"` and has a slot `"package"`, also of class `"character"`. ### Examples ``` ## Not run: className("vector") # will be found, from package "methods" className("vector", "magic") # OK, even though the class doesn't exist className("An unknown class") # Will cause an error ## End(Not run) ``` r None `ObjectsWithPackage-class` A Vector of Object Names, with associated Package Names ----------------------------------------------------------------------------------- ### Description This class of objects is used to represent ordinary character string object names, extended with a `package` slot naming the package associated with each object. ### Objects from the Class The function `[getGenerics](genericfunctions)` returns an object of this class. ### Slots `.Data`: Object of class `"character"`: the object names. `package`: Object of class `"character"` the package names. ### Extends Class `"character"`, from data part. Class `"vector"`, by class `"character"`. ### See Also `Methods` for general background. r None `findClass` Find Class Definitions ----------------------------------- ### Description Functions to find classes: `isClass` tests for a class; `findClass` returns the name(s) of packages containing the class; `getClasses` returns the names of all the classes in an environment, typically a namespace. To examine the definition of a class, use `[getClass](getclass)`. ### Usage ``` isClass(Class, formal=TRUE, where) getClasses(where, inherits = missing(where)) findClass(Class, where, unique = "") ## The remaining functions are retained for compatibility ## but not generally recommended removeClass(Class, where) resetClass(Class, classDef, where) sealClass(Class, where) ``` ### Arguments | | | | --- | --- | | `Class` | character string name for the class. The functions will usually take a class definition instead of the string. To restrict the class to those defined in a particular package, set the `[packageSlot](getpackagename)` of the character string. | | `where` | the `[environment](../../base/html/environment)` in which to search for the class definition. Defaults to the top-level environment of the calling function. When called from the command line, this has the effect of using all the package environments in the search list. To restrict the search to classes in a particular package, use `where = asNamespace(pkg)` with `pkg` the package name; to restrict it to the *exported* classes, use `where = "package:pkg"` after the package is attached to the search list. | | `formal` | `[logical](../../base/html/logical)` is a formal definition required? For S compatibility, and always treated as `TRUE`. | | `unique` | if `findClass` expects a unique location for the class, `unique` is a character string explaining the purpose of the search (and is used in warning and error messages). By default, multiple locations are possible and the function always returns a list. | | `inherits` | in a call to `getClasses`, should the value returned include all parent environments of `where`, or that environment only? Defaults to `TRUE` if `where` is omitted, and to `FALSE` otherwise. | | `classDef` | For `resetClass`, the optional class definition. | ### Functions `isClass`: Is this the name of a formally defined class? `getClasses`: The names of all the classes formally defined on `where`. If called with no argument, all the classes visible from the calling function (if called from the top-level, all the classes in any of the environments on the search list). The `where` argument is used to search only in a particular package. `findClass`: The list of environments in which a class definition of `Class` is found. If `where` is supplied, a list is still returned, either empty or containing the environment corresponding to `where`. By default when called from the **R** session, the global environment and all the currently attached packages are searched. If `unique` is supplied as a character string, `findClass` will warn if there is more than one definition visible (using the string to identify the purpose of the call), and will generate an error if no definition can be found. *The remaining functions are retained for back-compatibility and internal use, but not generally recommended.* `removeClass`: Remove the definition of this class. This can't be used if the class is in another package, and would rarely be needed in source code defining classes in a package. `resetClass`: Reset the internal definition of a class. Not legitimate for a class definition not in this package and rarely needed otherwise. `sealClass`: Seal the current definition of the specified class, to prevent further changes, by setting the corresponding slot in the class definition. This is rarely used, since classes in loaded packages are sealed by locking their namespace. ### References Chambers, John M. (2016) *Extending R*, Chapman & Hall. (Chapters 9 and 10.) Chambers, John M. (2008) *Software for Data Analysis: Programming with R* Springer. (Chapter 9 has some details not in the later reference.) ### See Also `[getClass](getclass)`, `[Classes\_Details](classes_details)`, `[Methods\_Details](methods_details)`, `[makeClassRepresentation](setsclass)` r None `Methods_for_Nongenerics` Methods for Non-Generic Functions in Other Packages ------------------------------------------------------------------------------ ### Description In writing methods for an **R** package, it's common for these methods to apply to a function (in another package) that is not generic in that package; that is, there are no formal methods for the function in its own package, although it may have S3 methods. The programming in this case involves one extra step, to call `[setGeneric](setgeneric)()` to declare that the function *is* generic in your package. Calls to the function in your package will then use all methods defined there or in any other loaded package that creates the same generic function. Similarly, calls to the function in those packages will use your methods. The original version, however, remains non-generic. Calls in that package or in other packages that use that version will not dispatch your methods except for special circumstances: 1. If the function is one of the primitive functions that accept methods, the internal C implementation will dispatch methods if one of the arguments is an S4 object, as should be the case. 2. If the other version of the function dispatches S3 methods *and* your methods are also registered as S3 methods, the method will usually be dispatched as that S3 method. 3. Otherwise, you will need to ensure that all calls to the function come from a package in which the function is generic, perhaps by copying code to your package. Details and the underlying reasons are discussed in the following sections. ### Generic and Non-Generic Calls Creating methods for a function (any function) in a package means that calls to the function in that package will select methods according to the actual arguments. However, if the function was originally a non-generic in another package, calls to the function from that package will *not* dispatch methods. In addition, calls from any third package that imports the non-generic version will also not dispatch methods. This section considers the reason and how one might deal with the consequences. The reason is simply the **R** namespace mechanism and its role in evaluating function calls. When a name (such as the name of a function) needs to be evaluated in a call to a function from some package, the evaluator looks first in the frame of the call, then in the namespace of the package and then in the imports to that package. Defining methods for a function in a package ensures that calls to the function in that package will select the methods, because a generic version of the function is created in the namespace. Similarly, calls from another package that has or imports the generic version will select methods. Because the generic versions are identical, all methods will be available in all these packages. However, calls from any package that imports the old version or just selects it from the search list will usually *not* select methods. A an example, consider the function `[data.frame](../../base/html/data.frame)()` in the base package. This function takes any number of objects as arguments and attempts to combine them as variables into a data frame object. It does this by calling `[as.data.frame](../../base/html/as.data.frame)()`, also in the base package, for each of the objects. A reasonable goal would be to extend the classes of objects that can be included in a data frame by defining methods for `[as.data.frame](../../base/html/as.data.frame)()`. But calls to `[data.frame](../../base/html/data.frame)()`, will still use the version of that function in the base package, which continues to call the non-generic `[as.data.frame](../../base/html/as.data.frame)()` in that package. The details of what happens and options for dealing with it depend on the form of the function: a primitive function; a function that dispatches S3 methods; or an ordinary **R** function. Primitive functions are not actual **R** function objects. They go directly to internal C code. Some of them, however, have been implemented to recognize methods. These functions dispatch both S4 and S3 methods from the internal C code. There is no explicit generic function, either S3 or S4. The internal code looks for S4 methods if the first argument, or either of the arguments in the case of a binary operator, is an S4 object. If no S4 method is found, a search is made for an S3 method. So defining methods for these functions works as long as the relevant classes have been defined, which should always be the case. A function dispatches S3 methods by calling `[UseMethod](../../base/html/usemethod)()`, which does *not* look for formal methods regardless of whether the first argument is an S4 object or not. This applies to the `[as.data.frame](../../base/html/as.data.frame)()` example above. To have methods called in this situation, your package must also define the method as an S3 method, if possible. See section ‘S3 “Generic” Functions’. In the third possibility, the function is defined with no expectation of methods. For example, the base package has a number of functions that compute numerical decompositions of matrix arguments. Some, such as `[chol](../../matrix/html/chol)()` and `[qr](../../matrix/html/qr-methods)()` are implemented to dispatch S3 methods; others, such as `[svd](../../base/html/svd)()` are implemented directly as a specific computation. A generic version of the latter functions can be written and called directly to define formal methods, but no code in another package that does not import this generic version will dispatch such methods. In this case, you need to have the generic version used in all the indirect calls to the function supplying arguments that should dispatch methods. This may require supplying new functions that dispatch methods and then call the function they replace. For example, if S3 methods did not work for `[as.data.frame](../../base/html/as.data.frame)()`, one could call a function that applied the generic version to all its arguments and then called `[data.frame](../../base/html/data.frame)()` as a replacement for that function. If all else fails, it might be necessary to copy over the relevant functions so that they would find the generic versions. ### S3 “Generic” Functions S3 method dispatch looks at the class of the first argument. S3 methods are ordinary functions with the same arguments as the generic function. The “signature” of an S3 method is identified by the name to which the method is assigned, composed of the name of the generic function, followed by `"."`, followed by the name of the class. For details, see `[UseMethod](../../base/html/usemethod)`. To implement a method for one of these functions corresponding to S4 classes, there are two possibilities: either an S4 method or an S3 method with the S4 class name. The S3 method is only possible if the intended signature has the first argument and nothing else. In this case, the recommended approach is to define the S3 method and also supply the identical function as the definition of the S4 method. If the S3 generic function was `f3(x, ...)` and the S4 class for the new method was `"myClass"`: `f3.myClass <- function(x, ...) { ..... }` `setMethod("f3", "myClass", f3.myClass)` Defining both methods usually ensures that all calls to the original function will dispatch the intended method. The S4 method alone would not be called from other packages using the original version of the function. On the other hand, an S3 method alone will not be called if there is *any* eligible non-default S4 method. S4 and S3 method selection are designed to follow compatible rules of inheritance, as far as possible. S3 classes can be used for any S4 method selection, provided that the S3 classes have been registered by a call to `[setOldClass](setoldclass)`, with that call specifying the correct S3 inheritance pattern. S4 classes can be used for any S3 method selection; when an S4 object is detected, S3 method selection uses the contents of `[extends](is)(class(x))` as the equivalent of the S3 inheritance (the inheritance is cached after the first call). An existing S3 method may not behave as desired for an S4 subclass, in which case utilities such as `[asS3](../../base/html/iss4)` and `[S3Part](s3part)` may be useful. If the S3 method fails on the S4 object, `asS3(x)` may be passed instead; if the object returned by the S3 method needs to be incorporated in the S4 object, the replacement function for `S3Part` may be useful. ### References Chambers, John M. (2016) *Extending R*, Chapman & Hall. (Chapters 9 and 10.) ### See Also [Methods\_for\_S3](methods_for_s3) for suggested implementation of methods that work for both S3 and S4 dispatch. ### Examples ``` ## A class that extends a registered S3 class inherits that class' S3 ## methods. setClass("myFrame", contains = "data.frame", slots = c(timestamps = "POSIXt")) df1 <- data.frame(x = 1:10, y = rnorm(10), z = sample(letters,10)) mydf1 <- new("myFrame", df1, timestamps = Sys.time()) ## "myFrame" objects inherit "data.frame" S3 methods; e.g., for `[` mydf1[1:2, ] # a data frame object (with extra attributes) ## a method explicitly for "myFrame" class setMethod("[", signature(x = "myFrame"), function (x, i, j, ..., drop = TRUE) { S3Part(x) <- callNextMethod() x@timestamps <- c(Sys.time(), as.POSIXct(x@timestamps)) x } ) mydf1[1:2, ] setClass("myDateTime", contains = "POSIXt") now <- Sys.time() # class(now) is c("POSIXct", "POSIXt") nowLt <- as.POSIXlt(now)# class(nowLt) is c("POSIXlt", "POSIXt") mCt <- new("myDateTime", now) mLt <- new("myDateTime", nowLt) ## S3 methods for an S4 object will be selected using S4 inheritance ## Objects mCt and mLt have different S3Class() values, but this is ## not used. f3 <- function(x)UseMethod("f3") # an S3 generic to illustrate inheritance f3.POSIXct <- function(x) "The POSIXct result" f3.POSIXlt <- function(x) "The POSIXlt result" f3.POSIXt <- function(x) "The POSIXt result" stopifnot(identical(f3(mCt), f3.POSIXt(mCt))) stopifnot(identical(f3(mLt), f3.POSIXt(mLt))) ## An S4 object selects S3 methods according to its S4 "inheritance" setClass("classA", contains = "numeric", slots = c(realData = "numeric")) Math.classA <- function(x) { (getFunction(.Generic))(x@realData) } setMethod("Math", "classA", Math.classA) x <- new("classA", log(1:10), realData = 1:10) stopifnot(identical(abs(x), 1:10)) setClass("classB", contains = "classA") y <- new("classB", x) stopifnot(identical(abs(y), abs(x))) # (version 2.9.0 or earlier fails here) ## an S3 generic: just for demonstration purposes f3 <- function(x, ...) UseMethod("f3") f3.default <- function(x, ...) "Default f3" ## S3 method (only) for classA f3.classA <- function(x, ...) "Class classA for f3" ## S3 and S4 method for numeric f3.numeric <- function(x, ...) "Class numeric for f3" setMethod("f3", "numeric", f3.numeric) ## The S3 method for classA and the closest inherited S3 method for classB ## are not found. f3(x); f3(y) # both choose "numeric" method ## to obtain the natural inheritance, set identical S3 and S4 methods setMethod("f3", "classA", f3.classA) f3(x); f3(y) # now both choose "classA" method ## Need to define an S3 as well as S4 method to use on an S3 object ## or if called from a package without the S4 generic MathFun <- function(x) { # a smarter "data.frame" method for Math group for (i in seq_len(ncol(x))[sapply(x, is.numeric)]) x[, i] <- (getFunction(.Generic))(x[, i]) x } setMethod("Math", "data.frame", MathFun) ## S4 method works for an S4 class containing data.frame, ## but not for data.frame objects (not S4 objects) try(logIris <- log(iris)) #gets an error from the old method ## Define an S3 method with the same computation Math.data.frame <- MathFun logIris <- log(iris) ```
programming_docs
r None `GenericFunctions` Tools for Managing Generic Functions -------------------------------------------------------- ### Description The functions documented here manage collections of methods associated with a generic function, as well as providing information about the generic functions themselves. ### Usage ``` isGeneric(f, where, fdef, getName = FALSE) isGroup(f, where, fdef) removeGeneric(f, where) dumpMethod(f, signature, file, where, def) findFunction(f, generic = TRUE, where = topenv(parent.frame())) dumpMethods(f, file, signature, methods, where) signature(...) removeMethods(f, where = topenv(parent.frame()), all = missing(where)) setReplaceMethod(f, ..., where = topenv(parent.frame())) getGenerics(where, searchForm = FALSE) ``` ### Arguments | | | | --- | --- | | `f` | The character string naming the function. | | `where` | The environment, namespace, or search-list position from which to search for objects. By default, start at the top-level environment of the calling function, typically the global environment (i.e., use the search list), or the namespace of a package from which the call came. It is important to supply this argument when calling any of these functions indirectly. With package namespaces, the default is likely to be wrong in such calls. | | `signature` | The class signature of the relevant method. A signature is a named or unnamed vector of character strings. If named, the names must be formal argument names for the generic function. Signatures are matched to the arguments specified in the signature slot of the generic function (see the Details section of the `[setMethod](setmethod)` documentation). The `signature` argument to `dumpMethods` is ignored (it was used internally in previous implementations). | | `file` | The file or connection on which to dump method definitions. | | `def` | The function object defining the method; if omitted, the current method definition corresponding to the signature. | | `...` | Named or unnamed arguments to form a signature. | | `generic` | In testing or finding functions, should generic functions be included. Supply as `FALSE` to get only non-generic functions. | | `fdef` | Optional, the generic function definition. Usually omitted in calls to `isGeneric` | | `getName` | If `TRUE`, `isGeneric` returns the name of the generic. By default, it returns `TRUE`. | | `methods` | The methods object containing the methods to be dumped. By default, the methods defined for this generic (optionally on the specified `where` location). | | `all` | in `removeMethods`, logical indicating if all (default) or only the first method found should be removed. | | `searchForm` | In `getGenerics`, if `TRUE`, the `package` slot of the returned result is in the form used by `search()`, otherwise as the simple package name (e.g, `"package:base"` vs `"base"`). | ### Summary of Functions `isGeneric`: Is there a function named `f`, and if so, is it a generic? The `getName` argument allows a function to find the name from a function definition. If it is `TRUE` then the name of the generic is returned, or `FALSE` if this is not a generic function definition. The behavior of `isGeneric` and `[getGeneric](rmethodutils)` for primitive functions is slightly different. These functions don't exist as formal function objects (for efficiency and historical reasons), regardless of whether methods have been defined for them. A call to `isGeneric` tells you whether methods have been defined for this primitive function, anywhere in the current search list, or in the specified position `where`. In contrast, a call to `[getGeneric](rmethodutils)` will return what the generic for that function would be, even if no methods have been currently defined for it. `removeGeneric`, `removeMethods`: Remove all the methods for the generic function of this name. In addition, `removeGeneric` removes the function itself; `removeMethods` restores the non-generic function which was the default method. If there was no default method, `removeMethods` leaves a generic function with no methods. `standardGeneric`: Dispatches a method from the current function call for the generic function `f`. It is an error to call `standardGeneric` anywhere except in the body of the corresponding generic function. Note that `[standardGeneric](../../base/html/standardgeneric)` is a primitive function in the base package for efficiency reasons, but rather documented here where it belongs naturally. `dumpMethod`: Dump the method for this generic function and signature. `findFunction`: return a list of either the positions on the search list, or the current top-level environment, on which a function object for `name` exists. The returned value is *always* a list, use the first element to access the first visible version of the function. See the example. *NOTE:* Use this rather than `[find](../../utils/html/apropos)` with `mode="function"`, which is not as meaningful, and has a few subtle bugs from its use of regular expressions. Also, `findFunction` works correctly in the code for a package when attaching the package via a call to `[library](../../base/html/library)`. `dumpMethods`: Dump all the methods for this generic. `signature`: Returns a named list of classes to be matched to arguments of a generic function. `getGenerics`: returns the names of the generic functions that have methods defined on `where`; this argument can be an environment or an index into the search list. By default, the whole search list is used. The methods definitions are stored with package qualifiers; for example, methods for function `"initialize"` might refer to two different functions of that name, on different packages. The package names corresponding to the method list object are contained in the slot `package` of the returned object. The form of the returned name can be plain (e.g., `"base"`), or in the form used in the search list (`"package:base"`) according to the value of `searchForm` ### Details `isGeneric`: If the `fdef` argument is supplied, take this as the definition of the generic, and test whether it is really a generic, with `f` as the name of the generic. (This argument is not available in S-Plus.) `removeGeneric`: If `where` supplied, just remove the version on this element of the search list; otherwise, removes the first version encountered. `standardGeneric`: Generic functions should usually have a call to `standardGeneric` as their entire body. They can, however, do any other computations as well. The usual `setGeneric` (directly or through calling `setMethod`) creates a function with a call to `standardGeneric`. `dumpMethod`: The resulting source file will recreate the method. `findFunction`: If `generic` is `FALSE`, ignore generic functions. `dumpMethods`: If `signature` is supplied only the methods matching this initial signature are dumped. (This feature is not found in S-Plus: don't use it if you want compatibility.) `signature`: The advantage of using `signature` is to provide a check on which arguments you meant, as well as clearer documentation in your method specification. In addition, `signature` checks that each of the elements is a single character string. `removeMethods`: Returns `TRUE` if `f` was a generic function, `FALSE` (silently) otherwise. If there is a default method, the function will be re-assigned as a simple function with this definition. Otherwise, the generic function remains but with no methods (so any call to it will generate an error). In either case, a following call to `setMethod` will consistently re-establish the same generic function as before. ### References Chambers, John M. (2016) *Extending R*, Chapman & Hall. (Chapters 9 and 10.) ### See Also `[getMethod](getmethod)` (also for `selectMethod`), `[setGeneric](setgeneric)`, `[setClass](setclass)`, `[showMethods](showmethods)` ### Examples ``` require(stats) # for lm ## get the function "myFun" -- throw an error if 0 or > 1 versions visible: findFuncStrict <- function(fName) { allF <- findFunction(fName) if(length(allF) == 0) stop("No versions of ",fName," visible") else if(length(allF) > 1) stop(fName," is ambiguous: ", length(allF), " versions") else get(fName, allF[[1]]) } try(findFuncStrict("myFun"))# Error: no version lm <- function(x) x+1 try(findFuncStrict("lm"))# Error: 2 versions findFuncStrict("findFuncStrict")# just 1 version rm(lm) ## method dumping ------------------------------------ setClass("A", slots = c(a="numeric")) setMethod("plot", "A", function(x,y,...){ cat("A meth\n") }) dumpMethod("plot","A", file="") ## Not run: setMethod("plot", "A", function (x, y, ...) { cat("AAAAA\n") } ) ## End(Not run) tmp <- tempfile() dumpMethod("plot","A", file=tmp) ## now remove, and see if we can parse the dump stopifnot(removeMethod("plot", "A")) source(tmp) stopifnot(is(getMethod("plot", "A"), "MethodDefinition")) ## same with dumpMethods() : setClass("B", contains="A") setMethod("plot", "B", function(x,y,...){ cat("B ...\n") }) dumpMethods("plot", file=tmp) stopifnot(removeMethod("plot", "A"), removeMethod("plot", "B")) source(tmp) stopifnot(is(getMethod("plot", "A"), "MethodDefinition"), is(getMethod("plot", "B"), "MethodDefinition")) ``` r None `methods-package` Formal Methods and Classes --------------------------------------------- ### Description Formally defined methods and classes for R objects, plus other programming tools, as described in the references. ### Details This package provides the “S4” or “S version 4” approach to methods and classes in a functional language. For basic use of the techniques, start with [Introduction](introduction) and follow the links there to the key functions for programming, notably `[setClass](setclass)` and `[setMethod](setmethod)`. Some specific topics: Classes: Creating one, see `[setClass](setclass)`; examining definitions, see `[getClassDef](getclass)` and [classRepresentation](classrepresentation-class); inheritance and coercing, see `<is>` and `<as>` Generic functions: Basic programming, see `[setGeneric](setgeneric)`; the class of objects, see [genericFunction](genericfunction-class); other functions to examine or manipulate them, see [GenericFunctions](genericfunctions). S3: Using classes, see `[setOldClass](setoldclass)`; methods, see [Methods\_for\_S3](methods_for_s3). Reference classes: See [ReferenceClasses](refclass). Class unions; virtual classes See `[setClassUnion](setclassunion)`. These pages will have additional links to related topics. For a complete list of functions and classes, use `library(help="methods")`. ### Author(s) R Core Team Maintainer: R Core Team [[email protected]](mailto:[email protected]) ### References Chambers, John M. (2016) *Extending R*, Chapman & Hall. (Chapters 9 and 10.) Chambers, John M. (2008) *Software for Data Analysis: Programming with R* Springer. (Chapter 10 has some additional details.) r None `testInheritedMethods` Test for and Report about Selection of Inherited Methods -------------------------------------------------------------------------------- ### Description A set of distinct inherited signatures is generated to test inheritance for all the methods of a specified generic function. If method selection is ambiguous for some of these, a summary of the ambiguities is attached to the returned object. This test should be performed by package authors *before* releasing a package. ### Usage ``` testInheritedMethods(f, signatures, test = TRUE, virtual = FALSE, groupMethods = TRUE, where = .GlobalEnv) ``` ### Arguments | | | | --- | --- | | `f` | a generic function or the character string name of one. By default, all currently defined subclasses of all the method signatures for this generic will be examined. The other arguments are mainly options to modify which inheritance patterns will be examined. | | `signatures` | An optional set of subclass signatures to use instead of the relevant subclasses computed by `testInheritedMethods`. See the Details for how this is done. This argument might be supplied after a call with `test = FALSE`, to test selection in batches. | | `test` | optional flag to control whether method selection is actually tested. If `FALSE`, returns just the list of relevant signatures for subclasses, without calling `[selectMethod](getmethod)` for each signature. If there are a very large number of signatures, you may want to collect the full list and then test them in batches. | | `virtual` | should virtual classes be included in the relevant subclasses. Normally not, since only the classes of actual arguments will trigger the inheritance calculation in a call to the generic function. Including virtual classes may be useful if the class has no current non-virtual subclasses but you anticipate your users may define such classes in the future. | | `groupMethods` | should methods for the group generic function be included? | | `where` | the environment in which to look for class definitions. Nearly always, use the default global environment after attaching all the packages with relevant methods and/or class definitions. | ### Details The following description applies when the optional arguments are omitted, the usual case. First, the defining signatures for all methods are computed by calls to `[findMethodSignatures](findmethods)`. From these all the known non-virtual subclasses are found for each class that appears in the signature of some method. These subclasses are split into groups according to which class they inherit from, and only one subclass from each group is retained (for each argument in the generic signature). So if a method was defined with class `"vector"` for some argument, one actual vector class is chosen arbitrarily. The case of `"ANY"` is dealt with specially, since all classes extend it. A dummy, nonvirtual class, `".Other"`, is used to correspond to all classes that have no superclasses among those being tested. All combinations of retained subclasses for the arguments in the generic signature are then computed. Each row of the resulting matrix is a signature to be tested by a call to `[selectMethod](getmethod)`. To collect information on ambiguous selections, `testInheritedMethods` establishes a calling handler for the special signal `"ambiguousMethodSelection"`, by setting the corresponding option. ### Value An object of class `"methodSelectionReport"`. The details of this class are currently subject to change. It has slots `"target"`, `"selected"`, `"candidates"`, and `"note"`, all referring to the ambiguous cases (and so of length 0 if there were none). These slots are intended to be examined by the programmer to detect and preferably fix ambiguous method selections. The object contains in addition slots `"generic"`, the name of the generic function, and `"allSelections"`, giving the vector of labels for all the signatures tested. ### References Chambers, John M. (2008) *Software for Data Analysis: Programming with R* Springer. (Section 10.6 for basics of method selection.) Chambers, John M. (2009) *Class Inheritance in R* <https://statweb.stanford.edu/~jmc4/classInheritance.pdf>. ### Examples ``` ## if no other attached packages have methods for `+` or its group ## generic functions, this returns a 16 by 2 matrix of selection ## patterns (in R 2.9.0) testInheritedMethods("+") ``` r None `setIs` Specify a Superclass Explicitly ---------------------------------------- ### Description `setIs` is an explicit alternative to the `contains=` argument to `[setClass](setclass)`. It is only needed to create relations with explicit test or coercion. These have not proved to be of much practical value, so this function should not likely be needed in applications. Where the programming goal is to define methods for transforming one class of objects to another, it is usually better practice to call `[setAs](setas)()`, which requires the transformations to be done explicitly. ### Usage ``` setIs(class1, class2, test=NULL, coerce=NULL, replace=NULL, by = character(), where = topenv(parent.frame()), classDef =, extensionObject = NULL, doComplete = TRUE) ``` ### Arguments | | | | --- | --- | | `class1, class2` | the names of the classes between which `is` relations are to be examined defined, or (more efficiently) the class definition objects for the classes. | | `coerce, replace` | functions optionally supplied to coerce the object to `class2`, and to alter the object so that `is(object, class2)` is identical to `value`. See the details section below. | | `test` | a *conditional* relationship is defined by supplying this function. Conditional relations are discouraged and are not included in selecting methods. See the details section below. The remaining arguments are for internal use and/or usually omitted. | | `extensionObject` | alternative to the `test, coerce, replace, by` arguments; an object from class `SClassExtension` describing the relation. (Used in internal calls.) | | `doComplete` | when `TRUE`, the class definitions will be augmented with indirect relations as well. (Used in internal calls.) | | `by` | In a call to `setIs`, the name of an intermediary class. Coercion will proceed by first coercing to this class and from there to the target class. (The intermediate coercions have to be valid.) | | `where` | In a call to `setIs`, where to store the metadata defining the relationship. Default is the global environment for calls from the top level of the session or a source file evaluated there. When the call occurs in the top level of a file in the source of a package, the default will be the namespace or environment of the package. Other uses are tricky and not usually a good idea, unless you really know what you are doing. | | `classDef` | Optional class definition for `class` , required internally when `setIs` is called during the initial definition of the class by a call to `[setClass](setclass)`. *Don't* use this argument, unless you really know why you're doing so. | ### Details Arranging for a class to inherit from another class is a key tool in programming. In **R**, there are three basic techniques, the first two providing what is called “simple” inheritance, the preferred form: 1. By the `contains=` argument in a call to `[setClass](setclass)`. This is and should be the most common mechanism. It arranges that the new class contains all the structure of the existing class, and in particular all the slots with the same class specified. The resulting class extension is defined to be `simple`, with important implications for method definition (see the section on this topic below). 2. Making `class1` a subclass of a virtual class either by a call to `[setClassUnion](setclassunion)` to make the subclass a member of a new class union, or by a call to `setIs` to add a class to an existing class union or as a new subclass of an existing virtual class. In either case, the implication should be that methods defined for the class union or other superclass all work correctly for the subclass. This may depend on some similarity in the structure of the subclasses or simply indicate that the superclass methods are defined in terms of generic functions that apply to all the subclasses. These relationships are also generally simple. 3. Supplying `coerce` and `replace` arguments to `setAs`. **R** allows arbitrary inheritance relationships, using the same mechanism for defining coerce methods by a call to `[setAs](setas)`. The difference between the two is simply that `[setAs](setas)` will require a call to `<as>` for a conversion to take place, whereas after the call to `[setIs](setis)`, objects will be automatically converted to the superclass. The automatic feature is the dangerous part, mainly because it results in the subclass potentially inheriting methods that do not work. See the section on inheritance below. If the two classes involved do not actually inherit a large collection of methods, as in the first example below, the danger may be relatively slight. If the superclass inherits methods where the subclass has only a default or remotely inherited method, problems are more likely. In this case, a general recommendation is to use the `[setAs](setas)` mechanism instead, unless there is a strong counter reason. Otherwise, be prepared to override some of the methods inherited. With this caution given, the rest of this section describes what happens when `coerce=` and `replace=` arguments are supplied to `setIs`. The `coerce` and `replace` arguments are functions that define how to coerce a `class1` object to `class2`, and how to replace the part of the subclass object that corresponds to `class2`. The first of these is a function of one argument which should be `from`, and the second of two arguments (`from`, `value`). For details, see the section on coerce functions below . When `by` is specified, the coerce process first coerces to this class and then to `class2`. It's unlikely you would use the `by` argument directly, but it is used in defining cached information about classes. The value returned (invisibly) by `setIs` is the revised class definition of `class1`. ### Coerce, replace, and test functions The `coerce` argument is a function that turns a `class1` object into a `class2` object. The `replace` argument is a function of two arguments that modifies a `class1` object (the first argument) to replace the part of it that corresponds to `class2` (supplied as `value`, the second argument). It then returns the modified object as the value of the call. In other words, it acts as a replacement method to implement the expression `as(object, class2) <- value`. The easiest way to think of the `coerce` and `replace` functions is by thinking of the case that `class1` contains `class2` in the usual sense, by including the slots of the second class. (To repeat, in this situation you would not call `setIs`, but the analogy shows what happens when you do.) The `coerce` function in this case would just make a `class2` object by extracting the corresponding slots from the `class1` object. The `replace` function would replace in the `class1` object the slots corresponding to `class2`, and return the modified object as its value. For additional discussion of these functions, see the documentation of the `[setAs](setas)` function. (Unfortunately, argument `def` to that function corresponds to argument `coerce` here.) The inheritance relationship can also be conditional, if a function is supplied as the `test` argument. This should be a function of one argument that returns `TRUE` or `FALSE` according to whether the object supplied satisfies the relation `is(object, class2)`. Conditional relations between classes are discouraged in general because they require a per-object calculation to determine their validity. They cannot be applied as efficiently as ordinary relations and tend to make the code that uses them harder to interpret. *NOTE: conditional inheritance is not used to dispatch methods.* Methods for conditional superclasses will not be inherited. Instead, a method for the subclass should be defined that tests the conditional relationship. ### Inherited methods A method written for a particular signature (classes matched to one or more formal arguments to the function) naturally assumes that the objects corresponding to the arguments can be treated as coming from the corresponding classes. The objects will have all the slots and available methods for the classes. The code that selects and dispatches the methods ensures that this assumption is correct. If the inheritance was “simple”, that is, defined by one or more uses of the `contains=` argument in a call to `[setClass](setclass)`, no extra work is generally needed. Classes are inherited from the superclass, with the same definition. When inheritance is defined by a general call to `setIs`, extra computations are required. This form of inheritance implies that the subclass does *not* just contain the slots of the superclass, but instead requires the explicit call to the coerce and/or replace method. To ensure correct computation, the inherited method is supplemented by calls to `<as>` before the body of the method is evaluated. The calls to `<as>` generated in this case have the argument `strict = FALSE`, meaning that extra information can be left in the converted object, so long as it has all the appropriate slots. (It's this option that allows simple subclass objects to be used without any change.) When you are writing your coerce method, you may want to take advantage of that option. Methods inherited through non-simple extensions can result in ambiguities or unexpected selections. If `class2` is a specialized class with just a few applicable methods, creating the inheritance relation may have little effect on the behavior of `class1`. But if `class2` is a class with many methods, you may find that you now inherit some undesirable methods for `class1`, in some cases, fail to inherit expected methods. In the second example below, the non-simple inheritance from class `"factor"` might be assumed to inherit S3 methods via that class. But the S3 class is ambiguous, and in fact is `"character"` rather than `"factor"`. For some generic functions, methods inherited by non-simple extensions are either known to be invalid or sufficiently likely to be so that the generic function has been defined to exclude such inheritance. For example `[initialize](new)` methods must return an object of the target class; this is straightforward if the extension is simple, because no change is made to the argument object, but is essentially impossible. For this reason, the generic function insists on only simple extensions for inheritance. See the `simpleInheritanceOnly` argument to `[setGeneric](setgeneric)` for the mechanism. You can use this mechanism when defining new generic functions. If you get into problems with functions that do allow non-simple inheritance, there are two basic choices. Either back off from the `setIs` call and settle for explicit coercing defined by a call to `[setAs](setas)`; or, define explicit methods involving `class1` to override the bad inherited methods. The first choice is the safer, when there are serious problems. ### References Chambers, John M. (2016) *Extending R*, Chapman & Hall. (Chapters 9 and 10.) ### Examples ``` ## Two examples of setIs() with coerce= and replace= arguments ## The first one works fairly well, because neither class has many ## inherited methods do be disturbed by the new inheritance ## The second example does NOT work well, because the new superclass, ## "factor", causes methods to be inherited that should not be. ## First example: ## a class definition (see \link{setClass} for class "track") setClass("trackCurve", contains = "track", slots = c( smooth = "numeric")) ## A class similar to "trackCurve", but with different structure ## allowing matrices for the "y" and "smooth" slots setClass("trackMultiCurve", slots = c(x="numeric", y="matrix", smooth="matrix"), prototype = structure(list(), x=numeric(), y=matrix(0,0,0), smooth= matrix(0,0,0))) ## Automatically convert an object from class "trackCurve" into ## "trackMultiCurve", by making the y, smooth slots into 1-column matrices setIs("trackCurve", "trackMultiCurve", coerce = function(obj) { new("trackMultiCurve", x = obj@x, y = as.matrix(obj@y), smooth = as.matrix(obj@smooth)) }, replace = function(obj, value) { obj@y <- as.matrix(value@y) obj@x <- value@x obj@smooth <- as.matrix(value@smooth) obj}) ## Second Example: ## A class that adds a slot to "character" setClass("stringsDated", contains = "character", slots = c(stamp="POSIXt")) ## Convert automatically to a factor by explicit coerce setIs("stringsDated", "factor", coerce = function(from) factor([email protected]), replace= function(from, value) { [email protected] <- as.character(value); from }) ll <- sample(letters, 10, replace = TRUE) ld <- new("stringsDated", ll, stamp = Sys.time()) levels(as(ld, "factor")) levels(ld) # will be NULL--see comment in section on inheritance above. ## In contrast, a class that simply extends "factor" ## has no such ambiguities setClass("factorDated", contains = "factor", slots = c(stamp="POSIXt")) fd <- new("factorDated", factor(ll), stamp = Sys.time()) identical(levels(fd), levels(as(fd, "factor"))) ```
programming_docs
r None `signature-class` Class "signature" For Method Definitions ----------------------------------------------------------- ### Description This class represents the mapping of some of the formal arguments of a function onto the corresponding classes. It is used for two slots in the `[MethodDefinition](methoddefinition-class)` class. ### Objects from the Class Objects can be created by calls of the form `new("signature", functionDef, ...)`. The `functionDef` argument, if it is supplied as a function object, defines the formal names. The other arguments define the classes. More typically, the objects are created as side effects of defining methods. Either way, note that the classes are expected to be well defined, usually because the corresponding class definitions exist. See the comment on the `package` slot. ### Slots `.Data`: Object of class `"character"` the class names. `names`: Object of class `"character"` the corresponding argument names. `package`: Object of class `"character"` the names of the packages corresponding to the class names. The combination of class name and package uniquely defines the class. In principle, the same class name could appear in more than one package, in which case the `package` information is required for the signature to be well defined. ### Extends Class `"character"`, from data part. Class `"vector"`, by class "character". ### Methods initialize `signature(object = "signature")`: see the discussion of objects from the class, above. ### See Also class `[MethodDefinition](methoddefinition-class)` for the use of this class. r None `SClassExtension-class` Class to Represent Inheritance (Extension) Relations ----------------------------------------------------------------------------- ### Description An object from this class represents a single ‘is’ relationship; lists of these objects are used to represent all the extensions (superclasses) and subclasses for a given class. The object contains information about how the relation is defined and methods to coerce, test, and replace correspondingly. ### Objects from the Class Objects from this class are generated by `[setIs](setis)`, from direct calls and from the `contains=` information in a call to `[setClass](setclass)`, and from class unions created by `[setClassUnion](setclassunion)`. In the last case, the information is stored in defining the *subclasses* of the union class (allowing unions to contain sealed classes). ### Slots `subClass`, `superClass`: The classes being extended: corresponding to the `from`, and `to` arguments to `[setIs](setis)`. `package`: The package to which that class belongs. `coerce`: A function to carry out the as() computation implied by the relation. Note that these functions should *not* be used directly. They only deal with the `strict=TRUE` calls to the `<as>` function, with the full method constructed from this mechanically. `test`: The function that would test whether the relation holds. Except for explicitly specified `test` arguments to `[setIs](setis)`, this function is trivial. `replace`: The method used to implement `as(x, Class) <- value`. `simple`: A `"logical"` flag, `TRUE` if this is a simple relation, either because one class is contained in the definition of another, or because a class has been explicitly stated to extend a virtual class. For simple extensions, the three methods are generated automatically. `by`: If this relation has been constructed transitively, the first intermediate class from the subclass. `dataPart`: A `"logical"` flag, `TRUE` if the extended class is in fact the data part of the subclass. In this case the extended class is a basic class (i.e., a type). `distance`: The distance between the two classes, 1 for directly contained classes, plus the number of generations between otherwise. ### Methods No methods defined with class `"SClassExtension"` in the signature. ### See Also `<is>`, `<as>`, and the `[classRepresentation](classrepresentation-class)` class. r None `S4groupGeneric` S4 Group Generic Functions -------------------------------------------- ### Description Methods can be defined for *group generic functions*. Each group generic function has a number of *member* generic functions associated with it. Methods defined for a group generic function cause the same method to be defined for each member of the group, but a method explicitly defined for a member of the group takes precedence over a method defined, with the same signature, for the group generic. The functions shown in this documentation page all reside in the methods package, but the mechanism is available to any programmer, by calling `[setGroupGeneric](setgroupgeneric)` (provided package methods is attached). ### Usage ``` ## S4 group generics: Arith(e1, e2) Compare(e1, e2) Ops(e1, e2) Logic(e1, e2) Math(x) Math2(x, digits) Summary(x, ..., na.rm = FALSE) Complex(z) ``` ### Arguments | | | | --- | --- | | `x, z, e1, e2` | objects. | | `digits` | number of digits to be used in `round` or `signif`. | | `...` | further arguments passed to or from methods. | | `na.rm` | logical: should missing values be removed? | ### Details Methods can be defined for the group generic functions by calls to `[setMethod](setmethod)` in the usual way. Note that the group generic functions should never be called directly – a suitable error message will result if they are. When metadata for a group generic is loaded, the methods defined become methods for the members of the group, but only if no method has been specified directly for the member function for the same signature. The effect is that group generic definitions are selected before inherited methods but after directly specified methods. For more on method selection, see `[Methods\_Details](methods_details)`. There are also S3 groups `Math`, `Ops`, `Summary` and `Complex`, see `?[S3groupGeneric](../../base/html/groupgeneric)`, with no corresponding **R** objects, but these are irrelevant for S4 group generic functions. The members of the group defined by a particular generic can be obtained by calling `[getGroupMembers](rmethodutils)`. For the group generic functions currently defined in this package the members are as follows: `Arith` `"+"`, `"-"`, `"*"`, `"^"`, `"%%"`, `"%/%"`, `"/"` `Compare` `"=="`, `">"`, `"<"`, `"!="`, `"<="`, `">="` `Logic` `"&"`, `"|"`. `Ops` `"Arith"`, `"Compare"`, `"Logic"` `Math` `"abs"`, `"sign"`, `"sqrt"`, `"ceiling"`, `"floor"`, `"trunc"`, `"cummax"`, `"cummin"`, `"cumprod"`, `"cumsum"`, `"log"`, `"log10"`, `"log2"`, `"log1p"`, `"acos"`, `"acosh"`, `"asin"`, `"asinh"`, `"atan"`, `"atanh"`, `"exp"`, `"expm1"`, `"cos"`, `"cosh"`, `"cospi"`, `"sin"`, `"sinh"`, `"sinpi"`, `"tan"`, `"tanh"`, `"tanpi"`, `"gamma"`, `"lgamma"`, `"digamma"`, `"trigamma"` `Math2` `"round"`, `"signif"` `Summary` `"max"`, `"min"`, `"range"`, `"prod"`, `"sum"`, `"any"`, `"all"` `Complex` `"Arg"`, `"Conj"`, `"Im"`, `"Mod"`, `"Re"` Note that `Ops` merely consists of three sub groups. All the functions in these groups (other than the group generics themselves) are basic functions in **R**. They are not by default S4 generic functions, and many of them are defined as primitives. However, you can still define formal methods for them, both individually and via the group generics. It all works more or less as you might expect, admittedly via a bit of trickery in the background. See [Methods\_Details](methods_details) for details. Note that two members of the `Math` group, `[log](../../base/html/log)` and `[trunc](../../base/html/round)`, have ... as an extra formal argument. Since methods for `Math` will have only one formal argument, you must set a specific method for these functions in order to call them with the extra argument(s). For further details about group generic functions see section 10.5 of the second reference. ### References Chambers, John M. (2016) *Extending R*, Chapman & Hall. (Chapters 9 and 10.) Chambers, John M. (2008) *Software for Data Analysis: Programming with R* Springer. (Section 10.5) ### See Also The function `[callGeneric](callgeneric)` is nearly always relevant when writing a method for a group generic. See the examples below and in section 10.5 of *Software for Data Analysis*. See [S3groupGeneric](../../base/html/groupgeneric) for S3 group generics. ### Examples ``` setClass("testComplex", slots = c(zz = "complex")) ## method for whole group "Complex" setMethod("Complex", "testComplex", function(z) c("groupMethod", callGeneric(z@zz))) ## exception for Arg() : setMethod("Arg", "testComplex", function(z) c("ArgMethod", Arg(z@zz))) z1 <- 1+2i z2 <- new("testComplex", zz = z1) stopifnot(identical(Mod(z2), c("groupMethod", Mod(z1)))) stopifnot(identical(Arg(z2), c("ArgMethod", Arg(z1)))) ``` r None `isSealedMethod` Check for a Sealed Method or Class ---------------------------------------------------- ### Description These functions check for either a method or a class that has been *sealed* when it was defined, and which therefore cannot be re-defined. ### Usage ``` isSealedMethod(f, signature, fdef, where) isSealedClass(Class, where) ``` ### Arguments | | | | --- | --- | | `f` | The quoted name of the generic function. | | `signature` | The class names in the method's signature, as they would be supplied to `[setMethod](setmethod)`. | | `fdef` | Optional, and usually omitted: the generic function definition for `f`. | | `Class` | The quoted name of the class. | | `where` | where to search for the method or class definition. By default, searches from the top environment of the call to `isSealedMethod` or `isSealedClass`, typically the global environment or the namespace of a package containing a call to one of the functions. | ### Details In the **R** implementation of classes and methods, it is possible to seal the definition of either a class or a method. The basic classes (numeric and other types of vectors, matrix and array data) are sealed. So also are the methods for the primitive functions on those data types. The effect is that programmers cannot re-define the meaning of these basic data types and computations. More precisely, for primitive functions that depend on only one data argument, methods cannot be specified for basic classes. For functions (such as the arithmetic operators) that depend on two arguments, methods can be specified if *one* of those arguments is a basic class, but not if both are. Programmers can seal other class and method definitions by using the `sealed` argument to `[setClass](setclass)` or `[setMethod](setmethod)`. ### Value The functions return `FALSE` if the method or class is not sealed (including the case that it is not defined); `TRUE` if it is. ### References Chambers, John M. (2008) *Software for Data Analysis: Programming with R* Springer. (For the R version.) Chambers, John M. (1998) *Programming with Data* Springer (For the original S4 version.) ### Examples ``` ## these are both TRUE isSealedMethod("+", c("numeric", "character")) isSealedClass("matrix") setClass("track", slots = c(x="numeric", y="numeric")) ## but this is FALSE isSealedClass("track") ## and so is this isSealedClass("A Name for an undefined Class") ## and so are these, because only one of the two arguments is basic isSealedMethod("+", c("track", "numeric")) isSealedMethod("+", c("numeric", "track")) ``` r None `MethodDefinition-class` Classes to Represent Method Definitions ----------------------------------------------------------------- ### Description These classes extend the basic class `"function"` when functions are to be stored and used as method definitions. ### Details Method definition objects are functions with additional information defining how the function is being used as a method. The `target` slot is the class signature for which the method will be dispatched, and the `defined` slot the signature for which the method was originally specified (that is, the one that appeared in some call to `[setMethod](setmethod)`). ### Objects from the Class The action of setting a method by a call to `[setMethod](setmethod)` creates an object of this class. It's unwise to create them directly. The class `"SealedMethodDefinition"` is created by a call to `[setMethod](setmethod)` with argument `sealed = TRUE`. It has the same representation as `"MethodDefinition"`. ### Slots `.Data`: Object of class `"function"`; the data part of the definition. `target`: Object of class `"signature"`; the signature for which the method was wanted. `defined`: Object of class `"signature"`; the signature for which a method was found. If the method was inherited, this will not be identical to `target`. `generic`: Object of class `"character"`; the function for which the method was created. ### Extends Class `"function"`, from data part. Class `"PossibleMethod"`, directly. Class `"OptionalMethods"`, by class `"function"`. ### See Also class `[MethodsList](methodslist-class)` for the objects defining sets of methods associated with a particular generic function. The individual method definitions stored in these objects are from class `MethodDefinition`, or an extension. Class `[MethodWithNext](methodwithnext-class)` for an extension used by `[callNextMethod](nextmethod)`. r None `Methods` S4 Class Documentation --------------------------------- ### Description You have navigated to an old link to documentation of S4 methods. For basic use of classes and methods, see [Introduction](introduction); to create new method definitions, see `[setMethod](setmethod)`; for technical details on S4 methods, see [Methods\_Details](methods_details). ### References Chambers, John M. (2016) *Extending R*, Chapman & Hall. (Chapters 9 and 10.) r None `getClass` Get Class Definition -------------------------------- ### Description Get the definition of a class. ### Usage ``` getClass (Class, .Force = FALSE, where) getClassDef(Class, where, package, inherits = TRUE) ``` ### Arguments | | | | --- | --- | | `Class` | the character-string name of the class, often with a `"package"` attribute as noted below under `package`. | | `.Force` | if `TRUE`, return `NULL` if the class is undefined; otherwise, an undefined class results in an error. | | `where` | environment from which to begin the search for the definition; by default, start at the top-level (global) environment and proceed through the search list. | | `package` | the name or environment of the package asserted to hold the definition. If it is a non-empty string it is used instead of `where`, as the first place to look for the class. Note that the package must be loaded but need not be attached. By default, the package attribute of the `Class` argument is used, if any. There will usually be a package attribute if `Class` comes from `class(x)` for some object. | | `inherits` | logical; should the class definition be retrieved from any enclosing environment and also from the cache? If `FALSE` only a definition in the environment `where` will be returned. | ### Details Class definitions are stored in metadata objects in a package namespace or other environment where they are defined. When packages are loaded, the class definitions in the package are cached in an internal table. Therefore, most calls to `getClassDef` will find the class in the cache or fail to find it at all, unless `inherits` is `FALSE`, in which case only the environment(s) defined by `package` or `where` are searched. The class cache allows for multiple definitions of the same class name in separate environments, with of course the limitation that the package attribute or package name must be provided in the call to ### Value The object defining the class. If the class definition is not found, `getClassDef` returns `NULL`, while `getClass`, which calls `getClassDef`, either generates an error or, if `.Force` is `TRUE`, returns a simple definition for the class. The latter case is used internally, but is not typically sensible in user code. The non-null returned value is an object of class `[classRepresentation](classrepresentation-class)`. Use functions such as `[setClass](setclass)` and `[setClassUnion](setclassunion)` to create class definitions. ### References Chambers, John M. (2016) *Extending R*, Chapman & Hall. (Chapters 9 and 10.) ### See Also [classRepresentation](classrepresentation-class), `[setClass](setclass)`, `[isClass](findclass)`. ### Examples ``` getClass("numeric") ## a built in class cld <- getClass("thisIsAnUndefinedClass", .Force = TRUE) cld ## a NULL prototype ## If you are really curious: utils::str(cld) ## Whereas these generate errors: try(getClass("thisIsAnUndefinedClass")) try(getClassDef("thisIsAnUndefinedClass")) ``` r None `refClass` Objects With Fields Treated by Reference (OOP-style) ---------------------------------------------------------------- ### Description The software described here allows packages to define *reference classes* that behave in the style of “OOP” languages such as Java and C++. This model for OOP differs from the functional model implemented by S4 (and S3) classes and methods, in which methods are defined for generic functions. Methods for reference classes are “encapsulated” in the class definition. Computations with objects from reference classes invoke methods on them and extract or set their fields, using the ``$`` operator in **R**. The field and method computations potentially modify the object. All computations referring to the objects see the modifications, in contrast to the usual functional programming model in **R**. A call to `setRefClass` in the source code for a package defines the class and returns a generator object. Subsequent calls to the `$methods()` method of the generator will define methods for the class. As with functional classes, if the class is exported from the package, it will be available when the package is loaded. Methods are **R** functions. In their usual implementation, they refer to fields and other methods of the class directly by name. See the section on “Writing Reference Methods”. As with functional classes, reference classes can inherit from other reference classes via a `contains=` argument to `setRefClass`. Fields and methods will be inherited, except where the new class overrides method definitions. See the section on “Inheritance”. ### Usage ``` setRefClass(Class, fields = , contains = , methods =, where =, inheritPackage =, ...) getRefClass(Class, where =) ``` ### Arguments | | | | --- | --- | | `Class` | character string name for the class. In the call to `getRefClass()` this argument can also be any object from the relevant class. | | `fields` | either a character vector of field names or a named list of the fields. The resulting fields will be accessed with reference semantics (see the section on “Reference Objects”). If the argument is a list, each element of the list should usually be the character string name of a class, in which case the object in the field must be from that class or a subclass. An alternative, but not generally recommended, is to supply an *accessor function*; see the section on “Implementation” for accessor functions and the related internal mechanism. Note that fields are distinct from slots. Reference classes should not define class-specific slots. See the note on slots in the “Implementation” section. | | `contains` | optional vector of superclasses for this class. If a superclass is also a reference class, the fields and class-based methods will be inherited. | | `methods` | a named list of function definitions that can be invoked on objects from this class. These can also be created by invoking the `$methods` method on the generator object returned. See the section on “Writing Reference Methods” for details. | | `where` | for `setRefClass`, the environment in which to store the class definition. Should be omitted in calls from a package's source code. For `getRefClass`, the environment from which to search for the definition. If the package is not loaded or you need to be specific, use `[asNamespace](../../base/html/ns-internal)` with the package name. | | `inheritPackage` | Should objects from the new class inherit the package environment of a contained superclass? Default `FALSE`. See the Section “Inter-Package Superclasses and External Methods”. | | `...` | other arguments to be passed to `[setClass](setclass)`. | ### Value `setRefClass()` returns a generator function suitable for creating objects from the class, invisibly. A call to this function takes any number of arguments, which will be passed on to the initialize method. If no `initialize` method is defined for the class or one of its superclasses, the default method expects named arguments with the name of one of the fields and unnamed arguments, if any, that are objects from one of the superclasses of this class (but only superclasses that are themselves reference classes have any effect). The generator function is similar to the S4 generator function returned by `[setClass](setclass)`. In addition to being a generator function, however, it is also a reference class generator object, with reference class methods for various utilities. See the section on reference class generator objects below. `getRefClass()` also returns the generator function for the class. Note that the package slot in the value is the correct package from the class definition, regardless of the `where` argument, which is used only to find the class if necessary. ### Reference Objects Normal objects in **R** are passed as arguments in function calls consistently with functional programming semantics; that is, changes made to an object passed as an argument are local to the function call. The object that supplied the argument is unchanged. The functional model (sometimes called pass-by-value, although this is inaccurate for **R**) is suitable for many statistical computations and is implicit, for example, in the basic **R** software for fitting statistical models. In some other situations, one would like all the code dealing with an object to see the exact same content, so that changes made in any computation would be reflected everywhere. This is often suitable if the object has some “objective” reality, such as a window in a user interface. In addition, commonly used languages, including Java, C++ and many others, support a version of classes and methods assuming reference semantics. The corresponding programming mechanism is to invoke a method on an object. In the **R** syntax we use `"$"` for this operation; one invokes a method, `m1` say, on an object `x` by the expression `x$m1(...)`. Methods in this paradigm are associated with the object, or more precisely with the class of the object, as opposed to methods in a function-based class/method system, which are fundamentally associated with the function (in **R**, for example, a generic function in an **R** session has a table of all its currently known methods). In this document “methods for a class” as opposed to “methods for a function” will make the distinction. Objects in this paradigm usually have named fields on which the methods operate. In the **R** implementation, the fields are defined when the class is created. The field itself can optionally have a specified class, meaning that only objects from this class or one of its subclasses can be assigned to the field. By default, fields have class `"ANY"`. Fields are accessed by reference. In particular, invoking a method may modify the content of the fields. Programming for such classes involves writing new methods for a particular class. In the **R** implementation, these methods are **R** functions, with zero or more formal arguments. For standard reference methods, the object itself is not an explicit argument to the method. Instead, fields and methods for the class can be referred to by name in the method definition. The implementation uses **R** environments to make fields and other methods available by name within the method. Specifically, the parent environment of the method is the object itself. See the section on “Writing Reference Methods”. This special use of environments is optional. If a method is defined with an initial formal argument `.self`, that will be passed in as the whole object, and the method follows the standard rules for any function in a package. See the section on “External Methods” The goal of the software described here is to provide a uniform programming style in **R** for software dealing with reference classes, whether implemented directly in **R** or through an interface to one of the OOP languages. ### Writing Reference Methods Reference methods are functions supplied as elements of a named list, either when invoking `$methods()` on a generator object `g` or as the argument `methods` in a call to `setRefClass`. The two mechanisms have the same effect, but the first makes the code more readable. Methods are written as ordinary **R** functions but have some special features and restrictions in their usual form. In contrast to some other languages (e.g., Python), the object itself does not need to be an argument in the method definition. The body of the function can contain calls to any other reference method, including those inherited from other reference classes and may refer to methods and to fields in the object by name. Alternatively, a method may be an *external* method. This is signalled by `.self` being the first formal argument to the method. The body of the method then works like any ordinary function. The methods are called like other methods (without the `.self` argument, which is supplied internally and always refers to the object itself). Inside the method, fields and other methods are accessed in the form `.self$x`. External methods exist so that reference classes can inherit the package environment of superclasses in other packages; see the section on “External Methods”. Fields may be modified in a method by using the non-local assignment operator, `<<-`, as in the `$edit` and `$undo` methods in the example below. Note that non-local assignment is required: a local assignment with the `<-` operator just creates a local object in the function call, as it would in any **R** function. When methods are installed, a heuristic check is made for local assignments to field names and a warning issued if any are detected. Reference methods should be kept simple; if they need to do some specialized **R** computation, that computation should use a separate **R** function that is called from the reference method. Specifically, methods can not use special features of the enclosing environment mechanism, since the method's environment is used to access fields and other methods. In particular, methods should not use non-exported entries in the package's namespace, because the methods may be inherited by a reference class in another package. Two method names are interpreted specially, `initialize` and `finalize`. If an `initialize` method is defined, it will be invoked when an object is generated from the class. See the discussion of method `$new(...)` in the section “Initialization Methods”. If a `finalize` method is defined, a function will be [registered](../../base/html/reg.finalizer) to invoke it before the environment in the object is discarded by the garbage collector; finalizers are registered with `atexit=TRUE`, and so are also run at the end of **R** sessions. See the matrix viewer example for both initialize and finalize methods. Reference methods can not themselves be generic functions; if you want additional function-based method dispatch, write a separate generic function and call that from the method. Two special object names are available. The entire object can be referred to in a method by the reserved name `.self`. The object `.refClassDef` contains the definition of the class of the object. These are accessed as fields but are read-only, with one exception. In principal, the `.self` field can be modified in the `$initialize` method, because the object is still being created at this stage. This is not recommended, as it can invalidate the object with respect to its class. The methods available include methods inherited from superclasses, as discussed in the section “Inheritance”. Only methods actually used will be included in the environment corresponding to an individual object. To declare that a method requires a particular other method, the first method should include a call to `$usingMethods()` with the name of the other method as an argument. Declaring the methods this way is essential if the other method is used indirectly (e.g., via `[sapply](../../base/html/lapply)()` or `[do.call](../../base/html/do.call)()`). If it is called directly, code analysis will find it. Declaring the method is harmless in any case, however, and may aid readability of the source code. Documentation for the methods can be obtained by the `$help` method for the generator object. Methods for classes are not documented in the `Rd` format used for **R** functions. Instead, the `$help` method prints the calling sequence of the method, followed by self-documentation from the method definition, in the style of Python. If the first element of the body of the method is a literal character string (possibly multi-line), that string is interpreted as documentation. See the method definitions in the example. ### Initialization Methods If the class has a method defined for `$initialize()`, this method will be called once the reference object has been created. You should write such a method for a class that needs to do some special initialization. In particular, a reference method is recommended rather than a method for the S4 generic function `initialize()`, because some special initialization is required for reference objects *before* the initialization of fields. As with S4 classes, methods are written for `$initialize()` and not for `$new()`, both for the previous reason and also because `$new()` is invoked on the generator object and would be a method for that class. The default method for `$initialize()` is equivalent to invoking the method `$initFields(...)`. Named arguments assign initial values to the corresponding fields. Unnamed arguments must be objects from this class or a reference superclass of this class. Fields will be initialized to the contents of the fields in such objects, but named arguments override the corresponding inherited fields. Note that fields are simply assigned. If the field is itself a reference object, that object is not copied. The new and previous object will share the reference. Also, a field assigned from an unnamed argument counts as an assignment for locked fields. To override an inherited value for a locked field, the new value must be one of the named arguments in the initializing call. A later assignment of the field will result in an error. Initialization methods need some care in design. The generator for a reference class will be called with no arguments, for example when copying the object. To ensure that these calls do not fail, the method must have defaults for all arguments or check for `missing()`. The method should include `...` as an argument and pass this on via `$callSuper()` (or `$initFields()` if you know that your superclasses have no initialization methods). This allows future class definitions that subclass this class, with additional fields. ### Inheritance Reference classes inherit from other reference classes by using the standard **R** inheritance; that is, by including the superclasses in the `contains=` argument when creating the new class. The names of the reference superclasses are in slot `refSuperClasses` of the class definition. Reference classes can inherit from ordinary S4 classes also, but this is usually a bad idea if it mixes reference fields and non-reference slots. See the comments in the section on “Implementation”. Class fields are inherited. A class definition can override a field of the same name in a superclass only if the overriding class is a subclass of the class of the inherited field. This ensures that a valid object in the field remains valid for the superclass as well. Inherited methods are installed in the same way as directly specified methods. The code in a method can refer to inherited methods in the same way as directly specified methods. A method may override a method of the same name in a superclass. The overriding method can call the superclass method by `callSuper(...)` as described below. ### Methods Provided for all Objects All reference classes inherit from the class `"envRefClass"`. All reference objects can use the following methods. `$callSuper(...)` Calls the method inherited from a reference superclass. The call is meaningful only from within another method, and will be resolved to call the inherited method of the same name. The arguments to `$callSuper` are passed to the superclass version. See the matrix viewer class in the example. Note that the intended arguments for the superclass method must be supplied explicitly; there is no convention for supplying the arguments automatically, in contrast to the similar mechanism for functional methods. `$copy(shallow = FALSE)` Creates a copy of the object. With reference classes, unlike ordinary **R** objects, merely assigning the object with a different name does not create an independent copy. If `shallow` is `FALSE`, any field that is itself a reference object will also be copied, and similarly recursively for its fields. Otherwise, while reassigning a field to a new reference object will have no side effect, modifying such a field will still be reflected in both copies of the object. The argument has no effect on non-reference objects in fields. When there are reference objects in some fields but it is asserted that they will not be modified, using `shallow = TRUE` will save some memory and time. `$field(name, value)` With one argument, returns the field of the object with character string `name`. With two arguments, the corresponding field is assigned `value`. Assignment checks that `name` specifies a valid field, but the single-argument version will attempt to get anything of that name from the object's environment. The `$field()` method replaces the direct use of a field name, when the name of the field must be calculated, or for looping over several fields. `$export(Class)` Returns the result of coercing the object to `Class` (typically one of the superclasses of the object's class). Calling the method has no side effect on the object itself. `$getRefClass()`; `$getClass()` These return respectively the generator object and the formal class definition for the reference class of this object, efficiently. `$import(value, Class = class(value))` Import the object `value` into the current object, replacing the corresponding fields in the current object. Object `value` must come from one of the superclasses of the current object's class. If argument `Class` is supplied, `value` is first coerced to that class. `$initFields(...)` Initialize the fields of the object from the supplied arguments. This method is usually only called from a class with a `$initialize()` method. It corresponds to the default initialization for reference classes. If there are slots and non-reference superclasses, these may be supplied in the ... argument as well. Typically, a specialized `$initialize()` method carries out its own computations, then invokes `$initFields()` to perform standard initialization, as shown in the `matrixViewer` class in the example below. `$show()` This method is called when the object is printed automatically, analogously to the `<show>` function. A general method is defined for class `"envRefClass"`. User-defined reference classes will often define their own method: see the Example below. Note two points in the example. As with any `show()` method, it is a good idea to print the class explicitly to allow for subclasses using the method. Second, to call the *function* `show()` from the method, as opposed to the `$show()` method itself, refer to `methods::show()` explicitly. `$trace(what, ...)`, `$untrace(what)` Apply the tracing and debugging facilities of the `[trace](../../base/html/trace)` function to the reference method `what`. All the arguments of the `[trace](../../base/html/trace)` function can be supplied, except for `signature`, which is not meaningful. The reference method can be invoked on either an object or the generator for the class. See the section on Debugging below for details. `$usingMethods(...)` Reference methods used by this method are named as the arguments either quoted or unquoted. In the code analysis phase of installing the the present method, the declared methods will be included. It is essential to declare any methods used in a nonstandard way (e.g., via an apply function). Methods called directly do not need to be declared, but it is harmless to do so. `$usingMethods()` does nothing at run time. Objects also inherit two reserved fields: `.self` a reference to the entire object; `.refClassDef` the class definition. The defined fields should not override these, and in general it is unwise to define a field whose name begins with `"."`, since the implementation may use such names for special purposes. ### External Methods; Inter-Package Superclasses The environment of a method in a reference class is the object itself, as an environment. This allows the method to refer directly to fields and other methods, without using the whole object and the `"$"` operator. The parent of that environment is the namespace of the package in which the reference class is defined. Computations in the method have access to all the objects in the package's namespace, exported or not. When defining a class that contains a reference superclass in another package, there is an ambiguity about which package namespace should have that role. The argument `inheritPackage` to `setRefClass()` controls whether the environment of new objects should inherit from an inherited class in another package or continue to inherit from the current package's namespace. If the superclass is “lean”, with few methods, or exists primarily to support a family of subclasses, then it may be better to continue to use the new package's environment. On the other hand, if the superclass was originally written as a standalone, this choice may invalidate existing superclass methods. For the superclass methods to continue to work, they must use only exported functions in their package and the new package must import these. Either way, some methods may need to be written that do *not* assume the standard model for reference class methods, but behave essentially as ordinary functions would in dealing with reference class objects. The mechanism is to recognize *external methods*. An external method is written as a function in which the first argument, named `.self`, stands for the reference class object. This function is supplied as the definition for a reference class method. The method will be called, automatically, with the first argument being the current object and the other arguments, if any, passed along from the actual call. Since an external method is an ordinary function in the source code for its package, it has access to all the objects in the namespace. Fields and methods in the reference class must be referred to in the form `.self$name`. If for some reason you do not want to use `.self` as the first argument, a function `f()` can be converted explicitly as `externalRefMethod(f)`, which returns an object of class `"externalRefMethod"` that can be supplied as a method for the class. The first argument will still correspond to the whole object. External methods can be supplied for any reference class, but there is no obvious advantage unless they are needed. They are more work to write, harder to read and (slightly) slower to execute. *NOTE:* If you are the author of a package whose reference classes are likely to be subclassed in other packages, you can avoid these questions entirely by writing methods that *only* use exported functions from your package, so that all the methods will work from another package that imports yours. ### Reference Class Generators The call to `setRefClass` defines the specified class and returns a “generator function” object for that class. This object has class `"refObjectGenerator"`; it inherits from `"function"` via `"classGeneratorFunction"` and can be called to generate new objects from the reference class. The returned object is also a reference class object, although not of the standard construction. It can be used to invoke reference methods and access fields in the usual way, but instead of being implemented directly as an environment it has a subsidiary generator object as a slot, a standard reference object (of class `"refGeneratorSlot"`). Note that if one wanted to extend the reference class generator capability with a subclass, this should be done by subclassing `"refGeneratorSlot"`, not `"refObjectGenerator"`. The fields are `def`, the class definition, and `className`, the character string name of the class. Methods generate objects from the class, to access help on reference methods, and to define new reference methods for the class. The currently available methods are: `$new(...)` This method is equivalent to calling the generator function returned by `setRefClass`. `$help(topic)` Prints brief help on the topic. The topics recognized are reference method names, quoted or not. The information printed is the calling sequence for the method, plus self-documentation if any. Reference methods can have an initial character string or vector as the first element in the body of the function defining the method. If so, this string is taken as self-documentation for the method (see the section on “Writing Reference Methods” for details). If no topic is given or if the topic is not a method name, the definition of the class is printed. `$methods(...)` With no arguments, returns the names of the reference methods for this class. With one character string argument, returns the method of that name. Named arguments are method definitions, which will be installed in the class, as if they had been supplied in the `methods` argument to `setRefClass()`. Supplying methods in this way, rather than in the call to `setRefClass()`, is recommended for the sake of clearer source code. See the section on “Writing Reference Methods” for details. All methods for a class should be defined in the source code that defines the class, typically as part of a package. In particular, methods can not be redefined in a class in an attached package with a namespace: The class method checks for a locked binding of the class definition. The new methods can refer to any currently defined method by name (including other methods supplied in this call to `$methods()`). Note though that previously defined methods are not re-analyzed meaning that they will not call the new method (unless it redefines an existing method of the same name). To remove a method, supply `NULL` as its new definition. `$fields()` Returns a list of the fields, each with its corresponding class. Fields for which an accessor function was supplied in the definition have class `"activeBindingFunction"`. `$lock(...)` The fields named in the arguments are locked; specifically, after the lock method is called, the field may be set once. Any further attempt to set it will generate an error. If called with no arguments, the method returns the names of the locked fields. Fields that are defined by an explicit accessor function can not be locked (on the other hand, the accessor function can be defined to generate an error if called with an argument). All code to lock fields should normally be part of the definition of a class; that is, the read-only nature of the fields is meant to be part of the class definition, not a dynamic property added later. In particular, fields can not be locked in a class in an attached package with a namespace: The class method checks for a locked binding of the class definition. Locked fields can not be subsequently unlocked. `$trace(what, ..., classMethod = FALSE)` Establish a traced version of method `what` for objects generated from this class. The generator object tracing works like the `$trace()` method for objects from the class, with two differences. Since it changes the method definition in the class object itself, tracing applies to all objects, not just the one on which the trace method is invoked. Second, the optional argument `classMethod = TRUE` allows tracing on the methods of the generator object itself. By default, `what` is interpreted as the name of a method in the class for which this object is the generator. `$accessors(...)` A number of systems using the OOP programming paradigm recommend or enforce *getter and setter methods* corresponding to each field, rather than direct access by name. If you like this style and want to extract a field named `abc` by `x$getAbc()` and assign it by `x$setAbc(value)`, the `$accessors` method is a convenience function that creates such getter and setter methods for the specified fields. Otherwise there is no reason to use this mechanism. In particular, it has nothing to do with the general ability to define fields by functions as described in the section on “Reference Objects”. ### Implementation; Reference Classes as S4 Classes Reference classes are implemented as S4 classes with a data part of type `"environment"`. Fields correspond to named objects in the environment. A field associated with a function is implemented as an [active binding](../../base/html/bindenv). In particular, fields with a specified class are implemented as a special form of active binding to enforce valid assignment to the field. As a related feature, the element in the `fields=` list supplied to `setRefClass` can be an *accessor function*, a function of one argument that returns the field if called with no argument or sets it to the value of the argument otherwise. Accessor functions are used internally and for inter-system interface applications, but not generally recommended as they blur the concept of fields as data within the object. A field, say `data`, can be accessed generally by an expression of the form `x$data` for any object from the relevant class. In an internal method for this class, the field can be accessed by the name `data`. A field that is not locked can be set by an expression of the form `x$data <- value`. Inside an internal method, a field can be assigned by an expression of the form `x <<- value`. Note the [non-local assignment](../../base/html/assignops) operator. The standard **R** interpretation of this operator works to assign it in the environment of the object. If the field has an accessor function defined, getting and setting will call that function. When a method is invoked on an object, the function defining the method is installed in the object's environment, with the same environment as the environment of the function. Reference classes can have validity methods in the same sense as any S4 class (see `[setValidity](validobject)`). Such methods are often a good idea; they will be called by calling `[validObject](validobject)` and a validity method, if one is defined, will be called when a reference object is created (from version 3.4 of **R** on). Just remember that these are S4 methods. The function will be called with the `object` as its argument. Fields and methods must be accessed using `$`. *Note: Slots.* Because of the implementation, new reference classes can inherit from non-reference S4 classes as well as reference classes, and can include class-specific slots in the definition. This is usually a bad idea, if the slots from the non-reference class are thought of as alternatives to fields. Slots will as always be treated functionally. Therefore, changes to the slots and the fields will behave inconsistently, mixing the functional and reference paradigms for properties of the same object, conceptually unclear and prone to errors. In addition, the initialization method for the class will have to sort out fields from slots, with a good chance of creating anomalous behavior for subclasses of this class. Inheriting from a [class union](setclassunion), however, is a reasonable strategy (with all members of the union likely to be reference classes). ### Debugging The standard **R** debugging and tracing facilities can be applied to reference methods. Reference methods can be passed to `[debug](../../base/html/debug)` and its relatives from an object to debug further method invocations on that object; for example, `debug(xx$edit)`. Somewhat more flexible use is available for a reference method version of the `[trace](../../base/html/trace)` function. A corresponding `$trace()` reference method is available for either an object or for the reference class generator (`xx$trace()` or `mEdit$trace()` in the example below). Using `$trace()` on an object sets up a tracing version for future invocations of the specified method for that object. Using `$trace()` on the generator for the class sets up a tracing version for all future objects from that class (and sometimes for existing objects from the class if the method is not declared or previously invoked). In either case, all the arguments to the standard `[trace](../../base/html/trace)` function are available, except for `signature=` which is meaningless since reference methods can not be S4 generic functions. This includes the typical style `trace(what, browser)` for interactive debugging and `trace(what, edit = TRUE)` to edit the reference method interactively. ### References Chambers, John M. (2016) *Extending R*, Chapman & Hall. (Chapters 9 and 11.) ### Examples ``` ## a simple editor for matrix objects. Method $edit() changes some ## range of values; method $undo() undoes the last edit. mEdit <- setRefClass("mEdit", fields = list( data = "matrix", edits = "list")) ## The basic edit, undo methods mEdit$methods( edit = function(i, j, value) { ## the following string documents the edit method 'Replaces the range [i, j] of the object by value. ' backup <- list(i, j, data[i,j]) data[i,j] <<- value edits <<- c(edits, list(backup)) invisible(value) }, undo = function() { 'Undoes the last edit() operation and update the edits field accordingly. ' prev <- edits if(length(prev)) prev <- prev[[length(prev)]] else stop("No more edits to undo") edit(prev[[1]], prev[[2]], prev[[3]]) ## trim the edits list length(edits) <<- length(edits) - 2 invisible(prev) }) ## A method to automatically print objects mEdit$methods( show = function() { 'Method for automatically printing matrix editors' cat("Reference matrix editor object of class", classLabel(class(.self)), "\n") cat("Data: \n") methods::show(data) cat("Undo list is of length", length(edits), "\n") } ) xMat <- matrix(1:12,4,3) xx <- mEdit(data = xMat) xx$edit(2, 2, 0) xx xx$undo() mEdit$help("undo") stopifnot(all.equal(xx$data, xMat)) utils::str(xx) # show fields and names of methods ## A method to save the object mEdit$methods( save = function(file) { 'Save the current object on the file in R external object format. ' base::save(.self, file = file) } ) tf <- tempfile() xx$save(tf) ## Not run: ## Inheriting a reference class: a matrix viewer mv <- setRefClass("matrixViewer", fields = c("viewerDevice", "viewerFile"), contains = "mEdit", methods = list( view = function() { dd <- dev.cur(); dev.set(viewerDevice) devAskNewPage(FALSE) matplot(data, main = paste("After",length(edits),"edits")) dev.set(dd)}, edit = # invoke previous method, then replot function(i, j, value) { callSuper(i, j, value) view() })) ## initialize and finalize methods mv$methods( initialize = function(file = "./matrixView.pdf", ...) { viewerFile <<- file pdf(viewerFile) viewerDevice <<- dev.cur() dev.set(dev.prev()) callSuper(...) }, finalize = function() { dev.off(viewerDevice) }) ## debugging an object: call browser() in method $edit() xx$trace(edit, browser) ## debugging all objects from class mEdit in method $undo() mEdit$trace(undo, browser) ## End(Not run) ```
programming_docs
r None `MethodsList-class` Class MethodsList, Defunct Representation of Methods ------------------------------------------------------------------------- ### Description This class of objects was used in the original implementation of the package to control method dispatch. Its use is now defunct, but object appear as the default method slot in generic functions. This and any other remaining uses will be removed in the future. For the modern alternative, see [listOfMethods](findmethods). The details in this documentation are retained to allow analysis of old-style objects. ### Details Suppose a function `f` has formal arguments `x` and `y`. The methods list object for that function has the object `as.name("x")` as its `argument` slot. An element of the methods named `"track"` is selected if the actual argument corresponding to `x` is an object of class `"track"`. If there is such an element, it can generally be either a function or another methods list object. In the first case, the function defines the method to use for any call in which `x` is of class `"track"`. In the second case, the new methods list object defines the available methods depending on the remaining formal arguments, in this example, `y`. Each method corresponds conceptually to a *signature*; that is a named list of classes, with names corresponding to some or all of the formal arguments. In the previous example, if selecting class `"track"` for `x`, finding that the selection was another methods list and then selecting class `"numeric"` for `y` would produce a method associated with the signature `x = "track", y = "numeric"`. ### Slots `argument`: Object of class `"name"`. The name of the argument being used for dispatch at this level. `methods`: A named list of the methods (and method lists) defined *explicitly* for this argument. The names are the names of classes, and the corresponding element defines the method or methods to be used if the corresponding argument has that class. See the details below. `allMethods`: A named list, contains all the directly defined methods from the `methods` slot, plus any inherited methods. Ignored when methods tables are used for dispatch (see [Methods\_Details](methods_details)). ### Extends Class `"OptionalMethods"`, directly. r None `implicitGeneric` Manage Implicit Versions of Generic Functions ---------------------------------------------------------------- ### Description The implicit generic mechanism stores generic versions of functions in a table in a package. The package does not want the current version of the function to be a generic, however, and retains the non-generic version. When a call to `[setMethod](setmethod)` or `[setGeneric](setgeneric)` creates a generic version for one of these functions, the object in the table is used. This mechanism is only needed if special arguments were used to create the generic; e.g., the `signature` or the `valueClass` options. Function `implicitGeneric()` returns the implicit generic version, `setGenericImplicit()` turns a generic implicit, `prohibitGeneric()` prevents your function from being made generic, and `registerImplicitGenerics()` saves a set of implicit generic definitions in the cached table of the current session. ### Usage ``` implicitGeneric(name, where, generic) setGenericImplicit(name, where, restore = TRUE) prohibitGeneric(name, where) registerImplicitGenerics(what, where) ``` ### Arguments | | | | --- | --- | | `name` | Character string name of the function. | | `where` | Package or environment in which to register the implicit generics. When using the functions from the top level of your own package source, this argument should be omitted. | | `generic` | Obsolete, and likely to be deprecated. | | `restore` | Should the non-generic version of the function be restored?. | | `what` | Optional table of the implicit generics to register, but nearly always omitted, when it defaults to a standard metadata name. | ### Details Multiple packages may define methods for the same function, to apply to classes defined in that package. Arithmetic and other operators, `plot()` and many other basic computations are typical examples. It's essential that all such packages write methods for the *same* definition of the generic function. So long as that generic uses the default choice for signature and other parameters, nothing needs to be done. If the generic has special properties, these need to be ensured for all packages creating methods for it. The simplest solution is just to make the function generic in the package that originally owned it. If for some reason the owner(s) of that package are unwilling to do this, the alternative is to define the correct generic, save it in a special table and restore the non-generic version by calling `setGenericImplicit`. Note that the package containing the function can define methods for the implicit generic as well; when the implicit generic is made a real generic, those methods will be included. The usual reason for having a non-default implicit generic is to provide a non-default signature, and the usual reason for *that* is to allow lazy evaluation of some arguments. All arguments in the signature of a generic function must be evaluated at the time the function needs to select a method. In the base function `with()` in the example below, evaluation of the argument `expr` must be delayed; therefore, it is excluded from the signature. If you want to completely prohibit anyone from turning your function into a generic, call `prohibitGeneric()`. Function `implicitGeneric()` returns the implicit generic version of the named function. If there is no table of these or if this function is not in the table, the result of a simple call `setGeneric(name)` is returned. ### Value Function `implicitGeneric()` returns the implicit generic definition (and caches that definition the first time if it has to construct it). The other functions exist for their side effect and return nothing useful. ### Implicit Generics for Base Functions Implicit generic versions exist for some functions in the packages supplied in the distribution of **R** itself. These are stored in the ‘methods’ package itself and will always be available. As emphasized repeatedly in the documentation, `[setGeneric](setgeneric)()` calls for a function in another package should never have non-default settings for arguments such as `signature`. The reasoning applies specially to functions in supplied packages, since methods for these are likely to exist in multiple packages. A call to `implicitGeneric()` will show the generic version. ### See Also `[setGeneric](setgeneric)` ### Examples ``` ### How we would make the function with() into a generic: ## Since the second argument, 'expr' is used literally, we want ## with() to only have "data" in the signature. ## Not run: setGeneric("with", signature = "data") ## Now we could predefine methods for "with" if we wanted to. ## When ready, we store the generic as implicit, and restore the original setGenericImplicit("with") ## End(Not run) implicitGeneric("with") # (This implicit generic is stored in the 'methods' package.) ``` r None `Classes_Details` Class Definitions ------------------------------------ ### Description Class definitions are objects that contain the formal definition of a class of **R** objects, usually referred to as an S4 class, to distinguish them from the informal S3 classes. This document gives an overview of S4 classes; for details of the class representation objects, see help for the class `[classRepresentation](classrepresentation-class)`. ### Metadata Information When a class is defined, an object is stored that contains the information about that class. The object, known as the *metadata* defining the class, is not stored under the name of the class (to allow programmers to write generating functions of that name), but under a specially constructed name. To examine the class definition, call `[getClass](getclass)`. The information in the metadata object includes: Slots: The data contained in an object from an S4 class is defined by the *slots* in the class definition. Each slot in an object is a component of the object; like components (that is, elements) of a list, these may be extracted and set, using the function `<slot>()` or more often the operator `"[@](../../base/html/slotop)"`. However, they differ from list components in important ways. First, slots can only be referred to by name, not by position, and there is no partial matching of names as with list elements. All the objects from a particular class have the same set of slot names; specifically, the slot names that are contained in the class definition. Each slot in each object always is an object of the class specified for this slot in the definition of the current class. The word “is” corresponds to the **R** function of the same name (`<is>`), meaning that the class of the object in the slot must be the same as the class specified in the definition, or some class that extends the one in the definition (a *subclass*). A special slot name, `.Data`, stands for the ‘data part’ of the object. An object from a class with a data part is defined by specifying that the class contains one of the **R** object types or one of the special pseudo-classes, `matrix` or `array`, usually because the definition of the class, or of one of its superclasses, has included the type or pseudo-class in its `contains` argument. A second special slot name, `.xData`, is used to enable inheritance from abnormal types such as `"environment"` See the section on inheriting from non-S4 classes for details on the representation and for the behavior of S3 methods with objects from these classes. Some slot names correspond to attributes used in old-style S3 objects and in **R** objects without an explicit class, for example, the `names` attribute. If you define a class for which that attribute will be set, such as a subclass of named vectors, you should include `"names"` as a slot. See the definition of class `"namedList"` for an example. Using the `names()` assignment to set such names will generate a warning if there is no names slot and an error if the object in question is not a vector type. A slot called `"names"` can be used anywhere, but only if it is assigned as a slot, not via the default `names()` assignment. Superclasses: The definition of a class includes the *superclasses* —the classes that this class extends. A class `Fancy`, say, extends a class `Simple` if an object from the `Fancy` class has all the capabilities of the `Simple` class (and probably some more as well). In particular, and very usefully, any method defined to work for a `Simple` object can be applied to a `Fancy` object as well. This relationship is expressed equivalently by saying that `Simple` is a superclass of `Fancy`, or that `Fancy` is a subclass of `Simple`. The direct superclasses of a class are those superclasses explicitly defined. Direct superclasses can be defined in three ways. Most commonly, the superclasses are listed in the `contains=` argument in the call to `[setClass](setclass)` that creates the subclass. In this case the subclass will contain all the slots of the superclass, and the relation between the class is called *simple*, as it in fact is. Superclasses can also be defined explicitly by a call to `[setIs](setis)`; in this case, the relation requires methods to be specified to go from subclass to superclass. Thirdly, a class union is a superclass of all the members of the union. In this case too the relation is simple, but notice that the relation is defined when the superclass is created, not when the subclass is created as with the `contains=` mechanism. The definition of a superclass will also potentially contain its own direct superclasses. These are considered (and shown) as superclasses at distance 2 from the original class; their direct superclasses are at distance 3, and so on. All these are legitimate superclasses for purposes such as method selection. When superclasses are defined by including the names of superclasses in the `contains=` argument to `[setClass](setclass)`, an object from the class will have all the slots defined for its own class *and* all the slots defined for all its superclasses as well. The information about the relation between a class and a particular superclass is encoded as an object of class `[SClassExtension](sclassextension-class)`. A list of such objects for the superclasses (and sometimes for the subclasses) is included in the metadata object defining the class. If you need to compute with these objects (for example, to compare the distances), call the function `[extends](is)` with argument `fullInfo=TRUE`. Prototype: The objects from a class created by a call to `<new>` are defined by the *prototype* object for the class and by additional arguments in the call to `<new>`, which are passed to a method for that class for the function `[initialize](new)`. Each class representation object contains a prototype object for the class (although for a virtual class the prototype may be `NULL`). The prototype object must have values for all the slots of the class. By default, these are the prototypes of the corresponding slot classes. However, the definition of the class can specify any valid object for any of the slots. ### Basic classes There are a number of ‘basic’ classes, corresponding to the ordinary kinds of data occurring in **R**. For example, `"numeric"` is a class corresponding to numeric vectors. The other vector basic classes are `"logical"`, `"integer"`, `"complex"`, `"character"`, `"raw"`, `"list"` and `"expression"`. The prototypes for the vector classes are vectors of length 0 of the corresponding type. Notice that basic classes are unusual in that the prototype object is from the class itself. In addition to the vector classes there are also basic classes corresponding to objects in the language, such as `"function"` and `"call"`. These classes are subclasses of the virtual class `"language"`. Finally, there are object types and corresponding basic classes for “abnormal” objects, such as `"environment"` and `"externalptr"`. These objects do not follow the functional behavior of the language; in particular, they are not copied and so cannot have attributes or slots defined locally. All these classes can be used as slots or as superclasses for any other class definitions, although they do not themselves come with an explicit class. For the abnormal object types, a special mechanism is used to enable inheritance as described below. ### Inheriting from non-S4 Classes A class definition can extend classes other than regular S4 classes, usually by specifying them in the `contains=` argument to `[setClass](setclass)`. Three groups of such classes behave distinctly: 1. S3 classes, which must have been registered by a previous call to `[setOldClass](setoldclass)` (you can check that this has been done by calling `[getClass](getclass)`, which should return a class that extends [oldClass](setoldclass)); 2. One of the **R** object types, typically a vector type, which then defines the type of the S4 objects, but also a type such as `[environment](../../base/html/environment)` that can not be used directly as a type for an S4 object. See below. 3. One of the pseudo-classes `[matrix](structureclasses)` and `[array](structureclasses)`, implying objects with arbitrary vector types plus the `dim` and `dimnames` attributes. This section describes the approach to combining S4 computations with older S3 computations by using such classes as superclasses. The design goal is to allow the S4 class to inherit S3 methods and default computations in as consistent a form as possible. As part of a general effort to make the S4 and S3 code in R more consistent, when objects from an S4 class are used as the first argument to a non-default S3 method, either for an S3 generic function (one that calls `[UseMethod](../../base/html/usemethod)`) or for one of the primitive functions that dispatches S3 methods, an effort is made to provide a valid object for that method. In particular, if the S4 class extends an S3 class or `matrix` or `array`, and there is an S3 method matching one of these classes, the S4 object will be coerced to a valid S3 object, to the extent that is possible given that there is no formal definition of an S3 class. For example, suppose `"myFrame"` is an S4 class that includes the S3 class `"data.frame"` in the `contains=` argument to `[setClass](setclass)`. If an object from this S4 class is passed to a function, say `[as.matrix](../../base/html/matrix)`, that has an S3 method for `"data.frame"`, the internal code for `[UseMethod](../../base/html/usemethod)` will convert the object to a data frame; in particular, to an S3 object whose class attribute will be the vector corresponding to the S3 class (possibly containing multiple class names). Similarly for an S4 object inheriting from `"matrix"` or `"array"`, the S4 object will be converted to a valid S3 matrix or array. Note that the conversion is *not* applied when an S4 object is passed to the default S3 method. Some S3 generics attempt to deal with general objects, including S4 objects. Also, no transformation is applied to S4 objects that do not correspond to a selected S3 method; in particular, to objects from a class that does not contain either an S3 class or one of the basic types. See `[asS4](../../base/html/iss4)` for the transformation details. In addition to explicit S3 generic functions, S3 methods are defined for a variety of operators and functions implemented as primitives. These methods are dispatched by some internal C code that operates partly through the same code as real S3 generic functions and partly via special considerations (for example, both arguments to a binary operator are examined when looking for methods). The same mechanism for adapting S4 objects to S3 methods has been applied to these computations as well, with a few exceptions such as generating an error if an S4 object that does not extend an appropriate S3 class or type is passed to a binary operator. The remainder of this section discusses the mechanisms for inheriting from basic object types. See `[matrix](structureclasses)` or `[array](structureclasses)` for inhering from the matrix and array pseudo-classes, or from time-series. For the corresponding details for inheritance from S3 classes, see `[setOldClass](setoldclass)`. An object from a class that directly and simply contains one of the basic object types in **R**, has implicitly a corresponding `.Data` slot of that type, allowing computations to extract or replace the data part while leaving other slots unchanged. If the type is one that can accept attributes and is duplicated normally, the inheritance also determines the type of the object; if the class definition has a `.Data` slot corresponding to a normal type, the class of the slot determines the type of the object (that is, the value of `[typeof](../../base/html/typeof)(x)`). For such classes, `.Data` is a pseudo-slot; that is, extracting or setting it modifies the non-slot data in the object. The functions `[getDataPart](rclassutils)` and `[setDataPart](rclassutils)` are a cleaner, but essentially equivalent way to deal with the data part. Extending a basic type this way allows objects to use old-style code for the corresponding type as well as S4 methods. Any basic type can be used for `.Data`, but a few types are treated differently because they do not behave like ordinary objects; for example, `"NULL"`, environments, and external pointers. Classes extend these types by having a slot, `.xData`, itself inherited from an internally defined S4 class. This slot actually contains an object of the inherited type, to protect computations from the reference semantics of the type. Coercing to the nonstandard object type then requires an actual computation, rather than the `"simple"` inclusion for other types and classes. The intent is that programmers will not need to take account of the mechanism, but one implication is that you should *not* explicitly use the type of an S4 object to detect inheritance from an arbitrary object type. Use `<is>` and similar functions instead. ### References Chambers, John M. (2016) *Extending R*, Chapman & Hall. (Chapters 9 and 10.) ### See Also `[Methods\_Details](methods_details)` for analogous discussion of methods, `[setClass](setclass)` for details of specifying class definitions, `<is>`, `<as>`, `<new>`, `<slot>`
programming_docs
r None `methodUtilities` Utility Functions for Methods and S-Plus Compatibility ------------------------------------------------------------------------- ### Description These are *internal* utilities, currently in the methods package, that either provide some functionality needed by the package (e.g., element matching by name), or add compatibility with S-Plus, or both. ### Usage ``` functionBody(fun=sys.function(sys.parent())) allNames(x) getFunction(name, generic=TRUE, mustFind=TRUE, where) el(object, where) elNamed(x, name, mustFind=FALSE) formalArgs(def) Quote(expr) showDefault(object, oldMethods = TRUE) initMethodDispatch(where = topenv(parent.frame())) methodSignatureMatrix(object, sigSlots = c("target", "defined")) ``` ### Summary of Functions `allNames`: the character vector of names (unlike `names()`, never returns `NULL`). `getFunction`: find the object as a function. `el`: `el(object, i)` is equivalent to `object[i][[1]]` (and should typically be replaceable by object[[i]]). `elNamed`: get the element of the vector corresponding to name. Unlike the `[[](../../base/html/extract)`, `[[[](../../base/html/extract)`, and `[$](../../base/html/extract)` operators, this function requires `name` to match the element name exactly (no partial matching). `formalArgs`: Returns the names of the formal arguments of this function. `existsFunction`: Is there a function of this name? If `generic` is `FALSE`, generic functions are not counted. `findFunction`: return all the indices of the search list on which a function definition for `name` exists. If `generic` is `FALSE`, ignore generic functions. `showDefault`: Utility, used to enable `show` methods to be called by the automatic printing (via `print.default`). Argument `oldMethods` is deprecated as it has been unused since **R** >= 1.7.0. `initMethodDispatch`: Turn on the internal method dispatch code. Called on loading the namespace. Also, if dispatch has been turned off (by calling `.isMethodsDispatchOn(FALSE)`—a very gutsy thing to do), calling this function should turn dispatch back on again. `methodSignatureMatrix`: Returns a matrix with the contents of the specified slots as rows. The slots should be named character strings of the same length. Basically used to turn the signatures of a `"MethodDefinition"` object into a matrix for printing. `Quote`: is a synonym of `[quote](../../base/html/substitute)()` and considered deprecated. r None `genericFunction-class` Generic Function Objects ------------------------------------------------- ### Description Generic functions (objects from or extending class `genericFunction`) are extended function objects, containing information used in creating and dispatching methods for this function. They also identify the package associated with the function and its methods. ### Objects from the Class Generic functions are created and assigned by `[setGeneric](setgeneric)` or `[setGroupGeneric](setgroupgeneric)` and, indirectly, by `[setMethod](setmethod)`. As you might expect `[setGeneric](setgeneric)` and `[setGroupGeneric](setgroupgeneric)` create objects of class `"genericFunction"` and `"groupGenericFunction"` respectively. ### Slots `.Data`: Object of class `"function"`, the function definition of the generic, usually created automatically as a call to `[standardGeneric](../../base/html/standardgeneric)`. `generic`: Object of class `"character"`, the name of the generic function. `package`: Object of class `"character"`, the name of the package to which the function definition belongs (and *not* necessarily where the generic function is stored). If the package is not specified explicitly in the call to `setGeneric`, it is usually the package on which the corresponding non-generic function exists. `group`: Object of class `"list"`, the group or groups to which this generic function belongs. Empty by default. `valueClass`: Object of class `"character"`; if not an empty character vector, identifies one or more classes. It is asserted that all methods for this function return objects from these class (or from classes that extend them). `signature`: Object of class `"character"`, the vector of formal argument names that can appear in the signature of methods for this generic function. By default, it is all the formal arguments, except for .... Order matters for efficiency: the most commonly used arguments in specifying methods should come first. `default`: Object of class `"optionalMethod"` (a union of classes `"function"` and `"NULL"`), containing the default method for this function if any. Generated automatically and used to initialize method dispatch. `skeleton`: Object of class `"call"`, a slot used internally in method dispatch. Don't expect to use it directly. ### Extends Class `"function"`, from data part. Class `"OptionalMethods"`, by class `"function"`. Class `"PossibleMethod"`, by class `"function"`. ### Methods Generic function objects are used in the creation and dispatch of formal methods; information from the object is used to create methods list objects and to merge or update the existing methods for this generic. r None `TraceClasses` Classes Used Internally to Control Tracing ---------------------------------------------------------- ### Description The classes described here are used by the R function `[trace](../../base/html/trace)` to create versions of functions and methods including browser calls, etc., and also to `[untrace](../../base/html/trace)` the same objects. ### Usage ``` ### Objects from the following classes are generated ### by calling trace() on an object from the corresponding ### class without the "WithTrace" in the name. "functionWithTrace" "MethodDefinitionWithTrace" "MethodWithNextWithTrace" "genericFunctionWithTrace" "groupGenericFunctionWithTrace" ### the following is a virtual class extended by each of the ### classes above "traceable" ``` ### Objects from the Class Objects will be created from these classes by calls to `trace`. (There is an `[initialize](new)` method for class `"traceable"`, but you are unlikely to need it directly.) ### Slots `.Data`: The data part, which will be `"function"` for class `"functionWithTrace"`, and similarly for the other classes. `original`: Object of the original class; e.g., `"function"` for class `"functionWithTrace"`. ### Extends Each of the classes extends the corresponding untraced class, from the data part; e.g., `"functionWithTrace"` extends `"function"`. Each of the specific classes extends `"traceable"`, directly, and class `"VIRTUAL"`, by class `"traceable"`. ### Methods The point of the specific classes is that objects generated from them, by function `trace()`, remain callable or dispatchable, in addition to their new trace information. ### See Also function `[trace](../../base/html/trace)` r None `slot` The Slots in an Object from a Formal Class -------------------------------------------------- ### Description These functions return or set information about the individual slots in an object. ### Usage ``` object@name object@name <- value slot(object, name) slot(object, name, check = TRUE) <- value .hasSlot(object, name) slotNames(x) getSlots(x) ``` ### Arguments | | | | --- | --- | | `object` | An object from a formally defined class. | | `name` | The name of the slot. The operator takes a fixed name, which can be unquoted if it is syntactically a name in the language. A slot name can be any non-empty string, but if the name is not made up of letters, numbers, and `.`, it needs to be quoted (by backticks or single or double quotes). In the case of the `slot` function, `name` can be any expression that evaluates to a valid slot in the class definition. Generally, the only reason to use the functional form rather than the simpler operator is *because* the slot name has to be computed. | | `value` | A new value for the named slot. The value must be valid for this slot in this object's class. | | `check` | In the replacement version of `slot`, a flag. If `TRUE`, check the assigned value for validity as the value of this slot. User's code should not set this to `FALSE` in normal use, since the resulting object can be invalid. | | `x` | either the name of a class (as character string), or a class definition. If given an argument that is neither a character string nor a class definition, `slotNames` (only) uses `class(x)` instead. | ### Details The definition of the class specifies all slots directly and indirectly defined for that class. Each slot has a name and an associated class. Extracting a slot returns an object from that class. Setting a slot first coerces the value to the specified slot and then stores it. Unlike general attributes, slots are not partially matched, and asking for (or trying to set) a slot with an invalid name for that class generates an error. The `[@](../../base/html/slotop)` extraction operator and `slot` function themselves do no checking against the class definition, simply matching the name in the object itself. The replacement forms do check (except for `slot` in the case `check=FALSE`). So long as slots are set without cheating, the extracted slots will be valid. Be aware that there are two ways to cheat, both to be avoided but with no guarantees. The obvious way is to assign a slot with `check=FALSE`. Also, slots in **R** are implemented as attributes, for the sake of some back compatibility. The current implementation does not prevent attributes being assigned, via `[attr<-](../../base/html/attr)`, and such assignments are not checked for legitimate slot names. Note that the `"@"` operators for extraction and replacement are primitive and actually reside in the base package. The replacement versions of `"@"` and `slot()` differ in the computations done to coerce the right side of the assignment to the declared class of the slot. Both verify that the value provided is from a subclass of the declared slot class. The `slot()` version will go on to call the coerce method if there is one, in effect doing the computation `as(value, slotClass, strict = FALSE)`. The `"@"` version just verifies the relation, leaving any coerce to be done later (e.g., when a relevant method is dispatched). In most uses the result is equivalent, and the `"@"` version saves an extra function call, but if empirical evidence shows that a conversion is needed, either call `as()` before the replacement or use the replacement version of `slot()`. ### Value The `"@"` operator and the `slot` function extract or replace the formally defined slots for the object. Functions `slotNames` and `getSlots` return respectively the names of the slots and the classes associated with the slots in the specified class definition. Except for its extended interpretation of `x` (above), `slotNames(x)` is just `names(getSlots(x))`. ### References Chambers, John M. (2008) *Software for Data Analysis: Programming with R* Springer. (For the R version.) Chambers, John M. (1998) *Programming with Data* Springer (For the original S4 version.) ### See Also `[@](../../base/html/slotop)`, `[Classes\_Details](classes_details)`, `[Methods\_Details](methods_details)`, `[getClass](getclass)`, `[names](../../base/html/names)`. ### Examples ``` setClass("track", slots = c(x="numeric", y="numeric")) myTrack <- new("track", x = -4:4, y = exp(-4:4)) slot(myTrack, "x") slot(myTrack, "y") <- log(slot(myTrack, "y")) utils::str(myTrack) getSlots("track") # or getSlots(getClass("track")) slotNames(class(myTrack)) # is the same as slotNames(myTrack) ``` r None `Methods_Details` General Information on Methods ------------------------------------------------- ### Description This documentation covers some general topics on how methods work and how the methods package interacts with the rest of **R**. The information is usually not needed to get started with methods and classes, but may be helpful for moderately ambitious projects, or when something doesn't work as expected. For additional information see documentation for the important steps: (`[setMethod](setmethod)()`, `[setClass](setclass)()` and `[setGeneric](setgeneric)()`). Also `[Methods\_for\_Nongenerics](methods_for_nongenerics)` on defining formal methods for functions that are not currently generic functions; [Methods\_for\_S3](methods_for_s3) for the relation to S3 classes and methods; `[Classes\_Details](classes_details)` for class definitions and Chapters 9 and 10 of the reference. ### How Methods Work A call to a generic function selects a method matching the actual arguments in the call. The body of the method is evaluated in the frame of the call to the generic function. A generic function is identified by its name and by the package to which it correspond. Unlike ordinary functions, the generic has a slot that specifies its package. In an **R** session, there is one version of each such generic, regardless of where the call to that generic originated, and the generic function has a table of all the methods currently available for it; that is, all the methods in packages currently loaded into the session. Methods are frequently defined for functions that are non-generic in their original package,. for example, for function `plot()` in package graphics. An identical version of the corresponding generic function may exist in several packages. All methods will be dispatched consistently from the **R** session. Each **R** package with a call to `[setMethod](setmethod)` in its source code will include a methods metadata object for that generic. When the package is loaded into an **R** session, the methods for each generic function are *cached*, that is, added to the environment of the generic function. This merged table of methods is used to dispatch or select methods from the generic, using class inheritance and possibly group generic functions (see `[GroupGenericFunctions](s4groupgeneric)`) to find an applicable method. See the “Method Selection and Dispatch” section below. The caching computations ensure that only one version of each generic function is visible globally; although different attached packages may contain a copy of the generic function, these behave identically with respect to method selection. In contrast, it is possible for the same function name to refer to more than one generic function, when these have different `package` slots. In the latter case, **R** considers the functions unrelated: A generic function is defined by the combination of name and package. See the “Generic Functions” section below. The methods for a generic are stored according to the corresponding `signature` in the call to `[setMethod](setmethod)` that defined the method. The signature associates one class name with each of a subset of the formal arguments to the generic function. Which formal arguments are available, and the order in which they appear, are determined by the `"signature"` slot of the generic function itself. By default, the signature of the generic consists of all the formal arguments except ..., in the order they appear in the function definition. Trailing arguments in the signature of the generic will be *inactive* if no method has yet been specified that included those arguments in its signature. Inactive arguments are not needed or used in labeling the cached methods. (The distinction does not change which methods are dispatched, but ignoring inactive arguments improves the efficiency of dispatch.) All arguments in the signature of the generic function will be evaluated when the function is called, rather than using lazy evaluation. Therefore, it's important to *exclude* from the signature any arguments that need to be dealt with symbolically (such as the `expr` argument to function `[with](../../base/html/with)`). Note that only actual arguments are evaluated, not default expressions. A missing argument enters into the method selection as class `"missing"`. The cached methods are stored in an environment object. The names used for assignment are a concatenation of the class names for the active arguments in the method signature. ### Method Selection: Details When a call to a generic function is evaluated, a method is selected corresponding to the classes of the actual arguments in the signature. First, the cached methods table is searched for an exact match; that is, a method stored under the signature defined by the string value of `class(x)` for each non-missing argument, and `"missing"` for each missing argument. If no method is found directly for the actual arguments in a call to a generic function, an attempt is made to match the available methods to the arguments by using the superclass information about the actual classes. A method found by this search is cached in the generic function so that future calls with the same argument classes will not require repeating the search. In any likely application, the search for inherited methods will be a negligible overhead. Each class definition may include a list of one or more direct *superclasses* of the new class. The simplest and most common specification is by the `contains=` argument in the call to `[setClass](setclass)`. Each class named in this argument is a superclass of the new class. A class will also have as a direct superclass any class union to which it is a member. Class unions are created by a call to `[setClassUnion](setclassunion)`. Additional members can be added to the union by a simple call to `[setIs](setis)`. Superclasses specified by either mechanism are the *direct* superclasses. Inheritance specified in either of these forms is *simple* in the sense that all the information needed for the superclass is asserted to be directly available from the object. **R** inherited from S a more general form of inheritance in which inheritance may require some transformation or be conditional on a test. This more general form has not proved to be useful in general practical situations. Since it also adds some computational costs non-simple inheritance is not recommended. See `[setIs](setis)` for the general version. The direct superclasses themselves may have direct superclasses and similarly through further generations. Putting all this information together produces the full list of superclasses for this class. The superclass list is included in the definition of the class that is cached during the **R** session. The *distance* between the two classes is defined to be the number of generations: `1` for direct superclasses (regardless of which mechanism defined them), then `2` for the direct superclasses of those classes, and so on. To see all the superclasses, with their distance, print the class definition by calling `[getClass](getclass)`. In addition, any class implicitly has class `"ANY"` as a superclass. The distance to `"ANY"` is treated as larger than the distance to any actual class. The special class `"missing"` corresponding to missing arguments has only `"ANY"` as a superclass, while `"ANY"` has no superclasses. When a method is to be selected by inheritance, a search is made in the table for all methods corresponding to a combination of either the direct class or one of its superclasses, for each argument in the active signature. For an example, suppose there is only one argument in the signature and that the class of the corresponding object was `"dgeMatrix"` (from the recommended package `Matrix`). This class has (currently) three direct superclasses and through these additional superclasses at distances 2 through 4. A method that had been defined for any of these classes or for class `"ANY"` (the default method) would be eligible. Methods for the shortest difference are preferred. If there is only one best method in this sense, method selection is unambiguous. When there are multiple arguments in the signature, each argument will generate a similar list of inherited classes. The possible matches are now all the combinations of classes from each argument (think of the function `outer` generating an array of all possible combinations). The search now finds all the methods matching any of this combination of classes. For each argument, the distance to the superclass defines which method(s) are preferred for that argument. A method is considered best for selection if it is among the best (i.e., has the least distance) for each argument. The end result is that zero, one or more methods may be “best”. If one, this method is selected and cached in the table of methods. If there is more than one best match, the selection is ambiguous and a message is printed noting which method was selected (the first method lexicographically in the ordering) and what other methods could have been selected. Since the ambiguity is usually nothing the end user could control, this is not a warning. Package authors should examine their package for possible ambiguous inheritance by calling `[testInheritedMethods](testinheritedmethods)`. Cached inherited selections are not themselves used in future inheritance searches, since that could result in invalid selections. If you want inheritance computations to be done again (for example, because a newly loaded package has a more direct method than one that has already been used in this session), call `[resetGeneric](methodsupport)`. Because classes and methods involving them tend to come from the same package, the current implementation does not reset all generics every time a new package is loaded. Besides being initiated through calls to the generic function, method selection can be done explicitly by calling the function `[selectMethod](getmethod)`. Note that some computations may use this function directly, with optional arguments. The prime example is the use of `[coerce](setas)()` methods by function `<as>()`. There has been some confusion from comparing coerce methods to a call to `[selectMethod](getmethod)` with other options. ### Method Evaluation: Details Once a method has been selected, the evaluator creates a new context in which a call to the method is evaluated. The context is initialized with the arguments from the call to the generic function. These arguments are not rematched. All the arguments in the signature of the generic will have been evaluated (including any that are currently inactive); arguments that are not in the signature will obey the usual lazy evaluation rules of the language. If an argument was missing in the call, its default expression if any will *not* have been evaluated, since method dispatch always uses class `missing` for such arguments. A call to a generic function therefore has two contexts: one for the function and a second for the method. The argument objects will be copied to the second context, but not any local objects created in a nonstandard generic function. The other important distinction is that the parent (“enclosing”) environment of the second context is the environment of the method as a function, so that all **R** programming techniques using such environments apply to method definitions as ordinary functions. For further discussion of method selection and dispatch, see the references in the sections indicated. ### Generic Functions In principle, a generic function could be any function that evaluates a call to `standardGeneric()`, the internal function that selects a method and evaluates a call to the selected method. In practice, generic functions are special objects that in addition to being from a subclass of class `"function"` also extend the class `[genericFunction](genericfunction-class)`. Such objects have slots to define information needed to deal with their methods. They also have specialized environments, containing the tables used in method selection. The slots `"generic"` and `"package"` in the object are the character string names of the generic function itself and of the package from which the function is defined. As with classes, generic functions are uniquely defined in **R** by the combination of the two names. There can be generic functions of the same name associated with different packages (although inevitably keeping such functions cleanly distinguished is not always easy). On the other hand, **R** will enforce that only one definition of a generic function can be associated with a particular combination of function and package name, in the current session or other active version of **R**. Tables of methods for a particular generic function, in this sense, will often be spread over several other packages. The total set of methods for a given generic function may change during a session, as additional packages are loaded. Each table must be consistent in the signature assumed for the generic function. **R** distinguishes *standard* and *nonstandard* generic functions, with the former having a function body that does nothing but dispatch a method. For the most part, the distinction is just one of simplicity: knowing that a generic function only dispatches a method call allows some efficiencies and also removes some uncertainties. In most cases, the generic function is the visible function corresponding to that name, in the corresponding package. There are two exceptions, *implicit* generic functions and the special computations required to deal with **R**'s *primitive* functions. Packages can contain a table of implicit generic versions of functions in the package, if the package wishes to leave a function non-generic but to constrain what the function would be like if it were generic. Such implicit generic functions are created during the installation of the package, essentially by defining the generic function and possibly methods for it, and then reverting the function to its non-generic form. (See [implicitGeneric](implicitgeneric) for how this is done.) The mechanism is mainly used for functions in the older packages in **R**, which may prefer to ignore S4 methods. Even in this case, the actual mechanism is only needed if something special has to be specified. All functions have a corresponding implicit generic version defined automatically (an implicit, implicit generic function one might say). This function is a standard generic with the same arguments as the non-generic function, with the non-generic version as the default (and only) method, and with the generic signature being all the formal arguments except .... The implicit generic mechanism is needed only to override some aspect of the default definition. One reason to do so would be to remove some arguments from the signature. Arguments that may need to be interpreted literally, or for which the lazy evaluation mechanism of the language is needed, must *not* be included in the signature of the generic function, since all arguments in the signature will be evaluated in order to select a method. For example, the argument `expr` to the function `[with](../../base/html/with)` is treated literally and must therefore be excluded from the signature. One would also need to define an implicit generic if the existing non-generic function were not suitable as the default method. Perhaps the function only applies to some classes of objects, and the package designer prefers to have no general default method. In the other direction, the package designer might have some ideas about suitable methods for some classes, if the function were generic. With reasonably modern packages, the simple approach in all these cases is just to define the function as a generic. The implicit generic mechanism is mainly attractive for older packages that do not want to require the methods package to be available. Generic functions will also be defined but not obviously visible for functions implemented as *primitive* functions in the base package. Primitive functions look like ordinary functions when printed but are in fact not function objects but objects of two types interpreted by the **R** evaluator to call underlying C code directly. Since their entire justification is efficiency, **R** refuses to hide primitives behind a generic function object. Methods may be defined for most primitives, and corresponding metadata objects will be created to store them. Calls to the primitive still go directly to the C code, which will sometimes check for applicable methods. The definition of “sometimes” is that methods must have been detected for the function in some package loaded in the session and `isS4(x)` is `TRUE` for the first argument (or for the second argument, in the case of binary operators). You can test whether methods have been detected by calling `[isGeneric](genericfunctions)` for the relevant function and you can examine the generic function by calling `[getGeneric](rmethodutils)`, whether or not methods have been detected. For more on generic functions, see the references and also section 2 of the *R Internals* document supplied with **R**. ### Method Definitions All method definitions are stored as objects from the `[MethodDefinition](methoddefinition-class)` class. Like the class of generic functions, this class extends ordinary **R** functions with some additional slots: `"generic"`, containing the name and package of the generic function, and two signature slots, `"defined"` and `"target"`, the first being the signature supplied when the method was defined by a call to `[setMethod](setmethod)`. The `"target"` slot starts off equal to the `"defined"` slot. When an inherited method is cached after being selected, as described above, a copy is made with the appropriate `"target"` signature. Output from `[showMethods](showmethods)`, for example, includes both signatures. Method definitions are required to have the same formal arguments as the generic function, since the method dispatch mechanism does not rematch arguments, for reasons of both efficiency and consistency. ### References Chambers, John M. (2016) *Extending R*, Chapman & Hall. (Chapters 9 and 10.) Chambers, John M. (2008) *Software for Data Analysis: Programming with R* Springer. (Section 10.5 for some details.) ### See Also For more specific information, see `[setGeneric](setgeneric)`, `[setMethod](setmethod)`, and `[setClass](setclass)`. For the use of ... in methods, see [dotsMethods](dotsmethods).
programming_docs
r None `getMethod` Get or Test for the Definition of a Method ------------------------------------------------------- ### Description The function `selectMethod()` returns the method that would be selected for a call to function `f` if the arguments had classes as specified by `signature`. Failing to find a method is an error, unless argument `optional = TRUE`, in which case `NULL` is returned. The function `findMethod()` returns a list of environments that contain a method for the specified function and signature; by default, these are a subset of the packages in the current search list. See section “Using `findMethod()`” for details. The function `getMethod()` returns the method corresponding to the function and signature supplied similarly to `selectMethod`, but without using inheritance or group generics. The functions `hasMethod()` and `existsMethod()` test whether `selectMethod()` or `getMethod()`, respectively, finds a matching method. ### Usage ``` selectMethod(f, signature, optional = FALSE, useInherited =, mlist = , fdef = , verbose = , doCache = ) findMethod(f, signature, where) getMethod(f, signature = character(), where, optional = FALSE, mlist, fdef) existsMethod(f, signature = character(), where) hasMethod(f, signature = character(), where) ``` ### Arguments | | | | --- | --- | | `f` | a generic function or the character-string name of one. | | `signature` | the signature of classes to match to the arguments of `f`. See the details below. | | `where` | the environment in which to look for the method(s). By default, if the call comes from the command line, the table of methods defined in the generic function itself is used, except for `findMethod` (see the section below). | | `optional` | if the selection in `selectMethod` does not find a valid method an error is generated, unless `optional` is `TRUE`, in which case the value returned is `NULL`. | | `mlist, fdef, useInherited, verbose, doCache` | optional arguments to `getMethod` and `selectMethod` for internal use. Avoid these: some will work as expected and others will not, and none of them is required for normal use of the functions. But see the section “Methods for `as()`” for nonstandard inheritance. | ### Details The `signature` argument specifies classes, corresponding to formal arguments of the generic function; to be precise, to the `signature` slot of the generic function object. The argument may be a vector of strings identifying classes, and may be named or not. Names, if supplied, match the names of those formal arguments included in the signature of the generic. That signature is normally all the arguments except .... However, generic functions can be specified with only a subset of the arguments permitted, or with the signature taking the arguments in a different order. It's a good idea to name the arguments in the signature to avoid confusion, if you're dealing with a generic that does something special with its signature. In any case, the elements of the signature are matched to the formal signature by the same rules used in matching arguments in function calls (see `[match.call](../../base/html/match.call)`). The strings in the signature may be class names, `"missing"` or `"ANY"`. See [Methods\_Details](methods_details) for the meaning of these in method selection. Arguments not supplied in the signature implicitly correspond to class `"ANY"`; in particular, giving an empty signature means to look for the default method. A call to `getMethod` returns the method for a particular function and signature. The search for the method makes no use of inheritance. The function `selectMethod` also looks for a method given the function and signature, but makes full use of the method dispatch mechanism; i.e., inherited methods and group generics are taken into account just as they would be in dispatching a method for the corresponding signature, with the one exception that conditional inheritance is not used. Like `getMethod`, `selectMethod` returns `NULL` or generates an error if the method is not found, depending on the argument `optional`. Both `selectMethod` and `getMethod` will normally use the current version of the generic function in the R session, which has a table of the methods obtained from all the packages loaded in the session. Optional arguments can cause a search for the generic function from a specified environment, but this is rarely a useful idea. In contrast, `findMethod` has a different default and the optional `where=` argument may be needed. See the section “Using `findMethod()`”. The functions `existsMethod` and `hasMethod` return `TRUE` or `FALSE` according to whether a method is found, the first corresponding to `getMethod` (no inheritance) and the second to `selectMethod`. ### Value The call to `selectMethod` or `getMethod` returns the selected method, if one is found. (This class extends `function`, so you can use the result directly as a function if that is what you want.) Otherwise an error is thrown if `optional` is `FALSE` and `NULL` is returned if `optional` is `TRUE`. The returned method object is a `[MethodDefinition](methoddefinition-class)` object, *except* that the default method for a primitive function is required to be the primitive itself. Note therefore that the only reliable test that the search failed is `is.null()`. The returned value of `findMethod` is a list of environments in which a corresponding method was found; that is, a table of methods including the one specified. ### Using `findMethod()` As its name suggests, this function is intended to behave like `[find](../../utils/html/apropos)`, which produces a list of the packages on the current search list which have, and have exported, the object named. That's what `findMethod` does also, by default. The “exported” part in this case means that the package's namespace has an `exportMethods` directive for this generic function. An important distinction is that the absence of such a directive does not prevent methods from the package from being called once the package is loaded. Otherwise, the code in the package could not use un-exported methods. So, if your question is whether loading package `thisPkg` will define a method for this function and signature, you need to ask that question about the namespace of the package: `findMethod(f, signature, where = asNamespace("thisPkg"))` If the package did not export the method, attaching it and calling `findMethod` with no `where` argument will not find the method. Notice also that the length of the signature must be what the corresponding package used. If `thisPkg` had only methods for one argument, only length-1 signatures will match (no trailing `"ANY"`), even if another currently loaded package had signatures with more arguments. ### Methods for `as()` The function `[setAs](setas)` allows packages to define methods for coercing one class of objects to another class. This works internally by defining methods for the generic function `[coerce](setas)(from, to)`, which can not be called directly. The **R** evaluator selects methods for this purpose using a different form of inheritance. While methods can be inherited for the object being coerced, they cannot inherit for the target class, since the result would not be a valid object from that class. If you want to examine the selection procedure, you must supply the optional argument `useInherited = c(TRUE, FALSE)` to `selectMethod`. ### References Chambers, John M. (2016) *Extending R*, Chapman & Hall. (Chapters 9 and 10.) Chambers, John M. (2008) *Software for Data Analysis: Programming with R* Springer. (Section 10.6 for some details of method selection.) ### See Also `[Methods\_Details](methods_details)` for the details of method selection; `[GenericFunctions](genericfunctions)` for other functions manipulating methods and generic function objects; `[MethodDefinition](methoddefinition-class)` for the class that represents method definitions. ### Examples ``` testFun <- function(x)x setGeneric("testFun") setMethod("testFun", "numeric", function(x)x+1) hasMethod("testFun", "numeric") # TRUE hasMethod("testFun", "integer") #TRUE, inherited existsMethod("testFun", "integer") #FALSE hasMethod("testFun") # TRUE, default method hasMethod("testFun", "ANY") ``` r None `setGeneric` Create a Generic Version of a Function ---------------------------------------------------- ### Description Create a generic version of the named function so that methods may be defined for it. A call to `[setMethod](setmethod)` will call `setGeneric` automatically if applied to a non-generic function. An explicit call to `setGeneric` is usually not required, but doesn't hurt and makes explicit that methods are being defined for a non-generic function. Standard calls will be of the form: `setGeneric(name)` where `name` specifies an existing function, possibly in another package. An alternative when creating a new generic function in this package is: `setGeneric(name, def)` where the function definition `def` specifies the formal arguments and becomes the default method. ### Usage ``` setGeneric(name, def= , group=list(), valueClass=character(), where= , package= , signature= , useAsDefault= , genericFunction= , simpleInheritanceOnly = ) ``` ### Arguments | | | | --- | --- | | `name` | The character string name of the generic function. | | `def` | An optional function object, defining the non-generic version, to become the default method. This is equivalent in effect to assigning `def` as the function and then using the one-argument call to `setGeneric`. *The following arguments are specialized, optionally used when creating a new generic function with non-standard features. They should not be used when the non-generic is in another package.* | | `group` | The name of the group generic function to which this function belongs. See [Methods\_Details](methods_details) for details of group generic functions in method selection and [S4groupGeneric](s4groupgeneric) for existing groups. | | `valueClass` | A character vector specifying one or more class names. The value returned by the generic function must have (or extend) this class, or one of the classes; otherwise, an error is generated. | | `signature` | The vector of names from among the formal arguments to the function, that will be allowed in the signature of methods for this function, in calls to `[setMethod](setmethod)`. By default and usually, this will be all formal arguments except `...`. A non-standard signature for the generic function may be used to exclude arguments that take advantage of lazy evaluation; in particular, if the argument may *not* be evaluated then it cannot be part of the signature. While `...` cannot be used as part of a general signature, it is possible to have this as the *only* element of the signature. Methods will then be selected if their signature matches all the `...` arguments. See the documentation for topic [dotsMethods](dotsmethods) for details. It is not possible to mix `...` and other arguments in the signature. It's usually a mistake to omit arguments from the signature in the belief that this improves efficiency. For method selection, the arguments that are used in the signatures for the *methods* are what counts, and then only seriously on the first call to the function with that combination of classes. | | `simpleInheritanceOnly` | Supply this argument as `TRUE` to require that methods selected be inherited through simple inheritance only; that is, from superclasses specified in the `contains=` argument to `[setClass](setclass)`, or by simple inheritance to a class union or other virtual class. Generic functions should require simple inheritance if they need to be assured that they get the complete original object, not one that has been transformed. Examples of functions requiring simple inheritance are `[initialize](new)`, because by definition it must return an object from the same class as its argument, and `<show>`, because it claims to give a full description of the object provided as its argument. | | `useAsDefault` | Override the usual default method mechanism. Only relevant when defining a nonstandard generic function. See the section ‘Specialized Local Generics’. *The remaining arguments are obsolete for normal applications.* | | `package` | The name of the package with which this function is associated. Should be determined automatically from the non-generic version. | | `where` | Where to store the resulting objects as side effects. The default, to store in the package's namespace, is the only safe choice. | | `genericFunction` | Obsolete. | ### Value The `setGeneric` function exists for its side effect: saving the generic function to allow methods to be specified later. It returns `name`. ### Basic Use The `setGeneric` function is called to initialize a generic function as preparation for defining some methods for that function. The simplest and most common situation is that `name` specifies an existing function, usually in another package. You now want to define methods for this function. In this case you should supply only `name`, for example: `setGeneric("colSums")` There must be an existing function of this name (in this case in package `"base"`). The non-generic function can be in the same package as the call, typically the case when you are creating a new function plus methods for it. When the function is in another package, it must be available by name, for example through an `importFrom()` directive in this package's `NAMESPACE` file. Not required for functions in `"base"`, which are implicitly imported. A generic version of the function will be created in the current package. The existing function becomes the default method, and the package slot of the new generic function is set to the location of the original function (`"base"` in the example). Two special types of non-generic should be noted. Functions that dispatch S3 methods by calling `[UseMethod](../../base/html/usemethod)` are ordinary functions, not objects from the `"genericFunction"` class. They are made generic like any other function, but some special considerations apply to ensure that S4 and S3 method dispatch is consistent (see [Methods\_for\_S3](methods_for_s3)). Primitive functions are handled in C code and don't exist as normal functions. A call to `setGeneric` is allowed in the simple form, but no actual generic function object is created. Method dispatch will take place in the C code. See the section on Primitive Functions for more details. It's an important feature that the identical generic function definition is created in every package that uses the same `setGeneric()` call. When any of these packages is loaded into an **R** session, this function will be added to a table of generic functions, and will contain a methods table of all the available methods for the function. Calling `setGeneric()` is not strictly necessary before calling `setMethod()`. If the function specified in the call to `setMethod` is not generic, `setMethod` will execute the call to `setGeneric` itself. In the case that the non-generic is in another package, does not dispatch S3 methods and is not a primitive, a message is printed noting the creation of the generic function the first time `setMethod` is called. The second common use of `setGeneric()` is to create a new generic function, unrelated to any existing function. See the `asRObject()` example below. This case can be handled just like the previous examples, with only the difference that the non-generic function exists in the current package. Again, the non-generic version becomes the default method. For clarity it's best for the assignment to immediately precede the call to `setGeneric()` in the source code. Exactly the same result can be obtained by supplying the default as the `def` argument instead of assigning it. In some applications, there will be no completely general default method. While there is a special mechanism for this (see the ‘Specialized Local Generics’ section), the recommendation is to provide a default method that signals an error, but with a message that explains as clearly as you can why a non-default method is needed. ### Specialized Local Generics The great majority of calls to `setGeneric()` should either have one argument to ensure that an existing function can have methods, or arguments `name` and `def` to create a new generic function and optionally a default method. It is possible to create generic functions with nonstandard signatures, or functions that do additional computations besides method dispatch or that belong to a group of generic functions. None of these mechanisms should be used with a non-generic function from a *different* package, because the result is to create a generic function that may not be consistent from one package to another. When any such options are used, the new generic function will be assigned with a package slot set to the *current* package, not the one in which the non-generic version of the function is found. There is a mechanism to define a specialized generic version of a non-generic function, the `[implicitGeneric](implicitgeneric)` construction. This defines the generic version, but then reverts the function to it non-generic form, saving the implicit generic in a table to be activated when methods are defined. However, the mechanism can only legitimately be used either for a non-generic in the same package or by the `"methods"` package itself. And in the first case, there is no compelling reason not to simply make the function generic, with the non-generic as the default method. See `[implicitGeneric](implicitgeneric)` for details. The body of a generic function usually does nothing except for dispatching methods by a call to `standardGeneric`. Under some circumstances you might just want to do some additional computation in the generic function itself. As long as your function eventually calls `standardGeneric` that is permissible. See the example `"authorNames"` below. In this case, the `def` argument will define the nonstandard generic, not the default method. An existing non-generic of the same name and calling sequence should be pre-assigned. It will become the default method, as usual. (An alternative is the `useAsDefault` argument.) By default, the generic function can return any object. If `valueClass` is supplied, it should be a vector of class names; the value returned by a method is then required to satisfy `is(object, Class)` for one of the specified classes. An empty (i.e., zero length) vector of classes means anything is allowed. Note that more complicated requirements on the result can be specified explicitly, by defining a non-standard generic function. If the `def` argument calls `standardGeneric()` (with or without additional computations) and there is no existing non-generic version of the function, the generic is created without a default method. This is not usually a good idea: better to have a default method that signals an error with a message explaining why the default case is not defined. A new generic function can be created belonging to an existing group by including the `group` argument. The argument list of the new generic must agree with that of the group. See `[setGroupGeneric](setgroupgeneric)` for defining a new group generic. For the role of group generics in dispatching methods, see [GroupGenericFunctions](s4groupgeneric) and section 10.5 of the second reference. ### Generic Functions and Primitive Functions A number of the basic **R** functions are specially implemented as primitive functions, to be evaluated directly in the underlying C code rather than by evaluating an **R** language definition. Most have implicit generics (see `[implicitGeneric](implicitgeneric)`), and become generic as soon as methods (including group methods) are defined on them. Others cannot be made generic. Calling `setGeneric()` for the primitive functions in the base package differs in that it does not, in fact, generate an explicit generic function. Methods for primitives are selected and dispatched from the internal C code, to satisfy concerns for efficiency. The same is true for a few non-primitive functions that dispatch internally. These include `unlist` and `as.vector`. Note, that the implementation restrict methods for primitive functions to signatures in which at least one of the classes in the signature is a formal S4 class. Otherwise the internal C code will not look for methods. This is a desirable restriction in principle, since optional packages should not be allowed to change the behavior of basic R computations on existing data types. To see the generic version of a primitive function, use `[getGeneric](rmethodutils)(name)`. The function `[isGeneric](genericfunctions)` will tell you whether methods are defined for the function in the current session. Note that S4 methods can only be set on those primitives which are ‘[internal generic](../../base/html/internalmethods)’, plus `%*%`. ### References Chambers, John M. (2016) *Extending R*, Chapman & Hall. (Chapters 9 and 10.) Chambers, John M. (2008) *Software for Data Analysis: Programming with R* Springer. (Section 10.5 for some details.) ### See Also `[Methods\_Details](methods_details)` and the links there for a general discussion, `[dotsMethods](dotsmethods)` for methods that dispatch on `...`, and `[setMethod](setmethod)` for method definitions. ### Examples ``` ## Specify that this package will define methods for plot() setGeneric("plot") ## create a new generic function, with a default method setGeneric("props", function(object) attributes(object)) ### A non-standard generic function. It insists that the methods ### return a non-empty character vector (a stronger requirement than ### valueClass = "character" in the call to setGeneric) setGeneric("authorNames", function(text) { value <- standardGeneric("authorNames") if(!(is(value, "character") && any(nchar(value)>0))) stop("authorNames methods must return non-empty strings") value }) ## the asRObject generic function, from package XR ## Its default method just returns object ## See the reference, Chapter 12 for methods setGeneric("asRObject", function(object, evaluator) { object }) ```
programming_docs
r None `MethodsList` MethodsList Objects ---------------------------------- ### Description These functions create and manipulate `MethodsList` objects, the objects formerly used in **R** to store methods for dispatch. Use of these objects is deprecated since **R** 3.2.0, as it will rarely be a good idea. Where methods dispatch is to be studied, see `[selectMethod](getmethod)`. For computations that iterate over methods or over method signatures, see `[findMethods](findmethods)`, which returns a linearized methods list to hold method definitions, usually more convenient for iteration than the recursive `MethodsList` objects. ### Usage ``` listFromMlist(mlist, prefix = list(), sigs. = TRUE, methods. = TRUE) linearizeMlist(mlist, inherited = TRUE) finalDefaultMethod(method) loadMethod(method, fname, envir) ##--------- These are all deprecated, since R 3.2.0 ---------- MethodsList(.ArgName, ...) makeMethodsList(object, level=1) SignatureMethod(names, signature, definition) insertMethod(mlist, signature, args, def, cacheOnly) inheritedSubMethodLists(object, thisClass, mlist, ev) showMlist(mlist, includeDefs = TRUE, inherited = TRUE, classes, useArgNames, printTo = stdout() ) ## S3 method for class 'MethodsList' print(x, ...) mergeMethods(m1, m2, genericLabel) ``` ### Details `listFromMlist`: Undo the recursive nature of the methods list, making a list of `list(sigs,methods)` of function definitions, i.e. of matching signatures and methods. `prefix` is the partial signature (a named list of classes) to be prepended to the signatures in this object. If `sigs.` or `methods.` are `FALSE`, the resulting part of the return value will be empty. A utility function used to iterate over all the individual methods in the object, it calls itself recursively. `linearizeMlist`: Undo the recursive nature of the methods list, making a list of function definitions, with the names of the list being the corresponding signatures. Designed for printing; for looping over the methods, use the above `listFromMlist` instead. `finalDefaultMethod`: The default method or NULL. With the demise of `"MethodsList"` objects, this function only checks that the value given it is a method definition, primitive or NULL. `loadMethod`: Called, if necessary, just before a call to `method` is dispatched in the frame `envir`. The function exists so that methods can be defined for special classes of objects. Usually the point is to assign or modify information in the frame environment to be used evaluation. For example, the standard class `MethodDefinition` has a method that stores the target and defined signatures in the environment. Class `MethodWithNext` has a method taking account of the mechanism for storing the method to be used in a call to `[callNextMethod](nextmethod)`. Any methods defined for `loadMethod` must return the function definition to be used for this call; typically, this is just the `method` argument. ### References Chambers, John M. (2008) *Software for Data Analysis: Programming with R* Springer. (For the R version.) Chambers, John M. (1998) *Programming with Data* Springer (For the original S4 version.) r None `classRepresentation-class` Class Objects ------------------------------------------ ### Description These are the objects that hold the definition of classes of objects. They are constructed and stored as meta-data by calls to the function `[setClass](setclass)`. Don't manipulate them directly, except perhaps to look at individual slots. ### Details Class definitions are stored as metadata in various packages. Additional metadata supplies information on inheritance (the result of calls to `[setIs](setis)`). Inheritance information implied by the class definition itself (because the class contains one or more other classes) is also constructed automatically. When a class is to be used in an R session, this information is assembled to complete the class definition. The completion is a second object of class `"classRepresentation"`, cached for the session or until something happens to change the information. A call to `[getClass](getclass)` returns the completed definition of a class; a call to `[getClassDef](getclass)` returns the stored definition (uncompleted). In particular, completion fills in the upward- and downward-pointing inheritance information for the class, in slots `contains` and `subclasses` respectively. It's in principle important to note that this information can depend on which packages are installed, since these may define additional subclasses or superclasses. ### Slots `slots`: A named list of the slots in this class; the elements of the list are the classes to which the slots must belong (or extend), and the names of the list gives the corresponding slot names. `contains`: A named list of the classes this class ‘contains’; the elements of the list are objects of `[SClassExtension](sclassextension-class)`. The list may be only the direct extensions or all the currently known extensions (see the details). `virtual`: Logical flag, set to `TRUE` if this is a virtual class. `prototype`: The object that represents the standard prototype for this class; i.e., the data and slots returned by a call to `<new>` for this class with no special arguments. Don't mess with the prototype object directly. `validity`: Optionally, a function to be used to test the validity of objects from this class. See `[validObject](validobject)`. `access`: Access control information. Not currently used. `className`: The character string name of the class. `package`: The character string name of the package to which the class belongs. Nearly always the package on which the metadata for the class is stored, but in operations such as constructing inheritance information, the internal package name rules. `subclasses`: A named list of the classes known to extend this class'; the elements of the list are objects of class `[SClassExtension](sclassextension-class)`. The list is currently only filled in when completing the class definition (see the details). `versionKey`: Object of class `"externalptr"`; eventually will perhaps hold some versioning information, but not currently used. `sealed`: Object of class `"logical"`; is this class sealed? If so, no modifications are allowed. ### See Also See function `[setClass](setclass)` to supply the information in the class definition. See [Classes\_Details](classes_details) for a more basic discussion of class information. r None `setAs` Methods for Coercing an Object to a Class -------------------------------------------------- ### Description A call to `setAs` defines a method for coercing an object of class `from` to class `to`. The methods will then be used by calls to `<as>` for objects with class `from`, including calls that replace part of the object. Methods for this purpose work indirectly, by defining methods for function `coerce`. The `coerce` function is *not* to be called directly, and method selection uses class inheritance only on the first argument. ### Usage ``` setAs(from, to, def, replace, where = topenv(parent.frame())) ``` ### Arguments | | | | --- | --- | | `from, to` | The classes between which the coerce methods `def` and `replace` perform coercion. | | `def` | function of one argument. It will get an object from class `from` and had better return an object of class `to`. The convention is that the name of the argument is `from`; if another argument name is used, `setAs` will attempt to substitute `from`. | | `replace` | if supplied, the function to use as a replacement method, when `as` is used on the left of an assignment. Should be a function of two arguments, `from, value`, although `setAs` will attempt to substitute if the arguments differ. *The remaining argument will not be used in standard applications.* | | `where` | the position or environment in which to store the resulting methods. Do not use this argument when defining a method in a package. Only the default, the namespace of the package, should be used in normal situations. | ### Inheritance and Coercion Objects from one class can turn into objects from another class either automatically or by an explicit call to the `as` function. Automatic conversion is special, and comes from the designer of one class of objects asserting that this class extends another class. The most common case is that one or more class names are supplied in the `contains=` argument to `setClass`, in which case the new class extends each of the earlier classes (in the usual terminology, the earlier classes are *superclasses* of the new class and it is a *subclass* of each of them). This form of inheritance is called *simple* inheritance in **R**. See `[setClass](setclass)` for details. Inheritance can also be defined explicitly by a call to `[setIs](setis)`. The two versions have slightly different implications for coerce methods. Simple inheritance implies that inherited slots behave identically in the subclass and the superclass. Whenever two classes are related by simple inheritance, corresponding coerce methods are defined for both direct and replacement use of `as`. In the case of simple inheritance, these methods do the obvious computation: they extract or replace the slots in the object that correspond to those in the superclass definition. The implicitly defined coerce methods may be overridden by a call to `setAs`; note, however, that the implicit methods are defined for each subclass-superclass pair, so that you must override each of these explicitly, not rely on inheritance. When inheritance is defined by a call to `setIs`, the coerce methods are provided explicitly, not generated automatically. Inheritance will apply (to the `from` argument, as described in the section below). You could also supply methods via `setAs` for non-inherited relationships, and now these also can be inherited. For further on the distinction between simple and explicit inheritance, see `[setIs](setis)`. ### How Functions 'as' and 'setAs' Work The function `as` turns `object` into an object of class `Class`. In doing so, it applies a “coerce method”, using S4 classes and methods, but in a somewhat special way. Coerce methods are methods for the function `coerce` or, in the replacement case the function ``coerce<-``. These functions have two arguments in method signatures, `from` and `to`, corresponding to the class of the object and the desired coerce class. These functions must not be called directly, but are used to store tables of methods for the use of `as`, directly and for replacements. In this section we will describe the direct case, but except where noted the replacement case works the same way, using ``coerce<-`` and the `replace` argument to `setAs`, rather than `coerce` and the `def` argument. Assuming the `object` is not already of the desired class, `as` first looks for a method in the table of methods for the function `coerce` for the signature `c(from = class(object), to = Class)`, in the same way method selection would do its initial lookup. To be precise, this means the table of both direct and inherited methods, but inheritance is used specially in this case (see below). If no method is found, `as` looks for one. First, if either `Class` or `class(object)` is a superclass of the other, the class definition will contain the information needed to construct a coerce method. In the usual case that the subclass contains the superclass (i.e., has all its slots), the method is constructed either by extracting or replacing the inherited slots. Non-simple extensions (the result of a call to `[setIs](setis)`) will usually contain explicit methods, though possibly not for replacement. If no subclass/superclass relationship provides a method, `as` looks for an inherited method, but applying, inheritance for the argument `from` only, not for the argument `to` (if you think about it, you'll probably agree that you wouldn't want the result to be from some class other than the `Class` specified). Thus, `selectMethod("coerce", sig, useInherited= c(from=TRUE, to= FALSE))` replicates the method selection used by `as()`. In nearly all cases the method found in this way will be cached in the table of coerce methods (the exception being subclass relationships with a test, which are legal but discouraged). So the detailed calculations should be done only on the first occurrence of a coerce from `class(object)` to `Class`. Note that `coerce` is not a standard generic function. It is not intended to be called directly. To prevent accidentally caching an invalid inherited method, calls are routed to an equivalent call to `as`, and a warning is issued. Also, calls to `[selectMethod](getmethod)` for this function may not represent the method that `as` will choose. You can only trust the result if the corresponding call to `as` has occurred previously in this session. With this explanation as background, the function `setAs` does a fairly obvious computation: It constructs and sets a method for the function `coerce` with signature `c(from, to)`, using the `def` argument to define the body of the method. The function supplied as `def` can have one argument (interpreted as an object to be coerced) or two arguments (the `from` object and the `to` class). Either way, `setAs` constructs a function of two arguments, with the second defaulting to the name of the `to` class. The method will be called from `as` with the object as the `from` argument and no `to` argument, with the default for this argument being the name of the intended `to` class, so the method can use this information in messages. The direct version of the `as` function also has a `strict=` argument that defaults to `TRUE`. Calls during the evaluation of methods for other functions will set this argument to `FALSE`. The distinction is relevant when the object being coerced is from a simple subclass of the `to` class; if `strict=FALSE` in this case, nothing need be done. For most user-written coerce methods, when the two classes have no subclass/superclass, the `strict=` argument is irrelevant. The `replace` argument to `setAs` provides a method for ``coerce<-``. As with all replacement methods, the last argument of the method must have the name `value` for the object on the right of the assignment. As with the `coerce` method, the first two arguments are `from, to`; there is no `strict=` option for the replace case. The function `coerce` exists as a repository for such methods, to be selected as described above by the `as` function. Actually dispatching the methods using `standardGeneric` could produce incorrect inherited methods, by using inheritance on the `to` argument; as mentioned, this is not the logic used for `as`. To prevent selecting and caching invalid methods, calls to `coerce` are currently mapped into calls to `as`, with a warning message. ### Basic Coercion Methods Methods are pre-defined for coercing any object to one of the basic datatypes. For example, `as(x, "numeric")` uses the existing `as.numeric` function. These built-in methods can be listed by `showMethods("coerce")`. ### References Chambers, John M. (2016) *Extending R*, Chapman & Hall. (Chapters 9 and 10.) ### See Also If you think of using `try(as(x, cl))`, consider `[canCoerce](cancoerce)(x, cl)` instead. ### Examples ``` ## using the definition of class "track" from \link{setClass} setAs("track", "numeric", function(from) from@y) t1 <- new("track", x=1:20, y=(1:20)^2) as(t1, "numeric") ## The next example shows: ## 1. A virtual class to define setAs for several classes at once. ## 2. as() using inherited information setClass("ca", slots = c(a = "character", id = "numeric")) setClass("cb", slots = c(b = "character", id = "numeric")) setClass("id") setIs("ca", "id") setIs("cb", "id") setAs("id", "numeric", function(from) from@id) CA <- new("ca", a = "A", id = 1) CB <- new("cb", b = "B", id = 2) setAs("cb", "ca", function(from, to )new(to, a=from@b, id = from@id)) as(CB, "numeric") ``` r None `nonStructure-class` A non-structure S4 Class for basic types -------------------------------------------------------------- ### Description S4 classes that are defined to extend one of the basic vector classes should contain the class `[structure](structureclasses)` if they behave like structures; that is, if they should retain their class behavior under math functions or operators, so long as their length is unchanged. On the other hand, if their class depends on the values in the object, not just its structure, then they should lose that class under any such transformations. In the latter case, they should be defined to contain `nonStructure`. If neither of these strategies applies, the class likely needs some methods of its own for `[Ops](s4groupgeneric)`, `[Math](s4groupgeneric)`, and/or other generic functions. What is not usually a good idea is to allow such computations to drop down to the default, base code. This is inconsistent with most definitions of such classes. ### Methods Methods are defined for operators and math functions (groups `[Ops](s4groupgeneric)`, `[Math](s4groupgeneric)` and `[Math2](s4groupgeneric)`). In all cases the result is an ordinary vector of the appropriate type. ### References Chambers, John M. (2008) *Software for Data Analysis: Programming with R* Springer. ### See Also `[structure](structureclasses)` ### Examples ``` setClass("NumericNotStructure", contains = c("numeric","nonStructure")) xx <- new("NumericNotStructure", 1:10) xx + 1 # vector log(xx) # vector sample(xx) # vector ``` r None `setClass` Create a Class Definition ------------------------------------- ### Description Create a class definition and return a generator function to create objects from the class. Typical usage will be of the style: `myClass <- setClass("myClass", slots= ...., contains =....)` where the first argument is the name of the new class and, if supplied, the arguments `slots=` and `contains=` specify the slots in the new class and existing classes from which the new class should inherit. Calls to `setClass()` are normally found in the source of a package; when the package is loaded the class will be defined in the package's namespace. Assigning the generator function with the name of the class is convenient for users, but not a requirement. ### Usage ``` setClass(Class, representation, prototype, contains=character(), validity, access, where, version, sealed, package, S3methods = FALSE, slots) ``` ### Arguments | | | | --- | --- | | `Class` | character string name for the class. | | `slots` | The names and classes for the slots in the new class. This argument must be supplied by name, `slots=`, in the call, for back compatibility with other arguments no longer recommended. The argument must be vector with a names attribute, the names being those of the slots in the new class. Each element of the vector specifies an existing class; the corresponding slot must be from this class or a subclass of it. Usually, this is a character vector naming the classes. It's also legal for the elements of the vector to be class representation objects, as returned by `[getClass](getclass)`. As a limiting case, the argument may be an unnamed character vector; the elements are taken as slot names and all slots have the unrestricted class `"ANY"`. | | `contains` | A vector specifying existing classes from which this class should inherit. The new class will have all the slots of the superclasses, with the same requirements on the classes of these slots. This argument must be supplied by name, `contains=`, in the call, for back compatibility with other arguments no longer recommended. See the section ‘Virtual Classes’ for the special superclass `"VIRTUAL"`. | | `prototype, where, validity, sealed, package` | *These arguments are currently allowed, but either they are unlikely to be useful or there are modern alternatives that are preferred.* `prototype`: supplies an object with the default data for the slots in this class. A more flexible approach is to write a method for `[initialize](new)()`. `where`: supplies an environment in which to store the definition. Should not be used: For calls to `setClass()` appearing in the source code for a package the definition will be stored in the namespace of the package. `validity`: supplied a validity-checking method for objects from this class. For clearer code, use a separate call to `[setValidity](validobject)()`. `sealed`: if `TRUE`, the class definition will be sealed, so that another call to `setClass` will fail on this class name. But the definition is automatically sealed after the namespace is loaded, so explicit sealing it is not needed. `package`: supplies an optional package name for the class, but the class attribute should be the package in which the class definition is assigned, as it is by default. | | `representation, access, version, S3methods` | *All these arguments are deprecated from version 3.0.0 of **R** and should be avoided*. `representation` is an argument inherited from S that included both `slots` and `contains`, but the use of the latter two arguments is clearer and recommended. `access` and `version` are included for historical compatibility with S-Plus, but ignored. `S3methods` is a flag indicating that old-style methods will be written involving this class; ignored now. | ### Value A generator function suitable for creating objects from the class is returned, invisibly. A call to this function generates a call to `<new>` for the class. The call takes any number of arguments, which will be passed on to the initialize method. If no `initialize` method is defined for the class or one of its superclasses, the default method expects named arguments with the name of one of the slots and unnamed arguments that are objects from one of the contained classes. Typically the generator function is assigned the name of the class, for programming clarity. This is not a requirement and objects from the class can also be generated directly from `<new>`. The advantages of the generator function are a slightly simpler and clearer call, and that the call will contain the package name of the class (eliminating any ambiguity if two classes from different packages have the same name). If the class is virtual, an attempt to generate an object from either the generator or `new()` will result in an error. ### Basic Use: Slots and Inheritance The two essential arguments other than the class name are `slots` and `contains`, defining the explicit slots and the inheritance (superclasses). Together, these arguments define all the information in an object from this class; that is, the names of all the slots and the classes required for each of them. The name of the class determines which methods apply directly to objects from this class. The superclass information specifies which methods apply indirectly, through inheritance. See [Methods\_Details](methods_details) for inheritance in method selection. The slots in a class definition will be the union of all the slots specified directly by `slots` and all the slots in all the contained classes. There can only be one slot with a given name. A class may override the definition of a slot with a given name, but *only* if the newly specified class is a subclass of the inherited one. For example, if the contained class had a slot `a` with class `"ANY"`, then a subclass could specify `a` with class `"numeric"`, but if the original specification for the slot was class `"character"`, the new call to `setClass` would generate an error. Slot names `"class"` and `"Class"` are not allowed. There are other slot names with a special meaning; these names start with the `"."` character. To be safe, you should define all of your own slots with names starting with an alphabetic character. Some inherited classes will be treated specially—object types, S3 classes and a few special cases—whether inherited directly or indirectly. See the next three sections. ### Virtual Classes Classes exist for which no actual objects can be created, the *virtual* classes. The most common and useful form of virtual class is the *class union*, a virtual class that is defined in a call to `[setClassUnion](setclassunion)()` rather than a call to `setClass()`. This call lists the *members* of the union—subclasses that extend the new class. Methods that are written with the class union in the signature are eligible for use with objects from any of the member classes. Class unions can include as members classes whose definition is otherwise sealed, including basic **R** data types. Calls to `setClass()` will also create a virtual class, either when only the `Class` argument is supplied (no slots or superclasses) or when the `contains=` argument includes the special class name `"VIRTUAL"`. In the latter case, a virtual class may include slots to provide some common behavior without fully defining the object—see the class `[traceable](traceclasses)` for an example. Note that `"VIRTUAL"` does not carry over to subclasses; a class that contains a virtual class is not itself automatically virtual. ### Inheriting from Object Types In addition to containing other S4 classes, a class definition can contain either an S3 class (see the next section) or a built-in R pseudo-class—one of the **R** object types or one of the special **R** pseudo-classes `"matrix"` and `"array"`. A class can contain at most one of the object types, directly or indirectly. When it does, that contained class determines the “data part” of the class. This appears as a pseudo-slot, `".Data"` and can be treated as a slot but actually determines the type of objects from this slot. Objects from the new class try to inherit the built in behavior of the contained type. In the case of normal **R** data types, including vectors, functions and expressions, the implementation is relatively straightforward. For any object `x` from the class, `typeof(x)` will be the contained basic type; and a special pseudo-slot, `.Data`, will be shown with the corresponding class. See the `"numWithId"` example below. Classes may also inherit from `"vector"`, `"matrix"` or `"array"`. The data part of these objects can be any vector data type. For an object from any class that does *not* contain one of these types or classes, `typeof(x)` will be `"S4"`. Some **R** data types do not behave normally, in the sense that they are non-local references or other objects that are not duplicated. Examples include those corresponding to classes `"environment"`, `"externalptr"`, and `"name"`. These can not be the types for objects with user-defined classes (either S4 or S3) because setting an attribute overwrites the object in all contexts. It is possible to define a class that inherits from such types, through an indirect mechanism that stores the inherited object in a reserved slot, `".xData"`. See the example for class `"stampedEnv"` below. An object from such a class does *not* have a `".Data"` pseudo-slot. For most computations, these classes behave transparently as if they inherited directly from the anomalous type. S3 method dispatch and the relevant `as.`*type*`()` functions should behave correctly, but code that uses the type of the object directly will not. For example, `as.environment(e1)` would work as expected with the `"stampedEnv"` class, but `typeof(e1)` is `"S4"`. ### Inheriting from S3 Classes Old-style S3 classes have no formal definition. Objects are “from” the class when their class attribute contains the character string considered to be the class name. Using such classes with formal classes and methods is necessarily a risky business, since there are no guarantees about the content of the objects or about consistency of inherited methods. Given that, it is still possible to define a class that inherits from an S3 class, providing that class has been registered as an old class (see `[setOldClass](setoldclass)`). Broadly speaking, both S3 and S4 method dispatch try to behave sensibly with respect to inheritance in either system. Given an S4 object, S3 method dispatch and the `[inherits](../../base/html/class)` function should use the S4 inheritance information. Given an S3 object, an S4 generic function will dispatch S4 methods using the S3 inheritance, provided that inheritance has been declared via `[setOldClass](setoldclass)`. For details, see `[setOldClass](setoldclass)` and Section 10.8 of the reference. ### Classes and Packages Class definitions normally belong to packages (but can be defined in the global environment as well, by evaluating the expression on the command line or in a file sourced from the command line). The corresponding package name is part of the class definition; that is, part of the `[classRepresentation](classrepresentation-class)` object holding that definition. Thus, two classes with the same name can exist in different packages, for most purposes. When a class name is supplied for a slot or a superclass in a call to `setClass`, a corresponding class definition will be found, looking from the namespace of the current package, assuming the call in question appears directly in the source for the package, as it should to avoid ambiguity. The class definition must be already defined in this package, in the imports directives of the package's `DESCRIPTION` and `NAMESPACE` files or in the basic classes defined by the methods package. (The ‘methods’ package must be included in the imports directives for any package that uses S4 methods and classes, to satisfy the `"CMD check"` utility.) If a package imports two classes of the same name from separate packages, the `[packageSlot](getpackagename)` of the `name` argument needs to be set to the package name of the particular class. This should be a rare occurrence. ### References Chambers, John M. (2016) *Extending R*, Chapman & Hall. (Chapters 9 and 10.) ### See Also `[Classes\_Details](classes_details)` for a general discussion of classes, `[Methods\_Details](methods_details)` for an analogous discussion of methods, `[makeClassRepresentation](setsclass)` ### Examples ``` ## A simple class with two slots track <- setClass("track", slots = c(x="numeric", y="numeric")) ## an object from the class t1 <- track(x = 1:10, y = 1:10 + rnorm(10)) ## A class extending the previous, adding one more slot trackCurve <- setClass("trackCurve", slots = c(smooth = "numeric"), contains = "track") ## an object containing a superclass object t1s <- trackCurve(t1, smooth = 1:10) ## A class similar to "trackCurve", but with different structure ## allowing matrices for the "y" and "smooth" slots setClass("trackMultiCurve", slots = c(x="numeric", y="matrix", smooth="matrix"), prototype = list(x=numeric(), y=matrix(0,0,0), smooth= matrix(0,0,0))) ## A class that extends the built-in data type "numeric" numWithId <- setClass("numWithId", slots = c(id = "character"), contains = "numeric") numWithId(1:3, id = "An Example") ## inherit from reference object of type "environment" stampedEnv <- setClass("stampedEnv", contains = "environment", slots = c(update = "POSIXct")) setMethod("[[<-", c("stampedEnv", "character", "missing"), function(x, i, j, ..., value) { ev <- as(x, "environment") ev[[i]] <- value #update the object in the environment x@update <- Sys.time() # and the update time x}) e1 <- stampedEnv(update = Sys.time()) e1[["noise"]] <- rnorm(10) ```
programming_docs
r None `hasArg` Look for an Argument in the Call ------------------------------------------ ### Description Returns `TRUE` if `name` corresponds to an argument in the call, either a formal argument to the function, or a component of `...`, and `FALSE` otherwise. ### Usage ``` hasArg(name) ``` ### Arguments | | | | --- | --- | | `name` | The name of a potential argument, as an unquoted name or character string. | ### Details The expression `hasArg(x)`, for example, is similar to `!missing(x)`, with two exceptions. First, `hasArg` will look for an argument named `x` in the call if `x` is not a formal argument to the calling function, but `...` is. Second, `hasArg` never generates an error if given a name as an argument, whereas `missing(x)` generates an error if `x` is not a formal argument. ### Value Always `TRUE` or `FALSE` as described above. ### See Also `[missing](../../base/html/missing)` ### Examples ``` ftest <- function(x1, ...) c(hasArg(x1), hasArg("y2")) ftest(1) ## c(TRUE, FALSE) ftest(1, 2) ## c(TRUE, FALSE) ftest(y2 = 2) ## c(FALSE, TRUE) ftest(y = 2) ## c(FALSE, FALSE) (no partial matching) ftest(y2 = 2, x = 1) ## c(TRUE, TRUE) partial match x1 ``` r None `stdRefClass` Class "envRefClass" ---------------------------------- ### Description Support Class to Implement R Objects using Reference Semantics ### NOTE: The software described here is an initial version. The eventual goal is to support reference-style classes with software in **R** itself or using inter-system interfaces. The current implementation (**R** version 2.12.0) is preliminary and subject to change, and currently includes only the **R**-only implementation. Developers are encouraged to experiment with the software, but the description here is more than usually subject to change. ### Purpose of the Class This class implements basic reference-style semantics for **R** objects. Objects normally do not come directly from this class, but from subclasses defined by a call to `[setRefClass](refclass)`. The documentation below is technical background describing the implementation, but applications should use the interface documented under `[setRefClass](refclass)`, in particular the `$` operator and field accessor functions as described there. ### A Basic Reference Class The design of reference classes for **R** divides those classes up according to the mechanism used for implementing references, fields, and class methods. Each version of this mechanism is defined by a *basic reference class*, which must implement a set of methods and provide some further information used by `[setRefClass](refclass)`. The required methods are for operators `$` and `$<-` to get and set a field in an object, and for `[initialize](new)` to initialize objects. To support these methods, the basic reference class needs to have some implementation mechanism to store and retrieve data from fields in the object. The mechanism needs to be consistent with reference semantics; that is, changes made to the contents of an object are global, seen by any code accessing that object, rather than only local to the function call where the change takes place. As described below, class `envRefClass` implements reference semantics through specialized use of [environment](environmentclass) objects. Other basic reference classes may use an interface to a language such as Java or C++ using reference semantics for classes. Usually, the **R** user will be able to invoke class methods on the class, using the `$` operator. The basic reference class method for `$` needs to make this possible. Essentially, the operator must return an **R** function corresponding to the object and the class method name. Class methods may include an implementation of data abstraction, in the sense that fields are accessed by “get” and “set” methods. The basic reference class provides this facility by setting the `"fieldAccessorGenerator"` slot in its definition to a function of one variable. This function will be called by `[setRefClass](refclass)` with the vector of field names as arguments. The generator function must return a list of defined accessor functions. An element corresponding to a get operation is invoked with no arguments and should extract the corresponding field; an element for a set operation will be invoked with a single argument, the value to be assigned to the field. The implementation needs to supply the object, since that is not an argument in the method invocation. The mechanism used currently by `envRefClass` is described below. ### Support Classes Two virtual classes are supplied to test for reference objects: `is(x, "refClass")` tests whether `x` comes from a class defined using the reference class mechanism described here; `is(x, "refObject")` tests whether the object has reference semantics generally, including the previous classes and also classes inheriting from the **R** types with reference semantics, such as `"environment"`. Installed class methods are `"classMethodDefinition"` objects, with slots that identify the name of the function as a class method and the other class methods called from this method. The latter information is determined heuristically when the class is defined by using the `codetools` recommended package. This package must be installed when reference classes are defined, but is not needed in order to use existing reference classes. ### Author(s) John Chambers r None `canCoerce` Can an Object be Coerced to a Certain S4 Class? ------------------------------------------------------------ ### Description Test if an object can be coerced to a given S4 class. Maybe useful inside `if()` to ensure that calling `as(object, Class)` will find a method. ### Usage ``` canCoerce(object, Class) ``` ### Arguments | | | | --- | --- | | `object` | any **R** object, typically of a formal S4 class. | | `Class` | an S4 class (see `[isClass](findclass)`). | ### Value a scalar logical, `TRUE` if there is a `coerce` method (as defined by e.g. `[setAs](setas)`) for the signature `(from = class(object), to = Class)`. ### See Also `<as>`, `[setAs](setas)`, `[selectMethod](getmethod)`, `[setClass](setclass)`, ### Examples ``` m <- matrix(pi, 2,3) canCoerce(m, "numeric") # TRUE canCoerce(m, "array") # TRUE ``` r None `Classes` S4 Class Documentation --------------------------------- ### Description You have navigated to an old link to documentation of S4 classes. For basic use of classes and methods, see [Introduction](introduction); to create new class definitions, see `[setClass](setclass)`; for technical details on S4 classes, see [Classes\_Details](classes_details). ### References Chambers, John M. (2016) *Extending R*, Chapman & Hall. (Chapters 9 and 10.) r None `zBasicFunsList` List of Builtin and Special Functions ------------------------------------------------------- ### Description A named list providing instructions for turning builtin and special functions into generic functions. Functions in R that are defined as `.Primitive(<name>)` are not suitable for formal methods, because they lack the basic reflectance property. You can't find the argument list for these functions by examining the function object itself. Future versions of R may fix this by attaching a formal argument list to the corresponding function. While generally the names of arguments are not checked by the internal code implementing the function, the number of arguments frequently is. In any case, some definition of a formal argument list is needed if users are to define methods for these functions. In particular, if methods are to be merged from multiple packages, the different sets of methods need to agree on the formal arguments. In the absence of reflectance, this list provides the relevant information via a dummy function associated with each of the known specials for which methods are allowed. At the same, the list flags those specials for which methods are meaningless (e.g., `for`) or just a very bad idea (e.g., `.Primitive`). A generic function created via `[setMethod](setmethod)`, for example, for one of these special functions will have the argument list from `.BasicFunsList`. If no entry exists, the argument list `(x, ...)` is assumed. r None `promptClass` Generate a Shell for Documentation of a Formal Class ------------------------------------------------------------------- ### Description Assembles all relevant slot and method information for a class, with minimal markup for Rd processing; no QC facilities at present. ### Usage ``` promptClass(clName, filename = NULL, type = "class", keywords = "classes", where = topenv(parent.frame()), generatorName = clName) ``` ### Arguments | | | | --- | --- | | `clName` | a character string naming the class to be documented. | | `filename` | usually, a connection or a character string giving the name of the file to which the documentation shell should be written. The default corresponds to a file whose name is the topic name for the class documentation, followed by `".Rd"`. Can also be `NA` (see below). | | `type` | the documentation type to be declared in the output file. | | `keywords` | the keywords to include in the shell of the documentation. The keyword `"classes"` should be one of them. | | `where` | where to look for the definition of the class and of methods that use it. | | `generatorName` | the name for a generator function for this class; only required if a generator function was created *and* saved under a name different from the class name. | ### Details The class definition is found on the search list. Using that definition, information about classes extended and slots is determined. In addition, the currently available generics with methods for this class are found (using `[getGenerics](genericfunctions)`). Note that these methods need not be in the same environment as the class definition; in particular, this part of the output may depend on which packages are currently in the search list. As with other prompt-style functions, unless `filename` is `NA`, the documentation shell is written to a file, and a message about this is given. The file will need editing to give information about the *meaning* of the class. The output of `promptClass` can only contain information from the metadata about the formal definition and how it is used. If `filename` is `NA`, a list-style representation of the documentation shell is created and returned. Writing the shell to a file amounts to `cat(unlist(x), file = filename, sep = "\n")`, where `x` is the list-style representation. If a generator function is found assigned under the class name or the optional `generatorName`, skeleton documentation for that function is added to the file. ### Value If `filename` is `NA`, a list-style representation of the documentation shell. Otherwise, the name of the file written to is returned invisibly. ### Author(s) VJ Carey [[email protected]](mailto:[email protected]) and John Chambers ### References Chambers, John M. (2008) *Software for Data Analysis: Programming with R* Springer. (For the R version.) Chambers, John M. (1998) *Programming with Data* Springer (For the original S4 version.) ### See Also `[prompt](../../utils/html/prompt)` for documentation of functions, `[promptMethods](promptmethods)` for documentation of method definitions. For processing of the edited documentation, either use `R CMD [Rdconv](../../base/html/rdutils)`, or include the edited file in the ‘man’ subdirectory of a package. ### Examples ``` ## Not run: > promptClass("track") A shell of class documentation has been written to the file "track-class.Rd". ## End(Not run) ``` r None `findMethods` Description of the Methods Defined for a Generic Function ------------------------------------------------------------------------ ### Description The function `findMethods` converts the methods defined in a table for a generic function (as used for selection of methods) into a list, for study or display. The list is actually from the class `listOfMethods` (see the section describing the class, below). The list will be limited to the methods defined in environment `where` if that argument is supplied and limited to those including one or more of the specified `classes` in the method signature if that argument is supplied. To see the actual table (an `[environment](../../base/html/environment)`) used for methods dispatch, call `[getMethodsForDispatch](methodsupport)`. The names of the list returned by `findMethods` are the names of the objects in the table. The function `findMethodSignatures` returns a character matrix whose rows are the class names from the signature of the corresponding methods; it operates either from a list returned by `findMethods`, or by computing such a list itself, given the same arguments as `findMethods` . The function `hasMethods` returns `TRUE` or `FALSE` according to whether there is a non-empty table of methods for function `f` in the environment or search position `where` (or for the generic function generally if `where` is missing). The defunct function `getMethods` is an older alternative to `findMethods` , returning information in the form of an object of class `MethodsList`, previously used for method dispatch. This class of objects is deprecated generally and will disappear in a future version of R. ### Usage ``` findMethods(f, where, classes = character(), inherited = FALSE, package = "") findMethodSignatures(..., target = TRUE, methods = ) hasMethods(f, where, package) ## Deprecated in 2010 and defunct in 2015 for 'table = FALSE': getMethods(f, where, table = FALSE) ``` ### Arguments | | | | --- | --- | | `f` | A generic function or the character-string name of one. | | `where` | Optionally, an environment or position on the search list to look for methods metadata. If `where` is missing, `findMethods` uses the current table of methods in the generic function itself, and `hasMethods` looks for metadata anywhere in the search list. | | `table` | If `TRUE` in a call to `getMethods` the returned value is the table used for dispatch, including inherited methods discovered to date. Used internally, but since the default result is the now unused `mlist` object, the default will likely be changed at some point. | | `classes` | If supplied, only methods whose signatures contain at least one of the supplied classes will be included in the value returned. | | `inherited` | Logical flag; if `TRUE`, the table of all methods, inherited or defined directly, will be used; otherwise, only the methods explicitly defined. Option `TRUE` is meaningful only if `where` is missing. | | `...` | In the call to `findMethodSignatures`, any arguments that might be given to `findMethods`. | | `target` | Optional flag to `findMethodSignatures`; if `TRUE`, the signatures used are the target signatures (the classes for which the method will be selected); if `FALSE`, they will be the signatures are defined. The difference is only meaningful if `inherited` is `TRUE`. | | `methods` | In the call to `findMethodSignatures`, an optional list of methods, presumably returned by a previous call to `findMethods`. If missing, that function will be call with the ... arguments. | | `package` | In a call to `hasMethods`, the package name for the generic function (e.g., `"base"` for primitives). If missing this will be inferred either from the `"package"` attribute of the function name, if any, or from the package slot of the generic function. See ‘Details’. | ### Details The functions obtain a table of the defined methods, either from the generic function or from the stored metadata object in the environment specified by `where`. In a call to `getMethods`, the information in the table is converted as described above to produce the returned value, except with the `table` argument. Note that `hasMethods`, but not the other functions, can be used even if no generic function of this name is currently found. In this case `package` must either be supplied as an argument or included as an attribute of `f`, since the package name is part of the identification of the methods tables. ### The Class for lists of methods The class `"listOfMethods"` returns the methods as a named list of method definitions (or a primitive function, see the slot documentation below). The names are the strings used to store the corresponding objects in the environment from which method dispatch is computed. The current implementation uses the names of the corresponding classes in the method signature, separated by `"#"` if more than one argument is involved in the signature. ### Slots `.Data`: Object of class `"list"` The method definitions. Note that these may include the primitive function itself as default method, when the generic corresponds to a primitive. (Basically, because primitive functions are abnormal R objects, which cannot currently be extended as method definitions.) Computations that use the returned list to derive other information need to take account of this possibility. See the implementation of `findMethodSignatures` for an example. `arguments`: Object of class `"character"`. The names of the formal arguments in the signature of the generic function. `signatures`: Object of class `"list"`. A list of the signatures of the individual methods. This is currently the result of splitting the `names` according to the `"#"` separator. If the object has been constructed from a table, as when returned by `findMethods`, the signatures will all have the same length. However, a list rather than a character matrix is used for generality. Calling `findMethodSignatures` as in the example below will always convert to the matrix form. `generic`: Object of class `"genericFunction"`. The generic function corresponding to these methods. There are plans to generalize this slot to allow reference to the function. `names`: Object of class `"character"`. The names as noted are the class names separated by `"#"` . ### Extends Class `"[namedList](basicclasses)"`, directly. Class `"[list](basicclasses)"`, by class `"namedList"`, distance 2. Class `"[vector](basicclasses)"`, by class `"namedList"`, distance 3. ### See Also `[showMethods](showmethods)`, `[selectMethod](getmethod)`, [Methods\_Details](methods_details) ### Examples ``` mm <- findMethods("Ops") findMethodSignatures(methods = mm) ``` r None `LinearMethodsList-class` Class "LinearMethodsList" ---------------------------------------------------- ### Description A version of methods lists that has been ‘linearized’ for producing summary information. The actual objects from class `"MethodsList"` used for method dispatch are defined recursively over the arguments involved. ### Objects from the Class The function `[linearizeMlist](methodslist)` converts an ordinary methods list object into the linearized form. ### Slots `methods`: Object of class `"list"`, the method definitions. `arguments`: Object of class `"list"`, the corresponding formal arguments, namely as many of the arguments in the signature of the generic function as are active in the relevant method table. `classes`: Object of class `"list"`, the corresponding classes in the signatures. `generic`: Object of class `"genericFunction"`; the generic function to which the methods correspond. ### Future Note The current version of `linearizeMlist` does not take advantage of the `MethodDefinition` class, and therefore does more work for less effect than it could. In particular, we may move to redefine both the function and the class to take advantage of the stored signatures. Don't write code depending precisely on the present form, although all the current information will be obtainable in the future. ### See Also Function `[linearizeMlist](methodslist)` for the computation, and class `[MethodsList](methodslist-class)` for the original, recursive form.
programming_docs
r None `RClassUtils` Utilities for Managing Class Definitions ------------------------------------------------------- ### Description These are various functions to support the definition and use of formal classes. Most of them are rarely suitable to be called directly. Others are somewhat experimental and/or partially implemented only. Do refer to `[setClass](setclass)` for normal code development. ### Usage ``` classLabel(Class) .classEnv(Class, default = .requirePackage("methods"), mustFind = TRUE) testVirtual(properties, extends, prototype, where) makePrototypeFromClassDef(slots, ClassDef, extends, where) newEmptyObject() completeClassDefinition(Class, ClassDef, where, doExtends) getAllSuperClasses(ClassDef, simpleOnly = TRUE) superClassDepth(ClassDef, soFar, simpleOnly = TRUE) isVirtualClass(Class, where) newBasic(Class, ...) makeExtends(Class, coerce, test, replace, by, package, slots, classDef1, classDef2) reconcilePropertiesAndPrototype(name, properties, prototype, superClasses, where) tryNew(Class, where) empty.dump() showClass(Class, complete=TRUE, propertiesAreCalled="Slots") showExtends(ext, printTo = stdout()) possibleExtends(class1, class2, ClassDef1 = getClassDef(class1), ClassDef2 = getClassDef(class2, where = .classEnv(ClassDef1))) completeExtends(ClassDef, class2, extensionDef, where) classMetaName(name) methodsPackageMetaName(prefix, name, package = "") metaNameUndo(strings, prefix, searchForm = FALSE) requireMethods(functions, signature, message, where) checkAtAssignment(cl, name, valueClass) checkSlotAssignment(obj, name, value) defaultPrototype() isClassDef(object) validSlotNames(names) getDataPart(object, NULL.for.none = FALSE) setDataPart(object, value, check = TRUE) ``` ### Summary of Functions `testVirtual`: Test for a Virtual Class. Figures out, as well as possible, whether the class with these properties, extension, and prototype is a virtual class. Can be forced to be virtual by extending `"VIRTUAL"`. Otherwise, a class is virtual only if it has no slots, extends no non-virtual classes, and has a `NULL` Prototype. `makePrototypeFromClassDef`: Makes the prototype implied by the class definition. The following three rules are applied in this order. 1. If the class has slots, then the prototype for each slot is used by default, but a corresponding element in the explicitly supplied prototype in `ClassDef`, if there is one, is used instead (but it must be coercible to the class of the slot). This includes the data part (`".Data"` slot) if there is one. 2. If there are no slots but a non-null prototype was specified, this is returned. 3. If there is a non-virtual superclass (a class in the extends list), then its prototype is used. The data part is extracted if needed (it is allowed to have two superclasses with a data part; the first is used and a warning issued on any others). If all three of the above fail, the prototype is `NULL`. `newEmptyObject`: Utility function to create an empty object into which slots can be set. Currently just creates an empty list with class `"NULL"`. Later version should create a special object reference that marks an object currently with no slots and no data. `completeClassDefinition`: Completes the definition of `Class`, relative to the class definitions visible from environment `where`. If `doExtends` is `TRUE`, complete the super- and sub-class information. This function is called when a class is defined or re-defined. `getFromClassDef`: Extracts one of the intrinsically defined class definition properties (".Properties", etc.) Strictly a utility function. `getSlots`: Returns a named character vector. The names are the names of the slots, the values are the classes of the corresponding slots. The argument `x` can either be the name of a class or the class definition object. `getAllSuperClasses`, `superClassDepth`: Get the names of all the classes that this class definition extends. `getAllSuperClasses` is a utility function used to complete a class definition. It returns all the superclasses reachable from this class, in breadth-first order (which is the order used for matching methods); that is, the first direct superclass followed by all its superclasses, then the next, etc. (The order is relevant only in the case that some of the superclasses have multiple inheritance.) `superClassDepth`, which is called from `getAllSuperClasses`, returns the same information, but as a list with components `label` and `depth`, the latter for the number of generations back each class is in the inheritance tree. The argument `soFar` is used to avoid loops in the network of class relationships. `isVirtualClass`: Is the named class a virtual class? A class is virtual if explicitly declared to be, and also if the class is not formally defined. `assignClassDef`: assign the definition of the class to the specially named object `newBasic`: the implementation of the function `new` for basic classes that don't have a formal definition. Any of these could have a formal definition, except for `Class="NULL"` (disallowed because `NULL` can't have attributes). For all cases except `"NULL"`, the class of the result will be set to `Class`. See `new` for the interpretation of the arguments. `makeExtends`: Construct an SClassExtension object representing the relationship from `Class` to the class defined by `classDef2`. `reconcilePropertiesAndPrototype`: makes a list or a structure look like a prototype for the given class. Specifically, returns a structure with attributes corresponding to the slot names in properties and values taken from prototype if they exist there, from `new(classi)` for the class, `classi` of the slot if that succeeds, and `NULL` otherwise. The prototype may imply slots not in the properties list, since properties does not include inherited slots (these are left unresolved until the class is used in a session). `tryNew`: Tries to generate a new element from this class, but if the attempt fails (as, e.g., when the class is undefined or virtual) just returns `NULL`. This is inefficient and also not a good idea when actually generating objects, but is useful in the initial definition of classes. `showClass`: Print the information about a class definition. If `complete` is `TRUE`, include the indirect information about extensions. It is the utility called from `<show>([getClass](getclass)(.))`, and the user should typically use `getClass(.)` for looking at class definitions. `showExtends`: Print the elements of the list of extensions; for `printTo = FALSE`, returns a list with components `what` and `how`; this is used e.g., by `[promptClass](promptclass)()`. `possibleExtends`: Find the information that says whether class1 extends class2, directly or indirectly. This can be either a logical value or an object of class `[SClassExtension](sclassextension-class)` containing various functions to test and/or coerce the relationship. `classLabel`: Returns an informative character string identifying the class and, if appropriate, the package from which the class came. `.classEnv`: Returns the environment, typically a namespace, in which the `Class` has been defined. `Class` should typically be the result of `[class](../../base/html/class)()` (and hence contain a `"package"` attribute) or `[getClass](getclass)` (or `[getClassDef](getclass)`). `completeExtends`: complete the extends information in the class definition, by following transitive chains. If `class2` and `extensionDef` are included, this class relation is to be added. Otherwise just use the current `ClassDef`. Both the `contains` and `subclasses` slots are completed with any indirect relations visible. `classMetaName`: a name for the object storing this class's definition `methodsPackageMetaName`: a name mangling device to hide metadata defining method and class information. `metaNameUndo` As its name implies, this function undoes the name-mangling used to produce meta-data object names, and returns a object of class `[ObjectsWithPackage](objectswithpackage-class)`. `requireMethods`: Require a subclass to implement methods for the generic functions, for this signature. For each generic, `setMethod` will be called to define a method that throws an error, with the supplied message. The `requireMethods` function allows virtual classes to require actual classes that extend them to implement methods for certain functions, in effect creating an API for the virtual class. Otherwise, default methods for the corresponding function would be called, resulting in less helpful error messages or (worse still) silently incorrect results. `checkSlotAssignment`, `checkAtAssignment`: Check that the value provided is allowed for this slot, by consulting the definition of the class. Called from the C code that assigns slots. For privileged slots (those that can only be set by accessor functions defined along with the class itself), the class designer may choose to improve efficiency by validating the value to be assigned in the accessor function and then calling `slot<-` with the argument `check=FALSE`, to prevent the call to `checkSlotAssignment`. `defaultPrototype`: The prototype for a class which will have slots, is not a virtual class, and does not extend one of the basic classes. Both its `[class](../../base/html/class)` and its (**R** internal) type, `[typeof](../../base/html/typeof)()`, are `"S4"`. `.InitBasicClasses`, `.InitMethodsListClass`, `.setCoerceGeneric`: These functions perform part of the initialization of classes and methods, and are called (only!) from `.onLoad`. `isClassDef`: Is `object` a representation of a class? `validSlotNames`: Returns `names` unless one of the names is reserved, in which case there is an error. (As of writing, `"class"` is the only reserved slot name.) `getDataPart`, `setDataPart`: Utilities called to implement `[email protected]`. Calls to `setDataPart` are also used to merge the data part of a superclass prototype. ### Examples ``` typeof(defaultPrototype()) #-> "S4" ## .classEnv() meth.ns <- asNamespace("methods") if(get4 <- !any("package:stats4" == search())) require("stats4") stopifnot(TRUE , identical(.classEnv("data.frame"), meth.ns) , identical(.classEnv(class(new("data.frame"))), meth.ns) , identical(.classEnv( "mle" ), meth.ns) # <- *not* 'stats4' , identical(.classEnv(class(new("mle"))), asNamespace("stats4")) , identical(.classEnv(getClass ("mle") ), asNamespace("stats4")) ) if(get4) detach("package:stats4") ``` r None `setMethod` Create and Save a Method ------------------------------------- ### Description Create a method for a generic function, corresponding to a signature of classes for the arguments. Standard usage will be of the form: `setMethod(f, signature, definition)` where `f` is the name of the function, `signature` specifies the argument classes for which the method applies and `definition` is the function definition for the method. ### Usage ``` setMethod(f, signature=character(), definition, where = topenv(parent.frame()), valueClass = NULL, sealed = FALSE) ``` ### Arguments | | | | --- | --- | | `f` | The character-string name of the generic function. The unquoted name usually works as well (evaluating to the generic function), except for a few functions in the base package. | | `signature` | The classes required for some of the arguments. Most applications just require one or two character strings matching the first argument(s) in the signature. More complicated cases follow R's rule for argument matching. See the details below; however, if the signature is not trivial, you should use `<method.skeleton>` to generate a valid call to `setMethod`. | | `definition` | A function definition, which will become the method called when the arguments in a call to `f` match the classes in `signature`, directly or through inheritance. The definition must be a function with the same formal arguments as the generic; however, `setMethod()` will handle methods that add arguments, if `...` is a formal argument to the generic. See the Details section. | | `where, valueClass, sealed` | *These arguments are allowed but either obsolete or rarely appropriate.* `where`: where to store the definition; should be the default, the namespace for the package. `valueClass` Obsolete. `sealed` prevents the method being redefined, but should never be needed when the method is defined in the source code of a package. | ### Value The function exists for its side-effect. The definition will be stored in a special metadata object and incorporated in the generic function when the corresponding package is loaded into an R session. ### Method Selection: Avoiding Ambiguity When defining methods, it's important to ensure that methods are selected correctly; in particular, packages should be designed to avoid ambiguous method selection. To describe method selection, consider first the case where only one formal argument is in the active signature; that is, there is only one argument, `x` say, for which methods have been defined. The generic function has a table of methods, indexed by the class for the argument in the calls to `setMethod`. If there is a method in the table for the class of `x` in the call, this method is selected. If not, the next best methods would correspond to the direct superclasses of `class(x)`—those appearing in the `contains=` argument when that class was defined. If there is no method for any of these, the next best would correspond to the direct superclasses of the first set of superclasses, and so on. The first possible source of ambiguity arises if the class has several direct superclasses and methods have been defined for more than one of those; **R** will consider these equally valid and report an ambiguous choice. If your package has the class definition for `class(x)`, then you need to define a method explicitly for this combination of generic function and class. When more than one formal argument appears in the method signature, **R** requires the “best” method to be chosen unambiguously for each argument. Ambiguities arise when one method is specific about one argument while another is specific about a different argument. A call that satisfies both requirements is then ambiguous: The two methods look equally valid, which should be chosen? In such cases the package needs to add a third method requiring both arguments to match. The most common examples arise with binary operators. Methods may be defined for individual operators, for special groups of operators such as `[Arith](s4groupgeneric)` or for group `[Ops](s4groupgeneric)`. ### Exporting Methods If a package defines methods for generic functions, those methods should be exported if any of the classes involved are exported; in other words, if someone using the package might expect these methods to be called. Methods are exported by including an `exportMethods()` directive in the `NAMESPACE` file for the package, with the arguments to the directive being the names of the generic functions for which methods have been defined. Exporting methods is always desirable in the sense of declaring what you want to happen, in that you do expect users to find such methods. It can be essential in the case that the method was defined for a function that is not originally a generic function in its own package (for example, `plot()` in the `graphics` package). In this case it may be that the version of the function in the **R** session is not generic, and your methods will not be called. Exporting methods for a function also exports the generic version of the function. Keep in mind that this does *not* conflict with the function as it was originally defined in another package; on the contrary, it's designed to ensure that the function in the **R** session dispatches methods correctly for your classes and continues to behave as expected when no specific methods apply. See [Methods\_Details](methods_details) for the actual mechanism. ### Details The call to `setMethod` stores the supplied method definition in the metadata table for this generic function in the environment, typically the global environment or the namespace of a package. In the case of a package, the table object becomes part of the namespace or environment of the package. When the package is loaded into a later session, the methods will be merged into the table of methods in the corresponding generic function object. Generic functions are referenced by the combination of the function name and the package name; for example, the function `"show"` from the package `"methods"`. Metadata for methods is identified by the two strings; in particular, the generic function object itself has slots containing its name and its package name. The package name of a generic is set according to the package from which it originally comes; in particular, and frequently, the package where a non-generic version of the function originated. For example, generic functions for all the functions in package base will have `"base"` as the package name, although none of them is an S4 generic on that package. These include most of the base functions that are primitives, rather than true functions; see the section on primitive functions in the documentation for `[setGeneric](setgeneric)` for details. Multiple packages can have methods for the same generic function; that is, for the same combination of generic function name and package name. Even though the methods are stored in separate tables in separate environments, loading the corresponding packages adds the methods to the table in the generic function itself, for the duration of the session. The class names in the signature can be any formal class, including basic classes such as `"numeric"`, `"character"`, and `"matrix"`. Two additional special class names can appear: `"ANY"`, meaning that this argument can have any class at all; and `"missing"`, meaning that this argument *must not* appear in the call in order to match this signature. Don't confuse these two: if an argument isn't mentioned in a signature, it corresponds implicitly to class `"ANY"`, not to `"missing"`. See the example below. Old-style (‘S3’) classes can also be used, if you need compatibility with these, but you should definitely declare these classes by calling `[setOldClass](setoldclass)` if you want S3-style inheritance to work. Method definitions can have default expressions for arguments, but only if the generic function must have *some* default expression for the same argument. (This restriction is imposed by the way **R** manages formal arguments.) If so, and if the corresponding argument is missing in the call to the generic function, the default expression in the method is used. If the method definition has no default for the argument, then the expression supplied in the definition of the generic function itself is used, but note that this expression will be evaluated using the enclosing environment of the method, not of the generic function. Method selection does not evaluate default expressions. All actual (non-missing) arguments in the signature of the generic function will be evaluated when a method is selected—when the call to `standardGeneric(f)` occurs. Note that specifying class `"missing"` in the signature does not require any default expressions. It is possible to have some differences between the formal arguments to a method supplied to `setMethod` and those of the generic. Roughly, if the generic has ... as one of its arguments, then the method may have extra formal arguments, which will be matched from the arguments matching ... in the call to `f`. (What actually happens is that a local function is created inside the method, with the modified formal arguments, and the method is re-defined to call that local function.) Method dispatch tries to match the class of the actual arguments in a call to the available methods collected for `f`. If there is a method defined for the exact same classes as in this call, that method is used. Otherwise, all possible signatures are considered corresponding to the actual classes or to superclasses of the actual classes (including `"ANY"`). The method having the least distance from the actual classes is chosen; if more than one method has minimal distance, one is chosen (the lexicographically first in terms of superclasses) but a warning is issued. All inherited methods chosen are stored in another table, so that the inheritance calculations only need to be done once per session per sequence of actual classes. See [Methods\_Details](methods_details) and Section 10.7 of the reference for more details. ### References Chambers, John M. (2016) *Extending R*, Chapman & Hall. (Chapters 9 and 10.) ### See Also [Methods\_for\_Nongenerics](methods_for_nongenerics) discusses method definition for functions that are not generic functions in their original package; [Methods\_for\_S3](methods_for_s3) discusses the integration of formal methods with the older S3 methods. `<method.skeleton>`, which is the recommended way to generate a skeleton of the call to `setMethod`, with the correct formal arguments and other details. [Methods\_Details](methods_details) and the links there for a general discussion, `[dotsMethods](dotsmethods)` for methods that dispatch on “...”, and `[setGeneric](setgeneric)` for generic functions. ### Examples ``` ## examples for a simple class with two numeric slots. ## (Run example(setMethod) to see the class and function definitions) ## methods for plotting track objects ## ## First, with only one object as argument, plot the two slots ## y must be included in the signature, it would default to "ANY" setMethod("plot", signature(x="track", y="missing"), function(x, y, ...) plot(x@x, x@y, ...) ) ## plot numeric data on either axis against a track object ## (reducing the track object to the cumulative distance along the track) ## Using a short form for the signature, which matches like formal arguments setMethod("plot", c("track", "numeric"), function(x, y, ...) plot(cumdist(x@x, x@y), y, xlab = "Distance",...) ) ## and similarly for the other axis setMethod("plot", c("numeric", "track"), function(x, y, ...) plot(x, cumdist(y@x, y@y), ylab = "Distance",...) ) t1 <- new("track", x=1:20, y=(1:20)^2) plot(t1) plot(qnorm(ppoints(20)), t1) ## Now a class that inherits from "track", with a vector for data at ## the points setClass("trackData", contains = c("numeric", "track")) tc1 <- new("trackData", t1, rnorm(20)) ## a method for plotting the object ## This method has an extra argument, allowed because ... is an ## argument to the generic function. setMethod("plot", c("trackData", "missing"), function(x, y, maxRadius = max(par("cin")), ...) { plot(x@x, x@y, type = "n", ...) symbols(x@x, x@y, circles = abs(x), inches = maxRadius) } ) plot(tc1) ## Without other methods for "trackData", methods for "track" ## will be selected by inheritance plot(qnorm(ppoints(20)), tc1) ## defining methods for primitive function. ## Although "[" and "length" are not ordinary functions ## methods can be defined for them. setMethod("[", "track", function(x, i, j, ..., drop) { x@x <- x@x[i]; x@y <- x@y[i] x }) plot(t1[1:15]) setMethod("length", "track", function(x)length(x@y)) length(t1) ## Methods for binary operators ## A method for the group generic "Ops" will apply to all operators ## unless a method for a more specific operator has been defined. ## For one trackData argument, go on with just the data part setMethod("Ops", signature(e1 = "trackData"), function(e1, e2) callGeneric([email protected], e2)) setMethod("Ops", signature(e2 = "trackData"), function(e1, e2) callGeneric(e1, [email protected])) ## At this point, the choice of a method for a call with BOTH ## arguments from "trackData" is ambiguous. We must define a method. setMethod("Ops", signature(e1 = "trackData", e2 = "trackData"), function(e1, e2) callGeneric([email protected], [email protected])) ## (well, really we should only do this if the "track" part ## of the two arguments matched) tc1 +1 1/tc1 all(tc1 == tc1) ```
programming_docs
r None `removeMethod` Remove a Method ------------------------------- ### Description Remove the method for a given function and signature. Obsolete for ordinary applications: Method definitions in a package should never need to remove methods and it's very bad practice to remove methods that were defined in other packages. ### Usage ``` removeMethod(f, signature, where) ``` ### Arguments | | | | --- | --- | | `f, signature, where` | As for `[setMethod](setmethod)()`. | ### Value `TRUE` if a method was found to be removed. ### References Chambers, John M. (2016) *Extending R*, Chapman & Hall. (Chapters 9 and 10.) r None `representation` Construct a Representation or a Prototype for a Class Definition ---------------------------------------------------------------------------------- ### Description These are old utility functions to construct, respectively a list designed to represent the slots and superclasses and a list of prototype specifications. The `representation()` function is no longer useful, since the arguments `slots` and `contains` to `[setClass](setclass)` are now recommended. The `prototype()` function may still be used for the corresponding argument, but a simple list of the same arguments works as well. ### Usage ``` representation(...) prototype(...) ``` ### Arguments | | | | --- | --- | | `...` | The call to representation takes arguments that are single character strings. Unnamed arguments are classes that a newly defined class extends; named arguments name the explicit slots in the new class, and specify what class each slot should have. In the call to `prototype`, if an unnamed argument is supplied, it unconditionally forms the basis for the prototype object. Remaining arguments are taken to correspond to slots of this object. It is an error to supply more than one unnamed argument. | ### Details The `representation` function applies tests for the validity of the arguments. Each must specify the name of a class. The classes named don't have to exist when `representation` is called, but if they do, then the function will check for any duplicate slot names introduced by each of the inherited classes. The arguments to `prototype` are usually named initial values for slots, plus an optional first argument that gives the object itself. The unnamed argument is typically useful if there is a data part to the definition (see the examples below). ### Value The value of `representation` is just the list of arguments, after these have been checked for validity. The value of `prototype` is the object to be used as the prototype. Slots will have been set consistently with the arguments, but the construction does *not* use the class definition to test validity of the contents (it hardly can, since the prototype object is usually supplied to create the definition). ### References Chambers, John M. (2008) *Software for Data Analysis: Programming with R* Springer. (For the R version.) Chambers, John M. (1998) *Programming with Data* Springer (For the original S4 version.) ### See Also `[setClass](setclass)` ### Examples ``` ## representation for a new class with a directly define slot "smooth" ## which should be a "numeric" object, and extending class "track" representation("track", smooth ="numeric") ### >>> This *is* old syntax -- use 'contains=*, slots=*' instead <<< ### ========== ---------- ------ ====== setClass("Character",representation("character")) setClass("TypedCharacter",representation("Character",type="character"), prototype(character(0),type="plain")) ttt <- new("TypedCharacter", "foo", type = "character") setClass("num1", representation(comment = "character"), contains = "numeric", prototype = prototype(pi, comment = "Start with pi")) ``` r None `BasicClasses` Classes Corresponding to Basic Data Types --------------------------------------------------------- ### Description Formal classes exist corresponding to the basic R object types, allowing these types to be used in method signatures, as slots in class definitions, and to be extended by new classes. ### Usage ``` ### The following are all basic vector classes. ### They can appear as class names in method signatures, ### in calls to as(), is(), and new(). "character" "complex" "double" "expression" "integer" "list" "logical" "numeric" "single" "raw" ### the class "vector" ### is a virtual class, extended by all the above ### the class "S4" ### is an object type for S4 objects that do not extend ### any of the basic vector classes. It is a virtual class. ### The following are additional basic classes "NULL" # NULL objects "function" # function objects, including primitives "externalptr" # raw external pointers for use in C code "ANY" # virtual classes used by the methods package itself "VIRTUAL" "missing" "namedList" # the alternative to "list" that preserves # the names attribute ``` ### Objects from the Classes If a class is not virtual (see section in `[Classes\_Details](classes_details)`), objects can be created by calls of the form `new(Class, ...)`, where `Class` is the quoted class name, and the remaining arguments if any are objects to be interpreted as vectors of this class. Multiple arguments will be concatenated. The class `"expression"` is slightly odd, in that the ... arguments will *not* be evaluated; therefore, don't enclose them in a call to `quote()`. Note that class `"list"` is a pure vector. Although lists with names go back to the earliest versions of S, they are an extension of the vector concept in that they have an attribute (which can now be a slot) and which is either `NULL` or a character vector of the same length as the vector. If you want to guarantee that list names are preserved, use class `"namedList"`, rather than `"list"`. Objects from this class must have a names attribute, corresponding to slot `"names"`, of type `"character"`. Internally, R treats names for lists specially, which makes it impractical to have the corresponding slot in class `"namedList"` be a union of character names and `NULL`. ### Classes and Types The basic classes include classes for the basic R types. Note that objects of these types will not usually be S4 objects (`[isS4](../../base/html/iss4)` will return `FALSE`), although objects from classes that contain the basic class will be S4 objects, still with the same type. The type as returned by `[typeof](../../base/html/typeof)` will sometimes differ from the class, either just from a choice of terminology (type `"symbol"` and class `"name"`, for example) or because there is not a one-to-one correspondence between class and type (most of the classes that inherit from class `"language"` have type `"language"`, for example). ### Extends The vector classes extend `"vector"`, directly. ### Methods coerce Methods are defined to coerce arbitrary objects to the vector classes, by calling the corresponding basic function, for example, `as(x, "numeric")` calls `as.numeric(x)`. r None `callGeneric` Call the Current Generic Function from a Method -------------------------------------------------------------- ### Description A call to `callGeneric` can only appear inside a method definition. It then results in a call to the current generic function. The value of that call is the value of `callGeneric`. While it can be called from any method, it is useful and typically used in methods for group generic functions. ### Usage ``` callGeneric(...) ``` ### Arguments | | | | --- | --- | | `...` | Optionally, the arguments to the function in its next call. If no arguments are included in the call to `callGeneric`, the effect is to call the function with the current arguments. See the detailed description for what this really means. | ### Details The name and package of the current generic function is stored in the environment of the method definition object. This name is looked up and the corresponding function called. The statement that passing no arguments to `callGeneric` causes the generic function to be called with the current arguments is more precisely as follows. Arguments that were missing in the current call are still missing (remember that `"missing"` is a valid class in a method signature). For a formal argument, say `x`, that appears in the original call, there is a corresponding argument in the generated call equivalent to `x = x`. In effect, this means that the generic function sees the same actual arguments, but arguments are evaluated only once. Using `callGeneric` with no arguments is prone to creating infinite recursion, unless one of the arguments in the signature has been modified in the current method so that a different method is selected. ### Value The value returned by the new call. ### References Chambers, John M. (2016) *Extending R*, Chapman & Hall. (Chapters 9 and 10.) Chambers, John M. (2008) *Software for Data Analysis: Programming with R* Springer. (Section 10.4 for some details.) ### See Also `[GroupGenericFunctions](s4groupgeneric)` for other information about group generic functions; [Methods\_Details](methods_details) for the general behavior of method dispatch ### Examples ``` ## the method for group generic function Ops ## for signature( e1="structure", e2="vector") function (e1, e2) { value <- callGeneric([email protected], e2) if (length(value) == length(e1)) { [email protected] <- value e1 } else value } ## For more examples ## Not run: showMethods("Ops", includeDefs = TRUE) ## End(Not run) ``` r None `Introduction` Basic use of S4 Methods and Classes --------------------------------------------------- ### Description The majority of applications using methods and classes will be in **R** packages implementing new computations for an application, using new *classes* of objects that represent the data and results. Computations will be implemented using *methods* that implement functional computations when one or more of the arguments is an object from these classes. Calls to the functions `[setClass](setclass)()` define the new classes; calls to `[setMethod](setmethod)` define the methods. These, along with ordinary **R** computations, are sufficient to get started for most applications. Classes are defined in terms of the data in them and what other classes of data they inherit from. Section ‘Defining Classes’ outlines the basic design of new classes. Methods are **R** functions, often implementing basic computations as they apply to the new classes of objects. Section ‘Defining Methods’ discusses basic requirements and special tools for defining methods. The classes discussed here are the original functional classes. **R** also supports formal classes and methods similar to those in other languages such as Python, in which methods are part of class definitions and invoked on an object. These are more appropriate when computations expect references to objects that are persistent, making changes to the object over time. See [ReferenceClasses](refclass) and Chapter 9 of the reference for the choice between these and S4 classes. ### Defining Classes All objects in **R** belong to a class; ordinary vectors and other basic objects are built-in ([builtin-class](basicclasses)). A new class is defined in terms of the named *slots* that is has and/or in terms of existing classes that it inherits from, or *contains* (discussed in ‘Class Inheritance’ below). A call to `[setClass](setclass)()` names a new class and uses the corresponding arguments to define it. For example, suppose we want a class of objects to represent a collection of positions, perhaps from GPS readings. A natural way to think of these in **R** would have vectors of numeric values for latitude, longitude and altitude. A class with three corresponding slots could be defined by: `Pos <- setClass("Pos", slots = c(latitude = "numeric", longitude = "numeric", altitude = "numeric"))` The value returned is a function, typically assigned as here with the name of the class. Calling this function returns an object from the class; its arguments are named with the slot names. If a function in the class had read the corresponding data, perhaps from a CSV file or from a data base, it could return an object from the class by: `Pos(latitude = x, longitude = y, altitude = z)` The slots are accessed by the `[@](../../base/html/slotop)` operator; for example, if `g` is an object from the class, `g@latitude`. In addition to returning a generator function the call to `[setClass](setclass)()` assigns a definition of the class in a special metadata object in the package's namespace. When the package is loaded into an **R** session, the class definition is added to a table of known classes. To make the class and the generating function publicly available, the package should include `POS` in `exportClasses()` and `export()` directives in its `NAMESPACE` file: `exportClasses(Pos); export(Pos)` ### Defining Methods Defining methods for an **R** function makes that function *generic*. Instead of a call to the function always being carried out by the same method, there will be several alternatives. These are selected by matching the classes of the arguments in the call to a table in the generic function, indexed by classes for one or more formal arguments to the function, known as the *signatures* for the methods. A method definition then specifies three things: the name of the function, the signature and the method definition itself. The definition must be a function with the same formal arguments as the generic. For example, a method to make a plot of an object from class `"Pos"` could be defined by: `setMethod("plot", c("Pos", "missing"), function(x, y, ...) { plotPos(x, y) })` This method will match a call to `[plot](../../graphics/html/plot.default)()` if the first argument is from class `"Pos"` or a subclass of that. The second argument must be missing; only a missing argument matches that class in the signature. Any object will match class `"ANY"` in the corresponding position of the signature. ### Class Inheritance A class may inherit all the slots and methods of one or more existing classes by specifying the names of the inherited classes in the `contains =` argument to `[setClass](setclass)()`. To define a class that extends class `"Pos"` to a class `"GPS"` with a slot for the observation times: `GPS <- setClass("GPS", slots = c(time = "POSIXt"), contains = "Pos")` The inherited classes may be S4 classes, S3 classes or basic data types. S3 classes need to be identified as such by a call to `[setOldClass](setoldclass)()`; most S3 classes in the base package and many in the other built-in packages are already declared, as is `"POSIXt"`. If it had not been, the application package should contain: `setOldClass("POSIXt")` Inheriting from one of the **R** types is special. Objects from the new class will have the same type. A class `Currency` that contains numeric data plus a slot `"unit"` would be created by `Currency <- setClass("Currency", slots = c(unit = "character"), contains = "numeric")` Objects created from this class will have type `"numeric"` and inherit all the builtin arithmetic and other computations for that type. Classes can only inherit from at most one such type; if the class does not inherit from a type, objects from the class will have type `"S4"`. ### References Chambers, John M. (2016) *Extending R*, Chapman & Hall. (Chapters 9 and 10.) r None `StructureClasses` Classes Corresponding to Basic Structures ------------------------------------------------------------- ### Description The virtual class `structure` and classes that extend it are formal classes analogous to S language structures such as arrays and time-series. ### Usage ``` ## The following class names can appear in method signatures, ## as the class in as() and is() expressions, and, except for ## the classes commented as VIRTUAL, in calls to new() "matrix" "array" "ts" "structure" ## VIRTUAL ``` ### Objects from the Classes Objects can be created by calls of the form `new(Class, ...)`, where `Class` is the quoted name of the specific class (e.g., `"matrix"`), and the other arguments, if any, are interpreted as arguments to the corresponding function, e.g., to function `matrix()`. There is no particular advantage over calling those functions directly, unless you are writing software designed to work for multiple classes, perhaps with the class name and the arguments passed in. Objects created from the classes `"matrix"` and `"array"` are unusual, to put it mildly, and have been for some time. Although they may appear to be objects from these classes, they do not have the internal structure of either an S3 or S4 class object. In particular, they have no `"class"` attribute and are not recognized as objects with classes (that is, both `[is.object](../../base/html/is.object)` and `[isS4](../../base/html/iss4)` will return `FALSE` for such objects). However, methods (both S4 and S3) can be defined for these pseudo-classes and new classes (both S4 and S3) can inherit from them. That the objects still behave as if they came from the corresponding class (most of the time, anyway) results from special code recognizing such objects being built into the base code of **R**. For most purposes, treating the classes in the usual way will work, fortunately. One consequence of the special treatment is that these two classes*may* be used as the data part of an S4 class; for example, you can get away with `contains = "matrix"` in a call to `[setGeneric](setgeneric)` to create an S4 class that is a subclass of `"matrix"`. There is no guarantee that everything will work perfectly, but a number of classes have been written in this form successfully. Note that a class containing `"matrix"` or `"array"` will have a `.Data` slot with that class. This is the only use of `.Data` other than as a pseudo-class indicating the type of the object. In this case the type of the object will be the type of the contained matrix or array. See `[Classes\_Details](classes_details)` for a general discussion. The class `"ts"` is basically an S3 class that has been registered with S4, using the `[setOldClass](setoldclass)` mechanism. Versions of **R** through 2.7.0 treated this class as a pure S4 class, which was in principal a good idea, but in practice did not allow subclasses to be defined and had other intrinsic problems. (For example, setting the `"tsp"` parameters as a slot often fails because the built-in implementation does not allow the slot to be temporarily inconsistent with the length of the data. Also, the S4 class prevented the correct specification of the S3 inheritance for class `"mts"`.) Time-series objects, in contrast to matrices and arrays, have a valid S3 class, `"ts"`, registered using an S4-style definition (see the documentation for `[setOldClass](setoldclass)` in the examples section for an abbreviated listing of how this is done). The S3 inheritance of `"mts"` in package stats is also registered. These classes, as well as `"matrix"` and `"array"` should be valid in most examples as superclasses for new S4 class definitions. All of these classes have special S4 methods for `[initialize](new)` that accept the same arguments as the basic generator functions, `[matrix](../../base/html/matrix)`, `[array](../../base/html/array)`, and `[ts](../../stats/html/ts)`, in so far as possible. The limitation is that a class that has more than one non-virtual superclass must accept objects from that superclass in the call to `<new>`; therefore, a such a class (what is called a “mixin” in some languages) uses the default method for `[initialize](new)`, with no special arguments. ### Extends The specific classes all extend class `"structure"`, directly, and class `"vector"`, by class `"structure"`. ### Methods coerce Methods are defined to coerce arbitrary objects to these classes, by calling the corresponding basic function, for example, `as(x, "matrix")` calls `as.matrix(x)`. If `strict = TRUE` in the call to `as()`, the method goes on to delete all other slots and attributes other than the `dim` and `dimnames`. Ops Group methods (see, e.g., `[S4groupGeneric](s4groupgeneric)`) are defined for combinations of structures and vectors (including special cases for array and matrix), implementing the concept of vector structures as in the reference. Essentially, structures combined with vectors retain the structure as long as the resulting object has the same length. Structures combined with other structures remove the structure, since there is no automatic way to determine what should happen to the slots defining the structure. Note that these methods will be activated when a package is loaded containing a class that inherits from any of the structure classes or class `"vector"`. ### References Chambers, John M. (2008) *Software for Data Analysis: Programming with R* Springer. (For the R version.) Chambers, John M. (1998) *Programming with Data* Springer (For the original S4 version.) Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) *The New S Language*. Wadsworth & Brooks/Cole (for the original vector structures). ### See Also Class [nonStructure](nonstructure-class), which enforces the alternative model, in which all slots are dropped if any math transformation or operation is applied to an object from a class extending one of the basic classes. ### Examples ``` showClass("structure") ## explore a bit : showClass("ts") (ts0 <- new("ts")) str(ts0) showMethods("Ops") # six methods from these classes, but maybe many more ```
programming_docs
r None `method.skeleton` Create a Skeleton File for a New Method ---------------------------------------------------------- ### Description This function writes a source file containing a call to `[setMethod](setmethod)` to define a method for the generic function and signature supplied. By default the method definition is in line in the call, but can be made an external (previously assigned) function. ### Usage ``` method.skeleton(generic, signature, file, external = FALSE, where) ``` ### Arguments | | | | --- | --- | | `generic` | the character string name of the generic function, or the generic function itself. In the first case, the function need not currently be a generic, as it would not for the resulting call to `[setMethod](setmethod)`. | | `signature` | the method signature, as it would be given to `[setMethod](setmethod)` | | `file` | a character string name for the output file, or a writable connection. By default the generic function name and the classes in the signature are concatenated, with separating underscore characters. The file name should normally end in `".R"`. | To write multiple method skeletons to one file, open the file connection first and then pass it to `method.skeleton()` in multiple calls. | | | | --- | --- | | `external` | flag to control whether the function definition for the method should be a separate external object assigned in the source file, or included in line in the call to `[setMethod](setmethod)`. If supplied as a character string, this will be used as the name for the external function; by default the name concatenates the generic and signature names, with separating underscores. | | `where` | The environment in which to look for the function; by default, the top-level environment of the call to `method.skeleton`. | ### Value The `file` argument, invisibly, but the function is used for its side effect. ### See Also `[setMethod](setmethod)`, `[package.skeleton](../../utils/html/package.skeleton)` ### Examples ``` setClass("track", slots = c(x ="numeric", y="numeric")) method.skeleton("show", "track") ## writes show_track.R method.skeleton("Ops", c("track", "track")) ## writes "Ops_track_track.R" ## write multiple method skeletons to one file con <- file("./Math_track.R", "w") method.skeleton("Math", "track", con) method.skeleton("exp", "track", con) method.skeleton("log", "track", con) close(con) ``` r None `new` Generate an Object from a Class -------------------------------------- ### Description A call to `new` returns a newly allocated object from the class identified by the first argument. This call in turn calls the method for the generic function `initialize` corresponding to the specified class, passing the `...` arguments to this method. In the default method for `initialize()`, named arguments provide values for the corresponding slots and unnamed arguments must be objects from superclasses of this class. A call to a generating function for a class (see `[setClass](setclass)`) will pass its ... arguments to a corresponding call to `new()`. ### Usage ``` new(Class, ...) initialize(.Object, ...) ``` ### Arguments | | | | --- | --- | | `Class` | either the name of a class, a `[character](../../base/html/character)` string, (the usual case) or the object describing the class (e.g., the value returned by `getClass`). Note that the character string passed from a generating function includes the package name as an attribute, avoiding ambiguity if two packages have identically named classes. | | `...` | arguments to specify properties of the new object, to be passed to `initialize()`. | | `.Object` | An object: see the “Initialize Methods” section. | ### Initialize Methods The generic function `initialize` is not called directly. A call to `new` begins by copying the prototype object from the class definition, and then calls `intialize()` with this object as the first argument, followed by the ... arguments. The interpretation of the `...` arguments in a call to a generator function or to `new()` can be specialized to particular classes, by defining an appropriate method for `"initialize"`. In the default method, unnamed arguments in the `...` are interpreted as objects from a superclass, and named arguments are interpreted as objects to be assigned into the correspondingly named slots. Explicitly specified slots override inherited information for the same slot, regardless of the order in which the arguments appear. The `initialize` methods do not have to have `...` as their second argument (see the examples). Initialize methods are often written when the natural parameters describing the new object are not the names of the slots. If you do define such a method, you should include `...` as a formal argument, and your method should pass such arguments along via `[callNextMethod](nextmethod)`. This helps the definition of future subclasses of your class. If these have additional slots and your method does *not* have this argument, it will be difficult for these slots to be included in an initializing call. See `<initialize-methods>` for a discussion of some classes with existing methods. Methods for `initialize` can be inherited only by simple inheritance, since it is a requirement that the method return an object from the target class. See the `simpleInheritanceOnly` argument to `[setGeneric](setgeneric)` and the discussion in `[setIs](setis)` for the general concept. Note that the basic vector classes, `"numeric"`, etc. are implicitly defined, so one can use `new` for these classes. The ... arguments are interpreted as objects of this type and are concatenated into the resulting vector. ### References Chambers, John M. (2016) *Extending R*, Chapman & Hall. (Chapters 9 and 10.) ### See Also [Classes\_Details](classes_details) for details of class definitions, and `[setOldClass](setoldclass)` for the relation to S3 classes. ### Examples ``` ## using the definition of class "track" from \link{setClass} ## a new object with two slots specified t1 <- new("track", x = seq_along(ydata), y = ydata) # a new object including an object from a superclass, plus a slot t2 <- new("trackCurve", t1, smooth = ysmooth) ### define a method for initialize, to ensure that new objects have ### equal-length x and y slots. In this version, the slots must still be ### supplied by name. setMethod("initialize", "track", function(.Object, ...) { .Object <- callNextMethod() if(length(.Object@x) != length(.Object@y)) stop("specified x and y of different lengths") .Object }) ### An alternative version that allows x and y to be supplied ### unnamed. A still more friendly version would make the default x ### a vector of the same length as y, and vice versa. setMethod("initialize", "track", function(.Object, x = numeric(0), y = numeric(0), ...) { .Object <- callNextMethod(.Object, ...) if(length(x) != length(y)) stop("specified x and y of different lengths") .Object@x <- x .Object@y <- y .Object }) ``` r None `is` Is an Object from a Class? -------------------------------- ### Description Functions to test inheritance relationships between an object and a class or between two classes (`extends`). ### Usage ``` is(object, class2) extends(class1, class2, maybe = TRUE, fullInfo = FALSE) ``` ### Arguments | | | | --- | --- | | `object` | any **R** object. | | `class1, class2` | the names of the classes between which `is` relations are to be examined defined, or (more efficiently) the class definition objects for the classes. | | `fullInfo` | In a call to `extends`, with `class2` missing, `fullInfo` is a flag, which if `TRUE` causes a list of objects of class `[SClassExtension](sclassextension-class)` to be returned, rather than just the names of the classes. Only the distance slot is likely to be useful in practice; see the ‘Selecting Superclasses’ section; | | `maybe` | What to return for conditional inheritance. But such relationships are rarely used and not recommended, so this argument should not be needed. | ### Selecting Superclasses A call to `[selectSuperClasses](selectsuperclasses)(cl)` returns a list of superclasses, similarly to `extends(cl)`. Additional arguments restrict the class names returned to direct superclasses and/or to non-virtual classes. Either way, programming with the result, particularly using `[sapply](../../base/html/lapply)`, can be useful. To find superclasses with more generally defined properties, one can program with the result returned by `extends` when called with one class as argument. By default, the call returns a character vector including the name of the class itself and of all its superclasses. Alternatively, if `extends` is called with `fullInfo = TRUE`, the return value is a named list, its names being the previous character vector. The elements of the list corresponding to superclasses are objects of class `[SClassExtension](sclassextension-class)`. Of the information in these objects, one piece can be useful: the number of generations between the classes, given by the `"distance"` slot. Programming with the result of the call to `extends`, particularly using `[sapply](../../base/html/lapply)`, can select superclasses. The programming technique is to define a test function that returns `TRUE` for superclasses or relationships obeying some requirement. For example, to find only next-to-direct superclasses, use this function with the list of extension objects: `function(what) is(what, "SClassExtension") && what@distance == 2` or, to find only superclasses from `"myPkg"`, use this function with the simple vector of names: `function(what) getClassDef(what)@package == "myPkg"` Giving such functions as an argument to `[sapply](../../base/html/lapply)` called on the output of `extends` allows you to find superclasses with desired properties. See the examples below. Note that the function using extension objects must test the class of its argument since, unfortunately for this purpose, the list returned by `extends` includes `class1` itself, as the object `TRUE`. ### References Chambers, John M. (2016) *Extending R*, Chapman & Hall. (Chapters 9 and 10.) ### See Also Although `[inherits](../../base/html/class)` is defined for S3 classes, it has been modified so that the result returned is nearly always equivalent to `is`, both for S4 and non-S4 objects. Since it is implemented in C, it is somewhat faster. The only non-equivalences arise from use of `[setIs](setis)`, which should rarely be encountered. ### Examples ``` ## Not run: ## this example can be run if package XRPython from CRAN is installed. supers <- extends("PythonInterface") ## find all the superclasses from package XR fromXR <- sapply(supers, function(what) getClassDef(what)@package == "XR") ## print them supers[fromXR] ## find all the superclasses at distance 2 superRelations <- extends("PythonInterface", fullInfo = TRUE) dist2 <- sapply(superRelations, function(what) is(what, "SClassExtension") && what@distance == 2) ## print them names(superRelations)[dist2] ## End(Not run) ``` r None `showMethods` Show all the methods for the specified function(s) or class -------------------------------------------------------------------------- ### Description Show a summary of the methods for one or more generic functions, possibly restricted to those involving specified classes. ### Usage ``` showMethods(f = character(), where = topenv(parent.frame()), classes = NULL, includeDefs = FALSE, inherited = !includeDefs, showEmpty, printTo = stdout(), fdef) .S4methods(generic.function, class) ``` ### Arguments | | | | --- | --- | | `f` | one or more function names. If omitted, all functions will be shown that match the other arguments. The argument can also be an expression that evaluates to a single generic function, in which case argument `fdef` is ignored. Providing an expression for the function allows examination of hidden or anonymous functions; see the example for `isDiagonal()`. | | `where` | Where to find the generic function, if not supplied as an argument. When `f` is missing, or length 0, this also determines which generic functions to examine. If `where` is supplied, only the generic functions returned by `getGenerics(where)` are eligible for printing. If `where` is also missing, all the cached generic functions are considered. | | `classes` | If argument `classes` is supplied, it is a vector of class names that restricts the displayed results to those methods whose signatures include one or more of those classes. | | `includeDefs` | If `includeDefs` is `TRUE`, include the definitions of the individual methods in the printout. | | `inherited` | logical indicating if methods that have been found by inheritance, so far in the session, will be included and marked as inherited. Note that an inherited method will not usually appear until it has been used in this session. See `[selectMethod](getmethod)` if you want to know what method would be dispatched for particular classes of arguments. | | `showEmpty` | logical indicating whether methods with no defined methods matching the other criteria should be shown at all. By default, `TRUE` if and only if argument `f` is not missing. | | `printTo` | The connection on which the information will be shown; by default, on standard output. | | `fdef` | Optionally, the generic function definition to use; if missing, one is found, looking in `where` if that is specified. See also comment in ‘Details’. | | `generic.function, class` | See `methods`. | ### Details See `methods` for a description of `.S4methods`. The name and package of the generic are followed by the list of signatures for which methods are currently defined, according to the criteria determined by the various arguments. Note that the package refers to the source of the generic function. Individual methods for that generic can come from other packages as well. When more than one generic function is involved, either as specified or because `f` was missing, the functions are found and `showMethods` is recalled for each, including the generic as the argument `fdef`. In complicated situations, this can avoid some anomalous results. ### Value If `printTo` is `FALSE`, the character vector that would have been printed is returned; otherwise the value is the connection or filename, via `[invisible](../../base/html/invisible)`. ### References Chambers, John M. (2008) *Software for Data Analysis: Programming with R* Springer. (For the R version.) Chambers, John M. (1998) *Programming with Data* Springer (For the original S4 version.) ### See Also `[setMethod](setmethod)`, and `[GenericFunctions](genericfunctions)` for other tools involving methods; `[selectMethod](getmethod)` will show you the method dispatched for a particular function and signature of classes for the arguments. `[methods](../../utils/html/methods)` provides method discovery tools for light-weight interactive use. ### Examples ``` require(graphics) ## Assuming the methods for plot ## are set up as in the example of help(setMethod), ## print (without definitions) the methods that involve class "track": showMethods("plot", classes = "track") ## Not run: # Function "plot": # x = ANY, y = track # x = track, y = missing # x = track, y = ANY require("Matrix") showMethods("%*%")# many! methods(class = "Matrix")# nothing showMethods(class = "Matrix")# everything showMethods(Matrix:::isDiagonal) # a non-exported generic ## End(Not run) if(no4 <- is.na(match("stats4", loadedNamespaces()))) loadNamespace("stats4") showMethods(classes = "mle") # -> a method for show() if(no4) unloadNamespace("stats4") ``` r None `localRefClass` Localized Objects based on Reference Classes ------------------------------------------------------------- ### Description Local reference classes are modified [ReferenceClasses](refclass) that isolate the objects to the local frame. Therefore, they do *not* propagate changes back to the calling environment. At the same time, they use the reference field semantics locally, avoiding the automatic duplication applied to standard **R** objects. The current implementation has no special construction. To create a local reference class, call `[setRefClass](refclass)()` with a `contains=` argument that includes `"localRefClass"`. See the example below. Local reference classes operate essentially as do regular, functional classes in **R**; that is, changes are made by assignment and take place in the local frame. The essential difference is that replacement operations (like the change to the `twiddle` field in the example) do not cause duplication of the entire object, as would be the case for a formal class or for data with attributes or in a named list. The purpose is to allow large objects in some fields that are not changed along with potentially frequent changes to other fields, but without copying the large fields. ### Usage ``` setRefClass(Class, fields = , contains = c("localRefClass",....), methods =, where =, ...) ``` ### Details Localization of objects is only partially automated in the current implementation. Replacement expressions using the `$<-` operator are safe. However, if reference methods for the class themselves modify fields, using `<<-`, for example, then one must ensure that the object is local to the relevant frame before any such method is called. Otherwise, standard reference class behavior still prevails. There are two ways to ensure locality. The direct way is to invoke the special method `x$ensureLocal()` on the object. The other way is to modify a field explicitly by `x$field <- ...` It's only necessary that one or the other of these happens once for each object, in order to trigger the shallow copy that provides locality for the references. In the example below, we show both mechanisms. However it's done, localization must occur *before* any methods make changes. (Eventually, some use of code tools should at least largely automate this process, although it may be difficult to guarantee success under arbitrary circumstances.) ### Author(s) John Chambers ### Examples ``` ## class "myIter" has a BigData field for the real (big) data ## and a "twiddle" field for some parameters that it twiddles ## ( for some reason) myIter <- setRefClass("myIter", contains = "localRefClass", fields = list(BigData = "numeric", twiddle = "numeric")) tw <- rnorm(3) x1 <- myIter(BigData = rnorm(1000), twiddle = tw) # OK, not REALLY big twiddler <- function(x, n) { x$ensureLocal() # see the Details. Not really needed in this example for(i in seq_len(n)) { x$twiddle <- x$twiddle + rnorm(length(x$twiddle)) ## then do something .... ## Snooping in gdb, etc will show that x$BigData is not copied } return(x) } x2 <- twiddler(x1, 10) stopifnot(identical(x1$twiddle, tw), !identical(x1$twiddle, x2$twiddle)) ``` r None `evalSource` Use Function Definitions from a Source File without Reinstalling a Package ---------------------------------------------------------------------------------------- ### Description Definitions of functions and/or methods from a source file are inserted into a package, using the `[trace](../../base/html/trace)` mechanism. Typically, this allows testing or debugging modified versions of a few functions without reinstalling a large package. ### Usage ``` evalSource(source, package = "", lock = TRUE, cache = FALSE) insertSource(source, package = "", functions = , methods = , force = ) ``` ### Arguments | | | | --- | --- | | `source` | A file to be parsed and evaluated by `evalSource` to find the new function and method definitions. The argument to `insertSource` can be an object of class `"sourceEnvironment"` returned from a previous call to `evalSource` If a file name is passed to `insertSource` it calls `evalSource` to obtain the corresponding object. See the section on the class for details. | | `package` | Optionally, the name of the package to which the new code corresponds and into which it will be inserted. Although the computations will attempt to infer the package if it is omitted, the safe approach is to supply it. In the case of a package that is not attached to the search list, the package name must be supplied. | | `functions, methods` | Optionally, the character-string names of the functions to be used in the insertion. Names supplied in the `functions` argument are expected to be defined as functions in the source. For names supplied in the `methods` argument, a table of methods is expected (as generated by calls to `[setMethod](setmethod)`, see the details section); methods from this table will be inserted by `insertSource`. In both cases, the revised function or method is inserted only if it differs from the version in the corresponding package as loaded. If `what` is omitted, the results of evaluating the source file will be compared to the contents of the package (see the details section). | | `lock, cache` | Optional arguments to control the actions taken by `evalSource`. If `lock` is `TRUE`, the environment in the object returned will be locked, and so will all its bindings. If `cache` is `FALSE`, the normal caching of method and class definitions will be suppressed during evaluation of the `source` file. The default settings are generally recommended, the `lock` to support the credibility of the object returned as a snapshot of the source file, and the second so that method definitions can be inserted later by `insertSource` using the trace mechanism. | | `force` | If `FALSE`, only functions currently in the environment will be redefined, using `[trace](../../base/html/trace)`. If `TRUE`, other objects/functions will be simply assigned. By default, `TRUE` if neither the `functions` nor the `methods` argument is supplied. | ### Details The `source` file is parsed and evaluated, suppressing by default the actual caching of method and class definitions contained in it, so that functions and methods can be tested out in a reversible way. The result, if all goes well, is an environment containing the assigned objects and metadata corresponding to method and class definitions in the source file. From this environment, the objects are inserted into the package, into its namespace if it has one, for use during the current session or until reverting to the original version by a call to `[untrace](../../base/html/trace)`. The insertion is done by calls to the internal version of `[trace](../../base/html/trace)`, to make reversion possible. Because the trace mechanism is used, only function-type objects will be inserted, functions themselves or S4 methods. When the `functions` and `methods` arguments are both omitted, `insertSource` selects all suitable objects from the result of evaluating the `source` file. In all cases, only objects in the source file that differ from the corresponding objects in the package are inserted. The definition of “differ” is that either the argument list (including default expressions) or the body of the function is not identical. Note that in the case of a method, there need be no specific method for the corresponding signature in the package: the comparison is made to the method that would be selected for that signature. Nothing in the computation requires that the source file supplied be the same file as in the original package source, although that case is both likely and sensible if one is revising the package. Nothing in the computations compares source files: the objects generated by evaluating `source` are compared as objects to the content of the package. ### Value An object from class `"sourceEnvironment"`, a subclass of `"environment"` (see the section on the class) The environment contains the versions of *all* object resulting from evaluation of the source file. The class also has slots for the time of creation, the source file and the package name. Future extensions may use these objects for versioning or other code tools. The object returned can be used in debugging (see the section on that topic) or as the `source` argument in a future call to `insertSource`. If only some of the revised functions were inserted in the first call, others can be inserted in a later call without re-evaluating the source file, by supplying the environment and optionally suitable `functions` and/or `methods` argument. ### Debugging Once a function or method has been inserted into a package by `insertSource`, it can be studied by the standard debugging tools; for example, `[debug](../../base/html/debug)` or the various versions of `[trace](../../base/html/trace)`. Calls to `[trace](../../base/html/trace)` should take the extra argument `edit = env`, where `env` is the value returned by the call to `evalSource`. The trace mechanism has been used to install the revised version from the source file, and supplying the argument ensures that it is this version, not the original, that will be traced. See the example below. To turn tracing off, but retain the source version, use `trace(x, edit = env)` as in the example. To return to the original version from the package, use `untrace(x)`. ### Class "sourceEnvironment" Objects from this class can be treated as environments, to extract the version of functions and methods generated by `evalSource`. The objects also have the following slots: `packageName`: The character-string name of the package to which the source code corresponds. `dateCreated`: The date and time that the source file was evaluated (usually from a call to `[Sys.time](../../base/html/sys.time)`). `sourceFile`: The character-string name of the source file used. Note that using the environment does not change the `dateCreated`. ### See Also `[trace](../../base/html/trace)` for the underlying mechanism, and also for the `edit=` argument that can be used for somewhat similar purposes; that function and also `[debug](../../base/html/debug)` and `[setBreakpoint](../../utils/html/findlinenum)`, for techniques more oriented to traditional debugging styles. The present function is directly intended for the case that one is modifying some of the source for an existing package, although it can be used as well by inserting debugging code in the source (more useful if the debugging involved is non-trivial). As noted in the details section, the source file need not be the same one in the original package source. ### Examples ``` ## Not run: ## Suppose package P0 has a source file "all.R" ## First, evaluate the source, and from it ## insert the revised version of methods for summary() env <- insertSource("./P0/R/all.R", package = "P0", methods = "summary") ## now test one of the methods, tracing the version from the source trace("summary", signature = "myMat", browser, edit = env) ## After testing, remove the browser() call but keep the source trace("summary", signature = "myMat", edit = env) ## Now insert all the (other) revised functions and methods ## without re-evaluating the source file. ## The package name is included in the object env. insertSource(env) ## End(Not run) ```
programming_docs
r None `getPackageName` The Name associated with a Given Package ---------------------------------------------------------- ### Description The functions below produce the package associated with a particular environment or position on the search list, or of the package containing a particular function. They are primarily used to support computations that need to differentiate objects on multiple packages. ### Usage ``` getPackageName(where, create = TRUE) setPackageName(pkg, env) packageSlot(object) packageSlot(object) <- value ``` ### Arguments | | | | --- | --- | | `where` | the environment or position on the search list associated with the desired package. | | `object` | object providing a character string name, plus the package in which this object is to be found. | | `value` | the name of the package. | | `create` | flag, should a package name be created if none can be inferred? If `TRUE` and no non-empty package name is found, the current date and time are used as a package name, and a warning is issued. The created name is stored in the environment if that environment is not locked. | | `pkg, env` | make the string in `pkg` the internal package name for all computations that set class and method definitions in environment `env`. | ### Details Package names are normally installed during loading of the package, by the [INSTALL](../../utils/html/install) script or by the `[library](../../base/html/library)` function. (Currently, the name is stored as the object `.packageName` but don't trust this for the future.) ### Value `getPackageName` returns the character-string name of the package (without the extraneous `"package:"` found in the search list). `packageSlot` returns or sets the package name slot (currently an attribute, not a formal slot, but this may change someday). `setPackageName` can be used to establish a package name in an environment that would otherwise not have one. This allows you to create classes and/or methods in an arbitrary environment, but it is usually preferable to create packages by the standard **R** programming tools (`[package.skeleton](../../utils/html/package.skeleton)`, etc.) ### See Also `[search](../../base/html/search)`, `[packageName](../../utils/html/packagename)` ### Examples ``` ## all the following usually return "base" getPackageName(length(search())) getPackageName(baseenv()) getPackageName(asNamespace("base")) getPackageName("package:base") ``` r None `setOldClass` Register Old-Style (S3) Classes and Inheritance -------------------------------------------------------------- ### Description Register an old-style (a.k.a. ‘S3’) class as a formally defined class. Simple usage will be of the form: `setOldClass(Classes)` where `Classes` is the character vector that would be the `class` attribute of the S3 object. Calls to `setOldClass()` in the code for a package allow the class to be used as a slot in formal (S4) classes and in signatures for methods (see [Methods\_for\_S3](methods_for_s3)). Formal classes can also contain a registered S3 class (see [S3Part](s3part) for details). If the S3 class has a known set of attributes, an equivalent S4 class can be specified by `S4Class=` in the call to `setOldClass()`; see the section “Known Attributes”. ### Usage ``` setOldClass(Classes, prototype, where, test = FALSE, S4Class) ``` ### Arguments | | | | --- | --- | | `Classes` | A character vector, giving the names for S3 classes, as they would appear on the right side of an assignment of the `class` attribute in S3 computations. In addition to S3 classes, an object type or other valid data part can be specified, if the S3 class is known to require its data to be of that form. | | `S4Class` | optionally, the class definition or the class name of an S4 class. The new class will have all the slots and other properties of this class, plus any S3 inheritance implied by multiple names in the `Classes` argument. See the section on “S3 classes with known attributes” below. | | `prototype, where, test` | *These arguments are currently allowed, but not recommended in typical applications.* `prototype`: An optional object to use as the prototype. If the S3 class is not to be `VIRTUAL` (the default), the use of `S4Class=` is preferred. `where`: Where to store the class definitions. Should be the default (the package namespace) for normal use in an application package. `test`: flag, if `TRUE`, arrange to test inheritance explicitly for each object, needed if the S3 class can have a different set of class strings, with the same first string. Such classes are inherently malformed, are rare, and should be avoided. | ### Details The name (or each of the names) in `Classes` will be defined as an S4 class, extending class `oldClass`, which is the ‘root’ of all old-style classes. S3 classes with multiple names in their class attribute will have a corresponding inheritance as formal classes. See the `"mlm"` example. S3 classes have no formal definition, and therefore no formally defined slots. If no S4 class is supplied as a model, the class created will be a virtual class. If a virtual class (any virtual class) is used for a slot in another class, then the initializing method for the class needs to put something legal in that slot; otherwise it will be set to `NULL`. See [Methods\_for\_S3](methods_for_s3) for the details of method dispatch and inheritance with mixed S3 and S4 methods. Some S3 classes cannot be represented as an ordinary combination of S4 classes and superclasses, because objects with the same initial string in the class attribute can have different strings following. Such classes are fortunately rare. They violate the basic idea of object-oriented programming and should be avoided. If you must deal with them, it is still possible to register such classes as S4 classes, but now the inheritance has to be verified for each object, and you must call `setOldClass` with argument `test=TRUE`. ### Pre-Defined Old Classes Many of the widely used S3 classes in the standard R distribution come pre-defined for use with S4. These don't need to be explicitly declared in your package (although it does no harm to do so). The list `.OldClassesList` contains the old-style classes that are defined by the methods package. Each element of the list is a character vector, with multiple strings if inheritance is included. Each element of the list was passed to `setOldClass` when creating the methods package; therefore, these classes can be used in `[setMethod](setmethod)` calls, with the inheritance as implied by the list. ### S3 Classes with known attributes A further specification of an S3 class can be made *if* the class is guaranteed to have some attributes of known class (where as with slots, “known” means that the attribute is an object of a specified class, or a subclass of that class). In this case, the call to `setOldClass()` can supply an S4 class definition representing the known structure. Since S4 slots are implemented as attributes (largely for just this reason), the known attributes can be specified in the representation of the S4 class. The usual technique will be to create an S4 class with the desired structure, and then supply the class name or definition as the argument `S4Class=` to `setOldClass()`. See the definition of class `"ts"` in the examples below and the `data.frame` example in Section 10.2 of the reference. The call to `[setClass](setclass)` to create the S4 class can use the same class name, as here, so long as the call to `setOldClass` follows in the same package. For clarity it should be the next expression in the same file. In the example, we define `"ts"` as a vector structure with a numeric slot for `"tsp"`. The validity of this definition relies on an assertion that all the S3 code for this class is consistent with that definition; specifically, that all `"ts"` objects will behave as vector structures and will have a numeric `"tsp"` attribute. We believe this to be true of all the base code in **R**, but as always with S3 classes, no guarantee is possible. The S4 class definition can have virtual superclasses (as in the `"ts"` case) if the S3 class is asserted to behave consistently with these (in the example, time-series objects are asserted to be consistent with the [structure](structureclasses) class). Failures of the S3 class to live up to its asserted behavior will usually go uncorrected, since S3 classes inherently have no definition, and the resulting invalid S4 objects can cause all sorts of grief. Many S3 classes are not candidates for known slots, either because the presence or class of the attributes are not guaranteed (e.g., `dimnames` in arrays, although these are not even S3 classes), or because the class uses named components of a list rather than attributes (e.g., `"lm"`). An attribute that is sometimes missing cannot be represented as a slot, not even by pretending that it is present with class `"NULL"`, because attributes, unlike slots, can not have value `NULL`. One irregularity that is usually tolerated, however, is to optionally add other attributes to those guaranteed to exist (for example, `"terms"` in `"data.frame"` objects returned by `[model.frame](../../stats/html/model.frame)`). Validity checks by `[validObject](validobject)` ignore extra attributes; even if this check is tightened in the future, classes extending S3 classes would likely be exempted because extra attributes are so common. ### References Chambers, John M. (2016) *Extending R*, Chapman & Hall. (Chapters 9 and 10, particularly Section 10.8) ### See Also `[setClass](setclass)`, `[setMethod](setmethod)` ### Examples ``` require(stats) ## "lm" and "mlm" are predefined; if they were not this would do it: ## Not run: setOldClass(c("mlm", "lm")) ## End(Not run) ## Define a new generic function to compute the residual degrees of freedom setGeneric("dfResidual", function(model) stop(gettextf( "This function only works for fitted model objects, not class %s", class(model)))) setMethod("dfResidual", "lm", function(model)model$df.residual) ## dfResidual will work on mlm objects as well as lm objects myData <- data.frame(time = 1:10, y = (1:10)^.5) myLm <- lm(cbind(y, y^3) ~ time, myData) ## two examples extending S3 class "lm": class "xlm" directly ## and "ylm" indirectly setClass("xlm", slots = c(eps = "numeric"), contains = "lm") setClass("ylm", slots = c(header = "character"), contains = "xlm") ym1 = new("ylm", myLm, header = "Example", eps = 0.) ## for more examples, see ?\link{S3Class}. ## Not run: ## The code in R that defines "ts" as an S4 class setClass("ts", contains = "structure", slots = c(tsp = "numeric"), prototype(NA, tsp = rep(1,3))) # prototype to be a legal S3 time-series ## and now registers it as an S3 class setOldClass("ts", S4Class = "ts", where = envir) ## End(Not run) ``` r None `validObject` Test the Validity of an Object --------------------------------------------- ### Description `validObject()` tests the validity of `object` related to its class definition; specifically, it checks that all slots specified in the class definition are present and that the object in the slot is from the required class or a subclass of that class. If the object is valid, `TRUE` is returned; otherwise, an error is generated, reporting all the validity failures encountered. If argument `test` is `TRUE`, the errors are returned as a character vector rather than generating an error. When an object from a class is initialized, the default method for `[initialize](new)()` calls `validObject`. A class definition may have a validity method, set by a call to the function `setValidity`, in the package or environment that defines the class (or via the `validity` argument to `[setClass](setclass)`). The method should be a function of one object that returns `TRUE` or a character-string description of the non-validity. If such a method exists, it will be called from `validObject` and any strings from failure will be included in the result or the error message. Any validity methods defined for superclasses (from the `contains=` argument to `[setClass](setclass)`), will also be called. ### Usage ``` validObject(object, test = FALSE, complete = FALSE) setValidity(Class, method, where = topenv(parent.frame()) ) getValidity(ClassDef) ``` ### Arguments | | | | --- | --- | | `object` | any object, but not much will happen unless the object's class has a formal definition. | | `test` | logical; if `TRUE` and validity fails, the function returns a vector of strings describing the problems. If `test` is `FALSE` (the default) validity failure generates an error. | | `complete` | logical; if `TRUE`, `validObject` is called recursively for each of the slots. The default is `FALSE`. | | `Class` | the name or class definition of the class whose validity method is to be set. | | `ClassDef` | a class definition object, as from `[getClassDef](getclass)`. | | `method` | a validity method; that is, either `NULL` or a function of one argument (`object`). Like `validObject`, the function should return `TRUE` if the object is valid, and one or more descriptive strings if any problems are found. Unlike `validObject`, it should never generate an error. | | `where` | an environment to store the modified class definition. Should be omitted, specifically for calls from a package that defines the class. The definition will be stored in the namespace of the package. | ### Details Validity testing takes place ‘bottom up’, checking the slots, then the superclasses, then the object's own validity method, if there is one. For each slot and superclass, the existence of the specified class is checked. For each slot, the object in the slot is tested for inheritance from the corresponding class. If `complete` is TRUE, `validObject` is called recursively for the object in the slot. Then, for each of the classes that this class extends (the ‘superclasses’), the explicit validity method of that class is called, if one exists. Finally, the validity method of `object`'s class is called, if there is one. ### Value `validObject` returns `TRUE` if the object is valid. Otherwise a vector of strings describing problems found, except that if `test` is `FALSE`, validity failure generates an error, with the corresponding strings in the error message. ### Validity methods A validity method must be a function of one argument; formally, that argument should be named `object`. If the argument has a different name, `setValidity` makes the substitution but in obscure cases that might fail, so it's wiser to name the argument `object`. A good method checks all the possible errors and returns a character vector citing all the exceptions found, rather than returning after the first one. `validObject` will accumulate these errors in its error message or its return value. Note that validity methods do not have to check validity of superclasses: `validObject` calls such methods explicitly. ### References Chambers, John M. (2016) *Extending R*, Chapman & Hall. (Chapters 9 and 10.) ### See Also `[setClass](setclass)`; class `[classRepresentation](classrepresentation-class)`. ### Examples ``` setClass("track", slots = c(x="numeric", y = "numeric")) t1 <- new("track", x=1:10, y=sort(stats::rnorm(10))) ## A valid "track" object has the same number of x, y values validTrackObject <- function(object) { if(length(object@x) == length(object@y)) TRUE else paste("Unequal x,y lengths: ", length(object@x), ", ", length(object@y), sep="") } ## assign the function as the validity method for the class setValidity("track", validTrackObject) ## t1 should be a valid "track" object validObject(t1) ## Now we do something bad t2 <- t1 t2@x <- 1:20 ## This should generate an error ## Not run: try(validObject(t2)) setClass("trackCurve", contains = "track", slots = c(smooth = "numeric")) ## all superclass validity methods are used when validObject ## is called from initialize() with arguments, so this fails ## Not run: trynew("trackCurve", t2) setClass("twoTrack", slots = c(tr1 = "track", tr2 ="track")) ## validity tests are not applied recursively by default, ## so this object is created (invalidly) tT <- new("twoTrack", tr2 = t2) ## A stricter test detects the problem ## Not run: try(validObject(tT, complete = TRUE)) ``` r None `cd4` CD4 Counts for HIV-Positive Patients ------------------------------------------- ### Description The `cd4` data frame has 20 rows and 2 columns. CD4 cells are carried in the blood as part of the human immune system. One of the effects of the HIV virus is that these cells die. The count of CD4 cells is used in determining the onset of full-blown AIDS in a patient. In this study of the effectiveness of a new anti-viral drug on HIV, 20 HIV-positive patients had their CD4 counts recorded and then were put on a course of treatment with this drug. After using the drug for one year, their CD4 counts were again recorded. The aim of the experiment was to show that patients taking the drug had increased CD4 counts which is not generally seen in HIV-positive patients. ### Usage ``` cd4 ``` ### Format This data frame contains the following columns: `baseline` The CD4 counts (in 100's) on admission to the trial. `oneyear` The CD4 counts (in 100's) after one year of treatment with the new drug. ### Source The data were obtained from DiCiccio, T.J. and Efron B. (1996) Bootstrap confidence intervals (with Discussion). *Statistical Science*, **11**, 189–228. ### References Davison, A.C. and Hinkley, D.V. (1997) *Bootstrap Methods and Their Application*. Cambridge University Press. r None `aids` Delay in AIDS Reporting in England and Wales ---------------------------------------------------- ### Description The `aids` data frame has 570 rows and 6 columns. Although all cases of AIDS in England and Wales must be reported to the Communicable Disease Surveillance Centre, there is often a considerable delay between the time of diagnosis and the time that it is reported. In estimating the prevalence of AIDS, account must be taken of the unknown number of cases which have been diagnosed but not reported. The data set here records the reported cases of AIDS diagnosed from July 1983 and until the end of 1992. The data are cross-classified by the date of diagnosis and the time delay in the reporting of the cases. ### Usage ``` aids ``` ### Format This data frame contains the following columns: `year` The year of the diagnosis. `quarter` The quarter of the year in which diagnosis was made. `delay` The time delay (in months) between diagnosis and reporting. 0 means that the case was reported within one month. Longer delays are grouped in 3 month intervals and the value of `delay` is the midpoint of the interval (therefore a value of `2` indicates that reporting was delayed for between 1 and 3 months). `dud` An indicator of censoring. These are categories for which full information is not yet available and the number recorded is a lower bound only. `time` The time interval of the diagnosis. That is the number of quarters from July 1983 until the end of the quarter in which these cases were diagnosed. `y` The number of AIDS cases reported. ### Source The data were obtained from De Angelis, D. and Gilks, W.R. (1994) Estimating acquired immune deficiency syndrome accounting for reporting delay. *Journal of the Royal Statistical Society, A*, **157**, 31–40. ### References Davison, A.C. and Hinkley, D.V. (1997) *Bootstrap Methods and Their Application*. Cambridge University Press. r None `downs.bc` Incidence of Down's Syndrome in British Columbia ------------------------------------------------------------ ### Description The `downs.bc` data frame has 30 rows and 3 columns. Down's syndrome is a genetic disorder caused by an extra chromosome 21 or a part of chromosome 21 being translocated to another chromosome. The incidence of Down's syndrome is highly dependent on the mother's age and rises sharply after age 30. In the 1960's a large scale study of the effect of maternal age on the incidence of Down's syndrome was conducted at the British Columbia Health Surveillance Registry. These are the data which was collected in that study. Mothers were classified by age. Most groups correspond to the age in years but the first group comprises all mothers with ages in the range 15-17 and the last is those with ages 46-49. No data for mothers over 50 or below 15 were collected. ### Usage ``` downs.bc ``` ### Format This data frame contains the following columns: `age` The average age of all mothers in the age category. `m` The total number of live births to mothers in the age category. `r` The number of cases of Down's syndrome. ### Source The data were obtained from Geyer, C.J. (1991) Constrained maximum likelihood exemplified by isotonic convex logistic regression. *Journal of the American Statistical Association*, **86**, 717–724. ### References Davison, A.C. and Hinkley, D.V. (1997) *Bootstrap Methods and Their Application*. Cambridge University Press.
programming_docs
r None `salinity` Water Salinity and River Discharge ---------------------------------------------- ### Description The `salinity` data frame has 28 rows and 4 columns. Biweekly averages of the water salinity and river discharge in Pamlico Sound, North Carolina were recorded between the years 1972 and 1977. The data in this set consists only of those measurements in March, April and May. ### Usage ``` salinity ``` ### Format This data frame contains the following columns: `sal` The average salinity of the water over two weeks. `lag` The average salinity of the water lagged two weeks. Since only spring is used, the value of `lag` is not always equal to the previous value of `sal`. `trend` A factor indicating in which of the 6 biweekly periods between March and May, the observations were taken. The levels of the factor are from 0 to 5 with 0 being the first two weeks in March. `dis` The amount of river discharge during the two weeks for which `sal` is the average salinity. ### Source The data were obtained from Ruppert, D. and Carroll, R.J. (1980) Trimmed least squares estimation in the linear model. *Journal of the American Statistical Association*, **75**, 828–838. ### References Davison, A.C. and Hinkley, D.V. (1997) *Bootstrap Methods and Their Application*. Cambridge University Press. r None `smooth.f` Smooth Distributions on Data Points ----------------------------------------------- ### Description This function uses the method of frequency smoothing to find a distribution on a data set which has a required value, `theta`, of the statistic of interest. The method results in distributions which vary smoothly with `theta`. ### Usage ``` smooth.f(theta, boot.out, index = 1, t = boot.out$t[, index], width = 0.5) ``` ### Arguments | | | | --- | --- | | `theta` | The required value for the statistic of interest. If `theta` is a vector, a separate distribution will be found for each element of `theta`. | | `boot.out` | A bootstrap output object returned by a call to `boot`. | | `index` | The index of the variable of interest in the output of `boot.out$statistic`. This argument is ignored if `t` is supplied. `index` must be a scalar. | | `t` | The bootstrap values of the statistic of interest. This must be a vector of length `boot.out$R` and the values must be in the same order as the bootstrap replicates in `boot.out`. | | `width` | The standardized width for the kernel smoothing. The smoothing uses a value of `width*s` for epsilon, where `s` is the bootstrap estimate of the standard error of the statistic of interest. `width` should take a value in the range (0.2, 1) to produce a reasonable smoothed distribution. If `width` is too large then the distribution becomes closer to uniform. | ### Details The new distributional weights are found by applying a normal kernel smoother to the observed values of `t` weighted by the observed frequencies in the bootstrap simulation. The resulting distribution may not have parameter value exactly equal to the required value `theta` but it will typically have a value which is close to `theta`. The details of how this method works can be found in Davison, Hinkley and Worton (1995) and Section 3.9.2 of Davison and Hinkley (1997). ### Value If `length(theta)` is 1 then a vector with the same length as the data set `boot.out$data` is returned. The value in position `i` is the probability to be given to the data point in position `i` so that the distribution has parameter value approximately equal to `theta`. If `length(theta)` is bigger than 1 then the returned value is a matrix with `length(theta)` rows each of which corresponds to a distribution with the parameter value approximately equal to the corresponding value of `theta`. ### References Davison, A.C. and Hinkley, D.V. (1997) *Bootstrap Methods and Their Application*. Cambridge University Press. Davison, A.C., Hinkley, D.V. and Worton, B.J. (1995) Accurate and efficient construction of bootstrap likelihoods. *Statistics and Computing*, **5**, 257–264. ### See Also `<boot>`, `<exp.tilt>`, `<tilt.boot>` ### Examples ``` # Example 9.8 of Davison and Hinkley (1997) requires tilting the resampling # distribution of the studentized statistic to be centred at the observed # value of the test statistic 1.84. In the book exponential tilting was used # but it is also possible to use smooth.f. grav1 <- gravity[as.numeric(gravity[, 2]) >= 7, ] grav.fun <- function(dat, w, orig) { strata <- tapply(dat[, 2], as.numeric(dat[, 2])) d <- dat[, 1] ns <- tabulate(strata) w <- w/tapply(w, strata, sum)[strata] mns <- as.vector(tapply(d * w, strata, sum)) # drop names mn2 <- tapply(d * d * w, strata, sum) s2hat <- sum((mn2 - mns^2)/ns) c(mns[2] - mns[1], s2hat, (mns[2]-mns[1]-orig)/sqrt(s2hat)) } grav.z0 <- grav.fun(grav1, rep(1, 26), 0) grav.boot <- boot(grav1, grav.fun, R = 499, stype = "w", strata = grav1[, 2], orig = grav.z0[1]) grav.sm <- smooth.f(grav.z0[3], grav.boot, index = 3) # Now we can run another bootstrap using these weights grav.boot2 <- boot(grav1, grav.fun, R = 499, stype = "w", strata = grav1[, 2], orig = grav.z0[1], weights = grav.sm) # Estimated p-values can be found from these as follows mean(grav.boot$t[, 3] >= grav.z0[3]) imp.prob(grav.boot2, t0 = -grav.z0[3], t = -grav.boot2$t[, 3]) # Note that for the importance sampling probability we must # multiply everything by -1 to ensure that we find the correct # probability. Raw resampling is not reliable for probabilities # greater than 0.5. Thus 1 - imp.prob(grav.boot2, index = 3, t0 = grav.z0[3])$raw # can give very strange results (negative probabilities). ``` r None `envelope` Confidence Envelopes for Curves ------------------------------------------- ### Description This function calculates overall and pointwise confidence envelopes for a curve based on bootstrap replicates of the curve evaluated at a number of fixed points. ### Usage ``` envelope(boot.out = NULL, mat = NULL, level = 0.95, index = 1:ncol(mat)) ``` ### Arguments | | | | --- | --- | | `boot.out` | An object of class `"boot"` for which `boot.out$t` contains the replicates of the curve at a number of fixed points. | | `mat` | A matrix of bootstrap replicates of the values of the curve at a number of fixed points. This is a required argument if `boot.out` is not supplied and is set to `boot.out$t` otherwise. | | `level` | The confidence level of the envelopes required. The default is to find 95% confidence envelopes. It can be a scalar or a vector of length 2. If it is scalar then both the pointwise and the overall envelopes are found at that level. If is a vector then the first element gives the level for the pointwise envelope and the second gives the level for the overall envelope. | | `index` | The numbers of the columns of `mat` which contain the bootstrap replicates. This can be used to ensure that other statistics which may have been calculated in the bootstrap are not considered as values of the function. | ### Details The pointwise envelope is found by simply looking at the quantiles of the replicates at each point. The overall error for that envelope is then calculated using equation (4.17) of Davison and Hinkley (1997). A sequence of pointwise envelopes is then found until one of them has overall error approximately equal to the level required. If no such envelope can be found then the envelope returned will just contain the extreme values of each column of `mat`. ### Value A list with the following components : | | | | --- | --- | | `point` | A matrix with two rows corresponding to the values of the upper and lower pointwise confidence envelope at the same points as the bootstrap replicates were calculated. | | `overall` | A matrix similar to `point` but containing the envelope which controls the overall error. | | `k.pt` | The quantiles used for the pointwise envelope. | | `err.pt` | A vector with two components, the first gives the pointwise error rate for the pointwise envelope, and the second the overall error rate for that envelope. | | `k.ov` | The quantiles used for the overall envelope. | | `err.ov` | A vector with two components, the first gives the pointwise error rate for the overall envelope, and the second the overall error rate for that envelope. | | `err.nom` | A vector of length 2 giving the nominal error rates for the pointwise and the overall envelopes. | ### References Davison, A.C. and Hinkley, D.V. (1997) *Bootstrap Methods and Their Application*. Cambridge University Press. ### See Also `<boot>`, `<boot.ci>` ### Examples ``` # Testing whether the final series of measurements of the gravity data # may come from a normal distribution. This is done in Examples 4.7 # and 4.8 of Davison and Hinkley (1997). grav1 <- gravity$g[gravity$series == 8] grav.z <- (grav1 - mean(grav1))/sqrt(var(grav1)) grav.gen <- function(dat, mle) rnorm(length(dat)) grav.qqboot <- boot(grav.z, sort, R = 999, sim = "parametric", ran.gen = grav.gen) grav.qq <- qqnorm(grav.z, plot.it = FALSE) grav.qq <- lapply(grav.qq, sort) plot(grav.qq, ylim = c(-3.5, 3.5), ylab = "Studentized Order Statistics", xlab = "Normal Quantiles") grav.env <- envelope(grav.qqboot, level = 0.9) lines(grav.qq$x, grav.env$point[1, ], lty = 4) lines(grav.qq$x, grav.env$point[2, ], lty = 4) lines(grav.qq$x, grav.env$overall[1, ], lty = 1) lines(grav.qq$x, grav.env$overall[2, ], lty = 1) ``` r None `glm.diag` Generalized Linear Model Diagnostics ------------------------------------------------ ### Description Calculates jackknife deviance residuals, standardized deviance residuals, standardized Pearson residuals, approximate Cook statistic, leverage and estimated dispersion. ### Usage ``` glm.diag(glmfit) ``` ### Arguments | | | | --- | --- | | `glmfit` | `glmfit` is a `glm.object` - the result of a call to `glm()` | ### Value Returns a list with the following components | | | | --- | --- | | `res` | The vector of jackknife deviance residuals. | | `rd` | The vector of standardized deviance residuals. | | `rp` | The vector of standardized Pearson residuals. | | `cook` | The vector of approximate Cook statistics. | | `h` | The vector of leverages of the observations. | | `sd` | The value used to standardize the residuals. This is the estimate of residual standard deviation in the Gaussian family and is the square root of the estimated shape parameter in the Gamma family. In all other cases it is 1. | ### Note See the help for `<glm.diag.plots>` for an example of the use of `glm.diag`. ### References Davison, A.C. and Snell, E.J. (1991) Residuals and diagnostics. In *Statistical Theory and Modelling: In Honour of Sir David Cox*. D.V. Hinkley, N. Reid and E.J. Snell (editors), 83–106. Chapman and Hall. ### See Also `[glm](../../stats/html/glm)`, `<glm.diag.plots>`, `[summary.glm](../../stats/html/summary.glm)` r None `coal` Dates of Coal Mining Disasters -------------------------------------- ### Description The `coal` data frame has 191 rows and 1 columns. This data frame gives the dates of 191 explosions in coal mines which resulted in 10 or more fatalities. The time span of the data is from March 15, 1851 until March 22 1962. ### Usage ``` coal ``` ### Format This data frame contains the following column: `date` The date of the disaster. The integer part of `date` gives the year. The day is represented as the fraction of the year that had elapsed on that day. ### Source The data were obtained from Hand, D.J., Daly, F., Lunn, A.D., McConway, K.J. and Ostrowski, E. (1994) *A Handbook of Small Data Sets*, Chapman and Hall. ### References Davison, A.C. and Hinkley, D.V. (1997) *Bootstrap Methods and Their Application*. Cambridge University Press. Jarrett, R.G. (1979) A note on the intervals between coal-mining disasters. *Biometrika*, **66**, 191-193. r None `tau` Tau Particle Decay Modes ------------------------------- ### Description The `tau` data frame has 60 rows and 2 columns. The tau particle is a heavy electron-like particle discovered in the 1970's by Martin Perl at the Stanford Linear Accelerator Center. Soon after its production the tau particle decays into various collections of more stable particles. About 86% of the time the decay involves just one charged particle. This rate has been measured independently 13 times. The one-charged-particle event is made up of four major modes of decay as well as a collection of other events. The four main types of decay are denoted rho, pi, e and mu. These rates have been measured independently 6, 7, 14 and 19 times respectively. Due to physical constraints each experiment can only estimate the composite one-charged-particle decay rate or the rate of one of the major modes of decay. Each experiment consists of a major research project involving many years work. One of the goals of the experiments was to estimate the rate of decay due to events other than the four main modes of decay. These are uncertain events and so cannot themselves be observed directly. ### Usage ``` tau ``` ### Format This data frame contains the following columns: `rate` The decay rate expressed as a percentage. `decay` The type of decay measured in the experiment. It is a factor with levels `1`, `rho`, `pi`, `e` and `mu`. ### Source The data were obtained from Efron, B. (1992) Jackknife-after-bootstrap standard errors and influence functions (with Discussion). *Journal of the Royal Statistical Society, B*, **54**, 83–127. ### References Davison, A.C. and Hinkley, D.V. (1997) *Bootstrap Methods and Their Application*. Cambridge University Press. Hayes, K.G., Perl, M.L. and Efron, B. (1989) Application of the bootstrap statistical method to the tau-decay-mode problem. *Physical Review, D*, **39**, 274-279. r None `var.linear` Linear Variance Estimate -------------------------------------- ### Description Estimates the variance of a statistic from its empirical influence values. ### Usage ``` var.linear(L, strata = NULL) ``` ### Arguments | | | | --- | --- | | `L` | Vector of the empirical influence values of a statistic. These will usually be calculated by a call to `empinf`. | | `strata` | A numeric vector or factor specifying which observations (and hence empirical influence values) come from which strata. | ### Value The variance estimate calculated from `L`. ### References Davison, A. C. and Hinkley, D. V. (1997) *Bootstrap Methods and Their Application*. Cambridge University Press. ### See Also `<empinf>`, `<linear.approx>`, `<k3.linear>` ### Examples ``` # To estimate the variance of the ratio of means for the city data. ratio <- function(d,w) sum(d$x * w)/sum(d$u * w) var.linear(empinf(data = city, statistic = ratio)) ``` r None `co.transfer` Carbon Monoxide Transfer --------------------------------------- ### Description The `co.transfer` data frame has 7 rows and 2 columns. Seven smokers with chickenpox had their levels of carbon monoxide transfer measured on entry to hospital and then again after 1 week. The main question being whether one week of hospitalization has changed the carbon monoxide transfer factor. ### Usage ``` co.transfer ``` ### Format This data frame contains the following columns: `entry` Carbon monoxide transfer factor on entry to hospital. `week` Carbon monoxide transfer one week after admittance to hospital. ### Source The data were obtained from Hand, D.J., Daly, F., Lunn, A.D., McConway, K.J. and Ostrowski, E (1994) *A Handbook of Small Data Sets*. Chapman and Hall. ### References Davison, A.C. and Hinkley, D.V. (1997) *Bootstrap Methods and Their Application*. Cambridge University Press. Ellis, M.E., Neal, K.R. and Webb, A.K. (1987) Is smoking a risk factor for pneumonia in patients with chickenpox? *British Medical Journal*, **294**, 1002. r None `poisons` Animal Survival Times -------------------------------- ### Description The `poisons` data frame has 48 rows and 3 columns. The data form a 3x4 factorial experiment, the factors being three poisons and four treatments. Each combination of the two factors was used for four animals, the allocation to animals having been completely randomized. ### Usage ``` poisons ``` ### Format This data frame contains the following columns: `time` The survival time of the animal in units of 10 hours. `poison` A factor with levels `1`, `2` and `3` giving the type of poison used. `treat` A factor with levels `A`, `B`, `C` and `D` giving the treatment. ### Source The data were obtained from Box, G.E.P. and Cox, D.R. (1964) An analysis of transformations (with Discussion). *Journal of the Royal Statistical Society, B*, **26**, 211–252. ### References Davison, A.C. and Hinkley, D.V. (1997) *Bootstrap Methods and Their Application*. Cambridge University Press. r None `manaus` Average Heights of the Rio Negro river at Manaus ---------------------------------------------------------- ### Description The `manaus` time series is of class `"ts"` and has 1080 observations on one variable. The data values are monthly averages of the daily stages (heights) of the Rio Negro at Manaus. Manaus is 18km upstream from the confluence of the Rio Negro with the Amazon but because of the tiny slope of the water surface and the lower courses of its flatland affluents, they may be regarded as a good approximation of the water level in the Amazon at the confluence. The data here cover 90 years from January 1903 until December 1992. The Manaus gauge is tied in with an arbitrary bench mark of 100m set in the steps of the Municipal Prefecture; gauge readings are usually referred to sea level, on the basis of a mark on the steps leading to the Parish Church (Matriz), which is assumed to lie at an altitude of 35.874 m according to observations made many years ago under the direction of Samuel Pereira, an engineer in charge of the Manaus Sanitation Committee Whereas such an altitude cannot, by any means, be considered to be a precise datum point, observations have been provisionally referred to it. The measurements are in metres. ### Source The data were kindly made available by Professors H. O'Reilly Sternberg and D. R. Brillinger of the University of California at Berkeley. ### References Davison, A.C. and Hinkley, D.V. (1997) *Bootstrap Methods and Their Application*. Cambridge University Press. Sternberg, H. O'R. (1987) Aggravation of floods in the Amazon river as a consequence of deforestation? *Geografiska Annaler*, **69A**, 201-219. Sternberg, H. O'R. (1995) Waters and wetlands of Brazilian Amazonia: An uncertain future. In *The Fragile Tropics of Latin America: Sustainable Management of Changing Environments*, Nishizawa, T. and Uitto, J.I. (editors), United Nations University Press, 113-179. r None `control` Control Variate Calculations --------------------------------------- ### Description This function will find control variate estimates from a bootstrap output object. It can either find the adjusted bias estimate using post-simulation balancing or it can estimate the bias, variance, third cumulant and quantiles, using the linear approximation as a control variate. ### Usage ``` control(boot.out, L = NULL, distn = NULL, index = 1, t0 = NULL, t = NULL, bias.adj = FALSE, alpha = NULL, ...) ``` ### Arguments | | | | --- | --- | | `boot.out` | A bootstrap output object returned from `boot`. The bootstrap replicates must have been generated using the usual nonparametric bootstrap. | | `L` | The empirical influence values for the statistic of interest. If `L` is not supplied then `empinf` is called to calculate them from `boot.out`. | | `distn` | If present this must be the output from `smooth.spline` giving the distribution function of the linear approximation. This is used only if `bias.adj` is `FALSE`. Normally this would be found using a saddlepoint approximation. If it is not supplied in that case then it is calculated by `saddle.distn`. | | `index` | The index of the variable of interest in the output of `boot.out$statistic`. | | `t0` | The observed value of the statistic of interest on the original data set `boot.out$data`. This argument is used only if `bias.adj` is `FALSE`. The input value is ignored if `t` is not also supplied. The default value is is `boot.out$t0[index]`. | | `t` | The bootstrap replicate values of the statistic of interest. This argument is used only if `bias.adj` is `FALSE`. The input is ignored if `t0` is not supplied also. The default value is `boot.out$t[,index]`. | | `bias.adj` | A logical variable which if `TRUE` specifies that the adjusted bias estimate using post-simulation balance is all that is required. If `bias.adj` is `FALSE` (default) then the linear approximation to the statistic is calculated and used as a control variate in estimates of the bias, variance and third cumulant as well as quantiles. | | `alpha` | The alpha levels for the required quantiles if `bias.adj` is `FALSE`. | | `...` | Any additional arguments that `boot.out$statistic` requires. These are passed unchanged every time `boot.out$statistic` is called. `boot.out$statistic` is called once if `bias.adj` is `TRUE`, otherwise it may be called by `empinf` for empirical influence calculations if `L` is not supplied. | ### Details If `bias.adj` is `FALSE` then the linear approximation to the statistic is found and evaluated at each bootstrap replicate. Then using the equation *T\* = Tl\*+(T\*-Tl\*)*, moment estimates can be found. For quantile estimation the distribution of the linear approximation to `t` is approximated very accurately by saddlepoint methods, this is then combined with the bootstrap replicates to approximate the bootstrap distribution of `t` and hence to estimate the bootstrap quantiles of `t`. ### Value If `bias.adj` is `TRUE` then the returned value is the adjusted bias estimate. If `bias.adj` is `FALSE` then the returned value is a list with the following components | | | | --- | --- | | `L` | The empirical influence values used. These are the input values if supplied, and otherwise they are the values calculated by `empinf`. | | `tL` | The linear approximations to the bootstrap replicates `t` of the statistic of interest. | | `bias` | The control estimate of bias using the linear approximation to `t` as a control variate. | | `var` | The control estimate of variance using the linear approximation to `t` as a control variate. | | `k3` | The control estimate of the third cumulant using the linear approximation to `t` as a control variate. | | `quantiles` | A matrix with two columns; the first column are the alpha levels used for the quantiles and the second column gives the corresponding control estimates of the quantiles using the linear approximation to `t` as a control variate. | | `distn` | An output object from `smooth.spline` describing the saddlepoint approximation to the bootstrap distribution of the linear approximation to `t`. If `distn` was supplied on input then this is the same as the input otherwise it is calculated by a call to `saddle.distn`. | ### References Davison, A.C. and Hinkley, D.V. (1997) *Bootstrap Methods and Their Application*. Cambridge University Press. Davison, A.C., Hinkley, D.V. and Schechtman, E. (1986) Efficient bootstrap simulation. *Biometrika*, **73**, 555–566. Efron, B. (1990) More efficient bootstrap computations. *Journal of the American Statistical Association*, **55**, 79–89. ### See Also `<boot>`, `<empinf>`, `<k3.linear>`, `<linear.approx>`, `<saddle.distn>`, `[smooth.spline](../../stats/html/smooth.spline)`, `<var.linear>` ### Examples ``` # Use of control variates for the variance of the air-conditioning data mean.fun <- function(d, i) { m <- mean(d$hours[i]) n <- nrow(d) v <- (n-1)*var(d$hours[i])/n^2 c(m, v) } air.boot <- boot(aircondit, mean.fun, R = 999) control(air.boot, index = 2, bias.adj = TRUE) air.cont <- control(air.boot, index = 2) # Now let us try the variance on the log scale. air.cont1 <- control(air.boot, t0 = log(air.boot$t0[2]), t = log(air.boot$t[, 2])) ```
programming_docs
r None `urine` Urine Analysis Data ---------------------------- ### Description The `urine` data frame has 79 rows and 7 columns. 79 urine specimens were analyzed in an effort to determine if certain physical characteristics of the urine might be related to the formation of calcium oxalate crystals. ### Usage ``` urine ``` ### Format This data frame contains the following columns: `r` Indicator of the presence of calcium oxalate crystals. `gravity` The specific gravity of the urine. `ph` The pH reading of the urine. `osmo` The osmolarity of the urine. Osmolarity is proportional to the concentration of molecules in solution. `cond` The conductivity of the urine. Conductivity is proportional to the concentration of charged ions in solution. `urea` The urea concentration in millimoles per litre. `calc` The calcium concentration in millimoles per litre. ### Source The data were obtained from Andrews, D.F. and Herzberg, A.M. (1985) *Data: A Collection of Problems from Many Fields for the Student and Research Worker*. Springer-Verlag. ### References Davison, A.C. and Hinkley, D.V. (1997) *Bootstrap Methods and Their Application*. Cambridge University Press. r None `cane` Sugar-cane Disease Data ------------------------------- ### Description The `cane` data frame has 180 rows and 5 columns. The data frame represents a randomized block design with 45 varieties of sugar-cane and 4 blocks. ### Usage ``` cane ``` ### Format This data frame contains the following columns: `n` The total number of shoots in each plot. `r` The number of diseased shoots. `x` The number of pieces of the stems, out of 50, planted in each plot. `var` A factor indicating the variety of sugar-cane in each plot. `block` A factor for the blocks. ### Details The aim of the experiment was to classify the varieties into resistant, intermediate and susceptible to a disease called "coal of sugar-cane" (carvao da cana-de-acucar). This is a disease that is common in sugar-cane plantations in certain areas of Brazil. For each plot, fifty pieces of sugar-cane stem were put in a solution containing the disease agent and then some were planted in the plot. After a fixed period of time, the total number of shoots and the number of diseased shoots were recorded. ### Source The data were kindly supplied by Dr. C.G.B. Demetrio of Escola Superior de Agricultura, Universidade de Sao Paolo, Brazil. ### References Davison, A.C. and Hinkley, D.V. (1997) *Bootstrap Methods and Their Application*. Cambridge University Press. r None `norm.ci` Normal Approximation Confidence Intervals ---------------------------------------------------- ### Description Using the normal approximation to a statistic, calculate equi-tailed two-sided confidence intervals. ### Usage ``` norm.ci(boot.out = NULL, conf = 0.95, index = 1, var.t0 = NULL, t0 = NULL, t = NULL, L = NULL, h = function(t) t, hdot = function(t) 1, hinv = function(t) t) ``` ### Arguments | | | | --- | --- | | `boot.out` | A bootstrap output object returned from a call to `boot`. If `t0` is missing then `boot.out` is a required argument. It is also required if both `var.t0` and `t` are missing. | | `conf` | A scalar or vector containing the confidence level(s) of the required interval(s). | | `index` | The index of the statistic of interest within the output of a call to `boot.out$statistic`. It is not used if `boot.out` is missing, in which case `t0` must be supplied. | | `var.t0` | The variance of the statistic of interest. If it is not supplied then `var(t)` is used. | | `t0` | The observed value of the statistic of interest. If it is missing then it is taken from `boot.out` which is required in that case. | | `t` | Bootstrap replicates of the variable of interest. These are used to estimate the variance of the statistic of interest if `var.t0` is not supplied. The default value is `boot.out$t[,index]`. | | `L` | The empirical influence values for the statistic of interest. These are used to calculate `var.t0` if neither `var.t0` nor `boot.out` are supplied. If a transformation is supplied through `h` then the influence values must be for the untransformed statistic `t0`. | | `h` | A function defining a monotonic transformation, the intervals are calculated on the scale of `h(t)` and the inverse function `hinv` is applied to the resulting intervals. `h` must be a function of one variable only and must be vectorized. The default is the identity function. | | `hdot` | A function of one argument returning the derivative of `h`. It is a required argument if `h` is supplied and is used for approximating the variance of `h(t0)`. The default is the constant function 1. | | `hinv` | A function, like `h`, which returns the inverse of `h`. It is used to transform the intervals calculated on the scale of `h(t)` back to the original scale. The default is the identity function. If `h` is supplied but `hinv` is not, then the intervals returned will be on the transformed scale. | ### Details It is assumed that the statistic of interest has an approximately normal distribution with variance `var.t0` and so a confidence interval of length `2*qnorm((1+conf)/2)*sqrt(var.t0)` is found. If `boot.out` or `t` are supplied then the interval is bias-corrected using the bootstrap bias estimate, and so the interval would be centred at `2*t0-mean(t)`. Otherwise the interval is centred at `t0`. ### Value If `length(conf)` is 1 then a vector containing the confidence level and the endpoints of the interval is returned. Otherwise, the returned value is a matrix where each row corresponds to a different confidence level. ### Note This function is primarily designed to be called by `boot.ci` to calculate the normal approximation after a bootstrap but it can also be used without doing any bootstrap calculations as long as `t0` and `var.t0` can be supplied. See the examples below. ### References Davison, A.C. and Hinkley, D.V. (1997) *Bootstrap Methods and Their Application*. Cambridge University Press. ### See Also `<boot.ci>` ### Examples ``` # In Example 5.1 of Davison and Hinkley (1997), normal approximation # confidence intervals are found for the air-conditioning data. air.mean <- mean(aircondit$hours) air.n <- nrow(aircondit) air.v <- air.mean^2/air.n norm.ci(t0 = air.mean, var.t0 = air.v) exp(norm.ci(t0 = log(air.mean), var.t0 = 1/air.n)[2:3]) # Now a more complicated example - the ratio estimate for the city data. ratio <- function(d, w) sum(d$x * w)/sum(d$u *w) city.v <- var.linear(empinf(data = city, statistic = ratio)) norm.ci(t0 = ratio(city,rep(0.1,10)), var.t0 = city.v) ``` r None `nuclear` Nuclear Power Station Construction Data -------------------------------------------------- ### Description The `nuclear` data frame has 32 rows and 11 columns. The data relate to the construction of 32 light water reactor (LWR) plants constructed in the U.S.A in the late 1960's and early 1970's. The data was collected with the aim of predicting the cost of construction of further LWR plants. 6 of the power plants had partial turnkey guarantees and it is possible that, for these plants, some manufacturers' subsidies may be hidden in the quoted capital costs. ### Usage ``` nuclear ``` ### Format This data frame contains the following columns: `cost` The capital cost of construction in millions of dollars adjusted to 1976 base. `date` The date on which the construction permit was issued. The data are measured in years since January 1 1990 to the nearest month. `t1` The time between application for and issue of the construction permit. `t2` The time between issue of operating license and construction permit. `cap` The net capacity of the power plant (MWe). `pr` A binary variable where `1` indicates the prior existence of a LWR plant at the same site. `ne` A binary variable where `1` indicates that the plant was constructed in the north-east region of the U.S.A. `ct` A binary variable where `1` indicates the use of a cooling tower in the plant. `bw` A binary variable where `1` indicates that the nuclear steam supply system was manufactured by Babcock-Wilcox. `cum.n` The cumulative number of power plants constructed by each architect-engineer. `pt` A binary variable where `1` indicates those plants with partial turnkey guarantees. ### Source The data were obtained from Cox, D.R. and Snell, E.J. (1981) *Applied Statistics: Principles and Examples*. Chapman and Hall. ### References Davison, A.C. and Hinkley, D.V. (1997) *Bootstrap Methods and Their Application*. Cambridge University Press. r None `print.bootci` Print Bootstrap Confidence Intervals ---------------------------------------------------- ### Description This is a method for the function `print()` to print objects of the class `"bootci"`. ### Usage ``` ## S3 method for class 'bootci' print(x, hinv = NULL, ...) ``` ### Arguments | | | | --- | --- | | `x` | The output from a call to `boot.ci`. | | `hinv` | A transformation to be made to the interval end-points before they are printed. | | `...` | further arguments passed to or from other methods. | ### Details This function prints out the results from `boot.ci` in a "nice" format. It also notes whether the scale of the intervals is the original scale of the input to `boot.ci` or a different scale and whether the calculations were done on a transformed scale. It also looks at the order statistics that were used in calculating the intervals. If the smallest or largest values were used then it prints a message `Warning : Intervals used Extreme Quantiles` Such intervals should be considered very unstable and not relied upon for inferences. Even if the extreme values are not used, it is possible that the intervals are unstable if they used quantiles close to the extreme values. The function alerts the user to intervals which use the upper or lower 10 order statistics with the message `Some intervals may be unstable` ### Value The object `ci.out` is returned invisibly. ### See Also `<boot.ci>` r None `acme` Monthly Excess Returns ------------------------------ ### Description The `acme` data frame has 60 rows and 3 columns. The excess return for the Acme Cleveland Corporation are recorded along with those for all stocks listed on the New York and American Stock Exchanges were recorded over a five year period. These excess returns are relative to the return on a risk-less investment such a U.S. Treasury bills. ### Usage ``` acme ``` ### Format This data frame contains the following columns: `month` A character string representing the month of the observation. `market` The excess return of the market as a whole. `acme` The excess return for the Acme Cleveland Corporation. ### Source The data were obtained from Simonoff, J.S. and Tsai, C.-L. (1994) Use of modified profile likelihood for improved tests of constancy of variance in regression. *Applied Statistics*, **43**, 353–370. ### References Davison, A.C. and Hinkley, D.V. (1997) *Bootstrap Methods and Their Application*. Cambridge University Press. r None `simplex` Simplex Method for Linear Programming Problems --------------------------------------------------------- ### Description This function will optimize the linear function `a%*%x` subject to the constraints `A1%*%x <= b1`, `A2%*%x >= b2`, `A3%*%x = b3` and `x >= 0`. Either maximization or minimization is possible but the default is minimization. ### Usage ``` simplex(a, A1 = NULL, b1 = NULL, A2 = NULL, b2 = NULL, A3 = NULL, b3 = NULL, maxi = FALSE, n.iter = n + 2 * m, eps = 1e-10) ``` ### Arguments | | | | --- | --- | | `a` | A vector of length `n` which gives the coefficients of the objective function. | | `A1` | An `m1` by `n` matrix of coefficients for the *<=* type of constraints. | | `b1` | A vector of length `m1` giving the right hand side of the *<=* constraints. This argument is required if `A1` is given and ignored otherwise. All values in `b1` must be non-negative. | | `A2` | An `m2` by `n` matrix of coefficients for the *>=* type of constraints. | | `b2` | A vector of length `m2` giving the right hand side of the *>=* constraints. This argument is required if `A2` is given and ignored otherwise. All values in `b2` must be non-negative. Note that the constraints `x >= 0` are included automatically and so should not be repeated here. | | `A3` | An `m3` by `n` matrix of coefficients for the equality constraints. | | `b3` | A vector of length `m3` giving the right hand side of equality constraints. This argument is required if `A3` is given and ignored otherwise. All values in `b3` must be non-negative. | | `maxi` | A logical flag which specifies minimization if `FALSE` (default) and maximization otherwise. If `maxi` is `TRUE` then the maximization problem is recast as a minimization problem by changing the objective function coefficients to their negatives. | | `n.iter` | The maximum number of iterations to be conducted in each phase of the simplex method. The default is `n+2*(m1+m2+m3)`. | | `eps` | The floating point tolerance to be used in tests of equality. | ### Details The method employed by this function is the two phase tableau simplex method. If there are *>=* or equality constraints an initial feasible solution is not easy to find. To find a feasible solution an artificial variable is introduced into each *>=* or equality constraint and an auxiliary objective function is defined as the sum of these artificial variables. If a feasible solution to the set of constraints exists then the auxiliary objective will be minimized when all of the artificial variables are 0. These are then discarded and the original problem solved starting at the solution to the auxiliary problem. If the only constraints are of the *<=* form, the origin is a feasible solution and so the first stage can be omitted. ### Value An object of class `"simplex"`: see `<simplex.object>`. ### Note The method employed here is suitable only for relatively small systems. Also if possible the number of constraints should be reduced to a minimum in order to speed up the execution time which is approximately proportional to the cube of the number of constraints. In particular if there are any constraints of the form `x[i] >= b2[i]` they should be omitted by setting `x[i] = x[i]-b2[i]`, changing all the constraints and the objective function accordingly and then transforming back after the solution has been found. ### References Gill, P.E., Murray, W. and Wright, M.H. (1991) *Numerical Linear Algebra and Optimization Vol. 1*. Addison-Wesley. Press, W.H., Teukolsky, S.A., Vetterling, W.T. and Flannery, B.P. (1992) *Numerical Recipes: The Art of Scientific Computing (Second Edition)*. Cambridge University Press. ### Examples ``` # This example is taken from Exercise 7.5 of Gill, Murray and Wright (1991). enj <- c(200, 6000, 3000, -200) fat <- c(800, 6000, 1000, 400) vitx <- c(50, 3, 150, 100) vity <- c(10, 10, 75, 100) vitz <- c(150, 35, 75, 5) simplex(a = enj, A1 = fat, b1 = 13800, A2 = rbind(vitx, vity, vitz), b2 = c(600, 300, 550), maxi = TRUE) ``` r None `censboot` Bootstrap for Censored Data --------------------------------------- ### Description This function applies types of bootstrap resampling which have been suggested to deal with right-censored data. It can also do model-based resampling using a Cox regression model. ### Usage ``` censboot(data, statistic, R, F.surv, G.surv, strata = matrix(1,n,2), sim = "ordinary", cox = NULL, index = c(1, 2), ..., parallel = c("no", "multicore", "snow"), ncpus = getOption("boot.ncpus", 1L), cl = NULL) ``` ### Arguments | | | | --- | --- | | `data` | The data frame or matrix containing the data. It must have at least two columns, one of which contains the times and the other the censoring indicators. It is allowed to have as many other columns as desired (although efficiency is reduced for large numbers of columns) except for `sim = "weird"` when it should only have two columns - the times and censoring indicators. The columns of `data` referenced by the components of `index` are taken to be the times and censoring indicators. | | `statistic` | A function which operates on the data frame and returns the required statistic. Its first argument must be the data. Any other arguments that it requires can be passed using the `...` argument. In the case of `sim = "weird"`, the data passed to `statistic` only contains the times and censoring indicator regardless of the actual number of columns in `data`. In all other cases the data passed to statistic will be of the same form as the original data. When `sim = "weird"`, the actual number of observations in the resampled data sets may not be the same as the number in `data`. For this reason, if `sim = "weird"` and `strata` is supplied, `statistic` should also take a numeric vector indicating the strata. This allows the statistic to depend on the strata if required. | | `R` | The number of bootstrap replicates. | | `F.surv` | An object returned from a call to `survfit` giving the survivor function for the data. This is a required argument unless `sim = "ordinary"` or `sim = "model"` and `cox` is missing. | | `G.surv` | Another object returned from a call to `survfit` but with the censoring indicators reversed to give the product-limit estimate of the censoring distribution. Note that for consistency the uncensored times should be reduced by a small amount in the call to `survfit`. This is a required argument whenever `sim = "cond"` or when `sim = "model"` and `cox` is supplied. | | `strata` | The strata used in the calls to `survfit`. It can be a vector or a matrix with 2 columns. If it is a vector then it is assumed to be the strata for the survival distribution, and the censoring distribution is assumed to be the same for all observations. If it is a matrix then the first column is the strata for the survival distribution and the second is the strata for the censoring distribution. When `sim = "weird"` only the strata for the survival distribution are used since the censoring times are considered fixed. When `sim = "ordinary"`, only one set of strata is used to stratify the observations, this is taken to be the first column of `strata` when it is a matrix. | | `sim` | The simulation type. Possible types are `"ordinary"` (case resampling), `"model"` (equivalent to `"ordinary"` if `cox` is missing, otherwise it is model-based resampling), `"weird"` (the weird bootstrap - this cannot be used if `cox` is supplied), and `"cond"` (the conditional bootstrap, in which censoring times are resampled from the conditional censoring distribution). | | `cox` | An object returned from `coxph`. If it is supplied, then `F.surv` should have been generated by a call of the form `survfit(cox)`. | | `index` | A vector of length two giving the positions of the columns in `data` which correspond to the times and censoring indicators respectively. | | `...` | Other named arguments which are passed unchanged to `statistic` each time it is called. Any such arguments to `statistic` must follow the arguments which `statistic` is required to have for the simulation. Beware of partial matching to arguments of `censboot` listed above, and that arguments named `X` and `FUN` cause conflicts in some versions of boot (but not this one). | | `parallel, ncpus, cl` | See the help for `<boot>`. | ### Details The various types of resampling are described in Davison and Hinkley (1997) in sections 3.5 and 7.3. The simplest is case resampling which simply resamples with replacement from the observations. The conditional bootstrap simulates failure times from the estimate of the survival distribution. Then, for each observation its simulated censoring time is equal to the observed censoring time if the observation was censored and generated from the estimated censoring distribution conditional on being greater than the observed failure time if the observation was uncensored. If the largest value is censored then it is given a nominal failure time of `Inf` and conversely if it is uncensored it is given a nominal censoring time of `Inf`. This is necessary to allow the largest observation to be in the resamples. If a Cox regression model is fitted to the data and supplied, then the failure times are generated from the survival distribution using that model. In this case the censoring times can either be simulated from the estimated censoring distribution (`sim = "model"`) or from the conditional censoring distribution as in the previous paragraph (`sim = "cond"`). The weird bootstrap holds the censored observations as fixed and also the observed failure times. It then generates the number of events at each failure time using a binomial distribution with mean 1 and denominator the number of failures that could have occurred at that time in the original data set. In our implementation we insist that there is a least one simulated event in each stratum for every bootstrap dataset. When there are strata involved and `sim` is either `"model"` or `"cond"` the situation becomes more difficult. Since the strata for the survival and censoring distributions are not the same it is possible that for some observations both the simulated failure time and the simulated censoring time are infinite. To see this consider an observation in stratum 1F for the survival distribution and stratum 1G for the censoring distribution. Now if the largest value in stratum 1F is censored it is given a nominal failure time of `Inf`, also if the largest value in stratum 1G is uncensored it is given a nominal censoring time of `Inf` and so both the simulated failure and censoring times could be infinite. When this happens the simulated value is considered to be a failure at the time of the largest observed failure time in the stratum for the survival distribution. When `parallel = "snow"` and `cl` is not supplied, `library(survival)` is run in each of the worker processes. ### Value An object of class `"boot"` containing the following components: | | | | --- | --- | | `t0` | The value of `statistic` when applied to the original data. | | `t` | A matrix of bootstrap replicates of the values of `statistic`. | | `R` | The number of bootstrap replicates performed. | | `sim` | The simulation type used. This will usually be the input value of `sim` unless that was `"model"` but `cox` was not supplied, in which case it will be `"ordinary"`. | | `data` | The data used for the bootstrap. This will generally be the input value of `data` unless `sim = "weird"`, in which case it will just be the columns containing the times and the censoring indicators. | | `seed` | The value of `.Random.seed` when `censboot` started work. | | `statistic` | The input value of `statistic`. | | `strata` | The strata used in the resampling. When `sim = "ordinary"` this will be a vector which stratifies the observations, when `sim = "weird"` it is the strata for the survival distribution and in all other cases it is a matrix containing the strata for the survival distribution and the censoring distribution. | | `call` | The original call to `censboot`. | ### Author(s) Angelo J. Canty. Parallel extensions by Brian Ripley ### References Andersen, P.K., Borgan, O., Gill, R.D. and Keiding, N. (1993) *Statistical Models Based on Counting Processes*. Springer-Verlag. Burr, D. (1994) A comparison of certain bootstrap confidence intervals in the Cox model. *Journal of the American Statistical Association*, **89**, 1290–1302. Davison, A.C. and Hinkley, D.V. (1997) *Bootstrap Methods and Their Application*. Cambridge University Press. Efron, B. (1981) Censored data and the bootstrap. *Journal of the American Statistical Association*, **76**, 312–319. Hjort, N.L. (1985) Bootstrapping Cox's regression model. Technical report NSF-241, Dept. of Statistics, Stanford University. ### See Also `<boot>`, `[coxph](../../survival/html/coxph)`, `[survfit](../../survival/html/survfit)` ### Examples ``` library(survival) # Example 3.9 of Davison and Hinkley (1997) does a bootstrap on some # remission times for patients with a type of leukaemia. The patients # were divided into those who received maintenance chemotherapy and # those who did not. Here we are interested in the median remission # time for the two groups. data(aml, package = "boot") # not the version in survival. aml.fun <- function(data) { surv <- survfit(Surv(time, cens) ~ group, data = data) out <- NULL st <- 1 for (s in 1:length(surv$strata)) { inds <- st:(st + surv$strata[s]-1) md <- min(surv$time[inds[1-surv$surv[inds] >= 0.5]]) st <- st + surv$strata[s] out <- c(out, md) } out } aml.case <- censboot(aml, aml.fun, R = 499, strata = aml$group) # Now we will look at the same statistic using the conditional # bootstrap and the weird bootstrap. For the conditional bootstrap # the survival distribution is stratified but the censoring # distribution is not. aml.s1 <- survfit(Surv(time, cens) ~ group, data = aml) aml.s2 <- survfit(Surv(time-0.001*cens, 1-cens) ~ 1, data = aml) aml.cond <- censboot(aml, aml.fun, R = 499, strata = aml$group, F.surv = aml.s1, G.surv = aml.s2, sim = "cond") # For the weird bootstrap we must redefine our function slightly since # the data will not contain the group number. aml.fun1 <- function(data, str) { surv <- survfit(Surv(data[, 1], data[, 2]) ~ str) out <- NULL st <- 1 for (s in 1:length(surv$strata)) { inds <- st:(st + surv$strata[s] - 1) md <- min(surv$time[inds[1-surv$surv[inds] >= 0.5]]) st <- st + surv$strata[s] out <- c(out, md) } out } aml.wei <- censboot(cbind(aml$time, aml$cens), aml.fun1, R = 499, strata = aml$group, F.surv = aml.s1, sim = "weird") # Now for an example where a cox regression model has been fitted # the data we will look at the melanoma data of Example 7.6 from # Davison and Hinkley (1997). The fitted model assumes that there # is a different survival distribution for the ulcerated and # non-ulcerated groups but that the thickness of the tumour has a # common effect. We will also assume that the censoring distribution # is different in different age groups. The statistic of interest # is the linear predictor. This is returned as the values at a # number of equally spaced points in the range of interest. data(melanoma, package = "boot") library(splines)# for ns mel.cox <- coxph(Surv(time, status == 1) ~ ns(thickness, df=4) + strata(ulcer), data = melanoma) mel.surv <- survfit(mel.cox) agec <- cut(melanoma$age, c(0, 39, 49, 59, 69, 100)) mel.cens <- survfit(Surv(time - 0.001*(status == 1), status != 1) ~ strata(agec), data = melanoma) mel.fun <- function(d) { t1 <- ns(d$thickness, df=4) cox <- coxph(Surv(d$time, d$status == 1) ~ t1+strata(d$ulcer)) ind <- !duplicated(d$thickness) u <- d$thickness[!ind] eta <- cox$linear.predictors[!ind] sp <- smooth.spline(u, eta, df=20) th <- seq(from = 0.25, to = 10, by = 0.25) predict(sp, th)$y } mel.str <- cbind(melanoma$ulcer, agec) # this is slow! mel.mod <- censboot(melanoma, mel.fun, R = 499, F.surv = mel.surv, G.surv = mel.cens, cox = mel.cox, strata = mel.str, sim = "model") # To plot the original predictor and a 95% pointwise envelope for it mel.env <- envelope(mel.mod)$point th <- seq(0.25, 10, by = 0.25) plot(th, mel.env[1, ], ylim = c(-2, 2), xlab = "thickness (mm)", ylab = "linear predictor", type = "n") lines(th, mel.mod$t0, lty = 1) matlines(th, t(mel.env), lty = 2) ```
programming_docs
r None `motor` Data from a Simulated Motorcycle Accident -------------------------------------------------- ### Description The `motor` data frame has 94 rows and 4 columns. The rows are obtained by removing replicate values of `time` from the dataset `[mcycle](../../mass/html/mcycle)`. Two extra columns are added to allow for strata with a different residual variance in each stratum. ### Usage ``` motor ``` ### Format This data frame contains the following columns: `times` The time in milliseconds since impact. `accel` The recorded head acceleration (in g). `strata` A numeric column indicating to which of the three strata (numbered 1, 2 and 3) the observations belong. `v` An estimate of the residual variance for the observation. `v` is constant within the strata but a different estimate is used for each of the three strata. ### Source The data were obtained from Silverman, B.W. (1985) Some aspects of the spline smoothing approach to non-parametric curve fitting. *Journal of the Royal Statistical Society, B*, **47**, 1–52. ### References Davison, A.C. and Hinkley, D.V. (1997) *Bootstrap Methods and Their Application*. Cambridge University Press. Venables, W.N. and Ripley, B.D. (1994) *Modern Applied Statistics with S-Plus*. Springer-Verlag. ### See Also `[mcycle](../../mass/html/mcycle)` r None `exp.tilt` Exponential Tilting ------------------------------- ### Description This function calculates exponentially tilted multinomial distributions such that the resampling distributions of the linear approximation to a statistic have the required means. ### Usage ``` exp.tilt(L, theta = NULL, t0 = 0, lambda = NULL, strata = rep(1, length(L))) ``` ### Arguments | | | | --- | --- | | `L` | The empirical influence values for the statistic of interest based on the observed data. The length of `L` should be the same as the size of the original data set. Typically `L` will be calculated by a call to `empinf`. | | `theta` | The value at which the tilted distribution is to be centred. This is not required if `lambda` is supplied but is needed otherwise. | | `t0` | The current value of the statistic. The default is that the statistic equals 0. | | `lambda` | The Lagrange multiplier(s). For each value of `lambda` a multinomial distribution is found with probabilities proportional to `exp(lambda * L)`. In general `lambda` is not known and so `theta` would be supplied, and the corresponding value of `lambda` found. If both `lambda` and `theta` are supplied then `lambda` is ignored and the multipliers for tilting to `theta` are found. | | `strata` | A vector or factor of the same length as `L` giving the strata for the observed data and the empirical influence values `L`. | ### Details Exponential tilting involves finding a set of weights for a data set to ensure that the bootstrap distribution of the linear approximation to a statistic of interest has mean `theta`. The weights chosen to achieve this are given by `p[j]` proportional to `exp(lambda*L[j]/n)`, where `n` is the number of data points. `lambda` is then chosen to make the mean of the bootstrap distribution, of the linear approximation to the statistic of interest, equal to the required value `theta`. Thus `lambda` is defined as the solution of a nonlinear equation. The equation is solved by minimizing the Euclidean distance between the left and right hand sides of the equation using the function `nlmin`. If this minimum is not equal to zero then the method fails. Typically exponential tilting is used to find suitable weights for importance resampling. If a small tail probability or quantile of the distribution of the statistic of interest is required then a more efficient simulation is to centre the resampling distribution close to the point of interest and then use the functions `imp.prob` or `imp.quantile` to estimate the required quantity. Another method of achieving a similar shifting of the distribution is through the use of `smooth.f`. The function `tilt.boot` uses `exp.tilt` or `smooth.f` to find the weights for a tilted bootstrap. ### Value A list with the following components : | | | | --- | --- | | `p` | The tilted probabilities. There will be `m` distributions where `m` is the length of `theta` (or `lambda` if supplied). If `m` is 1 then `p` is a vector of `length(L)` probabilities. If `m` is greater than 1 then `p` is a matrix with `m` rows, each of which contain `length(L)` probabilities. In this case the vector `p[i,]` is the distribution tilted to `theta[i]`. `p` is in the form required by the argument `weights` of the function `boot` for importance resampling. | | `lambda` | The Lagrange multiplier used in the equation to determine the tilted probabilities. `lambda` is a vector of the same length as `theta`. | | `theta` | The values of `theta` to which the distributions have been tilted. In general this will be the input value of `theta` but if `lambda` was supplied then this is the vector of the corresponding `theta` values. | ### References Davison, A. C. and Hinkley, D. V. (1997) *Bootstrap Methods and Their Application*. Cambridge University Press. Efron, B. (1981) Nonparametric standard errors and confidence intervals (with Discussion). *Canadian Journal of Statistics*, **9**, 139–172. ### See Also `<empinf>`, `[imp.prob](imp.estimates)`, `[imp.quantile](imp.estimates)`, `[optim](../../stats/html/optim)`, `<smooth.f>`, `<tilt.boot>` ### Examples ``` # Example 9.8 of Davison and Hinkley (1997) requires tilting the resampling # distribution of the studentized statistic to be centred at the observed # value of the test statistic 1.84. This can be achieved as follows. grav1 <- gravity[as.numeric(gravity[,2]) >=7 , ] grav.fun <- function(dat, w, orig) { strata <- tapply(dat[, 2], as.numeric(dat[, 2])) d <- dat[, 1] ns <- tabulate(strata) w <- w/tapply(w, strata, sum)[strata] mns <- as.vector(tapply(d * w, strata, sum)) # drop names mn2 <- tapply(d * d * w, strata, sum) s2hat <- sum((mn2 - mns^2)/ns) c(mns[2]-mns[1], s2hat, (mns[2]-mns[1]-orig)/sqrt(s2hat)) } grav.z0 <- grav.fun(grav1, rep(1, 26), 0) grav.L <- empinf(data = grav1, statistic = grav.fun, stype = "w", strata = grav1[,2], index = 3, orig = grav.z0[1]) grav.tilt <- exp.tilt(grav.L, grav.z0[3], strata = grav1[,2]) boot(grav1, grav.fun, R = 499, stype = "w", weights = grav.tilt$p, strata = grav1[,2], orig = grav.z0[1]) ``` r None `cum3` Calculate Third Order Cumulants --------------------------------------- ### Description Calculates an estimate of the third cumulant, or skewness, of a vector. Also, if more than one vector is specified, a product-moment of order 3 is estimated. ### Usage ``` cum3(a, b = a, c = a, unbiased = TRUE) ``` ### Arguments | | | | --- | --- | | `a` | A vector of observations. | | `b` | Another vector of observations, if not supplied it is set to the value of `a`. If supplied then it must be the same length as `a`. | | `c` | Another vector of observations, if not supplied it is set to the value of `a`. If supplied then it must be the same length as `a`. | | `unbiased` | A logical value indicating whether the unbiased estimator should be used. | ### Details The unbiased estimator uses a multiplier of `n/((n-1)*(n-2))` where `n` is the sample size, if `unbiased` is `FALSE` then a multiplier of `1/n` is used. This is multiplied by `sum((a-mean(a))*(b-mean(b))*(c-mean(c)))` to give the required estimate. ### Value The required estimate. r None `darwin` Darwin's Plant Height Differences ------------------------------------------- ### Description The `darwin` data frame has 15 rows and 1 columns. Charles Darwin conducted an experiment to examine the superiority of cross-fertilized plants over self-fertilized plants. 15 pairs of plants were used. Each pair consisted of one cross-fertilized plant and one self-fertilized plant which germinated at the same time and grew in the same pot. The plants were measured at a fixed time after planting and the difference in heights between the cross- and self-fertilized plants are recorded in eighths of an inch. ### Usage ``` darwin ``` ### Format This data frame contains the following column: `y` The difference in heights for the pairs of plants (in units of 0.125 inches). ### Source The data were obtained from Fisher, R.A. (1935) *Design of Experiments*. Oliver and Boyd. ### References Darwin, C. (1876) *The Effects of Cross- and Self-fertilisation in the Vegetable Kingdom*. John Murray. Davison, A.C. and Hinkley, D.V. (1997) *Bootstrap Methods and Their Application*. Cambridge University Press. r None `jack.after.boot` Jackknife-after-Bootstrap Plots -------------------------------------------------- ### Description This function calculates the jackknife influence values from a bootstrap output object and plots the corresponding jackknife-after-bootstrap plot. ### Usage ``` jack.after.boot(boot.out, index = 1, t = NULL, L = NULL, useJ = TRUE, stinf = TRUE, alpha = NULL, main = "", ylab = NULL, ...) ``` ### Arguments | | | | --- | --- | | `boot.out` | An object of class `"boot"` which would normally be created by a call to `<boot>`. It should represent a nonparametric bootstrap. For reliable results `boot.out$R` should be reasonably large. | | `index` | The index of the statistic of interest in the output of `boot.out$statistic`. | | `t` | A vector of length `boot.out$R` giving the bootstrap replicates of the statistic of interest. This is useful if the statistic of interest is a function of the calculated bootstrap output. If it is not supplied then the default is `boot.out$t[,index]`. | | `L` | The empirical influence values for the statistic of interest. These are used only if `useJ` is `FALSE`. If they are not supplied and are needed, they are calculated by a call to `empinf`. If `L` is supplied then it is assumed that they are the infinitesimal jackknife values. | | `useJ` | A logical variable indicating if the jackknife influence values calculated from the bootstrap replicates should be used. If `FALSE` the empirical influence values are used. The default is `TRUE`. | | `stinf` | A logical variable indicating whether to standardize the jackknife values before plotting them. If `TRUE` then the jackknife values used are divided by their standard error. | | `alpha` | The quantiles at which the plots are required. The default is `c(0.05, 0.1, 0.16, 0.5, 0.84, 0.9, 0.95)`. | | `main` | A character string giving the main title for the plot. | | `ylab` | The label for the Y axis. If the default values of `alpha` are used and `ylab` is not supplied then a label indicating which percentiles are plotted is used. If `alpha` is supplied then the default label will not say which percentiles were used. | | `...` | Any extra arguments required by `boot.out$statistic`. These are required only if `useJ` is `FALSE` and `L` is not supplied, in which case they are passed to `empinf` for use in calculation of the empirical influence values. | ### Details The centred jackknife quantiles for each observation are estimated from those bootstrap samples in which the particular observation did not appear. These are then plotted against the influence values. If `useJ` is `TRUE` then the influence values are found in the same way as the difference between the mean of the statistic in the samples excluding the observations and the mean in all samples. If `useJ` is `FALSE` then empirical influence values are calculated by calling `empinf`. The resulting plots are useful diagnostic tools for looking at the way individual observations affect the bootstrap output. The plot will consist of a number of horizontal dotted lines which correspond to the quantiles of the centred bootstrap distribution. For each data point the quantiles of the bootstrap distribution calculated by omitting that point are plotted against the (possibly standardized) jackknife values. The observation number is printed below the plots. To make it easier to see the effect of omitting points on quantiles, the plotted quantiles are joined by line segments. These plots provide a useful diagnostic tool in establishing the effect of individual observations on the bootstrap distribution. See the references below for some guidelines on the interpretation of the plots. ### Value There is no returned value but a plot is generated on the current graphics display. ### Side Effects A plot is created on the current graphics device. ### References Davison, A.C. and Hinkley, D.V. (1997) *Bootstrap Methods and Their Application*. Cambridge University Press. Efron, B. (1992) Jackknife-after-bootstrap standard errors and influence functions (with Discussion). *Journal of the Royal Statistical Society, B*, **54**, 83–127. ### See Also `<boot>`, `<empinf>` ### Examples ``` # To draw the jackknife-after-bootstrap plot for the head size data as in # Example 3.24 of Davison and Hinkley (1997) frets.fun <- function(data, i) { pcorr <- function(x) { # Function to find the correlations and partial correlations between # the four measurements. v <- cor(x) v.d <- diag(var(x)) iv <- solve(v) iv.d <- sqrt(diag(iv)) iv <- - diag(1/iv.d) %*% iv %*% diag(1/iv.d) q <- NULL n <- nrow(v) for (i in 1:(n-1)) q <- rbind( q, c(v[i, 1:i], iv[i,(i+1):n]) ) q <- rbind( q, v[n, ] ) diag(q) <- round(diag(q)) q } d <- data[i, ] v <- pcorr(d) c(v[1,], v[2,], v[3,], v[4,]) } frets.boot <- boot(log(as.matrix(frets)), frets.fun, R = 999) # we will concentrate on the partial correlation between head breadth # for the first son and head length for the second. This is the 7th # element in the output of frets.fun so we set index = 7 jack.after.boot(frets.boot, useJ = FALSE, stinf = FALSE, index = 7) ``` r None `catsM` Weight Data for Domestic Cats -------------------------------------- ### Description The `catsM` data frame has 97 rows and 3 columns. 144 adult (over 2kg in weight) cats used for experiments with the drug digitalis had their heart and body weight recorded. 47 of the cats were female and 97 were male. The `catsM` data frame consists of the data for the male cats. The full data are in dataset `[cats](../../mass/html/cats)` in package `MASS`. ### Usage ``` catsM ``` ### Format This data frame contains the following columns: `Sex` A factor for the sex of the cat (levels are `F` and `M`: all cases are `M` in this subset). `Bwt` Body weight in kg. `Hwt` Heart weight in g. ### Source The data were obtained from Fisher, R.A. (1947) The analysis of covariance method for the relation between a part and the whole. *Biometrics*, **3**, 65–68. ### References Davison, A.C. and Hinkley, D.V. (1997) *Bootstrap Methods and Their Application*. Cambridge University Press. Venables, W.N. and Ripley, B.D. (1994) *Modern Applied Statistics with S-Plus*. Springer-Verlag. ### See Also `[cats](../../mass/html/cats)` r None `saddle` Saddlepoint Approximations for Bootstrap Statistics ------------------------------------------------------------- ### Description This function calculates a saddlepoint approximation to the distribution of a linear combination of **W** at a particular point `u`, where **W** is a vector of random variables. The distribution of **W** may be multinomial (default), Poisson or binary. Other distributions are possible also if the adjusted cumulant generating function and its second derivative are given. Conditional saddlepoint approximations to the distribution of one linear combination given the values of other linear combinations of **W** can be calculated for **W** having binary or Poisson distributions. ### Usage ``` saddle(A = NULL, u = NULL, wdist = "m", type = "simp", d = NULL, d1 = 1, init = rep(0.1, d), mu = rep(0.5, n), LR = FALSE, strata = NULL, K.adj = NULL, K2 = NULL) ``` ### Arguments | | | | --- | --- | | `A` | A vector or matrix of known coefficients of the linear combinations of **W**. It is a required argument unless `K.adj` and `K2` are supplied, in which case it is ignored. | | `u` | The value at which it is desired to calculate the saddlepoint approximation to the distribution of the linear combination of **W**. It is a required argument unless `K.adj` and `K2` are supplied, in which case it is ignored. | | `wdist` | The distribution of **W**. This can be one of `"m"` (multinomial), `"p"` (Poisson), `"b"` (binary) or `"o"` (other). If `K.adj` and `K2` are given `wdist` is set to `"o"`. | | `type` | The type of saddlepoint approximation. Possible types are `"simp"` for simple saddlepoint and `"cond"` for the conditional saddlepoint. When `wdist` is `"o"` or `"m"`, `type` is automatically set to `"simp"`, which is the only type of saddlepoint currently implemented for those distributions. | | `d` | This specifies the dimension of the whole statistic. This argument is required only when `wdist = "o"` and defaults to 1 if not supplied in that case. For other distributions it is set to `ncol(A)`. | | `d1` | When `type` is `"cond"` this is the dimension of the statistic of interest which must be less than `length(u)`. Then the saddlepoint approximation to the conditional distribution of the first `d1` linear combinations given the values of the remaining combinations is found. Conditional distribution function approximations can only be found if the value of `d1` is 1. | | `init` | Used if `wdist` is either `"m"` or `"o"`, this gives initial values to `nlmin` which is used to solve the saddlepoint equation. | | `mu` | The values of the parameters of the distribution of **W** when `wdist` is `"m"`, `"p"` `"b"`. `mu` must be of the same length as W (i.e. `nrow(A)`). The default is that all values of `mu` are equal and so the elements of **W** are identically distributed. | | `LR` | If `TRUE` then the Lugananni-Rice approximation to the cdf is used, otherwise the approximation used is based on Barndorff-Nielsen's r\*. | | `strata` | The strata for stratified data. | | `K.adj` | The adjusted cumulant generating function used when `wdist` is `"o"`. This is a function of a single parameter, `zeta`, which calculates `K(zeta)-u%*%zeta`, where `K(zeta)` is the cumulant generating function of **W**. | | `K2` | This is a function of a single parameter `zeta` which returns the matrix of second derivatives of `K(zeta)` for use when `wdist` is `"o"`. If `K.adj` is given then this must be given also. It is called only once with the calculated solution to the saddlepoint equation being passed as the argument. This argument is ignored if `K.adj` is not supplied. | ### Details If `wdist` is `"o"` or `"m"`, the saddlepoint equations are solved using `nlmin` to minimize `K.adj` with respect to its parameter `zeta`. For the Poisson and binary cases, a generalized linear model is fitted such that the parameter estimates solve the saddlepoint equations. The response variable 'y' for the `glm` must satisfy the equation `t(A)%*%y = u` (`t()` being the transpose function). Such a vector can be found as a feasible solution to a linear programming problem. This is done by a call to `simplex`. The covariate matrix for the `glm` is given by `A`. ### Value A list consisting of the following components | | | | --- | --- | | `spa` | The saddlepoint approximations. The first value is the density approximation and the second value is the distribution function approximation. | | `zeta.hat` | The solution to the saddlepoint equation. For the conditional saddlepoint this is the solution to the saddlepoint equation for the numerator. | | `zeta2.hat` | If `type` is `"cond"` this is the solution to the saddlepoint equation for the denominator. This component is not returned for any other value of `type`. | ### References Booth, J.G. and Butler, R.W. (1990) Randomization distributions and saddlepoint approximations in generalized linear models. *Biometrika*, **77**, 787–796. Canty, A.J. and Davison, A.C. (1997) Implementation of saddlepoint approximations to resampling distributions. *Computing Science and Statistics; Proceedings of the 28th Symposium on the Interface*, 248–253. Davison, A.C. and Hinkley, D.V. (1997) *Bootstrap Methods and their Application*. Cambridge University Press. Jensen, J.L. (1995) *Saddlepoint Approximations*. Oxford University Press. ### See Also `<saddle.distn>`, `<simplex>` ### Examples ``` # To evaluate the bootstrap distribution of the mean failure time of # air-conditioning equipment at 80 hours saddle(A = aircondit$hours/12, u = 80) # Alternatively this can be done using a conditional poisson saddle(A = cbind(aircondit$hours/12,1), u = c(80, 12), wdist = "p", type = "cond") # To use the Lugananni-Rice approximation to this saddle(A = cbind(aircondit$hours/12,1), u = c(80, 12), wdist = "p", type = "cond", LR = TRUE) # Example 9.16 of Davison and Hinkley (1997) calculates saddlepoint # approximations to the distribution of the ratio statistic for the # city data. Since the statistic is not in itself a linear combination # of random Variables, its distribution cannot be found directly. # Instead the statistic is expressed as the solution to a linear # estimating equation and hence its distribution can be found. We # get the saddlepoint approximation to the pdf and cdf evaluated at # t = 1.25 as follows. jacobian <- function(dat,t,zeta) { p <- exp(zeta*(dat$x-t*dat$u)) abs(sum(dat$u*p)/sum(p)) } city.sp1 <- saddle(A = city$x-1.25*city$u, u = 0) city.sp1$spa[1] <- jacobian(city, 1.25, city.sp1$zeta.hat) * city.sp1$spa[1] city.sp1 ```
programming_docs
r None `gravity` Acceleration Due to Gravity -------------------------------------- ### Description The `gravity` data frame has 81 rows and 2 columns. The `grav` data set has 26 rows and 2 columns. Between May 1934 and July 1935, the National Bureau of Standards in Washington D.C. conducted a series of experiments to estimate the acceleration due to gravity, *g*, at Washington. Each experiment produced a number of replicate estimates of *g* using the same methodology. Although the basic method remained the same for all experiments, that of the reversible pendulum, there were changes in configuration. The `gravity` data frame contains the data from all eight experiments. The `grav` data frame contains the data from the experiments 7 and 8. The data are expressed as deviations from 980.000 in centimetres per second squared. ### Usage ``` gravity ``` ### Format This data frame contains the following columns: `g` The deviation of the estimate from 980.000 centimetres per second squared. `series` A factor describing from which experiment the estimate was derived. ### Source The data were obtained from Cressie, N. (1982) Playing safe with misweighted means. *Journal of the American Statistical Association*, **77**, 754–759. ### References Davison, A.C. and Hinkley, D.V. (1997) *Bootstrap Methods and Their Application*. Cambridge University Press. r None `EEF.profile` Empirical Likelihoods ------------------------------------ ### Description Construct the empirical log likelihood or empirical exponential family log likelihood for a mean. ### Usage ``` EEF.profile(y, tmin = min(y) + 0.1, tmax = max(y) - 0.1, n.t = 25, u = function(y, t) y - t) EL.profile(y, tmin = min(y) + 0.1, tmax = max(y) - 0.1, n.t = 25, u = function(y, t) y - t) ``` ### Arguments | | | | --- | --- | | `y` | A vector or matrix of data | | `tmin` | The minimum value of the range over which the likelihood should be computed. This must be larger than `min(y)`. | | `tmax` | The maximum value of the range over which the likelihood should be computed. This must be smaller than `max(y)`. | | `n.t` | The number of points between `tmin` and `tmax` at which the value of the log-likelihood should be computed. | | `u` | A function of the data and the parameter. | ### Details These functions calculate the log likelihood for a mean using either an empirical likelihood or an empirical exponential family likelihood. They are supplied as part of the package `boot` for demonstration purposes with the practicals in chapter 10 of Davison and Hinkley (1997). The functions are not intended for general use and are not supported as part of the `boot`package. For more general and more robust code to calculate empirical likelihoods see Professor A. B. Owen's empirical likelihood home page at the URL <https://statweb.stanford.edu/~owen/empirical/>. ### Value A matrix with `n.t` rows. The first column contains the values of the parameter used. The second column of the output of `EL.profile` contains the values of the empirical log likelihood. The second and third columns of the output of `EEF.profile` contain two versions of the empirical exponential family log-likelihood. The final column of the output matrix contains the values of the Lagrange multiplier used in the optimization procedure. ### Author(s) Angelo J. Canty ### References Davison, A. C. and Hinkley, D. V. (1997) *Bootstrap Methods and Their Application*. Cambridge University Press. r None `aml` Remission Times for Acute Myelogenous Leukaemia ------------------------------------------------------ ### Description The `aml` data frame has 23 rows and 3 columns. A clinical trial to evaluate the efficacy of maintenance chemotherapy for acute myelogenous leukaemia was conducted by Embury et al. (1977) at Stanford University. After reaching a stage of remission through treatment by chemotherapy, patients were randomized into two groups. The first group received maintenance chemotherapy and the second group did not. The aim of the study was to see if maintenance chemotherapy increased the length of the remission. The data here formed a preliminary analysis which was conducted in October 1974. ### Usage ``` aml ``` ### Format This data frame contains the following columns: `time` The length of the complete remission (in weeks). `cens` An indicator of right censoring. 1 indicates that the patient had a relapse and so `time` is the length of the remission. 0 indicates that the patient had left the study or was still in remission in October 1974, that is the length of remission is right-censored. `group` The group into which the patient was randomized. Group 1 received maintenance chemotherapy, group 2 did not. ### Note Package survival also has a dataset `aml`. It is the same data with different names and with `group` replaced by a factor `x`. ### Source The data were obtained from Miller, R.G. (1981) *Survival Analysis*. John Wiley. ### References Davison, A.C. and Hinkley, D.V. (1997) *Bootstrap Methods and Their Application*. Cambridge University Press. Embury, S.H, Elias, L., Heller, P.H., Hood, C.E., Greenberg, P.L. and Schrier, S.L. (1977) Remission maintenance therapy in acute myelogenous leukaemia. *Western Journal of Medicine*, **126**, 267-272. r None `paulsen` Neurotransmission in Guinea Pig Brains ------------------------------------------------- ### Description The `paulsen` data frame has 346 rows and 1 columns. Sections were prepared from the brain of adult guinea pigs. Spontaneous currents that flowed into individual brain cells were then recorded and the peak amplitude of each current measured. The aim of the experiment was to see if the current flow was quantal in nature (i.e. that it is not a single burst but instead is built up of many smaller bursts of current). If the current was indeed quantal then it would be expected that the distribution of the current amplitude would be multimodal with modes at regular intervals. The modes would be expected to decrease in magnitude for higher current amplitudes. ### Usage ``` paulsen ``` ### Format This data frame contains the following column: `y` The current flowing into individual brain cells. The currents are measured in pico-amperes. ### Source The data were kindly made available by Dr. O. Paulsen from the Department of Pharmacology at the University of Oxford. Paulsen, O. and Heggelund, P. (1994) The quantal size at retinogeniculate synapses determined from spontaneous and evoked EPSCs in guinea-pig thalamic slices. *Journal of Physiology*, **480**, 505–511. ### References Davison, A.C. and Hinkley, D.V. (1997) *Bootstrap Methods and Their Application*. Cambridge University Press. r None `print.simplex` Print Solution to Linear Programming Problem ------------------------------------------------------------- ### Description This is a method for the function `print()` to print objects of class `"simplex"`. ### Usage ``` ## S3 method for class 'simplex' print(x, ...) ``` ### Arguments | | | | --- | --- | | `x` | An object of class `"simplex"` created by calling the function `simplex` to solve a linear programming problem. | | `...` | further arguments passed to or from other methods. | ### Details The coefficients of the objective function are printed. If a solution to the linear programming problem was found then the solution and the optimal value of the objective function are printed. If a feasible solution was found but the maximum number of iterations was exceeded then the last feasible solution and the objective function value at that point are printed. If no feasible solution could be found then a message stating that is printed. ### Value `x` is returned silently. ### See Also `<simplex>` r None `polar` Pole Positions of New Caledonian Laterites --------------------------------------------------- ### Description The `polar` data frame has 50 rows and 2 columns. The data are the pole positions from a paleomagnetic study of New Caledonian laterites. ### Usage ``` polar ``` ### Format This data frame contains the following columns: `lat` The latitude (in degrees) of the pole position. Note that all latitudes are negative as the axis is taken to be in the lower hemisphere. `long` The longitude (in degrees) of the pole position. ### Source The data were obtained from Fisher, N.I., Lewis, T. and Embleton, B.J.J. (1987) *Statistical Analysis of Spherical Data*. Cambridge University Press. ### References Davison, A.C. and Hinkley, D.V. (1997) *Bootstrap Methods and Their Application*. Cambridge University Press. r None `print.saddle.distn` Print Quantiles of Saddlepoint Approximations ------------------------------------------------------------------- ### Description This is a method for the function `print()` to print objects of class `"saddle.distn"`. ### Usage ``` ## S3 method for class 'saddle.distn' print(x, ...) ``` ### Arguments | | | | --- | --- | | `x` | An object of class `"saddle.distn"` created by a call to `saddle.distn`. | | `...` | further arguments passed to or from other methods. | ### Details The quantiles of the saddlepoint approximation to the distribution are printed along with the original call and some other useful information. ### Value The input is returned invisibly. ### See Also `<lines.saddle.distn>`, `<saddle.distn>` r None `print.boot` Print a Summary of a Bootstrap Object --------------------------------------------------- ### Description This is a method for the function `print()` for objects of the class `"boot"` created by a call to `<boot>`, `<censboot>`, `<tilt.boot>` or `<tsboot>`. ### Usage ``` ## S3 method for class 'boot' print(x, digits = getOption("digits"), index = 1:ncol(boot.out$t), ...) ``` ### Arguments | | | | --- | --- | | `x` | A bootstrap output object of class `"boot"` generated by one of the bootstrap functions. | | `digits` | The number of digits to be printed in the summary statistics. | | `index` | Indices indicating for which elements of the bootstrap output summary statistics are required. | | `...` | further arguments passed to or from other methods. | ### Details For each statistic calculated in the bootstrap the original value and the bootstrap estimates of its bias and standard error are printed. If `boot.out$t0` is missing (such as when it was created by a call to `tsboot` with `orig.t = FALSE`) the bootstrap mean and standard error are printed. If resampling was done using importance resampling weights, then the bootstrap estimates are reweighted as if uniform resampling had been done. The ratio importance sampling estimates are used and if there were a number of distributions then defensive mixture distributions are used. In this case an extra column with the mean of the observed bootstrap statistics is also printed. ### Value The bootstrap object is returned invisibly. ### See Also `<boot>`, `<censboot>`, `[imp.moments](imp.estimates)`, `<plot.boot>`, `<tilt.boot>`, `<tsboot>` r None `plot.boot` Plots of the Output of a Bootstrap Simulation ---------------------------------------------------------- ### Description This takes a bootstrap object and produces plots for the bootstrap replicates of the variable of interest. ### Usage ``` ## S3 method for class 'boot' plot(x, index = 1, t0 = NULL, t = NULL, jack = FALSE, qdist = "norm", nclass = NULL, df, ...) ``` ### Arguments | | | | --- | --- | | `x` | An object of class `"boot"` returned from one of the bootstrap generation functions. | | `index` | The index of the variable of interest within the output of `boot.out`. This is ignored if `t` and `t0` are supplied. | | `t0` | The original value of the statistic. This defaults to `boot.out$t0[index]` unless `t` is supplied when it defaults to `NULL`. In that case no vertical line is drawn on the histogram. | | `t` | The bootstrap replicates of the statistic. Usually this will take on its default value of `boot.out$t[,index]`, however it may be useful sometimes to supply a different set of values which are a function of `boot.out$t`. | | `jack` | A logical value indicating whether a jackknife-after-bootstrap plot is required. The default is not to produce such a plot. | | `qdist` | The distribution against which the Q-Q plot should be drawn. At present `"norm"` (normal distribution - the default) and `"chisq"` (chi-squared distribution) are the only possible values. | | `nclass` | An integer giving the number of classes to be used in the bootstrap histogram. The default is the integer between 10 and 100 closest to `ceiling(length(t)/25)`. | | `df` | If `qdist` is `"chisq"` then this is the degrees of freedom for the chi-squared distribution to be used. It is a required argument in that case. | | `...` | When `jack` is `TRUE` additional parameters to `jack.after.boot` can be supplied. See the help file for `jack.after.boot` for details of the possible parameters. | ### Details This function will generally produce two side-by-side plots. The left plot will be a histogram of the bootstrap replicates. Usually the breaks of the histogram will be chosen so that `t0` is at a breakpoint and all intervals are of equal length. A vertical dotted line indicates the position of `t0`. This cannot be done if `t` is supplied but `t0` is not and so, in that case, the breakpoints are computed by `hist` using the `nclass` argument and no vertical line is drawn. The second plot is a Q-Q plot of the bootstrap replicates. The order statistics of the replicates can be plotted against normal or chi-squared quantiles. In either case the expected line is also plotted. For the normal, this will have intercept `mean(t)` and slope `sqrt(var(t))` while for the chi-squared it has intercept 0 and slope 1. If `jack` is `TRUE` a third plot is produced beneath these two. That plot is the jackknife-after-bootstrap plot. This plot may only be requested when nonparametric simulation has been used. See `jack.after.boot` for further details of this plot. ### Value `boot.out` is returned invisibly. ### Side Effects All screens are closed and cleared and a number of plots are produced on the current graphics device. Screens are closed but not cleared at termination of this function. ### See Also `<boot>`, `<jack.after.boot>`, `<print.boot>` ### Examples ``` # We fit an exponential model to the air-conditioning data and use # that for a parametric bootstrap. Then we look at plots of the # resampled means. air.rg <- function(data, mle) rexp(length(data), 1/mle) air.boot <- boot(aircondit$hours, mean, R = 999, sim = "parametric", ran.gen = air.rg, mle = mean(aircondit$hours)) plot(air.boot) # In the difference of means example for the last two series of the # gravity data grav1 <- gravity[as.numeric(gravity[, 2]) >= 7, ] grav.fun <- function(dat, w) { strata <- tapply(dat[, 2], as.numeric(dat[, 2])) d <- dat[, 1] ns <- tabulate(strata) w <- w/tapply(w, strata, sum)[strata] mns <- as.vector(tapply(d * w, strata, sum)) # drop names mn2 <- tapply(d * d * w, strata, sum) s2hat <- sum((mn2 - mns^2)/ns) c(mns[2] - mns[1], s2hat) } grav.boot <- boot(grav1, grav.fun, R = 499, stype = "w", strata = grav1[, 2]) plot(grav.boot) # now suppose we want to look at the studentized differences. grav.z <- (grav.boot$t[, 1]-grav.boot$t0[1])/sqrt(grav.boot$t[, 2]) plot(grav.boot, t = grav.z, t0 = 0) # In this example we look at the one of the partial correlations for the # head dimensions in the dataset frets. frets.fun <- function(data, i) { pcorr <- function(x) { # Function to find the correlations and partial correlations between # the four measurements. v <- cor(x) v.d <- diag(var(x)) iv <- solve(v) iv.d <- sqrt(diag(iv)) iv <- - diag(1/iv.d) %*% iv %*% diag(1/iv.d) q <- NULL n <- nrow(v) for (i in 1:(n-1)) q <- rbind( q, c(v[i, 1:i], iv[i,(i+1):n]) ) q <- rbind( q, v[n, ] ) diag(q) <- round(diag(q)) q } d <- data[i, ] v <- pcorr(d) c(v[1,], v[2,], v[3,], v[4,]) } frets.boot <- boot(log(as.matrix(frets)), frets.fun, R = 999) plot(frets.boot, index = 7, jack = TRUE, stinf = FALSE, useJ = FALSE) ``` r None `islay` Jura Quartzite Azimuths on Islay ----------------------------------------- ### Description The `islay` data frame has 18 rows and 1 columns. Measurements were taken of paleocurrent azimuths from the Jura Quartzite on the Scottish island of Islay. ### Usage ``` islay ``` ### Format This data frame contains the following column: `theta` The angle of the azimuth in degrees East of North. ### Source The data were obtained from Hand, D.J., Daly, F., Lunn, A.D., McConway, K.J. and Ostrowski, E. (1994) *A Handbook of Small Data Sets*, Chapman and Hall. ### References Davison, A.C. and Hinkley, D.V. (1997) *Bootstrap Methods and Their Application*. Cambridge University Press. Till, R. (1974) *Statistical Methods for the Earth Scientist*. Macmillan. r None `boot.array` Bootstrap Resampling Arrays ----------------------------------------- ### Description This function takes a bootstrap object calculated by one of the functions `boot`, `censboot`, or `tilt.boot` and returns the frequency (or index) array for the bootstrap resamples. ### Usage ``` boot.array(boot.out, indices) ``` ### Arguments | | | | --- | --- | | `boot.out` | An object of class `"boot"` returned by one of the generation functions for such an object. | | `indices` | A logical argument which specifies whether to return the frequency array or the raw index array. The default is `indices=FALSE` unless `boot.out` was created by `tsboot` in which case the default is `indices=TRUE`. | ### Details The process by which the original index array was generated is repeated with the same value of `.Random.seed`. If the frequency array is required then `freq.array` is called to convert the index array to a frequency array. A resampling array can only be returned when such a concept makes sense. In particular it cannot be found for any parametric or model-based resampling schemes. Hence for objects generated by `censboot` the only resampling scheme for which such an array can be found is ordinary case resampling. Similarly if `boot.out$sim` is `"parametric"` in the case of `boot` or `"model"` in the case of `tsboot` the array cannot be found. Note also that for post-blackened bootstraps from `tsboot` the indices found will relate to those prior to any post-blackening and so will not be useful. Frequency arrays are used in many post-bootstrap calculations such as the jackknife-after-bootstrap and finding importance sampling weights. They are also used to find empirical influence values through the regression method. ### Value A matrix with `boot.out$R` rows and `n` columns where `n` is the number of observations in `boot.out$data`. If `indices` is `FALSE` then this will give the frequency of each of the original observations in each bootstrap resample. If `indices` is `TRUE` it will give the indices of the bootstrap resamples in the order in which they would have been passed to the statistic. ### Side Effects This function temporarily resets `.Random.seed` to the value in `boot.out$seed` and then returns it to its original value at the end of the function. ### See Also `<boot>`, `<censboot>`, `<freq.array>`, `<tilt.boot>`, `<tsboot>` ### Examples ``` # A frequency array for a nonparametric bootstrap city.boot <- boot(city, corr, R = 40, stype = "w") boot.array(city.boot) perm.cor <- function(d,i) cor(d$x,d$u[i]) city.perm <- boot(city, perm.cor, R = 40, sim = "permutation") boot.array(city.perm, indices = TRUE) ```
programming_docs
r None `saddle.distn` Saddlepoint Distribution Approximations for Bootstrap Statistics -------------------------------------------------------------------------------- ### Description Approximate an entire distribution using saddlepoint methods. This function can calculate simple and conditional saddlepoint distribution approximations for a univariate quantity of interest. For the simple saddlepoint the quantity of interest is a linear combination of **W** where **W** is a vector of random variables. For the conditional saddlepoint we require the distribution of one linear combination given the values of any number of other linear combinations. The distribution of **W** must be one of multinomial, Poisson or binary. The primary use of this function is to calculate quantiles of bootstrap distributions using saddlepoint approximations. Such quantiles are required by the function `<control>` to approximate the distribution of the linear approximation to a statistic. ### Usage ``` saddle.distn(A, u = NULL, alpha = NULL, wdist = "m", type = "simp", npts = 20, t = NULL, t0 = NULL, init = rep(0.1, d), mu = rep(0.5, n), LR = FALSE, strata = NULL, ...) ``` ### Arguments | | | | --- | --- | | `A` | This is a matrix of known coefficients or a function which returns such a matrix. If a function then its first argument must be the point `t` at which a saddlepoint is required. The most common reason for A being a function would be if the statistic is not itself a linear combination of the **W** but is the solution to a linear estimating equation. | | `u` | If `A` is a function then `u` must also be a function returning a vector with length equal to the number of columns of the matrix returned by `A`. Usually all components other than the first will be constants as the other components are the values of the conditioning variables. If `A` is a matrix with more than one column (such as when `wdist = "cond"`) then `u` should be a vector with length one less than `ncol(A)`. In this case `u` specifies the values of the conditioning variables. If `A` is a matrix with one column or a vector then `u` is not used. | | `alpha` | The alpha levels for the quantiles of the distribution which should be returned. By default the 0.1, 0.5, 1, 2.5, 5, 10, 20, 50, 80, 90, 95, 97.5, 99, 99.5 and 99.9 percentiles are calculated. | | `wdist` | The distribution of **W**. Possible values are `"m"` (multinomial), `"p"` (Poisson), or `"b"` (binary). | | `type` | The type of saddlepoint to be used. Possible values are `"simp"` (simple saddlepoint) and `"cond"` (conditional). If `wdist` is `"m"`, `type` is set to `"simp"`. | | `npts` | The number of points at which the saddlepoint approximation should be calculated and then used to fit the spline. | | `t` | A vector of points at which the saddlepoint approximations are calculated. These points should extend beyond the extreme quantiles required but still be in the possible range of the bootstrap distribution. The observed value of the statistic should not be included in `t` as the distribution function approximation breaks down at that point. The points should, however cover the entire effective range of the distribution including close to the centre. If `t` is supplied then `npts` is set to `length(t)`. When `t` is not supplied, the function attempts to find the effective range of the distribution and then selects points to cover this range. | | `t0` | If `t` is not supplied then a vector of length 2 should be passed as `t0`. The first component of `t0` should be the centre of the distribution and the second should be an estimate of spread (such as a standard error). These two are then used to find the effective range of the distribution. The range finding mechanism does rely on an accurate estimate of location in `t0[1]`. | | `init` | When `wdist` is `"m"`, this vector should contain the initial values to be passed to `nlmin` when it is called to solve the saddlepoint equations. | | `mu` | The vector of parameter values for the distribution. The default is that the components of **W** are identically distributed. | | `LR` | A logical flag. When `LR` is `TRUE` the Lugananni-Rice cdf approximations are calculated and used to fit the spline. Otherwise the cdf approximations used are based on Barndorff-Nielsen's r\*. | | `strata` | A vector giving the strata when the rows of A relate to stratified data. This is used only when `wdist` is `"m"`. | | `...` | When `A` and `u` are functions any additional arguments are passed unchanged each time one of them is called. | ### Details The range at which the saddlepoint is used is such that the cdf approximation at the endpoints is more extreme than required by the extreme values of `alpha`. The lower endpoint is found by evaluating the saddlepoint at the points `t0[1]-2*t0[2]`, `t0[1]-4*t0[2]`, `t0[1]-8*t0[2]` etc. until a point is found with a cdf approximation less than `min(alpha)/10`, then a bisection method is used to find the endpoint which has cdf approximation in the range (`min(alpha)/1000`, `min(alpha)/10`). Then a number of, equally spaced, points are chosen between the lower endpoint and `t0[1]` until a total of `npts/2` approximations have been made. The remaining `npts/2` points are chosen to the right of `t0[1]` in a similar manner. Any points which are very close to the centre of the distribution are then omitted as the cdf approximations are not reliable at the centre. A smoothing spline is then fitted to the probit of the saddlepoint distribution function approximations at the remaining points and the required quantiles are predicted from the spline. Sometimes the function will terminate with the message `"Unable to find range"`. There are two main reasons why this may occur. One is that the distribution is too discrete and/or the required quantiles too extreme, this can cause the function to be unable to find a point within the allowable range which is beyond the extreme quantiles. Another possibility is that the value of `t0[2]` is too small and so too many steps are required to find the range. The first problem cannot be solved except by asking for less extreme quantiles, although for very discrete distributions the approximations may not be very good. In the second case using a larger value of `t0[2]` will usually solve the problem. ### Value The returned value is an object of class `"saddle.distn"`. See the help file for `<saddle.distn.object>` for a description of such an object. ### References Booth, J.G. and Butler, R.W. (1990) Randomization distributions and saddlepoint approximations in generalized linear models. *Biometrika*, **77**, 787–796. Canty, A.J. and Davison, A.C. (1997) Implementation of saddlepoint approximations to resampling distributions. *Computing Science and Statistics; Proceedings of the 28th Symposium on the Interface* 248–253. Davison, A.C. and Hinkley, D.V. (1997) *Bootstrap Methods and their Application*. Cambridge University Press. Jensen, J.L. (1995) *Saddlepoint Approximations*. Oxford University Press. ### See Also `<lines.saddle.distn>`, `<saddle>`, `<saddle.distn.object>`, `[smooth.spline](../../stats/html/smooth.spline)` ### Examples ``` # The bootstrap distribution of the mean of the air-conditioning # failure data: fails to find value on R (and probably on S too) air.t0 <- c(mean(aircondit$hours), sqrt(var(aircondit$hours)/12)) ## Not run: saddle.distn(A = aircondit$hours/12, t0 = air.t0) # alternatively using the conditional poisson saddle.distn(A = cbind(aircondit$hours/12, 1), u = 12, wdist = "p", type = "cond", t0 = air.t0) # Distribution of the ratio of a sample of size 10 from the bigcity # data, taken from Example 9.16 of Davison and Hinkley (1997). ratio <- function(d, w) sum(d$x *w)/sum(d$u * w) city.v <- var.linear(empinf(data = city, statistic = ratio)) bigcity.t0 <- c(mean(bigcity$x)/mean(bigcity$u), sqrt(city.v)) Afn <- function(t, data) cbind(data$x - t*data$u, 1) ufn <- function(t, data) c(0,10) saddle.distn(A = Afn, u = ufn, wdist = "b", type = "cond", t0 = bigcity.t0, data = bigcity) # From Example 9.16 of Davison and Hinkley (1997) again, we find the # conditional distribution of the ratio given the sum of city$u. Afn <- function(t, data) cbind(data$x-t*data$u, data$u, 1) ufn <- function(t, data) c(0, sum(data$u), 10) city.t0 <- c(mean(city$x)/mean(city$u), sqrt(city.v)) saddle.distn(A = Afn, u = ufn, wdist = "p", type = "cond", t0 = city.t0, data = city) ``` r None `cav` Position of Muscle Caveolae ---------------------------------- ### Description The `cav` data frame has 138 rows and 2 columns. The data gives the positions of the individual caveolae in a square region with sides of length 500 units. This grid was originally on a 2.65mum square of muscle fibre. The data are those points falling in the lower left hand quarter of the region used for the dataset `caveolae.dat` in the spatial package by B.D. Ripley (1994). ### Usage ``` cav ``` ### Format This data frame contains the following columns: `x` The x coordinate of the caveola's position in the region. `y` The y coordinate of the caveola's position in the region. ### References Appleyard, S.T., Witkowski, J.A., Ripley, B.D., Shotton, D.M. and Dubowicz, V. (1985) A novel procedure for pattern analysis of features present on freeze fractured plasma membranes. *Journal of Cell Science*, **74**, 105–117. Davison, A.C. and Hinkley, D.V. (1997) *Bootstrap Methods and Their Application*. Cambridge University Press. r None `tilt.boot` Non-parametric Tilted Bootstrap -------------------------------------------- ### Description This function will run an initial bootstrap with equal resampling probabilities (if required) and will use the output of the initial run to find resampling probabilities which put the value of the statistic at required values. It then runs an importance resampling bootstrap using the calculated probabilities as the resampling distribution. ### Usage ``` tilt.boot(data, statistic, R, sim = "ordinary", stype = "i", strata = rep(1, n), L = NULL, theta = NULL, alpha = c(0.025, 0.975), tilt = TRUE, width = 0.5, index = 1, ...) ``` ### Arguments | | | | --- | --- | | `data` | The data as a vector, matrix or data frame. If it is a matrix or data frame then each row is considered as one (multivariate) observation. | | `statistic` | A function which when applied to data returns a vector containing the statistic(s) of interest. It must take at least two arguments. The first argument will always be `data` and the second should be a vector of indices, weights or frequencies describing the bootstrap sample. Any other arguments must be supplied to `tilt.boot` and will be passed unchanged to statistic each time it is called. | | `R` | The number of bootstrap replicates required. This will generally be a vector, the first value stating how many uniform bootstrap simulations are to be performed at the initial stage. The remaining values of `R` are the number of simulations to be performed resampling from each reweighted distribution. The first value of `R` must always be present, a value of 0 implying that no uniform resampling is to be carried out. Thus `length(R)` should always equal `1+length(theta)`. | | `sim` | This is a character string indicating the type of bootstrap simulation required. There are only two possible values that this can take: `"ordinary"` and `"balanced"`. If other simulation types are required for the initial un-weighted bootstrap then it will be necessary to run `boot`, calculate the weights appropriately, and run `boot` again using the calculated weights. | | `stype` | A character string indicating the type of second argument expected by `statistic`. The possible values that `stype` can take are `"i"` (indices), `"w"` (weights) and `"f"` (frequencies). | | `strata` | An integer vector or factor representing the strata for multi-sample problems. | | `L` | The empirical influence values for the statistic of interest. They are used only for exponential tilting when `tilt` is `TRUE`. If `tilt` is `TRUE` and they are not supplied then `tilt.boot` uses `empinf` to calculate them. | | `theta` | The required parameter value(s) for the tilted distribution(s). There should be one value of `theta` for each of the non-uniform distributions. If `R[1]` is 0 `theta` is a required argument. Otherwise `theta` values can be estimated from the initial uniform bootstrap and the values in `alpha`. | | `alpha` | The alpha level to which tilting is required. This parameter is ignored if `R[1]` is 0 or if `theta` is supplied, otherwise it is used to find the values of `theta` as quantiles of the initial uniform bootstrap. In this case `R[1]` should be large enough that `min(c(alpha, 1-alpha))*R[1] > 5`, if this is not the case then a warning is generated to the effect that the `theta` are extreme values and so the tilted output may be unreliable. | | `tilt` | A logical variable which if `TRUE` (the default) indicates that exponential tilting should be used, otherwise local frequency smoothing (`smooth.f`) is used. If `tilt` is `FALSE` then `R[1]` must be positive. In fact in this case the value of `R[1]` should be fairly large (in the region of 500 or more). | | `width` | This argument is used only if `tilt` is `FALSE`, in which case it is passed unchanged to `smooth.f` as the standardized bandwidth for the smoothing operation. The value should generally be in the range (0.2, 1). See `smooth.f` for for more details. | | `index` | The index of the statistic of interest in the output from `statistic`. By default the first element of the output of `statistic` is used. | | `...` | Any additional arguments required by `statistic`. These are passed unchanged to `statistic` each time it is called. | ### Value An object of class `"boot"` with the following components | | | | --- | --- | | `t0` | The observed value of the statistic on the original data. | | `t` | The values of the bootstrap replicates of the statistic. There will be `sum(R)` of these, the first `R[1]` corresponding to the uniform bootstrap and the remainder to the tilted bootstrap(s). | | `R` | The input vector of the number of bootstrap replicates. | | `data` | The original data as supplied. | | `statistic` | The `statistic` function as supplied. | | `sim` | The simulation type used in the bootstrap(s), it can either be `"ordinary"` or `"balanced"`. | | `stype` | The type of statistic supplied, it is the same as the input value `stype`. | | `call` | A copy of the original call to `tilt.boot`. | | `strata` | The strata as supplied. | | `weights` | The matrix of weights used. If `R[1]` is greater than 0 then the first row will be the uniform weights and each subsequent row the tilted weights. If `R[1]` equals 0 then the uniform weights are omitted and only the tilted weights are output. | | `theta` | The values of `theta` used for the tilted distributions. These are either the input values or the values derived from the uniform bootstrap and `alpha`. | ### References Booth, J.G., Hall, P. and Wood, A.T.A. (1993) Balanced importance resampling for the bootstrap. *Annals of Statistics*, **21**, 286–298. Davison, A.C. and Hinkley, D.V. (1997) *Bootstrap Methods and Their Application*. Cambridge University Press. Hinkley, D.V. and Shi, S. (1989) Importance sampling and the nested bootstrap. *Biometrika*, **76**, 435–446. ### See Also `<boot>`, `<exp.tilt>`, `[Imp.Estimates](imp.estimates)`, `<imp.weights>`, `<smooth.f>` ### Examples ``` # Note that these examples can take a while to run. # Example 9.9 of Davison and Hinkley (1997). grav1 <- gravity[as.numeric(gravity[,2]) >= 7, ] grav.fun <- function(dat, w, orig) { strata <- tapply(dat[, 2], as.numeric(dat[, 2])) d <- dat[, 1] ns <- tabulate(strata) w <- w/tapply(w, strata, sum)[strata] mns <- as.vector(tapply(d * w, strata, sum)) # drop names mn2 <- tapply(d * d * w, strata, sum) s2hat <- sum((mn2 - mns^2)/ns) c(mns[2]-mns[1],s2hat,(mns[2]-mns[1]-orig)/sqrt(s2hat)) } grav.z0 <- grav.fun(grav1, rep(1, 26), 0) tilt.boot(grav1, grav.fun, R = c(249, 375, 375), stype = "w", strata = grav1[,2], tilt = TRUE, index = 3, orig = grav.z0[1]) # Example 9.10 of Davison and Hinkley (1997) requires a balanced # importance resampling bootstrap to be run. In this example we # show how this might be run. acme.fun <- function(data, i, bhat) { d <- data[i,] n <- nrow(d) d.lm <- glm(d$acme~d$market) beta.b <- coef(d.lm)[2] d.diag <- boot::glm.diag(d.lm) SSx <- (n-1)*var(d$market) tmp <- (d$market-mean(d$market))*d.diag$res*d.diag$sd sr <- sqrt(sum(tmp^2))/SSx c(beta.b, sr, (beta.b-bhat)/sr) } acme.b <- acme.fun(acme, 1:nrow(acme), 0) acme.boot1 <- tilt.boot(acme, acme.fun, R = c(499, 250, 250), stype = "i", sim = "balanced", alpha = c(0.05, 0.95), tilt = TRUE, index = 3, bhat = acme.b[1]) ``` r None `breslow` Smoking Deaths Among Doctors --------------------------------------- ### Description The `breslow` data frame has 10 rows and 5 columns. In 1961 Doll and Hill sent out a questionnaire to all men on the British Medical Register enquiring about their smoking habits. Almost 70% of such men replied. Death certificates were obtained for medical practitioners and causes of death were assigned on the basis of these certificates. The `breslow` data set contains the person-years of observations and deaths from coronary artery disease accumulated during the first ten years of the study. ### Usage ``` breslow ``` ### Format This data frame contains the following columns: `age` The mid-point of the 10 year age-group for the doctors. `smoke` An indicator of whether the doctors smoked (1) or not (0). `n` The number of person-years in the category. `y` The number of deaths attributed to coronary artery disease. `ns` The number of smoker years in the category (`smoke*n`). ### Source The data were obtained from Breslow, N.E. (1985) Cohort Analysis in Epidemiology. In *A Celebration of Statistics* A.C. Atkinson and S.E. Fienberg (editors), 109–143. Springer-Verlag. ### References Davison, A.C. and Hinkley, D.V. (1997) *Bootstrap Methods and Their Application*. Cambridge University Press. Doll, R. and Hill, A.B. (1966) Mortality of British doctors in relation to smoking: Observations on coronary thrombosis. *National Cancer Institute Monograph*, **19**, 205-268. r None `nodal` Nodal Involvement in Prostate Cancer --------------------------------------------- ### Description The `nodal` data frame has 53 rows and 7 columns. The treatment strategy for a patient diagnosed with cancer of the prostate depend highly on whether the cancer has spread to the surrounding lymph nodes. It is common to operate on the patient to get samples from the nodes which can then be analysed under a microscope but clearly it would be preferable if an accurate assessment of nodal involvement could be made without surgery. For a sample of 53 prostate cancer patients, a number of possible predictor variables were measured before surgery. The patients then had surgery to determine nodal involvement. It was required to see if nodal involvement could be accurately predicted from the predictor variables and which ones were most important. ### Usage ``` nodal ``` ### Format This data frame contains the following columns: `m` A column of ones. `r` An indicator of nodal involvement. `aged` The patients age dichotomized into less than 60 (`0`) and 60 or over `1`. `stage` A measurement of the size and position of the tumour observed by palpitation with the fingers via the rectum. A value of `1` indicates a more serious case of the cancer. `grade` Another indicator of the seriousness of the cancer, this one is determined by a pathology reading of a biopsy taken by needle before surgery. A value of `1` indicates a more serious case of the cancer. `xray` A third measure of the seriousness of the cancer taken from an X-ray reading. A value of `1` indicates a more serious case of the cancer. `acid` The level of acid phosphatase in the blood serum. ### Source The data were obtained from Brown, B.W. (1980) Prediction analysis for binary data. In *Biostatistics Casebook*. R.G. Miller, B. Efron, B.W. Brown and L.E. Moses (editors), 3–18. John Wiley. ### References Davison, A.C. and Hinkley, D.V. (1997) *Bootstrap Methods and Their Application*. Cambridge University Press.
programming_docs
r None `simplex.object` Linear Programming Solution Objects ----------------------------------------------------- ### Description Class of objects that result from solving a linear programming problem using `simplex`. ### Generation This class of objects is returned from calls to the function `simplex`. ### Methods The class `"saddle.distn"` has a method for the function `print`. ### Structure Objects of class `"simplex"` are implemented as a list with the following components. soln The values of `x` which optimize the objective function under the specified constraints provided those constraints are jointly feasible. solved This indicates whether the problem was solved. A value of `-1` indicates that no feasible solution could be found. A value of `0` that the maximum number of iterations was reached without termination of the second stage. This may indicate an unbounded function or simply that more iterations are needed. A value of `1` indicates that an optimal solution has been found. value The value of the objective function at `soln`. val.aux This is `NULL` if a feasible solution is found. Otherwise it is a positive value giving the value of the auxiliary objective function when it was minimized. obj The original coefficients of the objective function. a The objective function coefficients re-expressed such that the basic variables have coefficient zero. a.aux This is `NULL` if a feasible solution is found. Otherwise it is the re-expressed auxiliary objective function at the termination of the first phase of the simplex method. A The final constraint matrix which is expressed in terms of the non-basic variables. If a feasible solution is found then this will have dimensions `m1+m2+m3` by `n+m1+m2`, where the final `m1+m2` columns correspond to slack and surplus variables. If no feasible solution is found there will be an additional `m1+m2+m3` columns for the artificial variables introduced to solve the first phase of the problem. basic The indices of the basic (non-zero) variables in the solution. Indices between `n+1` and `n+m1` correspond to slack variables, those between `n+m1+1` and `n+m2` correspond to surplus variables and those greater than `n+m2` are artificial variables. Indices greater than `n+m2` should occur only if `solved` is `-1` as the artificial variables are discarded in the second stage of the simplex method. slack The final values of the `m1` slack variables which arise when the "<=" constraints are re-expressed as the equalities `A1%*%x + slack = b1`. surplus The final values of the `m2` surplus variables which arise when the "<=" constraints are re-expressed as the equalities `A2%*%x - surplus = b2`. artificial This is NULL if a feasible solution can be found. If no solution can be found then this contains the values of the `m1+m2+m3` artificial variables which minimize their sum subject to the original constraints. A feasible solution exists only if all of the artificial variables can be made 0 simultaneously. ### See Also `<print.simplex>`, `<simplex>` r None `ducks` Behavioral and Plumage Characteristics of Hybrid Ducks --------------------------------------------------------------- ### Description The `ducks` data frame has 11 rows and 2 columns. Each row of the data frame represents a male duck who is a second generation cross of mallard and pintail ducks. For 11 such ducks a behavioural and plumage index were calculated. These were measured on scales devised for this experiment which was to examine whether there was any link between which species the ducks resembled physically and which they resembled in behaviour. The scale for the physical appearance ranged from 0 (identical in appearance to a mallard) to 20 (identical to a pintail). The behavioural traits of the ducks were on a scale from 0 to 15 with lower numbers indicating closer to mallard-like in behaviour. ### Usage ``` ducks ``` ### Format This data frame contains the following columns: `plumage` The index of physical appearance based on the plumage of individual ducks. `behaviour` The index of behavioural characteristics of the ducks. ### Source The data were obtained from Larsen, R.J. and Marx, M.L. (1986) *An Introduction to Mathematical Statistics and its Applications* (Second Edition). Prentice-Hall. ### References Davison, A.C. and Hinkley, D.V. (1997) *Bootstrap Methods and Their Application*. Cambridge University Press. Sharpe, R.S., and Johnsgard, P.A. (1966) Inheritance of behavioral characters in *F2* mallard x pintail (*Anas Platyrhynchos L. x Anas Acuta L.*) hybrids. *Behaviour*, **27**, 259-272. r None `logit` Logit of Proportions ----------------------------- ### Description This function calculates the logit of proportions. ### Usage ``` logit(p) ``` ### Arguments | | | | --- | --- | | `p` | A numeric Splus object, all of whose values are in the range [0,1]. Missing values (`NA`s) are allowed. | ### Details If any elements of `p` are outside the unit interval then an error message is generated. Values of `p` equal to 0 or 1 (to within machine precision) will return `-Inf` or `Inf` respectively. Any `NA`s in the input will also be `NA`s in the output. ### Value A numeric object of the same type as `p` containing the logits of the input values. ### See Also `<inv.logit>`, `[qlogis](../../stats/html/logistic)` for which this is a wrapper. r None `cd4.nested` Nested Bootstrap of cd4 data ------------------------------------------ ### Description This is an example of a nested bootstrap for the correlation coefficient of the `cd4` data frame. It is used in a practical in Chapter 5 of Davison and Hinkley (1997). ### References Davison, A.C. and Hinkley, D.V. (1997) *Bootstrap Methods and Their Application*. Cambridge University Press. ### See Also `<cd4>` r None `Imp.Estimates` Importance Sampling Estimates ---------------------------------------------- ### Description Central moment, tail probability, and quantile estimates for a statistic under importance resampling. ### Usage ``` imp.moments(boot.out = NULL, index = 1, t = boot.out$t[, index], w = NULL, def = TRUE, q = NULL) imp.prob(boot.out = NULL, index = 1, t0 = boot.out$t0[index], t = boot.out$t[, index], w = NULL, def = TRUE, q = NULL) imp.quantile(boot.out = NULL, alpha = NULL, index = 1, t = boot.out$t[, index], w = NULL, def = TRUE, q = NULL) ``` ### Arguments | | | | --- | --- | | `boot.out` | A object of class `"boot"` generated by a call to `boot` or `tilt.boot`. Use of these functions makes sense only when the bootstrap resampling used unequal weights for the observations. If the importance weights `w` are not supplied then `boot.out` is a required argument. It is also required if `t` is not supplied. | | `alpha` | The alpha levels for the required quantiles. The default is to calculate the 1%, 2.5%, 5%, 10%, 90%, 95%, 97.5% and 99% quantiles. | | `index` | The index of the variable of interest in the output of `boot.out$statistic`. This is not used if the argument `t` is supplied. | | `t0` | The values at which tail probability estimates are required. For each value `t0[i]` the function will estimate the bootstrap cdf evaluated at `t0[i]`. If `imp.prob` is called without the argument `t0` then the bootstrap cdf evaluated at the observed value of the statistic is found. | | `t` | The bootstrap replicates of a statistic. By default these are taken from the bootstrap output object `boot.out` but they can be supplied separately if required (e.g. when the statistic of interest is a function of the calculated values in `boot.out`). Either `boot.out` or `t` must be supplied. | | `w` | The importance resampling weights for the bootstrap replicates. If they are not supplied then `boot.out` must be supplied, in which case the importance weights are calculated by a call to `imp.weights`. | | `def` | A logical value indicating whether a defensive mixture is to be used for weight calculation. This is used only if `w` is missing and it is passed unchanged to `imp.weights` to calculate `w`. | | `q` | A vector of probabilities specifying the resampling distribution from which any estimates should be found. In general this would correspond to the usual bootstrap resampling distribution which gives equal weight to each of the original observations. The estimates depend on this distribution only through the importance weights `w` so this argument is ignored if `w` is supplied. If `w` is missing then `q` is passed as an argument to `imp.weights` and used to find `w`. | ### Value A list with the following components : | | | | --- | --- | | `alpha` | The `alpha` levels used for the quantiles, if `imp.quantile` is used. | | `t0` | The values at which the tail probabilities are estimated, if `imp.prob` is used. | | `raw` | The raw importance resampling estimates. For `imp.moments` this has length 2, the first component being the estimate of the mean and the second being the variance estimate. For `imp.prob`, `raw` is of the same length as `t0`, and for `imp.quantile` it is of the same length as `alpha`. | | `rat` | The ratio importance resampling estimates. In this method the weights `w` are rescaled to have average value one before they are used. The format of this vector is the same as `raw`. | | `reg` | The regression importance resampling estimates. In this method the weights which are used are derived from a regression of `t*w` on `w`. This choice of weights can be shown to minimize the variance of the weights and also the Euclidean distance of the weights from the uniform weights. The format of this vector is the same as `raw`. | ### References Davison, A. C. and Hinkley, D. V. (1997) *Bootstrap Methods and Their Application*. Cambridge University Press. Hesterberg, T. (1995) Weighted average importance sampling and defensive mixture distributions. *Technometrics*, **37**, 185–194. Johns, M.V. (1988) Importance sampling for bootstrap confidence intervals. *Journal of the American Statistical Association*, **83**, 709–714. ### See Also `<boot>`, `<exp.tilt>`, `<imp.weights>`, `<smooth.f>`, `<tilt.boot>` ### Examples ``` # Example 9.8 of Davison and Hinkley (1997) requires tilting the # resampling distribution of the studentized statistic to be centred # at the observed value of the test statistic, 1.84. In this example # we show how certain estimates can be found using resamples taken from # the tilted distribution. grav1 <- gravity[as.numeric(gravity[,2]) >= 7, ] grav.fun <- function(dat, w, orig) { strata <- tapply(dat[, 2], as.numeric(dat[, 2])) d <- dat[, 1] ns <- tabulate(strata) w <- w/tapply(w, strata, sum)[strata] mns <- as.vector(tapply(d * w, strata, sum)) # drop names mn2 <- tapply(d * d * w, strata, sum) s2hat <- sum((mn2 - mns^2)/ns) c(mns[2] - mns[1], s2hat, (mns[2] - mns[1] - orig)/sqrt(s2hat)) } grav.z0 <- grav.fun(grav1, rep(1, 26), 0) grav.L <- empinf(data = grav1, statistic = grav.fun, stype = "w", strata = grav1[,2], index = 3, orig = grav.z0[1]) grav.tilt <- exp.tilt(grav.L, grav.z0[3], strata = grav1[, 2]) grav.tilt.boot <- boot(grav1, grav.fun, R = 199, stype = "w", strata = grav1[, 2], weights = grav.tilt$p, orig = grav.z0[1]) # Since the weights are needed for all calculations, we shall calculate # them once only. grav.w <- imp.weights(grav.tilt.boot) grav.mom <- imp.moments(grav.tilt.boot, w = grav.w, index = 3) grav.p <- imp.prob(grav.tilt.boot, w = grav.w, index = 3, t0 = grav.z0[3]) unlist(grav.p) grav.q <- imp.quantile(grav.tilt.boot, w = grav.w, index = 3, alpha = c(0.9, 0.95, 0.975, 0.99)) as.data.frame(grav.q) ``` r None `channing` Channing House Data ------------------------------- ### Description The `channing` data frame has 462 rows and 5 columns. Channing House is a retirement centre in Palo Alto, California. These data were collected between the opening of the house in 1964 until July 1, 1975. In that time 97 men and 365 women passed through the centre. For each of these, their age on entry and also on leaving or death was recorded. A large number of the observations were censored mainly due to the resident being alive on July 1, 1975 when the data was collected. Over the time of the study 130 women and 46 men died at Channing House. Differences between the survival of the sexes, taking age into account, was one of the primary concerns of this study. ### Usage ``` channing ``` ### Format This data frame contains the following columns: `sex` A factor for the sex of each resident (`"Male"` or `"Female"`). `entry` The residents age (in months) on entry to the centre `exit` The age (in months) of the resident on death, leaving the centre or July 1, 1975 whichever event occurred first. `time` The length of time (in months) that the resident spent at Channing House. (`time=exit-entry`) `cens` The indicator of right censoring. 1 indicates that the resident died at Channing House, 0 indicates that they left the house prior to July 1, 1975 or that they were still alive and living in the centre at that date. ### Source The data were obtained from Hyde, J. (1980) Testing survival with incomplete observations. *Biostatistics Casebook*. R.G. Miller, B. Efron, B.W. Brown and L.E. Moses (editors), 31–46. John Wiley. ### References Davison, A.C. and Hinkley, D.V. (1997) *Bootstrap Methods and Their Application*. Cambridge University Press. r None `capability` Simulated Manufacturing Process Data -------------------------------------------------- ### Description The `capability` data frame has 75 rows and 1 columns. The data are simulated successive observations from a process in equilibrium. The process is assumed to have specification limits (5.49, 5.79). ### Usage ``` capability ``` ### Format This data frame contains the following column: `y` The simulated measurements. ### Source The data were obtained from Bissell, A.F. (1990) How reliable is your capability index? *Applied Statistics*, **39**, 331–340. ### References Canty, A.J. and Davison, A.C. (1996) Implementation of saddlepoint approximations to resampling distributions. To appear in *Computing Science and Statistics; Proceedings of the 28th Symposium on the Interface*. Davison, A.C. and Hinkley, D.V. (1997) *Bootstrap Methods and Their Application*. Cambridge University Press. r None `nitrofen` Toxicity of Nitrofen in Aquatic Systems --------------------------------------------------- ### Description The `nitrofen` data frame has 50 rows and 5 columns. Nitrofen is a herbicide that was used extensively for the control of broad-leaved and grass weeds in cereals and rice. Although it is relatively non-toxic to adult mammals, nitrofen is a significant tetragen and mutagen. It is also acutely toxic and reproductively toxic to cladoceran zooplankton. Nitrofen is no longer in commercial use in the U.S., having been the first pesticide to be withdrawn due to tetragenic effects. The data here come from an experiment to measure the reproductive toxicity of nitrofen on a species of zooplankton (*Ceriodaphnia dubia*). 50 animals were randomized into batches of 10 and each batch was put in a solution with a measured concentration of nitrofen. Then the number of live offspring in each of the three broods to each animal was recorded. ### Usage ``` nitrofen ``` ### Format This data frame contains the following columns: `conc` The nitrofen concentration in the solution (mug/litre). `brood1` The number of live offspring in the first brood. `brood2` The number of live offspring in the second brood. `brood3` The number of live offspring in the third brood. `total` The total number of live offspring in the first three broods. ### Source The data were obtained from Bailer, A.J. and Oris, J.T. (1994) Assessing toxicity of pollutants in aquatic systems. In *Case Studies in Biometry*. N. Lange, L. Ryan, L. Billard, D. Brillinger, L. Conquest and J. Greenhouse (editors), 25–40. John Wiley. ### References Davison, A.C. and Hinkley, D.V. (1997) *Bootstrap Methods and Their Application*. Cambridge University Press. r None `hirose` Failure Time of PET Film ---------------------------------- ### Description The `hirose` data frame has 44 rows and 3 columns. PET film is used in electrical insulation. In this accelerated life test the failure times for 44 samples in gas insulated transformers. 4 different voltage levels were used. ### Usage ``` hirose ``` ### Format This data frame contains the following columns: `volt` The voltage (in kV). `time` The failure or censoring time in hours. `cens` The censoring indicator; `1` means right-censored data. ### Source The data were obtained from Hirose, H. (1993) Estimation of threshold stress in accelerated life-testing. *IEEE Transactions on Reliability*, **42**, 650–657. ### References Davison, A.C. and Hinkley, D.V. (1997) *Bootstrap Methods and Their Application*. Cambridge University Press. r None `imp.weights` Importance Sampling Weights ------------------------------------------ ### Description This function calculates the importance sampling weight required to correct for simulation from a distribution with probabilities `p` when estimates are required assuming that simulation was from an alternative distribution with probabilities `q`. ### Usage ``` imp.weights(boot.out, def = TRUE, q = NULL) ``` ### Arguments | | | | --- | --- | | `boot.out` | A object of class `"boot"` generated by `boot` or `tilt.boot`. Typically the bootstrap simulations would have been done using importance resampling and we wish to do our calculations under the assumption of sampling with equal probabilities. | | `def` | A logical variable indicating whether the defensive mixture distribution weights should be calculated. This makes sense only in the case where the replicates in `boot.out` were simulated under a number of different distributions. If this is the case then the defensive mixture weights use a mixture of the distributions used in the bootstrap. The alternative is to calculate the weights for each replicate using knowledge of the distribution from which the bootstrap resample was generated. | | `q` | A vector of probabilities specifying the resampling distribution from which we require inferences to be made. In general this would correspond to the usual bootstrap resampling distribution which gives equal weight to each of the original observations and this is the default. `q` must have length equal to the number of observations in the `boot.out$data` and all elements of `q` must be positive. | ### Details The importance sampling weight for a bootstrap replicate with frequency vector `f` is given by `prod((q/p)^f)`. This reweights the replicates so that estimates can be found as if the bootstrap resamples were generated according to the probabilities `q` even though, in fact, they came from the distribution `p`. ### Value A vector of importance weights of the same length as `boot.out$t`. These weights can then be used to reweight `boot.out$t` so that estimates can be found as if the simulations were from a distribution with probabilities `q`. ### Note See the example in the help for `imp.moments` for an example of using `imp.weights`. ### References Davison, A. C. and Hinkley, D. V. (1997) *Bootstrap Methods and Their Application*. Cambridge University Press. Hesterberg, T. (1995) Weighted average importance sampling and defensive mixture distributions. *Technometrics*, **37**, 185–194. Johns, M.V. (1988) Importance sampling for bootstrap confidence intervals. *Journal of the American Statistical Association*, **83**, 709–714. ### See Also `<boot>`, `<exp.tilt>`, `[imp.moments](imp.estimates)`, `<smooth.f>`, `<tilt.boot>`
programming_docs
r None `linear.approx` Linear Approximation of Bootstrap Replicates ------------------------------------------------------------- ### Description This function takes a bootstrap object and for each bootstrap replicate it calculates the linear approximation to the statistic of interest for that bootstrap sample. ### Usage ``` linear.approx(boot.out, L = NULL, index = 1, type = NULL, t0 = NULL, t = NULL, ...) ``` ### Arguments | | | | --- | --- | | `boot.out` | An object of class `"boot"` representing a nonparametric bootstrap. It will usually be created by the function `boot`. | | `L` | A vector containing the empirical influence values for the statistic of interest. If it is not supplied then `L` is calculated through a call to `empinf`. | | `index` | The index of the variable of interest within the output of `boot.out$statistic`. | | `type` | This gives the type of empirical influence values to be calculated. It is not used if `L` is supplied. The possible types of empirical influence values are described in the help for `<empinf>`. | | `t0` | The observed value of the statistic of interest. The input value is used only if one of `t` or `L` is also supplied. The default value is `boot.out$t0[index]`. If `t0` is supplied but neither `t` nor `L` are supplied then `t0` is set to `boot.out$t0[index]` and a warning is generated. | | `t` | A vector of bootstrap replicates of the statistic of interest. If `t0` is missing then `t` is not used, otherwise it is used to calculate the empirical influence values (if they are not supplied in `L`). | | `...` | Any extra arguments required by `boot.out$statistic`. These are needed if `L` is not supplied as they are used by `empinf` to calculate empirical influence values. | ### Details The linear approximation to a bootstrap replicate with frequency vector `f` is given by `t0 + sum(L * f)/n` in the one sample with an easy extension to the stratified case. The frequencies are found by calling `boot.array`. ### Value A vector of length `boot.out$R` with the linear approximations to the statistic of interest for each of the bootstrap samples. ### References Davison, A.C. and Hinkley, D.V. (1997) *Bootstrap Methods and Their Application*. Cambridge University Press. ### See Also `<boot>`, `<empinf>`, `<control>` ### Examples ``` # Using the city data let us look at the linear approximation to the # ratio statistic and its logarithm. We compare these with the # corresponding plots for the bigcity data ratio <- function(d, w) sum(d$x * w)/sum(d$u * w) city.boot <- boot(city, ratio, R = 499, stype = "w") bigcity.boot <- boot(bigcity, ratio, R = 499, stype = "w") op <- par(pty = "s", mfrow = c(2, 2)) # The first plot is for the city data ratio statistic. city.lin1 <- linear.approx(city.boot) lim <- range(c(city.boot$t,city.lin1)) plot(city.boot$t, city.lin1, xlim = lim, ylim = lim, main = "Ratio; n=10", xlab = "t*", ylab = "tL*") abline(0, 1) # Now for the log of the ratio statistic for the city data. city.lin2 <- linear.approx(city.boot,t0 = log(city.boot$t0), t = log(city.boot$t)) lim <- range(c(log(city.boot$t),city.lin2)) plot(log(city.boot$t), city.lin2, xlim = lim, ylim = lim, main = "Log(Ratio); n=10", xlab = "t*", ylab = "tL*") abline(0, 1) # The ratio statistic for the bigcity data. bigcity.lin1 <- linear.approx(bigcity.boot) lim <- range(c(bigcity.boot$t,bigcity.lin1)) plot(bigcity.lin1, bigcity.boot$t, xlim = lim, ylim = lim, main = "Ratio; n=49", xlab = "t*", ylab = "tL*") abline(0, 1) # Finally the log of the ratio statistic for the bigcity data. bigcity.lin2 <- linear.approx(bigcity.boot,t0 = log(bigcity.boot$t0), t = log(bigcity.boot$t)) lim <- range(c(log(bigcity.boot$t),bigcity.lin2)) plot(bigcity.lin2, log(bigcity.boot$t), xlim = lim, ylim = lim, main = "Log(Ratio); n=49", xlab = "t*", ylab = "tL*") abline(0, 1) par(op) ``` r None `lines.saddle.distn` Add a Saddlepoint Approximation to a Plot --------------------------------------------------------------- ### Description This function adds a line corresponding to a saddlepoint density or distribution function approximation to the current plot. ### Usage ``` ## S3 method for class 'saddle.distn' lines(x, dens = TRUE, h = function(u) u, J = function(u) 1, npts = 50, lty = 1, ...) ``` ### Arguments | | | | --- | --- | | `x` | An object of class `"saddle.distn"` (see `<saddle.distn.object>` representing a saddlepoint approximation to a distribution. | | `dens` | A logical variable indicating whether the saddlepoint density (`TRUE`; the default) or the saddlepoint distribution function (`FALSE`) should be plotted. | | `h` | Any transformation of the variable that is required. Its first argument must be the value at which the approximation is being performed and the function must be vectorized. | | `J` | When `dens=TRUE` this function specifies the Jacobian for any transformation that may be necessary. The first argument of `J` must the value at which the approximation is being performed and the function must be vectorized. If `h` is supplied `J` must also be supplied and both must have the same argument list. | | `npts` | The number of points to be used for the plot. These points will be evenly spaced over the range of points used in finding the saddlepoint approximation. | | `lty` | The line type to be used. | | `...` | Any additional arguments to `h` and `J`. | ### Details The function uses `smooth.spline` to produce the saddlepoint curve. When `dens=TRUE` the spline is on the log scale and when `dens=FALSE` it is on the probit scale. ### Value `sad.d` is returned invisibly. ### Side Effects A line is added to the current plot. ### References Davison, A.C. and Hinkley, D.V. (1997) *Bootstrap Methods and Their Application*. Cambridge University Press. ### See Also `<saddle.distn>` ### Examples ``` # In this example we show how a plot such as that in Figure 9.9 of # Davison and Hinkley (1997) may be produced. Note the large number of # bootstrap replicates required in this example. expdata <- rexp(12) vfun <- function(d, i) { n <- length(d) (n-1)/n*var(d[i]) } exp.boot <- boot(expdata,vfun, R = 9999) exp.L <- (expdata - mean(expdata))^2 - exp.boot$t0 exp.tL <- linear.approx(exp.boot, L = exp.L) hist(exp.tL, nclass = 50, probability = TRUE) exp.t0 <- c(0, sqrt(var(exp.boot$t))) exp.sp <- saddle.distn(A = exp.L/12,wdist = "m", t0 = exp.t0) # The saddlepoint approximation in this case is to the density of # t-t0 and so t0 must be added for the plot. lines(exp.sp, h = function(u, t0) u+t0, J = function(u, t0) 1, t0 = exp.boot$t0) ``` r None `saddle.distn.object` Saddlepoint Distribution Approximation Objects --------------------------------------------------------------------- ### Description Class of objects that result from calculating saddlepoint distribution approximations by a call to `saddle.distn`. ### Generation This class of objects is returned from calls to the function `<saddle.distn>`. ### Methods The class `"saddle.distn"` has methods for the functions `[lines](../../graphics/html/lines)` and `[print](../../base/html/print)`. ### Structure Objects of class `"saddle.distn"` are implemented as a list with the following components. quantiles A matrix with 2 columns. The first column contains the probabilities `alpha` and the second column contains the estimated quantiles of the distribution at those probabilities derived from the spline. points A matrix of evaluations of the saddlepoint approximation. The first column contains the values of `t` which were used, the second and third contain the density and cdf approximations at those points and the rest of the columns contain the solutions to the saddlepoint equations. When `type` is `"simp"`, there is only one of those. When `type` is `"cond"` there are `2*d-1` where `d` is the number of columns in `A` or the output of `A(t,...{})`. The first `d` of these correspond to the numerator and the remainder correspond to the denominator. distn An object of class `smooth.spline`. This corresponds to the spline fitted to the saddlepoint cdf approximations in points in order to approximate the entire distribution. For the structure of the object see `smooth.spline`. call The original call to `saddle.distn` which generated the object. LR A logical variable indicating whether the Lugananni-Rice approximations were used. ### See Also `<lines.saddle.distn>`, `<saddle.distn>`, `<print.saddle.distn>` r None `cv.glm` Cross-validation for Generalized Linear Models -------------------------------------------------------- ### Description This function calculates the estimated K-fold cross-validation prediction error for generalized linear models. ### Usage ``` cv.glm(data, glmfit, cost, K) ``` ### Arguments | | | | --- | --- | | `data` | A matrix or data frame containing the data. The rows should be cases and the columns correspond to variables, one of which is the response. | | `glmfit` | An object of class `"glm"` containing the results of a generalized linear model fitted to `data`. | | `cost` | A function of two vector arguments specifying the cost function for the cross-validation. The first argument to `cost` should correspond to the observed responses and the second argument should correspond to the predicted or fitted responses from the generalized linear model. `cost` must return a non-negative scalar value. The default is the average squared error function. | | `K` | The number of groups into which the data should be split to estimate the cross-validation prediction error. The value of `K` must be such that all groups are of approximately equal size. If the supplied value of `K` does not satisfy this criterion then it will be set to the closest integer which does and a warning is generated specifying the value of `K` used. The default is to set `K` equal to the number of observations in `data` which gives the usual leave-one-out cross-validation. | ### Details The data is divided randomly into `K` groups. For each group the generalized linear model is fit to `data` omitting that group, then the function `cost` is applied to the observed responses in the group that was omitted from the fit and the prediction made by the fitted models for those observations. When `K` is the number of observations leave-one-out cross-validation is used and all the possible splits of the data are used. When `K` is less than the number of observations the `K` splits to be used are found by randomly partitioning the data into `K` groups of approximately equal size. In this latter case a certain amount of bias is introduced. This can be reduced by using a simple adjustment (see equation 6.48 in Davison and Hinkley, 1997). The second value returned in `delta` is the estimate adjusted by this method. ### Value The returned value is a list with the following components. | | | | --- | --- | | `call` | The original call to `cv.glm`. | | `K` | The value of `K` used for the K-fold cross validation. | | `delta` | A vector of length two. The first component is the raw cross-validation estimate of prediction error. The second component is the adjusted cross-validation estimate. The adjustment is designed to compensate for the bias introduced by not using leave-one-out cross-validation. | | `seed` | The value of `.Random.seed` when `cv.glm` was called. | ### Side Effects The value of `.Random.seed` is updated. ### References Breiman, L., Friedman, J.H., Olshen, R.A. and Stone, C.J. (1984) *Classification and Regression Trees*. Wadsworth. Burman, P. (1989) A comparative study of ordinary cross-validation, *v*-fold cross-validation and repeated learning-testing methods. *Biometrika*, **76**, 503–514 Davison, A.C. and Hinkley, D.V. (1997) *Bootstrap Methods and Their Application*. Cambridge University Press. Efron, B. (1986) How biased is the apparent error rate of a prediction rule? *Journal of the American Statistical Association*, **81**, 461–470. Stone, M. (1974) Cross-validation choice and assessment of statistical predictions (with Discussion). *Journal of the Royal Statistical Society, B*, **36**, 111–147. ### See Also `[glm](../../stats/html/glm)`, `<glm.diag>`, `[predict](../../stats/html/predict)` ### Examples ``` # leave-one-out and 6-fold cross-validation prediction error for # the mammals data set. data(mammals, package="MASS") mammals.glm <- glm(log(brain) ~ log(body), data = mammals) (cv.err <- cv.glm(mammals, mammals.glm)$delta) (cv.err.6 <- cv.glm(mammals, mammals.glm, K = 6)$delta) # As this is a linear model we could calculate the leave-one-out # cross-validation estimate without any extra model-fitting. muhat <- fitted(mammals.glm) mammals.diag <- glm.diag(mammals.glm) (cv.err <- mean((mammals.glm$y - muhat)^2/(1 - mammals.diag$h)^2)) # leave-one-out and 11-fold cross-validation prediction error for # the nodal data set. Since the response is a binary variable an # appropriate cost function is cost <- function(r, pi = 0) mean(abs(r-pi) > 0.5) nodal.glm <- glm(r ~ stage+xray+acid, binomial, data = nodal) (cv.err <- cv.glm(nodal, nodal.glm, cost, K = nrow(nodal))$delta) (cv.11.err <- cv.glm(nodal, nodal.glm, cost, K = 11)$delta) ``` r None `corr` Correlation Coefficient ------------------------------- ### Description Calculates the weighted correlation given a data set and a set of weights. ### Usage ``` corr(d, w = rep(1, nrow(d))/nrow(d)) ``` ### Arguments | | | | --- | --- | | `d` | A matrix with two columns corresponding to the two variables whose correlation we wish to calculate. | | `w` | A vector of weights to be applied to each pair of observations. The default is equal weights for each pair. Normalization takes place within the function so `sum(w)` need not equal 1. | ### Details This function finds the correlation coefficient in weighted form. This is often useful in bootstrap methods since it allows for numerical differentiation to get the empirical influence values. It is also necessary to have the statistic in this form to find ABC intervals. ### Value The correlation coefficient between `d[,1]` and `d[,2]`. ### See Also `[cor](../../stats/html/cor)` r None `abc.ci` Nonparametric ABC Confidence Intervals ------------------------------------------------ ### Description Calculate equi-tailed two-sided nonparametric approximate bootstrap confidence intervals for a parameter, given a set of data and an estimator of the parameter, using numerical differentiation. ### Usage ``` abc.ci(data, statistic, index=1, strata=rep(1, n), conf=0.95, eps=0.001/n, ...) ``` ### Arguments | | | | --- | --- | | `data` | A data set expressed as a vector, matrix or data frame. | | `statistic` | A function which returns the statistic of interest. The function must take at least 2 arguments; the first argument should be the data and the second a vector of weights. The weights passed to `statistic` will be normalized to sum to 1 within each stratum. Any other arguments should be passed to `abc.ci` as part of the `...{}` argument. | | `index` | If `statistic` returns a vector of length greater than 1, then this indicates the position of the variable of interest within that vector. | | `strata` | A factor or numerical vector indicating to which sample each observation belongs in multiple sample problems. The default is the one-sample case. | | `conf` | A scalar or vector containing the confidence level(s) of the required interval(s). | | `eps` | The value of epsilon to be used for the numerical differentiation. | | `...` | Any other arguments for `statistic`. These will be passed unchanged to `statistic` each time it is called within `abc.ci`. | ### Details This function is based on the function `abcnon` written by R. Tibshirani. A listing of the original function is available in DiCiccio and Efron (1996). The function uses numerical differentiation for the first and second derivatives of the statistic and then uses these values to approximate the bootstrap BCa intervals. The total number of evaluations of the statistic is `2*n+2+2*length(conf)` where `n` is the number of data points (plus calculation of the original value of the statistic). The function works for the multiple sample case without the need to rewrite the statistic in an artificial form since the stratified normalization is done internally by the function. ### Value A `length(conf)` by 3 matrix where each row contains the confidence level followed by the lower and upper end-points of the ABC interval at that level. ### References Davison, A.C. and Hinkley, D.V. (1997) *Bootstrap Methods and Their Application*, Chapter 5. Cambridge University Press. DiCiccio, T. J. and Efron B. (1992) More accurate confidence intervals in exponential families. *Biometrika*, **79**, 231–245. DiCiccio, T. J. and Efron B. (1996) Bootstrap confidence intervals (with Discussion). *Statistical Science*, **11**, 189–228. ### See Also `<boot.ci>` ### Examples ``` # 90% and 95% confidence intervals for the correlation # coefficient between the columns of the bigcity data abc.ci(bigcity, corr, conf=c(0.90,0.95)) # A 95% confidence interval for the difference between the means of # the last two samples in gravity mean.diff <- function(y, w) { gp1 <- 1:table(as.numeric(y$series))[1] sum(y[gp1, 1] * w[gp1]) - sum(y[-gp1, 1] * w[-gp1]) } grav1 <- gravity[as.numeric(gravity[, 2]) >= 7, ] ## IGNORE_RDIFF_BEGIN abc.ci(grav1, mean.diff, strata = grav1$series) ## IGNORE_RDIFF_END ``` r None `k3.linear` Linear Skewness Estimate ------------------------------------- ### Description Estimates the skewness of a statistic from its empirical influence values. ### Usage ``` k3.linear(L, strata = NULL) ``` ### Arguments | | | | --- | --- | | `L` | Vector of the empirical influence values of a statistic. These will usually be calculated by a call to `empinf`. | | `strata` | A numeric vector or factor specifying which observations (and hence which components of `L`) come from which strata. | ### Value The skewness estimate calculated from `L`. ### References Davison, A. C. and Hinkley, D. V. (1997) *Bootstrap Methods and Their Application*. Cambridge University Press. ### See Also `<empinf>`, `<linear.approx>`, `<var.linear>` ### Examples ``` # To estimate the skewness of the ratio of means for the city data. ratio <- function(d, w) sum(d$x * w)/sum(d$u * w) k3.linear(empinf(data = city, statistic = ratio)) ``` r None `empinf` Empirical Influence Values ------------------------------------ ### Description This function calculates the empirical influence values for a statistic applied to a data set. It allows four types of calculation, namely the infinitesimal jackknife (using numerical differentiation), the usual jackknife estimates, the ‘positive’ jackknife estimates and a method which estimates the empirical influence values using regression of bootstrap replicates of the statistic. All methods can be used with one or more samples. ### Usage ``` empinf(boot.out = NULL, data = NULL, statistic = NULL, type = NULL, stype = NULL ,index = 1, t = NULL, strata = rep(1, n), eps = 0.001, ...) ``` ### Arguments | | | | --- | --- | | `boot.out` | A bootstrap object created by the function `boot`. If `type` is `"reg"` then this argument is required. For any of the other types it is an optional argument. If it is included when optional then the values of `data`, `statistic`, `stype`, and `strata` are taken from the components of `boot.out` and any values passed to `empinf` directly are ignored. | | `data` | A vector, matrix or data frame containing the data for which empirical influence values are required. It is a required argument if `boot.out` is not supplied. If `boot.out` is supplied then `data` is set to `boot.out$data` and any value supplied is ignored. | | `statistic` | The statistic for which empirical influence values are required. It must be a function of at least two arguments, the data set and a vector of weights, frequencies or indices. The nature of the second argument is given by the value of `stype`. Any other arguments that it takes must be supplied to `empinf` and will be passed to `statistic` unchanged. This is a required argument if `boot.out` is not supplied, otherwise its value is taken from `boot.out` and any value supplied here will be ignored. | | `type` | The calculation type to be used for the empirical influence values. Possible values of `type` are `"inf"` (infinitesimal jackknife), `"jack"` (usual jackknife), `"pos"` (positive jackknife), and `"reg"` (regression estimation). The default value depends on the other arguments. If `t` is supplied then the default value of `type` is `"reg"` and `boot.out` should be present so that its frequency array can be found. It `t` is not supplied then if `stype` is `"w"`, the default value of `type` is `"inf"`; otherwise, if `boot.out` is present the default is `"reg"`. If none of these conditions apply then the default is `"jack"`. Note that it is an error for `type` to be `"reg"` if `boot.out` is missing or to be `"inf"` if `stype` is not `"w"`. | | `stype` | A character variable giving the nature of the second argument to `statistic`. It can take on three values: `"w"` (weights), `"f"` (frequencies), or `"i"` (indices). If `boot.out` is supplied the value of `stype` is set to `boot.out$stype` and any value supplied here is ignored. Otherwise it is an optional argument which defaults to `"w"`. If `type` is `"inf"` then `stype` MUST be `"w"`. | | `index` | An integer giving the position of the variable of interest in the output of `statistic`. | | `t` | A vector of length `boot.out$R` which gives the bootstrap replicates of the statistic of interest. `t` is used only when `type` is `reg` and it defaults to `boot.out$t[,index]`. | | `strata` | An integer vector or a factor specifying the strata for multi-sample problems. If `boot.out` is supplied the value of `strata` is set to `boot.out$strata`. Otherwise it is an optional argument which has default corresponding to the single sample situation. | | `eps` | This argument is used only if `type` is `"inf"`. In that case the value of epsilon to be used for numerical differentiation will be `eps` divided by the number of observations in `data`. | | `...` | Any other arguments that `statistic` takes. They will be passed unchanged to `statistic` every time that it is called. | ### Details If `type` is `"inf"` then numerical differentiation is used to approximate the empirical influence values. This makes sense only for statistics which are written in weighted form (i.e. `stype` is `"w"`). If `type` is `"jack"` then the usual leave-one-out jackknife estimates of the empirical influence are returned. If `type` is `"pos"` then the positive (include-one-twice) jackknife values are used. If `type` is `"reg"` then a bootstrap object must be supplied. The regression method then works by regressing the bootstrap replicates of `statistic` on the frequency array from which they were derived. The bootstrap frequency array is obtained through a call to `boot.array`. Further details of the methods are given in Section 2.7 of Davison and Hinkley (1997). Empirical influence values are often used frequently in nonparametric bootstrap applications. For this reason many other functions call `empinf` when they are required. Some examples of their use are for nonparametric delta estimates of variance, BCa intervals and finding linear approximations to statistics for use as control variates. They are also used for antithetic bootstrap resampling. ### Value A vector of the empirical influence values of `statistic` applied to `data`. The values will be in the same order as the observations in data. ### Warning All arguments to `empinf` must be passed using the `name = value` convention. If this is not followed then unpredictable errors can occur. ### References Davison, A.C. and Hinkley, D.V. (1997) *Bootstrap Methods and Their Application*. Cambridge University Press. Efron, B. (1982) *The Jackknife, the Bootstrap and Other Resampling Plans*. CBMS-NSF Regional Conference Series in Applied Mathematics, **38**, SIAM. Fernholtz, L.T. (1983) *von Mises Calculus for Statistical Functionals*. Lecture Notes in Statistics, **19**, Springer-Verlag. ### See Also `<boot>`, `<boot.array>`, `<boot.ci>`, `<control>`, `<jack.after.boot>`, `<linear.approx>`, `<var.linear>` ### Examples ``` # The empirical influence values for the ratio of means in # the city data. ratio <- function(d, w) sum(d$x *w)/sum(d$u*w) empinf(data = city, statistic = ratio) city.boot <- boot(city, ratio, 499, stype="w") empinf(boot.out = city.boot, type = "reg") # A statistic that may be of interest in the difference of means # problem is the t-statistic for testing equality of means. In # the bootstrap we get replicates of the difference of means and # the variance of that statistic and then want to use this output # to get the empirical influence values of the t-statistic. grav1 <- gravity[as.numeric(gravity[,2]) >= 7,] grav.fun <- function(dat, w) { strata <- tapply(dat[, 2], as.numeric(dat[, 2])) d <- dat[, 1] ns <- tabulate(strata) w <- w/tapply(w, strata, sum)[strata] mns <- as.vector(tapply(d * w, strata, sum)) # drop names mn2 <- tapply(d * d * w, strata, sum) s2hat <- sum((mn2 - mns^2)/ns) c(mns[2] - mns[1], s2hat) } grav.boot <- boot(grav1, grav.fun, R = 499, stype = "w", strata = grav1[, 2]) # Since the statistic of interest is a function of the bootstrap # statistics, we must calculate the bootstrap replicates and pass # them to empinf using the t argument. grav.z <- (grav.boot$t[,1]-grav.boot$t0[1])/sqrt(grav.boot$t[,2]) empinf(boot.out = grav.boot, t = grav.z) ```
programming_docs
r None `aircondit` Failures of Air-conditioning Equipment --------------------------------------------------- ### Description Proschan (1963) reported on the times between failures of the air-conditioning equipment in 10 Boeing 720 aircraft. The `aircondit` data frame contains the intervals for the ninth aircraft while `aircondit7` contains those for the seventh aircraft. Both data frames have just one column. Note that the data have been sorted into increasing order. ### Usage ``` aircondit ``` ### Format The data frames contain the following column: `hours` The time interval in hours between successive failures of the air-conditioning equipment ### Source The data were taken from Cox, D.R. and Snell, E.J. (1981) *Applied Statistics: Principles and Examples*. Chapman and Hall. ### References Davison, A.C. and Hinkley, D.V. (1997) *Bootstrap Methods and Their Application*. Cambridge University Press. Proschan, F. (1963) Theoretical explanation of observed decreasing failure rate. *Technometrics*, **5**, 375-383. r None `brambles` Spatial Location of Bramble Canes --------------------------------------------- ### Description The `brambles` data frame has 823 rows and 3 columns. The location of living bramble canes in a 9m square plot was recorded. We take 9m to be the unit of distance so that the plot can be thought of as a unit square. The bramble canes were also classified by their age. ### Usage ``` brambles ``` ### Format This data frame contains the following columns: `x` The x coordinate of the position of the cane in the plot. `y` The y coordinate of the position of the cane in the plot. `age` The age classification of the canes; `0` indicates a newly emerged cane, `1` indicates a one year old cane and `2` indicates a two year old cane. ### Source The data were obtained from Diggle, P.J. (1983) *Statistical Analysis of Spatial Point Patterns*. Academic Press. ### References Davison, A.C. and Hinkley, D.V. (1997) *Bootstrap Methods and Their Application*. Cambridge University Press. r None `amis` Car Speeding and Warning Signs -------------------------------------- ### Description The `amis` data frame has 8437 rows and 4 columns. In a study into the effect that warning signs have on speeding patterns, Cambridgeshire County Council considered 14 pairs of locations. The locations were paired to account for factors such as traffic volume and type of road. One site in each pair had a sign erected warning of the dangers of speeding and asking drivers to slow down. No action was taken at the second site. Three sets of measurements were taken at each site. Each set of measurements was nominally of the speeds of 100 cars but not all sites have exactly 100 measurements. These speed measurements were taken before the erection of the sign, shortly after the erection of the sign, and again after the sign had been in place for some time. ### Usage ``` amis ``` ### Format This data frame contains the following columns: `speed` Speeds of cars (in miles per hour). `period` A numeric column indicating the time that the reading was taken. A value of 1 indicates a reading taken before the sign was erected, a 2 indicates a reading taken shortly after erection of the sign and a 3 indicates a reading taken after the sign had been in place for some time. `warning` A numeric column indicating whether the location of the reading was chosen to have a warning sign erected. A value of 1 indicates presence of a sign and a value of 2 indicates that no sign was erected. `pair` A numeric column giving the pair number at which the reading was taken. Pairs were numbered from 1 to 14. ### Source The data were kindly made available by Mr. Graham Amis, Cambridgeshire County Council, U.K. ### References Davison, A.C. and Hinkley, D.V. (1997) *Bootstrap Methods and Their Application*. Cambridge University Press. r None `sunspot` Annual Mean Sunspot Numbers -------------------------------------- ### Description `sunspot` is a time series and contains 289 observations. The Zurich sunspot numbers have been analyzed in almost all books on time series analysis as well as numerous papers. The data set, usually attributed to Rudolf Wolf, consists of means of daily relative numbers of sunspot sightings. The relative number for a day is given by k(f+10g) where g is the number of sunspot groups observed, f is the total number of spots within the groups and k is a scaling factor relating the observer and telescope to a baseline. The relative numbers are then averaged to give an annual figure. See Inzenman (1983) for a discussion of the relative numbers. The figures are for the years 1700-1988. ### Source The data were obtained from Tong, H. (1990) *Nonlinear Time Series: A Dynamical System Approach*. Oxford University Press ### References Davison, A.C. and Hinkley, D.V. (1997) *Bootstrap Methods and Their Application*. Cambridge University Press. Inzenman, A.J. (1983) J.R. Wolf and H.A. Wolfer: An historical note on the Zurich sunspot relative numbers. *Journal of the Royal Statistical Society, A*, **146**, 311-318. Waldmeir, M. (1961) *The Sunspot Activity in the Years 1610-1960*. Schulthess and Co. r None `bigcity` Population of U.S. Cities ------------------------------------ ### Description The `bigcity` data frame has 49 rows and 2 columns. The `city` data frame has 10 rows and 2 columns. The measurements are the population (in 1000's) of 49 U.S. cities in 1920 and 1930. The 49 cities are a random sample taken from the 196 largest cities in 1920. The `city` data frame consists of the first 10 observations in `bigcity`. ### Usage ``` bigcity ``` ### Format This data frame contains the following columns: `u` The 1920 population. `x` The 1930 population. ### Source The data were obtained from Cochran, W.G. (1977) *Sampling Techniques*. Third edition. John Wiley ### References Davison, A.C. and Hinkley, D.V. (1997) *Bootstrap Methods and Their Application*. Cambridge University Press. r None `claridge` Genetic Links to Left-handedness -------------------------------------------- ### Description The `claridge` data frame has 37 rows and 2 columns. The data are from an experiment which was designed to look for a relationship between a certain genetic characteristic and handedness. The 37 subjects were women who had a son with mental retardation due to inheriting a defective X-chromosome. For each such mother a genetic measurement of their DNA was made. Larger values of this measurement are known to be linked to the defective gene and it was hypothesized that larger values might also be linked to a progressive shift away from right-handednesss. Each woman also filled in a questionnaire regarding which hand they used for various tasks. From these questionnaires a measure of hand preference was found for each mother. The scale of this measure goes from 1, indicating someone who always favours their right hand, to 8, indicating someone who always favours their left hand. Between these two extremes are people who favour one hand for some tasks and the other for other tasks. ### Usage ``` claridge ``` ### Format This data frame contains the following columns: `dnan` The genetic measurement on each woman's DNA. `hand` The measure of left-handedness on an integer scale from 1 to 8. ### Source The data were kindly made available by Dr. Gordon S. Claridge from the Department of Experimental Psychology, University of Oxford. ### References Davison, A.C. and Hinkley, D.V. (1997) *Bootstrap Methods and Their Application*. Cambridge University Press. r None `frets` Head Dimensions in Brothers ------------------------------------ ### Description The `frets` data frame has 25 rows and 4 columns. The data consist of measurements of the length and breadth of the heads of pairs of adult brothers in 25 randomly sampled families. All measurements are expressed in millimetres. ### Usage ``` frets ``` ### Format This data frame contains the following columns: `l1` The head length of the eldest son. `b1` The head breadth of the eldest son. `l2` The head length of the second son. `b2` The head breadth of the second son. ### Source The data were obtained from Frets, G.P. (1921) Heredity of head form in man. *Genetica*, **3**, 193. ### References Davison, A.C. and Hinkley, D.V. (1997) *Bootstrap Methods and Their Application*. Cambridge University Press. Whittaker, J. (1990) *Graphical Models in Applied Multivariate Statistics*. John Wiley. r None `beaver` Beaver Body Temperature Data -------------------------------------- ### Description The `beaver` data frame has 100 rows and 4 columns. It is a multivariate time series of class `"ts"` and also inherits from class `"data.frame"`. This data set is part of a long study into body temperature regulation in beavers. Four adult female beavers were live-trapped and had a temperature-sensitive radio transmitter surgically implanted. Readings were taken every 10 minutes. The location of the beaver was also recorded and her activity level was dichotomized by whether she was in the retreat or outside of it since high-intensity activities only occur outside of the retreat. The data in this data frame are those readings for one of the beavers on a day in autumn. ### Usage ``` beaver ``` ### Format This data frame contains the following columns: `day` The day number. The data includes only data from day 307 and early 308. `time` The time of day formatted as hour-minute. `temp` The body temperature in degrees Celsius. `activ` The dichotomized activity indicator. `1` indicates that the beaver is outside of the retreat and therefore engaged in high-intensity activity. ### Source The data were obtained from Reynolds, P.S. (1994) Time-series analyses of beaver body temperatures. In *Case Studies in Biometry*. N. Lange, L. Ryan, L. Billard, D. Brillinger, L. Conquest and J. Greenhouse (editors), 211–228. John Wiley. ### References Davison, A.C. and Hinkley, D.V. (1997) *Bootstrap Methods and Their Application*. Cambridge University Press. r None `freq.array` Bootstrap Frequency Arrays ---------------------------------------- ### Description Take a matrix of indices for nonparametric bootstrap resamples and return the frequencies of the original observations in each resample. ### Usage ``` freq.array(i.array) ``` ### Arguments | | | | --- | --- | | `i.array` | This will be an matrix of integers between 1 and n, where n is the number of observations in a data set. The matrix will have n columns and R rows where R is the number of bootstrap resamples. Such matrices are found by `boot` when doing nonparametric bootstraps. They can also be found after a bootstrap has been run through the function `boot.array`. | ### Value A matrix of the same dimensions as the input matrix. Each row of the matrix corresponds to a single bootstrap resample. Each column of the matrix corresponds to one of the original observations and specifies its frequency in each bootstrap resample. Thus the first column tells us how often the first observation appeared in each bootstrap resample. Such frequency arrays are often useful for diagnostic purposes such as the jackknife-after-bootstrap plot. They are also necessary for the regression estimates of empirical influence values and for finding importance sampling weights. ### See Also `<boot.array>` r None `inv.logit` Inverse Logit Function ----------------------------------- ### Description Given a numeric object return the inverse logit of the values. ### Usage ``` inv.logit(x) ``` ### Arguments | | | | --- | --- | | `x` | A numeric object. Missing values (`NA`s) are allowed. | ### Details The inverse logit is defined by `exp(x)/(1+exp(x))`. Values in `x` of `-Inf` or `Inf` return logits of 0 or 1 respectively. Any `NA`s in the input will also be `NA`s in the output. ### Value An object of the same type as `x` containing the inverse logits of the input values. ### See Also `<logit>`, `[plogis](../../stats/html/logistic)` for which this is a wrapper. r None `wool` Australian Relative Wool Prices --------------------------------------- ### Description `wool` is a time series of class `"ts"` and contains 309 observations. Each week that the market is open the Australian Wool Corporation set a floor price which determines their policy on intervention and is therefore a reflection of the overall price of wool for the week in question. Actual prices paid can vary considerably about the floor price. The series here is the log of the ratio between the price for fine grade wool and the floor price, each market week between July 1976 and Jun 1984. ### Source The data were obtained from Diggle, P.J. (1990) *Time Series: A Biostatistical Introduction*. Oxford University Press. ### References Davison, A.C. and Hinkley, D.V. (1997) *Bootstrap Methods and Their Application*. Cambridge University Press. r None `tuna` Tuna Sighting Data -------------------------- ### Description The `tuna` data frame has 64 rows and 1 columns. The data come from an aerial line transect survey of Southern Bluefin Tuna in the Great Australian Bight. An aircraft with two spotters on board flies randomly allocated line transects. Each school of tuna sighted is counted and its perpendicular distance from the transect measured. The survey was conducted in summer when tuna tend to stay on the surface. ### Usage ``` tuna ``` ### Format This data frame contains the following column: `y` The perpendicular distance, in miles, from the transect for 64 independent sightings of tuna schools. ### Source The data were obtained from Chen, S.X. (1996) Empirical likelihood confidence intervals for nonparametric density estimation. *Biometrika*, **83**, 329–341. ### References Davison, A.C. and Hinkley, D.V. (1997) *Bootstrap Methods and Their Application*. Cambridge University Press. r None `fir` Counts of Balsam-fir Seedlings ------------------------------------- ### Description The `fir` data frame has 50 rows and 3 columns. The number of balsam-fir seedlings in each quadrant of a grid of 50 five foot square quadrants were counted. The grid consisted of 5 rows of 10 quadrants in each row. ### Usage ``` fir ``` ### Format This data frame contains the following columns: `count` The number of seedlings in the quadrant. `row` The row number of the quadrant. `col` The quadrant number within the row. ### Source Davison, A.C. and Hinkley, D.V. (1997) *Bootstrap Methods and Their Application*. Cambridge University Press. r None `survival` Survival of Rats after Radiation Doses -------------------------------------------------- ### Description The `survival` data frame has 14 rows and 2 columns. The data measured the survival percentages of batches of rats who were given varying doses of radiation. At each of 6 doses there were two or three replications of the experiment. ### Usage ``` survival ``` ### Format This data frame contains the following columns: `dose` The dose of radiation administered (rads). `surv` The survival rate of the batches expressed as a percentage. ### Source The data were obtained from Efron, B. (1988) Computer-intensive methods in statistical regression. *SIAM Review*, **30**, 421–449. ### References Davison, A.C. and Hinkley, D.V. (1997) *Bootstrap Methods and Their Application*. Cambridge University Press. r None `tsboot` Bootstrapping of Time Series -------------------------------------- ### Description Generate `R` bootstrap replicates of a statistic applied to a time series. The replicate time series can be generated using fixed or random block lengths or can be model based replicates. ### Usage ``` tsboot(tseries, statistic, R, l = NULL, sim = "model", endcorr = TRUE, n.sim = NROW(tseries), orig.t = TRUE, ran.gen, ran.args = NULL, norm = TRUE, ..., parallel = c("no", "multicore", "snow"), ncpus = getOption("boot.ncpus", 1L), cl = NULL) ``` ### Arguments | | | | --- | --- | | `tseries` | A univariate or multivariate time series. | | `statistic` | A function which when applied to `tseries` returns a vector containing the statistic(s) of interest. Each time `statistic` is called it is passed a time series of length `n.sim` which is of the same class as the original `tseries`. Any other arguments which `statistic` takes must remain constant for each bootstrap replicate and should be supplied through the ... argument to `tsboot`. | | `R` | A positive integer giving the number of bootstrap replicates required. | | `sim` | The type of simulation required to generate the replicate time series. The possible input values are `"model"` (model based resampling), `"fixed"` (block resampling with fixed block lengths of `l`), `"geom"` (block resampling with block lengths having a geometric distribution with mean `l`) or `"scramble"` (phase scrambling). | | `l` | If `sim` is `"fixed"` then `l` is the fixed block length used in generating the replicate time series. If `sim` is `"geom"` then `l` is the mean of the geometric distribution used to generate the block lengths. `l` should be a positive integer less than the length of `tseries`. This argument is not required when `sim` is `"model"` but it is required for all other simulation types. | | `endcorr` | A logical variable indicating whether end corrections are to be applied when `sim` is `"fixed"`. When `sim` is `"geom"`, `endcorr` is automatically set to `TRUE`; `endcorr` is not used when `sim` is `"model"` or `"scramble"`. | | `n.sim` | The length of the simulated time series. Typically this will be equal to the length of the original time series but there are situations when it will be larger. One obvious situation is if prediction is required. Another situation in which `n.sim` is larger than the original length is if `tseries` is a residual time series from fitting some model to the original time series. In this case, `n.sim` would usually be the length of the original time series. | | `orig.t` | A logical variable which indicates whether `statistic` should be applied to `tseries` itself as well as the bootstrap replicate series. If `statistic` is expecting a longer time series than `tseries` or if applying `statistic` to `tseries` will not yield any useful information then `orig.t` should be set to `FALSE`. | | `ran.gen` | This is a function of three arguments. The first argument is a time series. If `sim` is `"model"` then it will always be `tseries` that is passed. For other simulation types it is the result of selecting `n.sim` observations from `tseries` by some scheme and converting the result back into a time series of the same form as `tseries` (although of length `n.sim`). The second argument to `ran.gen` is always the value `n.sim`, and the third argument is `ran.args`, which is used to supply any other objects needed by `ran.gen`. If `sim` is `"model"` then the generation of the replicate time series will be done in `ran.gen` (for example through use of `[arima.sim](../../stats/html/arima.sim)`). For the other simulation types `ran.gen` is used for ‘post-blackening’. The default is that the function simply returns the time series passed to it. | | `ran.args` | This will be supplied to `ran.gen` each time it is called. If `ran.gen` needs any extra arguments then they should be supplied as components of `ran.args`. Multiple arguments may be passed by making `ran.args` a list. If `ran.args` is `NULL` then it should not be used within `ran.gen` but note that `ran.gen` must still have its third argument. | | `norm` | A logical argument indicating whether normal margins should be used for phase scrambling. If `norm` is `FALSE` then margins corresponding to the exact empirical margins are used. | | `...` | Extra named arguments to `statistic` may be supplied here. Beware of partial matching to the arguments of `tsboot` listed above. | | `parallel, ncpus, cl` | See the help for `<boot>`. | ### Details If `sim` is `"fixed"` then each replicate time series is found by taking blocks of length `l`, from the original time series and putting them end-to-end until a new series of length `n.sim` is created. When `sim` is `"geom"` a similar approach is taken except that now the block lengths are generated from a geometric distribution with mean `l`. Post-blackening can be carried out on these replicate time series by including the function `ran.gen` in the call to `tsboot` and having `tseries` as a time series of residuals. Model based resampling is very similar to the parametric bootstrap and all simulation must be in one of the user specified functions. This avoids the complicated problem of choosing the block length but relies on an accurate model choice being made. Phase scrambling is described in Section 8.2.4 of Davison and Hinkley (1997). The types of statistic for which this method produces reasonable results is very limited and the other methods seem to do better in most situations. Other types of resampling in the frequency domain can be accomplished using the function `boot` with the argument `sim = "parametric"`. ### Value An object of class `"boot"` with the following components. | | | | --- | --- | | `t0` | If `orig.t` is `TRUE` then `t0` is the result of `statistic(tseries,...{})` otherwise it is `NULL`. | | `t` | The results of applying `statistic` to the replicate time series. | | `R` | The value of `R` as supplied to `tsboot`. | | `tseries` | The original time series. | | `statistic` | The function `statistic` as supplied. | | `sim` | The simulation type used in generating the replicates. | | `endcorr` | The value of `endcorr` used. The value is meaningful only when `sim` is `"fixed"`; it is ignored for model based simulation or phase scrambling and is always set to `TRUE` if `sim` is `"geom"`. | | `n.sim` | The value of `n.sim` used. | | `l` | The value of `l` used for block based resampling. This will be `NULL` if block based resampling was not used. | | `ran.gen` | The `ran.gen` function used for generating the series or for ‘post-blackening’. | | `ran.args` | The extra arguments passed to `ran.gen`. | | `call` | The original call to `tsboot`. | ### References Davison, A.C. and Hinkley, D.V. (1997) *Bootstrap Methods and Their Application*. Cambridge University Press. Kunsch, H.R. (1989) The jackknife and the bootstrap for general stationary observations. *Annals of Statistics*, **17**, 1217–1241. Politis, D.N. and Romano, J.P. (1994) The stationary bootstrap. *Journal of the American Statistical Association*, **89**, 1303–1313. ### See Also `<boot>`, `[arima.sim](../../stats/html/arima.sim)` ### Examples ``` lynx.fun <- function(tsb) { ar.fit <- ar(tsb, order.max = 25) c(ar.fit$order, mean(tsb), tsb) } # the stationary bootstrap with mean block length 20 lynx.1 <- tsboot(log(lynx), lynx.fun, R = 99, l = 20, sim = "geom") # the fixed block bootstrap with length 20 lynx.2 <- tsboot(log(lynx), lynx.fun, R = 99, l = 20, sim = "fixed") # Now for model based resampling we need the original model # Note that for all of the bootstraps which use the residuals as their # data, we set orig.t to FALSE since the function applied to the residual # time series will be meaningless. lynx.ar <- ar(log(lynx)) lynx.model <- list(order = c(lynx.ar$order, 0, 0), ar = lynx.ar$ar) lynx.res <- lynx.ar$resid[!is.na(lynx.ar$resid)] lynx.res <- lynx.res - mean(lynx.res) lynx.sim <- function(res,n.sim, ran.args) { # random generation of replicate series using arima.sim rg1 <- function(n, res) sample(res, n, replace = TRUE) ts.orig <- ran.args$ts ts.mod <- ran.args$model mean(ts.orig)+ts(arima.sim(model = ts.mod, n = n.sim, rand.gen = rg1, res = as.vector(res))) } lynx.3 <- tsboot(lynx.res, lynx.fun, R = 99, sim = "model", n.sim = 114, orig.t = FALSE, ran.gen = lynx.sim, ran.args = list(ts = log(lynx), model = lynx.model)) # For "post-blackening" we need to define another function lynx.black <- function(res, n.sim, ran.args) { ts.orig <- ran.args$ts ts.mod <- ran.args$model mean(ts.orig) + ts(arima.sim(model = ts.mod,n = n.sim,innov = res)) } # Now we can run apply the two types of block resampling again but this # time applying post-blackening. lynx.1b <- tsboot(lynx.res, lynx.fun, R = 99, l = 20, sim = "fixed", n.sim = 114, orig.t = FALSE, ran.gen = lynx.black, ran.args = list(ts = log(lynx), model = lynx.model)) lynx.2b <- tsboot(lynx.res, lynx.fun, R = 99, l = 20, sim = "geom", n.sim = 114, orig.t = FALSE, ran.gen = lynx.black, ran.args = list(ts = log(lynx), model = lynx.model)) # To compare the observed order of the bootstrap replicates we # proceed as follows. table(lynx.1$t[, 1]) table(lynx.1b$t[, 1]) table(lynx.2$t[, 1]) table(lynx.2b$t[, 1]) table(lynx.3$t[, 1]) # Notice that the post-blackened and model-based bootstraps preserve # the true order of the model (11) in many more cases than the others. ```
programming_docs
r None `cloth` Number of Flaws in Cloth --------------------------------- ### Description The `cloth` data frame has 32 rows and 2 columns. ### Usage ``` cloth ``` ### Format This data frame contains the following columns: `x` The length of the roll of cloth. `y` The number of flaws found in the roll. ### Source The data were obtained from Bissell, A.F. (1972) A negative binomial model with varying element size. *Biometrika*, **59**, 435–441. ### References Davison, A.C. and Hinkley, D.V. (1997) *Bootstrap Methods and Their Application*. Cambridge University Press. r None `boot` Bootstrap Resampling ---------------------------- ### Description Generate `R` bootstrap replicates of a statistic applied to data. Both parametric and nonparametric resampling are possible. For the nonparametric bootstrap, possible resampling methods are the ordinary bootstrap, the balanced bootstrap, antithetic resampling, and permutation. For nonparametric multi-sample problems stratified resampling is used: this is specified by including a vector of strata in the call to boot. Importance resampling weights may be specified. ### Usage ``` boot(data, statistic, R, sim = "ordinary", stype = c("i", "f", "w"), strata = rep(1,n), L = NULL, m = 0, weights = NULL, ran.gen = function(d, p) d, mle = NULL, simple = FALSE, ..., parallel = c("no", "multicore", "snow"), ncpus = getOption("boot.ncpus", 1L), cl = NULL) ``` ### Arguments | | | | --- | --- | | `data` | The data as a vector, matrix or data frame. If it is a matrix or data frame then each row is considered as one multivariate observation. | | `statistic` | A function which when applied to data returns a vector containing the statistic(s) of interest. When `sim = "parametric"`, the first argument to `statistic` must be the data. For each replicate a simulated dataset returned by `ran.gen` will be passed. In all other cases `statistic` must take at least two arguments. The first argument passed will always be the original data. The second will be a vector of indices, frequencies or weights which define the bootstrap sample. Further, if predictions are required, then a third argument is required which would be a vector of the random indices used to generate the bootstrap predictions. Any further arguments can be passed to `statistic` through the `...` argument. | | `R` | The number of bootstrap replicates. Usually this will be a single positive integer. For importance resampling, some resamples may use one set of weights and others use a different set of weights. In this case `R` would be a vector of integers where each component gives the number of resamples from each of the rows of weights. | | `sim` | A character string indicating the type of simulation required. Possible values are `"ordinary"` (the default), `"parametric"`, `"balanced"`, `"permutation"`, or `"antithetic"`. Importance resampling is specified by including importance weights; the type of importance resampling must still be specified but may only be `"ordinary"` or `"balanced"` in this case. | | `stype` | A character string indicating what the second argument of `statistic` represents. Possible values of stype are `"i"` (indices - the default), `"f"` (frequencies), or `"w"` (weights). Not used for `sim = "parametric"`. | | `strata` | An integer vector or factor specifying the strata for multi-sample problems. This may be specified for any simulation, but is ignored when `sim = "parametric"`. When `strata` is supplied for a nonparametric bootstrap, the simulations are done within the specified strata. | | `L` | Vector of influence values evaluated at the observations. This is used only when `sim` is `"antithetic"`. If not supplied, they are calculated through a call to `empinf`. This will use the infinitesimal jackknife provided that `stype` is `"w"`, otherwise the usual jackknife is used. | | `m` | The number of predictions which are to be made at each bootstrap replicate. This is most useful for (generalized) linear models. This can only be used when `sim` is `"ordinary"`. `m` will usually be a single integer but, if there are strata, it may be a vector with length equal to the number of strata, specifying how many of the errors for prediction should come from each strata. The actual predictions should be returned as the final part of the output of `statistic`, which should also take an argument giving the vector of indices of the errors to be used for the predictions. | | `weights` | Vector or matrix of importance weights. If a vector then it should have as many elements as there are observations in `data`. When simulation from more than one set of weights is required, `weights` should be a matrix where each row of the matrix is one set of importance weights. If `weights` is a matrix then `R` must be a vector of length `nrow(weights)`. This parameter is ignored if `sim` is not `"ordinary"` or `"balanced"`. | | `ran.gen` | This function is used only when `sim = "parametric"` when it describes how random values are to be generated. It should be a function of two arguments. The first argument should be the observed data and the second argument consists of any other information needed (e.g. parameter estimates). The second argument may be a list, allowing any number of items to be passed to `ran.gen`. The returned value should be a simulated data set of the same form as the observed data which will be passed to `statistic` to get a bootstrap replicate. It is important that the returned value be of the same shape and type as the original dataset. If `ran.gen` is not specified, the default is a function which returns the original `data` in which case all simulation should be included as part of `statistic`. Use of `sim = "parametric"` with a suitable `ran.gen` allows the user to implement any types of nonparametric resampling which are not supported directly. | | `mle` | The second argument to be passed to `ran.gen`. Typically these will be maximum likelihood estimates of the parameters. For efficiency `mle` is often a list containing all of the objects needed by `ran.gen` which can be calculated using the original data set only. | | `simple` | logical, only allowed to be `TRUE` for `sim = "ordinary", stype = "i", n = 0` (otherwise ignored with a warning). By default a `n` by `R` index array is created: this can be large and if `simple = TRUE` this is avoided by sampling separately for each replication, which is slower but uses less memory. | | `...` | Other named arguments for `statistic` which are passed unchanged each time it is called. Any such arguments to `statistic` should follow the arguments which `statistic` is required to have for the simulation. Beware of partial matching to arguments of `boot` listed above, and that arguments named `X` and `FUN` cause conflicts in some versions of boot (but not this one). | | `parallel` | The type of parallel operation to be used (if any). If missing, the default is taken from the option `"boot.parallel"` (and if that is not set, `"no"`). | | `ncpus` | integer: number of processes to be used in parallel operation: typically one would chose this to the number of available CPUs. | | `cl` | An optional parallel or snow cluster for use if `parallel = "snow"`. If not supplied, a cluster on the local machine is created for the duration of the `boot` call. | ### Details The statistic to be bootstrapped can be as simple or complicated as desired as long as its arguments correspond to the dataset and (for a nonparametric bootstrap) a vector of indices, frequencies or weights. `statistic` is treated as a black box by the `boot` function and is not checked to ensure that these conditions are met. The first order balanced bootstrap is described in Davison, Hinkley and Schechtman (1986). The antithetic bootstrap is described by Hall (1989) and is experimental, particularly when used with strata. The other non-parametric simulation types are the ordinary bootstrap (possibly with unequal probabilities), and permutation which returns random permutations of cases. All of these methods work independently within strata if that argument is supplied. For the parametric bootstrap it is necessary for the user to specify how the resampling is to be conducted. The best way of accomplishing this is to specify the function `ran.gen` which will return a simulated data set from the observed data set and a set of parameter estimates specified in `mle`. ### Value The returned value is an object of class `"boot"`, containing the following components: | | | | --- | --- | | `t0` | The observed value of `statistic` applied to `data`. | | `t` | A matrix with `sum(R)` rows each of which is a bootstrap replicate of the result of calling `statistic`. | | `R` | The value of `R` as passed to `boot`. | | `data` | The `data` as passed to `boot`. | | `seed` | The value of `.Random.seed` when `boot` started work. | | `statistic` | The function `statistic` as passed to `boot`. | | `sim` | Simulation type used. | | `stype` | Statistic type as passed to `boot`. | | `call` | The original call to `boot`. | | `strata` | The strata used. This is the vector passed to `boot`, if it was supplied or a vector of ones if there were no strata. It is not returned if `sim` is `"parametric"`. | | `weights` | The importance sampling weights as passed to `boot` or the empirical distribution function weights if no importance sampling weights were specified. It is omitted if `sim` is not one of `"ordinary"` or `"balanced"`. | | `pred.i` | If predictions are required (`m > 0`) this is the matrix of indices at which predictions were calculated as they were passed to statistic. Omitted if `m` is `0` or `sim` is not `"ordinary"`. | | `L` | The influence values used when `sim` is `"antithetic"`. If no such values were specified and `stype` is not `"w"` then `L` is returned as consecutive integers corresponding to the assumption that data is ordered by influence values. This component is omitted when `sim` is not `"antithetic"`. | | `ran.gen` | The random generator function used if `sim` is `"parametric"`. This component is omitted for any other value of `sim`. | | `mle` | The parameter estimates passed to `boot` when `sim` is `"parametric"`. It is omitted for all other values of `sim`. | There are `c`, `plot` and `print` methods for this class. ### Parallel operation When `parallel = "multicore"` is used (not available on Windows), each worker process inherits the environment of the current session, including the workspace and the loaded namespaces and attached packages (but not the random number seed: see below). More work is needed when `parallel = "snow"` is used: the worker processes are newly created **R** processes, and `statistic` needs to arrange to set up the environment it needs: often a good way to do that is to make use of lexical scoping since when `statistic` is sent to the worker processes its enclosing environment is also sent. (E.g. see the example for `<jack.after.boot>` where ancillary functions are nested inside the `statistic` function.) `parallel = "snow"` is primarily intended to be used on multi-core Windows machine where `parallel = "multicore"` is not available. For most of the `boot` methods the resampling is done in the master process, but not if `simple = TRUE` nor `sim = "parametric"`. In those cases (or where `statistic` itself uses random numbers), more care is needed if the results need to be reproducible. Resampling is done in the worker processes by `<censboot>(sim = "wierd")` and by most of the schemes in `<tsboot>` (the exceptions being `sim == "fixed"` and `sim == "geom"` with the default `ran.gen`). Where random-number generation is done in the worker processes, the default behaviour is that each worker chooses a separate seed, non-reproducibly. However, with `parallel = "multicore"` or `parallel = "snow"` using the default cluster, a second approach is used if `[RNGkind](../../base/html/random)("L'Ecuyer-CMRG")` has been selected. In that approach each worker gets a different subsequence of the RNG stream based on the seed at the time the worker is spawned and so the results will be reproducible if `ncpus` is unchanged, and for `parallel = "multicore"` if `parallel::[mc.reset.stream](../../parallel/html/rngstream)()` is called: see the examples for `[mclapply](../../parallel/html/mclapply)`. Note that loading the parallel namespace may change the random seed, so for maximum reproducibility this should be done before calling this function. ### References There are many references explaining the bootstrap and its variations. Among them are : Booth, J.G., Hall, P. and Wood, A.T.A. (1993) Balanced importance resampling for the bootstrap. *Annals of Statistics*, **21**, 286–298. Davison, A.C. and Hinkley, D.V. (1997) *Bootstrap Methods and Their Application*. Cambridge University Press. Davison, A.C., Hinkley, D.V. and Schechtman, E. (1986) Efficient bootstrap simulation. *Biometrika*, **73**, 555–566. Efron, B. and Tibshirani, R. (1993) *An Introduction to the Bootstrap*. Chapman & Hall. Gleason, J.R. (1988) Algorithms for balanced bootstrap simulations. *American Statistician*, **42**, 263–266. Hall, P. (1989) Antithetic resampling for the bootstrap. *Biometrika*, **73**, 713–724. Hinkley, D.V. (1988) Bootstrap methods (with Discussion). *Journal of the Royal Statistical Society, B*, **50**, 312–337, 355–370. Hinkley, D.V. and Shi, S. (1989) Importance sampling and the nested bootstrap. *Biometrika*, **76**, 435–446. Johns M.V. (1988) Importance sampling for bootstrap confidence intervals. *Journal of the American Statistical Association*, **83**, 709–714. Noreen, E.W. (1989) *Computer Intensive Methods for Testing Hypotheses*. John Wiley & Sons. ### See Also `<boot.array>`, `<boot.ci>`, `<censboot>`, `<empinf>`, `<jack.after.boot>`, `<tilt.boot>`, `<tsboot>`. ### Examples ``` # Usual bootstrap of the ratio of means using the city data ratio <- function(d, w) sum(d$x * w)/sum(d$u * w) boot(city, ratio, R = 999, stype = "w") # Stratified resampling for the difference of means. In this # example we will look at the difference of means between the final # two series in the gravity data. diff.means <- function(d, f) { n <- nrow(d) gp1 <- 1:table(as.numeric(d$series))[1] m1 <- sum(d[gp1,1] * f[gp1])/sum(f[gp1]) m2 <- sum(d[-gp1,1] * f[-gp1])/sum(f[-gp1]) ss1 <- sum(d[gp1,1]^2 * f[gp1]) - (m1 * m1 * sum(f[gp1])) ss2 <- sum(d[-gp1,1]^2 * f[-gp1]) - (m2 * m2 * sum(f[-gp1])) c(m1 - m2, (ss1 + ss2)/(sum(f) - 2)) } grav1 <- gravity[as.numeric(gravity[,2]) >= 7,] boot(grav1, diff.means, R = 999, stype = "f", strata = grav1[,2]) # In this example we show the use of boot in a prediction from # regression based on the nuclear data. This example is taken # from Example 6.8 of Davison and Hinkley (1997). Notice also # that two extra arguments to 'statistic' are passed through boot. nuke <- nuclear[, c(1, 2, 5, 7, 8, 10, 11)] nuke.lm <- glm(log(cost) ~ date+log(cap)+ne+ct+log(cum.n)+pt, data = nuke) nuke.diag <- glm.diag(nuke.lm) nuke.res <- nuke.diag$res * nuke.diag$sd nuke.res <- nuke.res - mean(nuke.res) # We set up a new data frame with the data, the standardized # residuals and the fitted values for use in the bootstrap. nuke.data <- data.frame(nuke, resid = nuke.res, fit = fitted(nuke.lm)) # Now we want a prediction of plant number 32 but at date 73.00 new.data <- data.frame(cost = 1, date = 73.00, cap = 886, ne = 0, ct = 0, cum.n = 11, pt = 1) new.fit <- predict(nuke.lm, new.data) nuke.fun <- function(dat, inds, i.pred, fit.pred, x.pred) { lm.b <- glm(fit+resid[inds] ~ date+log(cap)+ne+ct+log(cum.n)+pt, data = dat) pred.b <- predict(lm.b, x.pred) c(coef(lm.b), pred.b - (fit.pred + dat$resid[i.pred])) } nuke.boot <- boot(nuke.data, nuke.fun, R = 999, m = 1, fit.pred = new.fit, x.pred = new.data) # The bootstrap prediction squared error would then be found by mean(nuke.boot$t[, 8]^2) # Basic bootstrap prediction limits would be new.fit - sort(nuke.boot$t[, 8])[c(975, 25)] # Finally a parametric bootstrap. For this example we shall look # at the air-conditioning data. In this example our aim is to test # the hypothesis that the true value of the index is 1 (i.e. that # the data come from an exponential distribution) against the # alternative that the data come from a gamma distribution with # index not equal to 1. air.fun <- function(data) { ybar <- mean(data$hours) para <- c(log(ybar), mean(log(data$hours))) ll <- function(k) { if (k <= 0) 1e200 else lgamma(k)-k*(log(k)-1-para[1]+para[2]) } khat <- nlm(ll, ybar^2/var(data$hours))$estimate c(ybar, khat) } air.rg <- function(data, mle) { # Function to generate random exponential variates. # mle will contain the mean of the original data out <- data out$hours <- rexp(nrow(out), 1/mle) out } air.boot <- boot(aircondit, air.fun, R = 999, sim = "parametric", ran.gen = air.rg, mle = mean(aircondit$hours)) # The bootstrap p-value can then be approximated by sum(abs(air.boot$t[,2]-1) > abs(air.boot$t0[2]-1))/(1+air.boot$R) ``` r None `calcium` Calcium Uptake Data ------------------------------ ### Description The `calcium` data frame has 27 rows and 2 columns. Howard Grimes from the Botany Department, North Carolina State University, conducted an experiment for biochemical analysis of intracellular storage and transport of calcium across plasma membrane. Cells were suspended in a solution of radioactive calcium for a certain length of time and then the amount of radioactive calcium that was absorbed by the cells was measured. The experiment was repeated independently with 9 different times of suspension each replicated 3 times. ### Usage ``` calcium ``` ### Format This data frame contains the following columns: `time` The time (in minutes) that the cells were suspended in the solution. `cal` The amount of calcium uptake (nmoles/mg). ### Source The data were obtained from Rawlings, J.O. (1988) *Applied Regression Analysis*. Wadsworth and Brooks/Cole Statistics/Probability Series. ### References Davison, A.C. and Hinkley, D.V. (1997) *Bootstrap Methods and Their Application*. Cambridge University Press. r None `melanoma` Survival from Malignant Melanoma -------------------------------------------- ### Description The `melanoma` data frame has 205 rows and 7 columns. The data consist of measurements made on patients with malignant melanoma. Each patient had their tumour removed by surgery at the Department of Plastic Surgery, University Hospital of Odense, Denmark during the period 1962 to 1977. The surgery consisted of complete removal of the tumour together with about 2.5cm of the surrounding skin. Among the measurements taken were the thickness of the tumour and whether it was ulcerated or not. These are thought to be important prognostic variables in that patients with a thick and/or ulcerated tumour have an increased chance of death from melanoma. Patients were followed until the end of 1977. ### Usage ``` melanoma ``` ### Format This data frame contains the following columns: `time` Survival time in days since the operation, possibly censored. `status` The patients status at the end of the study. 1 indicates that they had died from melanoma, 2 indicates that they were still alive and 3 indicates that they had died from causes unrelated to their melanoma. `sex` The patients sex; 1=male, 0=female. `age` Age in years at the time of the operation. `year` Year of operation. `thickness` Tumour thickness in mm. `ulcer` Indicator of ulceration; 1=present, 0=absent. ### Note This dataset is not related to the dataset in the lattice package with the same name. ### Source The data were obtained from Andersen, P.K., Borgan, O., Gill, R.D. and Keiding, N. (1993) *Statistical Models Based on Counting Processes*. Springer-Verlag. ### References Davison, A.C. and Hinkley, D.V. (1997) *Bootstrap Methods and Their Application*. Cambridge University Press. Venables, W.N. and Ripley, B.D. (1994) *Modern Applied Statistics with S-Plus*. Springer-Verlag.
programming_docs
r None `dogs` Cardiac Data for Domestic Dogs -------------------------------------- ### Description The `dogs` data frame has 7 rows and 2 columns. Data on the cardiac oxygen consumption and left ventricular pressure were gathered on 7 domestic dogs. ### Usage ``` dogs ``` ### Format This data frame contains the following columns: mvo Cardiac Oxygen Consumption lvp Left Ventricular Pressure ### References Davison, A. C. and Hinkley, D. V. (1997) *Bootstrap Methods and Their Application*. Cambridge University Press. r None `remission` Cancer Remission and Cell Activity ----------------------------------------------- ### Description The `remission` data frame has 27 rows and 3 columns. ### Usage ``` remission ``` ### Format This data frame contains the following columns: `LI` A measure of cell activity. `m` The number of patients in each group (all values are actually 1 here). `r` The number of patients (out of `m`) who went into remission. ### Source The data were obtained from Freeman, D.H. (1987) *Applied Categorical Data Analysis*. Marcel Dekker. ### References Davison, A.C. and Hinkley, D.V. (1997) *Bootstrap Methods and Their Application*. Cambridge University Press. r None `glm.diag.plots` Diagnostics plots for generalized linear models ----------------------------------------------------------------- ### Description Makes plot of jackknife deviance residuals against linear predictor, normal scores plots of standardized deviance residuals, plot of approximate Cook statistics against leverage/(1-leverage), and case plot of Cook statistic. ### Usage ``` glm.diag.plots(glmfit, glmdiag = glm.diag(glmfit), subset = NULL, iden = FALSE, labels = NULL, ret = FALSE) ``` ### Arguments | | | | --- | --- | | `glmfit` | `glm.object` : the result of a call to `glm()` | | `glmdiag` | Diagnostics of `glmfit` obtained from a call to `glm.diag`. If it is not supplied then it is calculated. | | `subset` | Subset of `data` for which `glm` fitting performed: should be the same as the `subset` option used in the call to `glm()` which generated `glmfit`. Needed only if the `subset=` option was used in the call to `glm`. | | `iden` | A logical argument. If `TRUE` then, after the plots are drawn, the user will be prompted for an integer between 0 and 4. A positive integer will select a plot and invoke `identify()` on that plot. After exiting `identify()`, the user is again prompted, this loop continuing until the user responds to the prompt with 0. If `iden` is `FALSE` (default) the user cannot interact with the plots. | | `labels` | A vector of labels for use with `identify()` if `iden` is `TRUE`. If it is not supplied then the labels are derived from `glmfit`. | | `ret` | A logical argument indicating if `glmdiag` should be returned. The default is `FALSE`. | ### Details The diagnostics required for the plots are calculated by `glm.diag`. These are then used to produce the four plots on the current graphics device. The plot on the top left is a plot of the jackknife deviance residuals against the fitted values. The plot on the top right is a normal QQ plot of the standardized deviance residuals. The dotted line is the expected line if the standardized residuals are normally distributed, i.e. it is the line with intercept 0 and slope 1. The bottom two panels are plots of the Cook statistics. On the left is a plot of the Cook statistics against the standardized leverages. In general there will be two dotted lines on this plot. The horizontal line is at 8/(n-2p) where n is the number of observations and p is the number of parameters estimated. Points above this line may be points with high influence on the model. The vertical line is at 2p/(n-2p) and points to the right of this line have high leverage compared to the variance of the raw residual at that point. If all points are below the horizontal line or to the left of the vertical line then the line is not shown. The final plot again shows the Cook statistic this time plotted against case number enabling us to find which observations are influential. Use of `iden=T` is encouraged for proper exploration of these four plots as a guide to how well the model fits the data and whether certain observations have an unduly large effect on parameter estimates. ### Value If `ret` is `TRUE` then the value of `glmdiag` is returned otherwise there is no returned value. ### Side Effects The current device is cleared and four plots are plotted by use of `split.screen(c(2,2))`. If `iden` is `TRUE`, interactive identification of points is enabled. All screens are closed, but not cleared, on termination of the function. ### References Davison, A. C. and Hinkley, D. V. (1997) *Bootstrap Methods and Their Application*. Cambridge University Press. Davison, A.C. and Snell, E.J. (1991) Residuals and diagnostics. In *Statistical Theory and Modelling: In Honour of Sir David Cox* D.V. Hinkley, N. Reid, and E.J. Snell (editors), 83–106. Chapman and Hall. ### See Also `[glm](../../stats/html/glm)`, `<glm.diag>`, `[identify](../../graphics/html/identify)` ### Examples ``` # In this example we look at the leukaemia data which was looked at in # Example 7.1 of Davison and Hinkley (1997) data(leuk, package = "MASS") leuk.mod <- glm(time ~ ag-1+log10(wbc), family = Gamma(log), data = leuk) leuk.diag <- glm.diag(leuk.mod) glm.diag.plots(leuk.mod, leuk.diag) ``` r None `neuro` Neurophysiological Point Process Data ---------------------------------------------- ### Description `neuro` is a matrix containing times of observed firing of a neuron in windows of 250ms either side of the application of a stimulus to a human subject. Each row of the matrix is a replication of the experiment and there were a total of 469 replicates. ### Note There are a lot of missing values in the matrix as different numbers of firings were observed in different replicates. The number of firings observed varied from 2 to 6. ### Source The data were collected and kindly made available by Dr. S.J. Boniface of the Neurophysiology Unit at the Radcliffe Infirmary, Oxford. ### References Davison, A.C. and Hinkley, D.V. (1997) *Bootstrap Methods and Their Application*. Cambridge University Press. Ventura, V., Davison, A.C. and Boniface, S.J. (1997) A stochastic model for the effect of magnetic brain stimulation on a motorneurone. To appear in *Applied Statistics*. r None `boot.ci` Nonparametric Bootstrap Confidence Intervals ------------------------------------------------------- ### Description This function generates 5 different types of equi-tailed two-sided nonparametric confidence intervals. These are the first order normal approximation, the basic bootstrap interval, the studentized bootstrap interval, the bootstrap percentile interval, and the adjusted bootstrap percentile (BCa) interval. All or a subset of these intervals can be generated. ### Usage ``` boot.ci(boot.out, conf = 0.95, type = "all", index = 1:min(2,length(boot.out$t0)), var.t0 = NULL, var.t = NULL, t0 = NULL, t = NULL, L = NULL, h = function(t) t, hdot = function(t) rep(1,length(t)), hinv = function(t) t, ...) ``` ### Arguments | | | | --- | --- | | `boot.out` | An object of class `"boot"` containing the output of a bootstrap calculation. | | `conf` | A scalar or vector containing the confidence level(s) of the required interval(s). | | `type` | A vector of character strings representing the type of intervals required. The value should be any subset of the values `c("norm","basic", "stud", "perc", "bca")` or simply `"all"` which will compute all five types of intervals. | | `index` | This should be a vector of length 1 or 2. The first element of `index` indicates the position of the variable of interest in `boot.out$t0` and the relevant column in `boot.out$t`. The second element indicates the position of the variance of the variable of interest. If both `var.t0` and `var.t` are supplied then the second element of `index` (if present) is ignored. The default is that the variable of interest is in position 1 and its variance is in position 2 (as long as there are 2 positions in `boot.out$t0`). | | `var.t0` | If supplied, a value to be used as an estimate of the variance of the statistic for the normal approximation and studentized intervals. If it is not supplied and `length(index)` is 2 then `var.t0` defaults to `boot.out$t0[index[2]]` otherwise `var.t0` is undefined. For studentized intervals `var.t0` must be defined. For the normal approximation, if `var.t0` is undefined it defaults to `var(t)`. If a transformation is supplied through the argument `h` then `var.t0` should be the variance of the untransformed statistic. | | `var.t` | This is a vector (of length `boot.out$R`) of variances of the bootstrap replicates of the variable of interest. It is used only for studentized intervals. If it is not supplied and `length(index)` is 2 then `var.t` defaults to `boot.out$t[,index[2]]`, otherwise its value is undefined which will cause an error for studentized intervals. If a transformation is supplied through the argument `h` then `var.t` should be the variance of the untransformed bootstrap statistics. | | `t0` | The observed value of the statistic of interest. The default value is `boot.out$t0[index[1]]`. Specification of `t0` and `t` allows the user to get intervals for a transformed statistic which may not be in the bootstrap output object. See the second example below. An alternative way of achieving this would be to supply the functions `h`, `hdot`, and `hinv` below. | | `t` | The bootstrap replicates of the statistic of interest. It must be a vector of length `boot.out$R`. It is an error to supply one of `t0` or `t` but not the other. Also if studentized intervals are required and `t0` and `t` are supplied then so should be `var.t0` and `var.t`. The default value is `boot.out$t[,index]`. | | `L` | The empirical influence values of the statistic of interest for the observed data. These are used only for BCa intervals. If a transformation is supplied through the parameter `h` then `L` should be the influence values for `t`; the values for `h(t)` are derived from these and `hdot` within the function. If `L` is not supplied then the values are calculated using `empinf` if they are needed. | | `h` | A function defining a transformation. The intervals are calculated on the scale of `h(t)` and the inverse function `hinv` applied to the resulting intervals. It must be a function of one variable only and for a vector argument, it must return a vector of the same length, i.e. `h(c(t1,t2,t3))` should return `c(h(t1),h(t2),h(t3))`. The default is the identity function. | | `hdot` | A function of one argument returning the derivative of `h`. It is a required argument if `h` is supplied and normal, studentized or BCa intervals are required. The function is used for approximating the variances of `h(t0)` and `h(t)` using the delta method, and also for finding the empirical influence values for BCa intervals. Like `h` it should be able to take a vector argument and return a vector of the same length. The default is the constant function 1. | | `hinv` | A function, like `h`, which returns the inverse of `h`. It is used to transform the intervals calculated on the scale of `h(t)` back to the original scale. The default is the identity function. If `h` is supplied but `hinv` is not, then the intervals returned will be on the transformed scale. | | `...` | Any extra arguments that `boot.out$statistic` is expecting. These arguments are needed only if BCa intervals are required and `L` is not supplied since in that case `L` is calculated through a call to `empinf` which calls `boot.out$statistic`. | ### Details The formulae on which the calculations are based can be found in Chapter 5 of Davison and Hinkley (1997). Function `boot` must be run prior to running this function to create the object to be passed as `boot.out`. Variance estimates are required for studentized intervals. The variance of the observed statistic is optional for normal theory intervals. If it is not supplied then the bootstrap estimate of variance is used. The normal intervals also use the bootstrap bias correction. Interpolation on the normal quantile scale is used when a non-integer order statistic is required. If the order statistic used is the smallest or largest of the R values in boot.out a warning is generated and such intervals should not be considered reliable. ### Value An object of type `"bootci"` which contains the intervals. It has components | | | | --- | --- | | `R` | The number of bootstrap replicates on which the intervals were based. | | `t0` | The observed value of the statistic on the same scale as the intervals. | | `call` | The call to `boot.ci` which generated the object. It will also contain one or more of the following components depending on the value of `type` used in the call to `bootci`. | | `normal` | A matrix of intervals calculated using the normal approximation. It will have 3 columns, the first being the level and the other two being the upper and lower endpoints of the intervals. | | `basic` | The intervals calculated using the basic bootstrap method. | | `student` | The intervals calculated using the studentized bootstrap method. | | `percent` | The intervals calculated using the bootstrap percentile method. | | `bca` | The intervals calculated using the adjusted bootstrap percentile (BCa) method. These latter four components will be matrices with 5 columns, the first column containing the level, the next two containing the indices of the order statistics used in the calculations and the final two the calculated endpoints themselves. | ### References Davison, A.C. and Hinkley, D.V. (1997) *Bootstrap Methods and Their Application*, Chapter 5. Cambridge University Press. DiCiccio, T.J. and Efron B. (1996) Bootstrap confidence intervals (with Discussion). *Statistical Science*, **11**, 189–228. Efron, B. (1987) Better bootstrap confidence intervals (with Discussion). *Journal of the American Statistical Association*, **82**, 171–200. ### See Also `<abc.ci>`, `<boot>`, `<empinf>`, `<norm.ci>` ### Examples ``` # confidence intervals for the city data ratio <- function(d, w) sum(d$x * w)/sum(d$u * w) city.boot <- boot(city, ratio, R = 999, stype = "w", sim = "ordinary") boot.ci(city.boot, conf = c(0.90, 0.95), type = c("norm", "basic", "perc", "bca")) # studentized confidence interval for the two sample # difference of means problem using the final two series # of the gravity data. diff.means <- function(d, f) { n <- nrow(d) gp1 <- 1:table(as.numeric(d$series))[1] m1 <- sum(d[gp1,1] * f[gp1])/sum(f[gp1]) m2 <- sum(d[-gp1,1] * f[-gp1])/sum(f[-gp1]) ss1 <- sum(d[gp1,1]^2 * f[gp1]) - (m1 * m1 * sum(f[gp1])) ss2 <- sum(d[-gp1,1]^2 * f[-gp1]) - (m2 * m2 * sum(f[-gp1])) c(m1 - m2, (ss1 + ss2)/(sum(f) - 2)) } grav1 <- gravity[as.numeric(gravity[,2]) >= 7, ] grav1.boot <- boot(grav1, diff.means, R = 999, stype = "f", strata = grav1[ ,2]) boot.ci(grav1.boot, type = c("stud", "norm")) # Nonparametric confidence intervals for mean failure time # of the air-conditioning data as in Example 5.4 of Davison # and Hinkley (1997) mean.fun <- function(d, i) { m <- mean(d$hours[i]) n <- length(i) v <- (n-1)*var(d$hours[i])/n^2 c(m, v) } air.boot <- boot(aircondit, mean.fun, R = 999) boot.ci(air.boot, type = c("norm", "basic", "perc", "stud")) # Now using the log transformation # There are two ways of doing this and they both give the # same intervals. # Method 1 boot.ci(air.boot, type = c("norm", "basic", "perc", "stud"), h = log, hdot = function(x) 1/x) # Method 2 vt0 <- air.boot$t0[2]/air.boot$t0[1]^2 vt <- air.boot$t[, 2]/air.boot$t[ ,1]^2 boot.ci(air.boot, type = c("norm", "basic", "perc", "stud"), t0 = log(air.boot$t0[1]), t = log(air.boot$t[,1]), var.t0 = vt0, var.t = vt) ``` r None `warpbreaks` The Number of Breaks in Yarn during Weaving --------------------------------------------------------- ### Description This data set gives the number of warp breaks per loom, where a loom corresponds to a fixed length of yarn. ### Usage ``` warpbreaks ``` ### Format A data frame with 54 observations on 3 variables. | | | | | | --- | --- | --- | --- | | `[,1]` | `breaks` | numeric | The number of breaks | | `[,2]` | `wool` | factor | The type of wool (A or B) | | `[,3]` | `tension` | factor | The level of tension (L, M, H) | There are measurements on 9 looms for each of the six types of warp (`AL`, `AM`, `AH`, `BL`, `BM`, `BH`). ### Source Tippett, L. H. C. (1950) *Technological Applications of Statistics*. Wiley. Page 106. ### References Tukey, J. W. (1977) *Exploratory Data Analysis*. Addison-Wesley. McNeil, D. R. (1977) *Interactive Data Analysis*. Wiley. ### See Also `[xtabs](../../stats/html/xtabs)` for ways to display these data as a table. ### Examples ``` require(stats); require(graphics) summary(warpbreaks) opar <- par(mfrow = c(1, 2), oma = c(0, 0, 1.1, 0)) plot(breaks ~ tension, data = warpbreaks, col = "lightgray", varwidth = TRUE, subset = wool == "A", main = "Wool A") plot(breaks ~ tension, data = warpbreaks, col = "lightgray", varwidth = TRUE, subset = wool == "B", main = "Wool B") mtext("warpbreaks data", side = 3, outer = TRUE) par(opar) summary(fm1 <- lm(breaks ~ wool*tension, data = warpbreaks)) anova(fm1) ``` r None `freeny` Freeny's Revenue Data ------------------------------- ### Description Freeny's data on quarterly revenue and explanatory variables. ### Usage ``` freeny freeny.x freeny.y ``` ### Format There are three ‘freeny’ data sets. `freeny.y` is a time series with 39 observations on quarterly revenue from (1962,2Q) to (1971,4Q). `freeny.x` is a matrix of explanatory variables. The columns are `freeny.y` lagged 1 quarter, price index, income level, and market potential. Finally, `freeny` is a data frame with variables `y`, `lag.quarterly.revenue`, `price.index`, `income.level`, and `market.potential` obtained from the above two data objects. ### Source A. E. Freeny (1977) *A Portable Linear Regression Package with Test Programs*. Bell Laboratories memorandum. ### References Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) *The New S Language*. Wadsworth & Brooks/Cole. ### Examples ``` require(stats); require(graphics) summary(freeny) pairs(freeny, main = "freeny data") # gives warning: freeny$y has class "ts" summary(fm1 <- lm(y ~ ., data = freeny)) opar <- par(mfrow = c(2, 2), oma = c(0, 0, 1.1, 0), mar = c(4.1, 4.1, 2.1, 1.1)) plot(fm1) par(opar) ``` r None `presidents` Quarterly Approval Ratings of US Presidents --------------------------------------------------------- ### Description The (approximately) quarterly approval rating for the President of the United States from the first quarter of 1945 to the last quarter of 1974. ### Usage ``` presidents ``` ### Format A time series of 120 values. ### Details The data are actually a fudged version of the approval ratings. See McNeil's book for details. ### Source The Gallup Organisation. ### References McNeil, D. R. (1977) *Interactive Data Analysis*. New York: Wiley. ### Examples ``` require(stats); require(graphics) plot(presidents, las = 1, ylab = "Approval rating (%)", main = "presidents data") ``` r None `UKLungDeaths` Monthly Deaths from Lung Diseases in the UK ----------------------------------------------------------- ### Description Three time series giving the monthly deaths from bronchitis, emphysema and asthma in the UK, 1974–1979, both sexes (`ldeaths`), males (`mdeaths`) and females (`fdeaths`). ### Usage ``` ldeaths fdeaths mdeaths ``` ### Source P. J. Diggle (1990) *Time Series: A Biostatistical Introduction.* Oxford, table A.3 ### Examples ``` require(stats); require(graphics) # for time plot(ldeaths) plot(mdeaths, fdeaths) ## Better labels: yr <- floor(tt <- time(mdeaths)) plot(mdeaths, fdeaths, xy.labels = paste(month.abb[12*(tt - yr)], yr-1900, sep = "'")) ```
programming_docs
r None `PlantGrowth` Results from an Experiment on Plant Growth --------------------------------------------------------- ### Description Results from an experiment to compare yields (as measured by dried weight of plants) obtained under a control and two different treatment conditions. ### Usage ``` PlantGrowth ``` ### Format A data frame of 30 cases on 2 variables. | | | | | --- | --- | --- | | [, 1] | weight | numeric | | [, 2] | group | factor | The levels of `group` are ‘ctrl’, ‘trt1’, and ‘trt2’. ### Source Dobson, A. J. (1983) *An Introduction to Statistical Modelling*. London: Chapman and Hall. ### Examples ``` ## One factor ANOVA example from Dobson's book, cf. Table 7.4: require(stats); require(graphics) boxplot(weight ~ group, data = PlantGrowth, main = "PlantGrowth data", ylab = "Dried weight of plants", col = "lightgray", notch = TRUE, varwidth = TRUE) anova(lm(weight ~ group, data = PlantGrowth)) ``` r None `InsectSprays` Effectiveness of Insect Sprays ---------------------------------------------- ### Description The counts of insects in agricultural experimental units treated with different insecticides. ### Usage ``` InsectSprays ``` ### Format A data frame with 72 observations on 2 variables. | | | | | | --- | --- | --- | --- | | [,1] | count | numeric | Insect count | | [,2] | spray | factor | The type of spray | ### Source Beall, G., (1942) The Transformation of data from entomological field experiments, *Biometrika*, **29**, 243–262. ### References McNeil, D. (1977) *Interactive Data Analysis*. New York: Wiley. ### Examples ``` require(stats); require(graphics) boxplot(count ~ spray, data = InsectSprays, xlab = "Type of spray", ylab = "Insect count", main = "InsectSprays data", varwidth = TRUE, col = "lightgray") fm1 <- aov(count ~ spray, data = InsectSprays) summary(fm1) opar <- par(mfrow = c(2, 2), oma = c(0, 0, 1.1, 0)) plot(fm1) fm2 <- aov(sqrt(count) ~ spray, data = InsectSprays) summary(fm2) plot(fm2) par(opar) ``` r None `treering` Yearly Treering Data, -6000–1979 -------------------------------------------- ### Description Contains normalized tree-ring widths in dimensionless units. ### Usage ``` treering ``` ### Format A univariate time series with 7981 observations. The object is of class `"ts"`. Each tree ring corresponds to one year. ### Details The data were recorded by Donald A. Graybill, 1980, from Gt Basin Bristlecone Pine 2805M, 3726-11810 in Methuselah Walk, California. ### Source Time Series Data Library: <https://robjhyndman.com/TSDL/>, series ‘CA535.DAT’ ### References For some photos of Methuselah Walk see <https://web.archive.org/web/20110523225828/http://www.ltrr.arizona.edu/~hallman/sitephotos/meth.html> r None `infert` Infertility after Spontaneous and Induced Abortion ------------------------------------------------------------ ### Description This is a matched case-control study dating from before the availability of conditional logistic regression. ### Usage ``` infert ``` ### Format | | | | | --- | --- | --- | | 1. | Education | 0 = 0-5 years | | | | 1 = 6-11 years | | | | 2 = 12+ years | | 2. | age | age in years of case | | 3. | parity | count | | 4. | number of prior | 0 = 0 | | | induced abortions | 1 = 1 | | | | 2 = 2 or more | | 5. | case status | 1 = case | | | | 0 = control | | 6. | number of prior | 0 = 0 | | | spontaneous abortions | 1 = 1 | | | | 2 = 2 or more | | 7. | matched set number | 1-83 | | 8. | stratum number | 1-63 | ### Note One case with two prior spontaneous abortions and two prior induced abortions is omitted. ### Source Trichopoulos *et al* (1976) *Br. J. of Obst. and Gynaec.* **83**, 645–650. ### Examples ``` require(stats) model1 <- glm(case ~ spontaneous+induced, data = infert, family = binomial()) summary(model1) ## adjusted for other potential confounders: summary(model2 <- glm(case ~ age+parity+education+spontaneous+induced, data = infert, family = binomial())) ## Really should be analysed by conditional logistic regression ## which is in the survival package if(require(survival)){ model3 <- clogit(case ~ spontaneous+induced+strata(stratum), data = infert) print(summary(model3)) detach() # survival (conflicts) } ``` r None `lynx` Annual Canadian Lynx trappings 1821–1934 ------------------------------------------------ ### Description Annual numbers of lynx trappings for 1821–1934 in Canada. Taken from Brockwell & Davis (1991), this appears to be the series considered by Campbell & Walker (1977). ### Usage ``` lynx ``` ### Source Brockwell, P. J. and Davis, R. A. (1991). *Time Series and Forecasting Methods*. Second edition. Springer. Series G (page 557). ### References Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988). *The New S Language*. Wadsworth & Brooks/Cole. Campbell, M. J. and Walker, A. M. (1977). A Survey of statistical work on the Mackenzie River series of annual Canadian lynx trappings for the years 1821–1934 and a new analysis. *Journal of the Royal Statistical Society series A*, **140**, 411–431. doi: [10.2307/2345277](https://doi.org/10.2307/2345277). r None `BJsales` Sales Data with Leading Indicator -------------------------------------------- ### Description The sales time series `BJsales` and leading indicator `BJsales.lead` each contain 150 observations. The objects are of class `"ts"`. ### Usage ``` BJsales BJsales.lead ``` ### Source The data are given in Box & Jenkins (1976). Obtained from the Time Series Data Library at <https://robjhyndman.com/TSDL/> ### References G. E. P. Box and G. M. Jenkins (1976): *Time Series Analysis, Forecasting and Control*, Holden-Day, San Francisco, p. 537. P. J. Brockwell and R. A. Davis (1991): *Time Series: Theory and Methods*, Second edition, Springer Verlag, NY, pp. 414. r None `women` Average Heights and Weights for American Women ------------------------------------------------------- ### Description This data set gives the average heights and weights for American women aged 30–39. ### Usage ``` women ``` ### Format A data frame with 15 observations on 2 variables. | | | | | | --- | --- | --- | --- | | `[,1]` | `height` | numeric | Height (in) | | `[,2]` | `weight` | numeric | Weight (lbs) | ### Details The data set appears to have been taken from the American Society of Actuaries *Build and Blood Pressure Study* for some (unknown to us) earlier year. The World Almanac notes: “The figures represent weights in ordinary indoor clothing and shoes, and heights with shoes”. ### Source The World Almanac and Book of Facts, 1975. ### References McNeil, D. R. (1977) *Interactive Data Analysis*. Wiley. ### Examples ``` require(graphics) plot(women, xlab = "Height (in)", ylab = "Weight (lb)", main = "women data: American women aged 30-39") ``` r None `LakeHuron` Level of Lake Huron 1875–1972 ------------------------------------------ ### Description Annual measurements of the level, in feet, of Lake Huron 1875–1972. ### Usage ``` LakeHuron ``` ### Format A time series of length 98. ### Source Brockwell, P. J. and Davis, R. A. (1991). *Time Series and Forecasting Methods*. Second edition. Springer, New York. Series A, page 555. Brockwell, P. J. and Davis, R. A. (1996). *Introduction to Time Series and Forecasting*. Springer, New York. Sections 5.1 and 7.6. r None `nhtemp` Average Yearly Temperatures in New Haven -------------------------------------------------- ### Description The mean annual temperature in degrees Fahrenheit in New Haven, Connecticut, from 1912 to 1971. ### Usage ``` nhtemp ``` ### Format A time series of 60 observations. ### Source Vaux, J. E. and Brinker, N. B. (1972) *Cycles*, **1972**, 117–121. ### References McNeil, D. R. (1977) *Interactive Data Analysis*. New York: Wiley. ### Examples ``` require(stats); require(graphics) plot(nhtemp, main = "nhtemp data", ylab = "Mean annual temperature in New Haven, CT (deg. F)") ``` r None `iris` Edgar Anderson's Iris Data ---------------------------------- ### Description This famous (Fisher's or Anderson's) iris data set gives the measurements in centimeters of the variables sepal length and width and petal length and width, respectively, for 50 flowers from each of 3 species of iris. The species are *Iris setosa*, *versicolor*, and *virginica*. ### Usage ``` iris iris3 ``` ### Format `iris` is a data frame with 150 cases (rows) and 5 variables (columns) named `Sepal.Length`, `Sepal.Width`, `Petal.Length`, `Petal.Width`, and `Species`. `iris3` gives the same data arranged as a 3-dimensional array of size 50 by 4 by 3, as represented by S-PLUS. The first dimension gives the case number within the species subsample, the second the measurements with names `Sepal L.`, `Sepal W.`, `Petal L.`, and `Petal W.`, and the third the species. ### Source Fisher, R. A. (1936) The use of multiple measurements in taxonomic problems. *Annals of Eugenics*, **7**, Part II, 179–188. The data were collected by Anderson, Edgar (1935). The irises of the Gaspe Peninsula, *Bulletin of the American Iris Society*, **59**, 2–5. ### References Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) *The New S Language*. Wadsworth & Brooks/Cole. (has `iris3` as `iris`.) ### See Also `[matplot](../../graphics/html/matplot)` some examples of which use `iris`. ### Examples ``` dni3 <- dimnames(iris3) ii <- data.frame(matrix(aperm(iris3, c(1,3,2)), ncol = 4, dimnames = list(NULL, sub(" L.",".Length", sub(" W.",".Width", dni3[[2]])))), Species = gl(3, 50, labels = sub("S", "s", sub("V", "v", dni3[[3]])))) all.equal(ii, iris) # TRUE ``` r None `Theoph` Pharmacokinetics of Theophylline ------------------------------------------ ### Description The `Theoph` data frame has 132 rows and 5 columns of data from an experiment on the pharmacokinetics of theophylline. ### Usage ``` Theoph ``` ### Format An object of class `c("nfnGroupedData", "nfGroupedData", "groupedData", "data.frame")` containing the following columns: Subject an ordered factor with levels `1`, ..., `12` identifying the subject on whom the observation was made. The ordering is by increasing maximum concentration of theophylline observed. Wt weight of the subject (kg). Dose dose of theophylline administered orally to the subject (mg/kg). Time time since drug administration when the sample was drawn (hr). conc theophylline concentration in the sample (mg/L). ### Details Boeckmann, Sheiner and Beal (1994) report data from a study by Dr. Robert Upton of the kinetics of the anti-asthmatic drug theophylline. Twelve subjects were given oral doses of theophylline then serum concentrations were measured at 11 time points over the next 25 hours. These data are analyzed in Davidian and Giltinan (1995) and Pinheiro and Bates (2000) using a two-compartment open pharmacokinetic model, for which a self-starting model function, `SSfol`, is available. This dataset was originally part of package `nlme`, and that has methods (including for `[`, `as.data.frame`, `plot` and `print`) for its grouped-data classes. ### Source Boeckmann, A. J., Sheiner, L. B. and Beal, S. L. (1994), *NONMEM Users Guide: Part V*, NONMEM Project Group, University of California, San Francisco. Davidian, M. and Giltinan, D. M. (1995) *Nonlinear Models for Repeated Measurement Data*, Chapman & Hall (section 5.5, p. 145 and section 6.6, p. 176) Pinheiro, J. C. and Bates, D. M. (2000) *Mixed-effects Models in S and S-PLUS*, Springer (Appendix A.29) ### See Also `[SSfol](../../stats/html/ssfol)` ### Examples ``` require(stats); require(graphics) coplot(conc ~ Time | Subject, data = Theoph, show.given = FALSE) Theoph.4 <- subset(Theoph, Subject == 4) fm1 <- nls(conc ~ SSfol(Dose, Time, lKe, lKa, lCl), data = Theoph.4) summary(fm1) plot(conc ~ Time, data = Theoph.4, xlab = "Time since drug administration (hr)", ylab = "Theophylline concentration (mg/L)", main = "Observed concentrations and fitted model", sub = "Theophylline data - Subject 4 only", las = 1, col = 4) xvals <- seq(0, par("usr")[2], length.out = 55) lines(xvals, predict(fm1, newdata = list(Time = xvals)), col = 4) ``` r None `Indometh` Pharmacokinetics of Indomethacin -------------------------------------------- ### Description The `Indometh` data frame has 66 rows and 3 columns of data on the pharmacokinetics of indometacin (or, older spelling, ‘indomethacin’). ### Usage ``` Indometh ``` ### Format An object of class `c("nfnGroupedData", "nfGroupedData", "groupedData", "data.frame")` containing the following columns: Subject an ordered factor with containing the subject codes. The ordering is according to increasing maximum response. time a numeric vector of times at which blood samples were drawn (hr). conc a numeric vector of plasma concentrations of indometacin (mcg/ml). ### Details Each of the six subjects were given an intravenous injection of indometacin. This dataset was originally part of package `nlme`, and that has methods (including for `[`, `as.data.frame`, `plot` and `print`) for its grouped-data classes. ### Source Kwan, Breault, Umbenhauer, McMahon and Duggan (1976) Kinetics of Indomethacin absorption, elimination, and enterohepatic circulation in man. *Journal of Pharmacokinetics and Biopharmaceutics* **4**, 255–280. Davidian, M. and Giltinan, D. M. (1995) *Nonlinear Models for Repeated Measurement Data*, Chapman & Hall (section 5.2.4, p. 129) Pinheiro, J. C. and Bates, D. M. (2000) *Mixed-effects Models in S and S-PLUS*, Springer. ### See Also `[SSbiexp](../../stats/html/ssbiexp)` for models fitted to this dataset. r None `crimtab` Student's 3000 Criminals Data ---------------------------------------- ### Description Data of 3000 male criminals over 20 years old undergoing their sentences in the chief prisons of England and Wales. ### Usage ``` crimtab ``` ### Format A `[table](../../base/html/table)` object of `[integer](../../base/html/integer)` counts, of dimension *42 \* 22* with a total count, `sum(crimtab)` of 3000. The 42 `[rownames](../../base/html/colnames)` (`"9.4"`, `"9.5"`, ...) correspond to midpoints of intervals of finger lengths whereas the 22 column names (`[colnames](../../base/html/colnames)`) (`"142.24"`, `"144.78"`, ...) correspond to (body) heights of 3000 criminals, see also below. ### Details Student is the pseudonym of William Sealy Gosset. In his 1908 paper he wrote (on page 13) at the beginning of section VI entitled *Practical Test of the forgoing Equations*: “Before I had succeeded in solving my problem analytically, I had endeavoured to do so empirically. The material used was a correlation table containing the height and left middle finger measurements of 3000 criminals, from a paper by W. R. MacDonell (*Biometrika*, Vol. I., p. 219). The measurements were written out on 3000 pieces of cardboard, which were then very thoroughly shuffled and drawn at random. As each card was drawn its numbers were written down in a book, which thus contains the measurements of 3000 criminals in a random order. Finally, each consecutive set of 4 was taken as a sample—750 in all—and the mean, standard deviation, and correlation of each sample determined. The difference between the mean of each sample and the mean of the population was then divided by the standard deviation of the sample, giving us the *z* of Section III.” The table is in fact page 216 and not page 219 in MacDonell(1902). In the MacDonell table, the middle finger lengths were given in mm and the heights in feet/inches intervals, they are both converted into cm here. The midpoints of intervals were used, e.g., where MacDonell has *4' 7''9/16 -- 8''9/16*, we have 142.24 which is 2.54\*56 = 2.54\*(*4' 8''*). MacDonell credited the source of data (page 178) as follows: *The data on which the memoir is based were obtained, through the kindness of Dr Garson, from the Central Metric Office, New Scotland Yard...* He pointed out on page 179 that : *The forms were drawn at random from the mass on the office shelves; we are therefore dealing with a random sampling.* ### Source <https://pbil.univ-lyon1.fr/R/donnees/criminals1902.txt> thanks to Jean R. Lobry and Anne-Béatrice Dufour. ### References Garson, J.G. (1900). The metric system of identification of criminals, as used in in Great Britain and Ireland. *The Journal of the Anthropological Institute of Great Britain and Ireland*, **30**, 161–198. doi: [10.2307/2842627](https://doi.org/10.2307/2842627). MacDonell, W.R. (1902). On criminal anthropometry and the identification of criminals. *Biometrika*, **1**(2), 177–227. doi: [10.2307/2331487](https://doi.org/10.2307/2331487). Student (1908). The probable error of a mean. *Biometrika*, **6**, 1–25. doi: [10.2307/2331554](https://doi.org/10.2307/2331554). ### Examples ``` require(stats) dim(crimtab) utils::str(crimtab) ## for nicer printing: local({cT <- crimtab colnames(cT) <- substring(colnames(cT), 2, 3) print(cT, zero.print = " ") }) ## Repeat Student's experiment: # 1) Reconstitute 3000 raw data for heights in inches and rounded to # nearest integer as in Student's paper: (heIn <- round(as.numeric(colnames(crimtab)) / 2.54)) d.hei <- data.frame(height = rep(heIn, colSums(crimtab))) # 2) shuffle the data: set.seed(1) d.hei <- d.hei[sample(1:3000), , drop = FALSE] # 3) Make 750 samples each of size 4: d.hei$sample <- as.factor(rep(1:750, each = 4)) # 4) Compute the means and standard deviations (n) for the 750 samples: h.mean <- with(d.hei, tapply(height, sample, FUN = mean)) h.sd <- with(d.hei, tapply(height, sample, FUN = sd)) * sqrt(3/4) # 5) Compute the difference between the mean of each sample and # the mean of the population and then divide by the # standard deviation of the sample: zobs <- (h.mean - mean(d.hei[,"height"]))/h.sd # 6) Replace infinite values by +/- 6 as in Student's paper: zobs[infZ <- is.infinite(zobs)] # none of them zobs[infZ] <- 6 * sign(zobs[infZ]) # 7) Plot the distribution: require(grDevices); require(graphics) hist(x = zobs, probability = TRUE, xlab = "Student's z", col = grey(0.8), border = grey(0.5), main = "Distribution of Student's z score for 'crimtab' data") ``` r None `sunspot.month` Monthly Sunspot Data, from 1749 to "Present" ------------------------------------------------------------- ### Description Monthly numbers of sunspots, as from the World Data Center, aka SIDC. This is the version of the data that will occasionally be updated when new counts become available. ### Usage ``` sunspot.month ``` ### Format The univariate time series `sunspot.year` and `sunspot.month` contain 289 and 2988 observations, respectively. The objects are of class `"ts"`. ### Author(s) R ### Source WDC-SILSO, Solar Influences Data Analysis Center (SIDC), Royal Observatory of Belgium, Av. Circulaire, 3, B-1180 BRUSSELS Currently at <http://www.sidc.be/silso/datafiles> ### See Also `sunspot.month` is a longer version of `<sunspots>`; the latter runs until 1983 and is kept fixed (for reproducibility as example dataset). ### Examples ``` require(stats); require(graphics) ## Compare the monthly series plot (sunspot.month, main="sunspot.month & sunspots [package'datasets']", col=2) lines(sunspots) # -> faint differences where they overlap ## Now look at the difference : all(tsp(sunspots) [c(1,3)] == tsp(sunspot.month)[c(1,3)]) ## Start & Periodicity are the same n1 <- length(sunspots) table(eq <- sunspots == sunspot.month[1:n1]) #> 132 are different ! i <- which(!eq) rug(time(eq)[i]) s1 <- sunspots[i] ; s2 <- sunspot.month[i] cbind(i = i, time = time(sunspots)[i], sunspots = s1, ss.month = s2, perc.diff = round(100*2*abs(s1-s2)/(s1+s2), 1)) ## How to recreate the "old" sunspot.month (R <= 3.0.3): .sunspot.diff <- cbind( i = c(1202L, 1256L, 1258L, 1301L, 1407L, 1429L, 1452L, 1455L, 1663L, 2151L, 2329L, 2498L, 2594L, 2694L, 2819L), res10 = c(1L, 1L, 1L, -1L, -1L, -1L, 1L, -1L, 1L, 1L, 1L, 1L, 1L, 20L, 1L)) ssm0 <- sunspot.month[1:2988] with(as.data.frame(.sunspot.diff), ssm0[i] <<- ssm0[i] - res10/10) sunspot.month.0 <- ts(ssm0, start = 1749, frequency = 12) ```
programming_docs
r None `eurodist` Distances Between European Cities and Between US Cities ------------------------------------------------------------------- ### Description The `eurodist` gives the road distances (in km) between 21 cities in Europe. The data are taken from a table in *The Cambridge Encyclopaedia*. `UScitiesD` gives “straight line” distances between 10 cities in the US. ### Usage ``` eurodist UScitiesD ``` ### Format `dist` objects based on 21 and 10 objects, respectively. (You must have the stats package loaded to have the methods for this kind of object available). ### Source Crystal, D. Ed. (1990) *The Cambridge Encyclopaedia*. Cambridge: Cambridge University Press, The US cities distances were provided by Pierre Legendre. r None `ChickWeight` Weight versus age of chicks on different diets ------------------------------------------------------------- ### Description The `ChickWeight` data frame has 578 rows and 4 columns from an experiment on the effect of diet on early growth of chicks. ### Usage ``` ChickWeight ``` ### Format An object of class `c("nfnGroupedData", "nfGroupedData", "groupedData", "data.frame")` containing the following columns: weight a numeric vector giving the body weight of the chick (gm). Time a numeric vector giving the number of days since birth when the measurement was made. Chick an ordered factor with levels `18` < ... < `48` giving a unique identifier for the chick. The ordering of the levels groups chicks on the same diet together and orders them according to their final weight (lightest to heaviest) within diet. Diet a factor with levels 1, ..., 4 indicating which experimental diet the chick received. ### Details The body weights of the chicks were measured at birth and every second day thereafter until day 20. They were also measured on day 21. There were four groups on chicks on different protein diets. This dataset was originally part of package `nlme`, and that has methods (including for `[`, `as.data.frame`, `plot` and `print`) for its grouped-data classes. ### Source Crowder, M. and Hand, D. (1990), *Analysis of Repeated Measures*, Chapman and Hall (example 5.3) Hand, D. and Crowder, M. (1996), *Practical Longitudinal Data Analysis*, Chapman and Hall (table A.2) Pinheiro, J. C. and Bates, D. M. (2000) *Mixed-effects Models in S and S-PLUS*, Springer. ### See Also `[SSlogis](../../stats/html/sslogis)` for models fitted to this dataset. ### Examples ``` require(graphics) coplot(weight ~ Time | Chick, data = ChickWeight, type = "b", show.given = FALSE) ``` r None `rivers` Lengths of Major North American Rivers ------------------------------------------------ ### Description This data set gives the lengths (in miles) of 141 “major” rivers in North America, as compiled by the US Geological Survey. ### Usage ``` rivers ``` ### Format A vector containing 141 observations. ### Source World Almanac and Book of Facts, 1975, page 406. ### References McNeil, D. R. (1977) *Interactive Data Analysis*. New York: Wiley. r None `stackloss` Brownlee's Stack Loss Plant Data --------------------------------------------- ### Description Operational data of a plant for the oxidation of ammonia to nitric acid. ### Usage ``` stackloss stack.x stack.loss ``` ### Format `stackloss` is a data frame with 21 observations on 4 variables. | | | | | --- | --- | --- | | [,1] | `Air Flow` | Flow of cooling air | | [,2] | `Water Temp` | Cooling Water Inlet Temperature | | [,3] | `Acid Conc.` | Concentration of acid [per 1000, minus 500] | | [,4] | `stack.loss` | Stack loss | | | For compatibility with S-PLUS, the data sets `stack.x`, a matrix with the first three (independent) variables of the data frame, and `stack.loss`, the numeric vector giving the fourth (dependent) variable, are provided as well. ### Details “Obtained from 21 days of operation of a plant for the oxidation of ammonia (NH*3*) to nitric acid (HNO*3*). The nitric oxides produced are absorbed in a countercurrent absorption tower”. (Brownlee, cited by Dodge, slightly reformatted by MM.) `Air Flow` represents the rate of operation of the plant. `Water Temp` is the temperature of cooling water circulated through coils in the absorption tower. `Acid Conc.` is the concentration of the acid circulating, minus 50, times 10: that is, 89 corresponds to 58.9 per cent acid. `stack.loss` (the dependent variable) is 10 times the percentage of the ingoing ammonia to the plant that escapes from the absorption column unabsorbed; that is, an (inverse) measure of the over-all efficiency of the plant. ### Source Brownlee, K. A. (1960, 2nd ed. 1965) *Statistical Theory and Methodology in Science and Engineering*. New York: Wiley. pp. 491–500. ### References Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) *The New S Language*. Wadsworth & Brooks/Cole. Dodge, Y. (1996) The guinea pig of multiple regression. In: *Robust Statistics, Data Analysis, and Computer Intensive Methods; In Honor of Peter Huber's 60th Birthday*, 1996, *Lecture Notes in Statistics* **109**, Springer-Verlag, New York. ### Examples ``` require(stats) summary(lm.stack <- lm(stack.loss ~ stack.x)) ``` r None `randu` Random Numbers from Congruential Generator RANDU --------------------------------------------------------- ### Description 400 triples of successive random numbers were taken from the VAX FORTRAN function RANDU running under VMS 1.5. ### Usage ``` randu ``` ### Format A data frame with 400 observations on 3 variables named `x`, `y` and `z` which give the first, second and third random number in the triple. ### Details In three dimensional displays it is evident that the triples fall on 15 parallel planes in 3-space. This can be shown theoretically to be true for all triples from the RANDU generator. These particular 400 triples start 5 apart in the sequence, that is they are ((U[5i+1], U[5i+2], U[5i+3]), i= 0, ..., 399), and they are rounded to 6 decimal places. Under VMS versions 2.0 and higher, this problem has been fixed. ### Source David Donoho ### Examples ``` ## We could re-generate the dataset by the following R code seed <- as.double(1) RANDU <- function() { seed <<- ((2^16 + 3) * seed) %% (2^31) seed/(2^31) } for(i in 1:400) { U <- c(RANDU(), RANDU(), RANDU(), RANDU(), RANDU()) print(round(U[1:3], 6)) } ``` r None `volcano` Topographic Information on Auckland's Maunga Whau Volcano -------------------------------------------------------------------- ### Description Maunga Whau (Mt Eden) is one of about 50 volcanos in the Auckland volcanic field. This data set gives topographic information for Maunga Whau on a 10m by 10m grid. ### Usage ``` volcano ``` ### Format A matrix with 87 rows and 61 columns, rows corresponding to grid lines running east to west and columns to grid lines running south to north. ### Source Digitized from a topographic map by Ross Ihaka. These data should not be regarded as accurate. ### See Also `[filled.contour](../../graphics/html/filled.contour)` for a nice plot. ### Examples ``` require(grDevices); require(graphics) filled.contour(volcano, color.palette = terrain.colors, asp = 1) title(main = "volcano data: filled contour map") ``` r None `lh` Luteinizing Hormone in Blood Samples ------------------------------------------ ### Description A regular time series giving the luteinizing hormone in blood samples at 10 mins intervals from a human female, 48 samples. ### Usage ``` lh ``` ### Source P.J. Diggle (1990) *Time Series: A Biostatistical Introduction.* Oxford, table A.1, series 3 r None `trees` Diameter, Height and Volume for Black Cherry Trees ----------------------------------------------------------- ### Description This data set provides measurements of the diameter, height and volume of timber in 31 felled black cherry trees. Note that the diameter (in inches) is erroneously labelled Girth in the data. It is measured at 4 ft 6 in above the ground. ### Usage ``` trees ``` ### Format A data frame with 31 observations on 3 variables. | | | | | | --- | --- | --- | --- | | `[,1]` | `Girth` | numeric | Tree diameter (rather than girth, actually) in inches | | `[,2]` | `Height` | numeric | Height in ft | | `[,3]` | `Volume` | numeric | Volume of timber in cubic ft | ### Source Ryan, T. A., Joiner, B. L. and Ryan, B. F. (1976) *The Minitab Student Handbook*. Duxbury Press. ### References Atkinson, A. C. (1985) *Plots, Transformations and Regression*. Oxford University Press. ### Examples ``` require(stats); require(graphics) pairs(trees, panel = panel.smooth, main = "trees data") plot(Volume ~ Girth, data = trees, log = "xy") coplot(log(Volume) ~ log(Girth) | Height, data = trees, panel = panel.smooth) summary(fm1 <- lm(log(Volume) ~ log(Girth), data = trees)) summary(fm2 <- update(fm1, ~ . + log(Height), data = trees)) step(fm2) ## i.e., Volume ~= c * Height * Girth^2 seems reasonable ``` r None `faithful` Old Faithful Geyser Data ------------------------------------ ### Description Waiting time between eruptions and the duration of the eruption for the Old Faithful geyser in Yellowstone National Park, Wyoming, USA. ### Usage ``` faithful ``` ### Format A data frame with 272 observations on 2 variables. | | | | | | --- | --- | --- | --- | | [,1] | eruptions | numeric | Eruption time in mins | | [,2] | waiting | numeric | Waiting time to next eruption (in mins) | | | ### Details A closer look at `faithful$eruptions` reveals that these are heavily rounded times originally in seconds, where multiples of 5 are more frequent than expected under non-human measurement. For a better version of the eruption times, see the example below. There are many versions of this dataset around: Azzalini and Bowman (1990) use a more complete version. ### Source W. Härdle. ### References Härdle, W. (1991). *Smoothing Techniques with Implementation in S*. New York: Springer. Azzalini, A. and Bowman, A. W. (1990). A look at some data on the Old Faithful geyser. *Applied Statistics*, **39**, 357–365. doi: [10.2307/2347385](https://doi.org/10.2307/2347385). ### See Also `geyser` in package [MASS](https://CRAN.R-project.org/package=MASS) for the Azzalini–Bowman version. ### Examples ``` require(stats); require(graphics) f.tit <- "faithful data: Eruptions of Old Faithful" ne60 <- round(e60 <- 60 * faithful$eruptions) all.equal(e60, ne60) # relative diff. ~ 1/10000 table(zapsmall(abs(e60 - ne60))) # 0, 0.02 or 0.04 faithful$better.eruptions <- ne60 / 60 te <- table(ne60) te[te >= 4] # (too) many multiples of 5 ! plot(names(te), te, type = "h", main = f.tit, xlab = "Eruption time (sec)") plot(faithful[, -3], main = f.tit, xlab = "Eruption time (min)", ylab = "Waiting time to next eruption (min)") lines(lowess(faithful$eruptions, faithful$waiting, f = 2/3, iter = 3), col = "red") ``` r None `longley` Longley's Economic Regression Data --------------------------------------------- ### Description A macroeconomic data set which provides a well-known example for a highly collinear regression. ### Usage ``` longley ``` ### Format A data frame with 7 economical variables, observed yearly from 1947 to 1962 (*n=16*). `GNP.deflator` GNP implicit price deflator (*1954=100*) `GNP` Gross National Product. `Unemployed` number of unemployed. `Armed.Forces` number of people in the armed forces. `Population` ‘noninstitutionalized’ population *≥* 14 years of age. `Year` the year (time). `Employed` number of people employed. The regression `lm(Employed ~ .)` is known to be highly collinear. ### Source J. W. Longley (1967) An appraisal of least-squares programs from the point of view of the user. *Journal of the American Statistical Association* **62**, 819–841. ### References Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) *The New S Language*. Wadsworth & Brooks/Cole. ### Examples ``` require(stats); require(graphics) ## give the data set in the form it is used in S-PLUS: longley.x <- data.matrix(longley[, 1:6]) longley.y <- longley[, "Employed"] pairs(longley, main = "longley data") summary(fm1 <- lm(Employed ~ ., data = longley)) opar <- par(mfrow = c(2, 2), oma = c(0, 0, 1.1, 0), mar = c(4.1, 4.1, 2.1, 1.1)) plot(fm1) par(opar) ``` r None `datasets-package` The R Datasets Package ------------------------------------------ ### Description Base R datasets ### Details This package contains a variety of datasets. For a complete list, use `library(help = "datasets")`. ### Author(s) R Core Team and contributors worldwide Maintainer: R Core Team [[email protected]](mailto:[email protected]) r None `precip` Annual Precipitation in US Cities ------------------------------------------- ### Description The average amount of precipitation (rainfall) in inches for each of 70 United States (and Puerto Rico) cities. ### Usage ``` precip ``` ### Format A named vector of length 70. ### Note The dataset version up to Nov.16, 2016 had a typo in `"Cincinnati"`'s name. The examples show how to recreate that version. ### Source Statistical Abstracts of the United States, 1975. ### References McNeil, D. R. (1977) *Interactive Data Analysis*. New York: Wiley. ### Examples ``` require(graphics) dotchart(precip[order(precip)], main = "precip data") title(sub = "Average annual precipitation (in.)") ## Old ("wrong") version of dataset (just name change): precip.O <- local({ p <- precip; names(p)[names(p) == "Cincinnati"] <- "Cincinati" ; p }) stopifnot(all(precip == precip.O), match("Cincinnati", names(precip)) == 46, identical(names(precip)[-46], names(precip.O)[-46])) ``` r None `USArrests` Violent Crime Rates by US State -------------------------------------------- ### Description This data set contains statistics, in arrests per 100,000 residents for assault, murder, and rape in each of the 50 US states in 1973. Also given is the percent of the population living in urban areas. ### Usage ``` USArrests ``` ### Format A data frame with 50 observations on 4 variables. | | | | | | --- | --- | --- | --- | | [,1] | Murder | numeric | Murder arrests (per 100,000) | | [,2] | Assault | numeric | Assault arrests (per 100,000) | | [,3] | UrbanPop | numeric | Percent urban population | | [,4] | Rape | numeric | Rape arrests (per 100,000) | ### Note `USArrests` contains the data as in McNeil's monograph. For the `UrbanPop` percentages, a review of the table (No. 21) in the Statistical Abstracts 1975 reveals a transcription error for Maryland (and that McNeil used the same “round to even” rule that **R**'s `[round](../../base/html/round)()` uses), as found by Daniel S Coven (Arizona). See the example below on how to correct the error and improve accuracy for the ‘<n>.5’ percentages. ### Source World Almanac and Book of facts 1975. (Crime rates). Statistical Abstracts of the United States 1975, p.20, (Urban rates), possibly available as <https://books.google.ch/books?id=zl9qAAAAMAAJ&pg=PA20>. ### References McNeil, D. R. (1977) *Interactive Data Analysis*. New York: Wiley. ### See Also The `<state>` data sets. ### Examples ``` summary(USArrests) require(graphics) pairs(USArrests, panel = panel.smooth, main = "USArrests data") ## Difference between 'USArrests' and its correction USArrests["Maryland", "UrbanPop"] # 67 -- the transcription error UA.C <- USArrests UA.C["Maryland", "UrbanPop"] <- 76.6 ## also +/- 0.5 to restore the original <n>.5 percentages s5u <- c("Colorado", "Florida", "Mississippi", "Wyoming") s5d <- c("Nebraska", "Pennsylvania") UA.C[s5u, "UrbanPop"] <- UA.C[s5u, "UrbanPop"] + 0.5 UA.C[s5d, "UrbanPop"] <- UA.C[s5d, "UrbanPop"] - 0.5 ## ==> UA.C is now a *C*orrected version of USArrests ``` r None `sunspots` Monthly Sunspot Numbers, 1749–1983 ---------------------------------------------- ### Description Monthly mean relative sunspot numbers from 1749 to 1983. Collected at Swiss Federal Observatory, Zurich until 1960, then Tokyo Astronomical Observatory. ### Usage ``` sunspots ``` ### Format A time series of monthly data from 1749 to 1983. ### Source Andrews, D. F. and Herzberg, A. M. (1985) *Data: A Collection of Problems from Many Fields for the Student and Research Worker*. New York: Springer-Verlag. ### See Also `<sunspot.month>` has a longer (and a bit different) series, `<sunspot.year>` is a much shorter one. See there for getting more current sunspot numbers. ### Examples ``` require(graphics) plot(sunspots, main = "sunspots data", xlab = "Year", ylab = "Monthly sunspot numbers") ``` r None `OrchardSprays` Potency of Orchard Sprays ------------------------------------------ ### Description An experiment was conducted to assess the potency of various constituents of orchard sprays in repelling honeybees, using a Latin square design. ### Usage ``` OrchardSprays ``` ### Format A data frame with 64 observations on 4 variables. | | | | | | --- | --- | --- | --- | | [,1] | rowpos | numeric | Row of the design | | [,2] | colpos | numeric | Column of the design | | [,3] | treatment | factor | Treatment level | | [,4] | decrease | numeric | Response | ### Details Individual cells of dry comb were filled with measured amounts of lime sulphur emulsion in sucrose solution. Seven different concentrations of lime sulphur ranging from a concentration of 1/100 to 1/1,562,500 in successive factors of 1/5 were used as well as a solution containing no lime sulphur. The responses for the different solutions were obtained by releasing 100 bees into the chamber for two hours, and then measuring the decrease in volume of the solutions in the various cells. An *8 x 8* Latin square design was used and the treatments were coded as follows: | | | | --- | --- | | A | highest level of lime sulphur | | B | next highest level of lime sulphur | | . | | | . | | | . | | | G | lowest level of lime sulphur | | H | no lime sulphur | ### Source Finney, D. J. (1947) *Probit Analysis*. Cambridge. ### References McNeil, D. R. (1977) *Interactive Data Analysis*. New York: Wiley. ### Examples ``` require(graphics) pairs(OrchardSprays, main = "OrchardSprays data") ``` r None `BOD` Biochemical Oxygen Demand -------------------------------- ### Description The `BOD` data frame has 6 rows and 2 columns giving the biochemical oxygen demand versus time in an evaluation of water quality. ### Usage ``` BOD ``` ### Format This data frame contains the following columns: `Time` A numeric vector giving the time of the measurement (days). `demand` A numeric vector giving the biochemical oxygen demand (mg/l). ### Source Bates, D.M. and Watts, D.G. (1988), *Nonlinear Regression Analysis and Its Applications*, Wiley, Appendix A1.4. Originally from Marske (1967), *Biochemical Oxygen Demand Data Interpretation Using Sum of Squares Surface* M.Sc. Thesis, University of Wisconsin – Madison. ### Examples ``` require(stats) # simplest form of fitting a first-order model to these data fm1 <- nls(demand ~ A*(1-exp(-exp(lrc)*Time)), data = BOD, start = c(A = 20, lrc = log(.35))) coef(fm1) fm1 # using the plinear algorithm (trace o/p differs by platform) ## IGNORE_RDIFF_BEGIN fm2 <- nls(demand ~ (1-exp(-exp(lrc)*Time)), data = BOD, start = c(lrc = log(.35)), algorithm = "plinear", trace = TRUE) ## IGNORE_RDIFF_END # using a self-starting model fm3 <- nls(demand ~ SSasympOrig(Time, A, lrc), data = BOD) summary(fm3) ```
programming_docs
r None `swiss` Swiss Fertility and Socioeconomic Indicators (1888) Data ----------------------------------------------------------------- ### Description Standardized fertility measure and socio-economic indicators for each of 47 French-speaking provinces of Switzerland at about 1888. ### Usage ``` swiss ``` ### Format A data frame with 47 observations on 6 variables, *each* of which is in percent, i.e., in *[0, 100]*. | | | | | --- | --- | --- | | [,1] | Fertility | *Ig*, ‘common standardized fertility measure’ | | [,2] | Agriculture | % of males involved in agriculture as occupation | | [,3] | Examination | % draftees receiving highest mark on army examination | | [,4] | Education | % education beyond primary school for draftees. | | [,5] | Catholic | % ‘catholic’ (as opposed to ‘protestant’). | | [,6] | Infant.Mortality | live births who live less than 1 year. | All variables but ‘Fertility’ give proportions of the population. ### Details (paraphrasing Mosteller and Tukey): Switzerland, in 1888, was entering a period known as the *demographic transition*; i.e., its fertility was beginning to fall from the high level typical of underdeveloped countries. The data collected are for 47 French-speaking “provinces” at about 1888. Here, all variables are scaled to *[0, 100]*, where in the original, all but `"Catholic"` were scaled to *[0, 1]*. ### Note Files for all 182 districts in 1888 and other years have been available at <https://opr.princeton.edu/archive/pefp/switz.aspx>. They state that variables `Examination` and `Education` are averages for 1887, 1888 and 1889. ### Source Project “16P5”, pages 549–551 in Mosteller, F. and Tukey, J. W. (1977) *Data Analysis and Regression: A Second Course in Statistics*. Addison-Wesley, Reading Mass. indicating their source as “Data used by permission of Franice van de Walle. Office of Population Research, Princeton University, 1976. Unpublished data assembled under NICHD contract number No 1-HD-O-2077.” ### References Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) *The New S Language*. Wadsworth & Brooks/Cole. ### Examples ``` require(stats); require(graphics) pairs(swiss, panel = panel.smooth, main = "swiss data", col = 3 + (swiss$Catholic > 50)) summary(lm(Fertility ~ . , data = swiss)) ``` r None `USPersonalExpenditure` Personal Expenditure Data -------------------------------------------------- ### Description This data set consists of United States personal expenditures (in billions of dollars) in the categories; food and tobacco, household operation, medical and health, personal care, and private education for the years 1940, 1945, 1950, 1955 and 1960. ### Usage ``` USPersonalExpenditure ``` ### Format A matrix with 5 rows and 5 columns. ### Source The World Almanac and Book of Facts, 1962, page 756. ### References Tukey, J. W. (1977) *Exploratory Data Analysis*. Addison-Wesley. McNeil, D. R. (1977) *Interactive Data Analysis*. Wiley. ### Examples ``` require(stats) # for medpolish USPersonalExpenditure medpolish(log10(USPersonalExpenditure)) ``` r None `USJudgeRatings` Lawyers' Ratings of State Judges in the US Superior Court --------------------------------------------------------------------------- ### Description Lawyers' ratings of state judges in the US Superior Court. ### Usage ``` USJudgeRatings ``` ### Format A data frame containing 43 observations on 12 numeric variables. | | | | | --- | --- | --- | | [,1] | CONT | Number of contacts of lawyer with judge. | | [,2] | INTG | Judicial integrity. | | [,3] | DMNR | Demeanor. | | [,4] | DILG | Diligence. | | [,5] | CFMG | Case flow managing. | | [,6] | DECI | Prompt decisions. | | [,7] | PREP | Preparation for trial. | | [,8] | FAMI | Familiarity with law. | | [,9] | ORAL | Sound oral rulings. | | [,10] | WRIT | Sound written rulings. | | [,11] | PHYS | Physical ability. | | [,12] | RTEN | Worthy of retention. | ### Source New Haven Register, 14 January, 1977 (from John Hartigan). ### Examples ``` require(graphics) pairs(USJudgeRatings, main = "USJudgeRatings data") ``` r None `occupationalStatus` Occupational Status of Fathers and their Sons ------------------------------------------------------------------- ### Description Cross-classification of a sample of British males according to each subject's occupational status and his father's occupational status. ### Usage ``` occupationalStatus ``` ### Format A `[table](../../base/html/table)` of counts, with classifying factors `origin` (father's occupational status; levels `1:8`) and `destination` (son's occupational status; levels `1:8`). ### Source Goodman, L. A. (1979) Simple Models for the Analysis of Association in Cross-Classifications having Ordered Categories. *J. Am. Stat. Assoc.*, **74** (367), 537–552. The data set has been in package [gnm](https://CRAN.R-project.org/package=gnm) and been provided by the package authors. ### Examples ``` require(stats); require(graphics) plot(occupationalStatus) ## Fit a uniform association model separating diagonal effects Diag <- as.factor(diag(1:8)) Rscore <- scale(as.numeric(row(occupationalStatus)), scale = FALSE) Cscore <- scale(as.numeric(col(occupationalStatus)), scale = FALSE) modUnif <- glm(Freq ~ origin + destination + Diag + Rscore:Cscore, family = poisson, data = occupationalStatus) summary(modUnif) plot(modUnif) # 4 plots, with warning about h_ii ~= 1 ``` r None `Harman23.cor` Harman Example 2.3 ---------------------------------- ### Description A correlation matrix of eight physical measurements on 305 girls between ages seven and seventeen. ### Usage ``` Harman23.cor ``` ### Source Harman, H. H. (1976) *Modern Factor Analysis*, Third Edition Revised, University of Chicago Press, Table 2.3. ### Examples ``` require(stats) (Harman23.FA <- factanal(factors = 1, covmat = Harman23.cor)) for(factors in 2:4) print(update(Harman23.FA, factors = factors)) ``` r None `Loblolly` Growth of Loblolly pine trees ----------------------------------------- ### Description The `Loblolly` data frame has 84 rows and 3 columns of records of the growth of Loblolly pine trees. ### Usage ``` Loblolly ``` ### Format An object of class `c("nfnGroupedData", "nfGroupedData", "groupedData", "data.frame")` containing the following columns: height a numeric vector of tree heights (ft). age a numeric vector of tree ages (yr). Seed an ordered factor indicating the seed source for the tree. The ordering is according to increasing maximum height. ### Details This dataset was originally part of package `nlme`, and that has methods (including for `[`, `as.data.frame`, `plot` and `print`) for its grouped-data classes. ### Source Kung, F. H. (1986), Fitting logistic growth curve with predetermined carrying capacity, in *Proceedings of the Statistical Computing Section, American Statistical Association*, 340–343. Pinheiro, J. C. and Bates, D. M. (2000) *Mixed-effects Models in S and S-PLUS*, Springer. ### Examples ``` require(stats); require(graphics) plot(height ~ age, data = Loblolly, subset = Seed == 329, xlab = "Tree age (yr)", las = 1, ylab = "Tree height (ft)", main = "Loblolly data and fitted curve (Seed 329 only)") fm1 <- nls(height ~ SSasymp(age, Asym, R0, lrc), data = Loblolly, subset = Seed == 329) age <- seq(0, 30, length.out = 101) lines(age, predict(fm1, list(age = age))) ``` r None `Nile` Flow of the River Nile ------------------------------ ### Description Measurements of the annual flow of the river Nile at Aswan (formerly `Assuan`), 1871–1970, in *10^8 m^3*, “with apparent changepoint near 1898” (Cobb(1978), Table 1, p.249). ### Usage ``` Nile ``` ### Format A time series of length 100. ### Source Durbin, J. and Koopman, S. J. (2001). *Time Series Analysis by State Space Methods*. Oxford University Press. <http://www.ssfpack.com/DKbook.html> ### References Balke, N. S. (1993). Detecting level shifts in time series. *Journal of Business and Economic Statistics*, **11**, 81–92. doi: [10.2307/1391308](https://doi.org/10.2307/1391308). Cobb, G. W. (1978). The problem of the Nile: conditional solution to a change-point problem. *Biometrika* **65**, 243–51. doi: [10.2307/2335202](https://doi.org/10.2307/2335202). ### Examples ``` require(stats); require(graphics) par(mfrow = c(2, 2)) plot(Nile) acf(Nile) pacf(Nile) ar(Nile) # selects order 2 cpgram(ar(Nile)$resid) par(mfrow = c(1, 1)) arima(Nile, c(2, 0, 0)) ## Now consider missing values, following Durbin & Koopman NileNA <- Nile NileNA[c(21:40, 61:80)] <- NA arima(NileNA, c(2, 0, 0)) plot(NileNA) pred <- predict(arima(window(NileNA, 1871, 1890), c(2, 0, 0)), n.ahead = 20) lines(pred$pred, lty = 3, col = "red") lines(pred$pred + 2*pred$se, lty = 2, col = "blue") lines(pred$pred - 2*pred$se, lty = 2, col = "blue") pred <- predict(arima(window(NileNA, 1871, 1930), c(2, 0, 0)), n.ahead = 20) lines(pred$pred, lty = 3, col = "red") lines(pred$pred + 2*pred$se, lty = 2, col = "blue") lines(pred$pred - 2*pred$se, lty = 2, col = "blue") ## Structural time series models par(mfrow = c(3, 1)) plot(Nile) ## local level model (fit <- StructTS(Nile, type = "level")) lines(fitted(fit), lty = 2) # contemporaneous smoothing lines(tsSmooth(fit), lty = 2, col = 4) # fixed-interval smoothing plot(residuals(fit)); abline(h = 0, lty = 3) ## local trend model (fit2 <- StructTS(Nile, type = "trend")) ## constant trend fitted pred <- predict(fit, n.ahead = 30) ## with 50% confidence interval ts.plot(Nile, pred$pred, pred$pred + 0.67*pred$se, pred$pred -0.67*pred$se) ## Now consider missing values plot(NileNA) (fit3 <- StructTS(NileNA, type = "level")) lines(fitted(fit3), lty = 2) lines(tsSmooth(fit3), lty = 3) plot(residuals(fit3)); abline(h = 0, lty = 3) ``` r None `HairEyeColor` Hair and Eye Color of Statistics Students --------------------------------------------------------- ### Description Distribution of hair and eye color and sex in 592 statistics students. ### Usage ``` HairEyeColor ``` ### Format A 3-dimensional array resulting from cross-tabulating 592 observations on 3 variables. The variables and their levels are as follows: | | | | | --- | --- | --- | | No | Name | Levels | | 1 | Hair | Black, Brown, Red, Blond | | 2 | Eye | Brown, Blue, Hazel, Green | | 3 | Sex | Male, Female | ### Details The Hair *x* Eye table comes from a survey of students at the University of Delaware reported by Snee (1974). The split by `Sex` was added by Friendly (1992a) for didactic purposes. This data set is useful for illustrating various techniques for the analysis of contingency tables, such as the standard chi-squared test or, more generally, log-linear modelling, and graphical methods such as mosaic plots, sieve diagrams or association plots. ### Source <http://www.datavis.ca/sas/vcd/catdata/haireye.sas> Snee (1974) gives the two-way table aggregated over `Sex`. The `Sex` split of the ‘Brown hair, Brown eye’ cell was changed to agree with that used by Friendly (2000). ### References Snee, R. D. (1974). Graphical display of two-way contingency tables. *The American Statistician*, **28**, 9–12. doi: [10.2307/2683520](https://doi.org/10.2307/2683520). Friendly, M. (1992a). Graphical methods for categorical data. *SAS User Group International Conference Proceedings*, **17**, 190–200. <http://datavis.ca/papers/sugi/sugi17.pdf> Friendly, M. (1992b). Mosaic displays for loglinear models. *Proceedings of the Statistical Graphics Section*, American Statistical Association, pp. 61–68. <http://www.datavis.ca/papers/asa92.html> Friendly, M. (2000). *Visualizing Categorical Data*. SAS Institute, ISBN 1-58025-660-0. ### See Also `[chisq.test](../../stats/html/chisq.test)`, `[loglin](../../stats/html/loglin)`, `[mosaicplot](../../graphics/html/mosaicplot)` ### Examples ``` require(graphics) ## Full mosaic mosaicplot(HairEyeColor) ## Aggregate over sex (as in Snee's original data) x <- apply(HairEyeColor, c(1, 2), sum) x mosaicplot(x, main = "Relation between hair and eye color") ``` r None `Formaldehyde` Determination of Formaldehyde --------------------------------------------- ### Description These data are from a chemical experiment to prepare a standard curve for the determination of formaldehyde by the addition of chromatropic acid and concentrated sulphuric acid and the reading of the resulting purple color on a spectrophotometer. ### Usage ``` Formaldehyde ``` ### Format A data frame with 6 observations on 2 variables. | | | | | | --- | --- | --- | --- | | [,1] | carb | numeric | Carbohydrate (ml) | | [,2] | optden | numeric | Optical Density | ### Source Bennett, N. A. and N. L. Franklin (1954) *Statistical Analysis in Chemistry and the Chemical Industry*. New York: Wiley. ### References McNeil, D. R. (1977) *Interactive Data Analysis.* New York: Wiley. ### Examples ``` require(stats); require(graphics) plot(optden ~ carb, data = Formaldehyde, xlab = "Carbohydrate (ml)", ylab = "Optical Density", main = "Formaldehyde data", col = 4, las = 1) abline(fm1 <- lm(optden ~ carb, data = Formaldehyde)) summary(fm1) opar <- par(mfrow = c(2, 2), oma = c(0, 0, 1.1, 0)) plot(fm1) par(opar) ``` r None `DNase` Elisa assay of DNase ----------------------------- ### Description The `DNase` data frame has 176 rows and 3 columns of data obtained during development of an ELISA assay for the recombinant protein DNase in rat serum. ### Usage ``` DNase ``` ### Format An object of class `c("nfnGroupedData", "nfGroupedData", "groupedData", "data.frame")` containing the following columns: Run an ordered factor with levels `10` < ... < `3` indicating the assay run. conc a numeric vector giving the known concentration of the protein. density a numeric vector giving the measured optical density (dimensionless) in the assay. Duplicate optical density measurements were obtained. ### Details This dataset was originally part of package `nlme`, and that has methods (including for `[`, `as.data.frame`, `plot` and `print`) for its grouped-data classes. ### Source Davidian, M. and Giltinan, D. M. (1995) *Nonlinear Models for Repeated Measurement Data*, Chapman & Hall (section 5.2.4, p. 134) Pinheiro, J. C. and Bates, D. M. (2000) *Mixed-effects Models in S and S-PLUS*, Springer. ### Examples ``` require(stats); require(graphics) coplot(density ~ conc | Run, data = DNase, show.given = FALSE, type = "b") coplot(density ~ log(conc) | Run, data = DNase, show.given = FALSE, type = "b") ## fit a representative run fm1 <- nls(density ~ SSlogis( log(conc), Asym, xmid, scal ), data = DNase, subset = Run == 1) ## compare with a four-parameter logistic fm2 <- nls(density ~ SSfpl( log(conc), A, B, xmid, scal ), data = DNase, subset = Run == 1) summary(fm2) anova(fm1, fm2) ``` r None `JohnsonJohnson` Quarterly Earnings per Johnson & Johnson Share ---------------------------------------------------------------- ### Description Quarterly earnings (dollars) per Johnson & Johnson share 1960–80. ### Usage ``` JohnsonJohnson ``` ### Format A quarterly time series ### Source Shumway, R. H. and Stoffer, D. S. (2000) *Time Series Analysis and its Applications*. Second Edition. Springer. Example 1.1. ### Examples ``` require(stats); require(graphics) JJ <- log10(JohnsonJohnson) plot(JJ) ## This example gives a possible-non-convergence warning on some ## platforms, but does seem to converge on x86 Linux and Windows. (fit <- StructTS(JJ, type = "BSM")) tsdiag(fit) sm <- tsSmooth(fit) plot(cbind(JJ, sm[, 1], sm[, 3]-0.5), plot.type = "single", col = c("black", "green", "blue")) abline(h = -0.5, col = "grey60") monthplot(fit) ``` r None `Orange` Growth of Orange Trees -------------------------------- ### Description The `Orange` data frame has 35 rows and 3 columns of records of the growth of orange trees. ### Usage ``` Orange ``` ### Format An object of class `c("nfnGroupedData", "nfGroupedData", "groupedData", "data.frame")` containing the following columns: Tree an ordered factor indicating the tree on which the measurement is made. The ordering is according to increasing maximum diameter. age a numeric vector giving the age of the tree (days since 1968/12/31) circumference a numeric vector of trunk circumferences (mm). This is probably “circumference at breast height”, a standard measurement in forestry. ### Details This dataset was originally part of package `nlme`, and that has methods (including for `[`, `as.data.frame`, `plot` and `print`) for its grouped-data classes. ### Source Draper, N. R. and Smith, H. (1998), *Applied Regression Analysis (3rd ed)*, Wiley (exercise 24.N). Pinheiro, J. C. and Bates, D. M. (2000) *Mixed-effects Models in S and S-PLUS*, Springer. ### Examples ``` require(stats); require(graphics) coplot(circumference ~ age | Tree, data = Orange, show.given = FALSE) fm1 <- nls(circumference ~ SSlogis(age, Asym, xmid, scal), data = Orange, subset = Tree == 3) plot(circumference ~ age, data = Orange, subset = Tree == 3, xlab = "Tree age (days since 1968/12/31)", ylab = "Tree circumference (mm)", las = 1, main = "Orange tree data and fitted model (Tree 3 only)") age <- seq(0, 1600, length.out = 101) lines(age, predict(fm1, list(age = age))) ``` r None `beavers` Body Temperature Series of Two Beavers ------------------------------------------------- ### Description Reynolds (1994) describes a small part of a study of the long-term temperature dynamics of beaver *Castor canadensis* in north-central Wisconsin. Body temperature was measured by telemetry every 10 minutes for four females, but data from a one period of less than a day for each of two animals is used there. ### Usage ``` beaver1 beaver2 ``` ### Format The `beaver1` data frame has 114 rows and 4 columns on body temperature measurements at 10 minute intervals. The `beaver2` data frame has 100 rows and 4 columns on body temperature measurements at 10 minute intervals. The variables are as follows: day Day of observation (in days since the beginning of 1990), December 12–13 (`beaver1`) and November 3–4 (`beaver2`). time Time of observation, in the form `0330` for 3:30am temp Measured body temperature in degrees Celsius. activ Indicator of activity outside the retreat. ### Note The observation at 22:20 is missing in `beaver1`. ### Source P. S. Reynolds (1994) Time-series analyses of beaver body temperatures. Chapter 11 of Lange, N., Ryan, L., Billard, L., Brillinger, D., Conquest, L. and Greenhouse, J. eds (1994) *Case Studies in Biometry.* New York: John Wiley and Sons. ### Examples ``` require(graphics) (yl <- range(beaver1$temp, beaver2$temp)) beaver.plot <- function(bdat, ...) { nam <- deparse(substitute(bdat)) with(bdat, { # Hours since start of day: hours <- time %/% 100 + 24*(day - day[1]) + (time %% 100)/60 plot (hours, temp, type = "l", ..., main = paste(nam, "body temperature")) abline(h = 37.5, col = "gray", lty = 2) is.act <- activ == 1 points(hours[is.act], temp[is.act], col = 2, cex = .8) }) } op <- par(mfrow = c(2, 1), mar = c(3, 3, 4, 2), mgp = 0.9 * 2:0) beaver.plot(beaver1, ylim = yl) beaver.plot(beaver2, ylim = yl) par(op) ``` r None `discoveries` Yearly Numbers of Important Discoveries ------------------------------------------------------ ### Description The numbers of “great” inventions and scientific discoveries in each year from 1860 to 1959. ### Usage ``` discoveries ``` ### Format A time series of 100 values. ### Source The World Almanac and Book of Facts, 1975 Edition, pages 315–318. ### References McNeil, D. R. (1977) *Interactive Data Analysis*. Wiley. ### Examples ``` require(graphics) plot(discoveries, ylab = "Number of important discoveries", las = 1) title(main = "discoveries data set") ```
programming_docs
r None `AirPassengers` Monthly Airline Passenger Numbers 1949-1960 ------------------------------------------------------------ ### Description The classic Box & Jenkins airline data. Monthly totals of international airline passengers, 1949 to 1960. ### Usage ``` AirPassengers ``` ### Format A monthly time series, in thousands. ### Source Box, G. E. P., Jenkins, G. M. and Reinsel, G. C. (1976) *Time Series Analysis, Forecasting and Control.* Third Edition. Holden-Day. Series G. ### Examples ``` ## Not run: ## These are quite slow and so not run by example(AirPassengers) ## The classic 'airline model', by full ML (fit <- arima(log10(AirPassengers), c(0, 1, 1), seasonal = list(order = c(0, 1, 1), period = 12))) update(fit, method = "CSS") update(fit, x = window(log10(AirPassengers), start = 1954)) pred <- predict(fit, n.ahead = 24) tl <- pred$pred - 1.96 * pred$se tu <- pred$pred + 1.96 * pred$se ts.plot(AirPassengers, 10^tl, 10^tu, log = "y", lty = c(1, 2, 2)) ## full ML fit is the same if the series is reversed, CSS fit is not ap0 <- rev(log10(AirPassengers)) attributes(ap0) <- attributes(AirPassengers) arima(ap0, c(0, 1, 1), seasonal = list(order = c(0, 1, 1), period = 12)) arima(ap0, c(0, 1, 1), seasonal = list(order = c(0, 1, 1), period = 12), method = "CSS") ## Structural Time Series ap <- log10(AirPassengers) - 2 (fit <- StructTS(ap, type = "BSM")) par(mfrow = c(1, 2)) plot(cbind(ap, fitted(fit)), plot.type = "single") plot(cbind(ap, tsSmooth(fit)), plot.type = "single") ## End(Not run) ``` r None `cars` Speed and Stopping Distances of Cars -------------------------------------------- ### Description The data give the speed of cars and the distances taken to stop. Note that the data were recorded in the 1920s. ### Usage ``` cars ``` ### Format A data frame with 50 observations on 2 variables. | | | | | | --- | --- | --- | --- | | [,1] | speed | numeric | Speed (mph) | | [,2] | dist | numeric | Stopping distance (ft) | ### Source Ezekiel, M. (1930) *Methods of Correlation Analysis*. Wiley. ### References McNeil, D. R. (1977) *Interactive Data Analysis*. Wiley. ### Examples ``` require(stats); require(graphics) plot(cars, xlab = "Speed (mph)", ylab = "Stopping distance (ft)", las = 1) lines(lowess(cars$speed, cars$dist, f = 2/3, iter = 3), col = "red") title(main = "cars data") plot(cars, xlab = "Speed (mph)", ylab = "Stopping distance (ft)", las = 1, log = "xy") title(main = "cars data (logarithmic scales)") lines(lowess(cars$speed, cars$dist, f = 2/3, iter = 3), col = "red") summary(fm1 <- lm(log(dist) ~ log(speed), data = cars)) opar <- par(mfrow = c(2, 2), oma = c(0, 0, 1.1, 0), mar = c(4.1, 4.1, 2.1, 1.1)) plot(fm1) par(opar) ## An example of polynomial regression plot(cars, xlab = "Speed (mph)", ylab = "Stopping distance (ft)", las = 1, xlim = c(0, 25)) d <- seq(0, 25, length.out = 200) for(degree in 1:4) { fm <- lm(dist ~ poly(speed, degree), data = cars) assign(paste("cars", degree, sep = "."), fm) lines(d, predict(fm, data.frame(speed = d)), col = degree) } anova(cars.1, cars.2, cars.3, cars.4) ``` r None `rock` Measurements on Petroleum Rock Samples ---------------------------------------------- ### Description Measurements on 48 rock samples from a petroleum reservoir. ### Usage ``` rock ``` ### Format A data frame with 48 rows and 4 numeric columns. | | | | | --- | --- | --- | | [,1] | area | area of pores space, in pixels out of 256 by 256 | | [,2] | peri | perimeter in pixels | | [,3] | shape | perimeter/sqrt(area) | | [,4] | perm | permeability in milli-Darcies | ### Details Twelve core samples from petroleum reservoirs were sampled by 4 cross-sections. Each core sample was measured for permeability, and each cross-section has total area of pores, total perimeter of pores, and shape. ### Source Data from BP Research, image analysis by Ronit Katz, U. Oxford. r None `WorldPhones` The World's Telephones ------------------------------------- ### Description The number of telephones in various regions of the world (in thousands). ### Usage ``` WorldPhones ``` ### Format A matrix with 7 rows and 8 columns. The columns of the matrix give the figures for a given region, and the rows the figures for a year. The regions are: North America, Europe, Asia, South America, Oceania, Africa, Central America. The years are: 1951, 1956, 1957, 1958, 1959, 1960, 1961. ### Source AT&T (1961) *The World's Telephones*. ### References McNeil, D. R. (1977) *Interactive Data Analysis*. New York: Wiley. ### Examples ``` require(graphics) matplot(rownames(WorldPhones), WorldPhones, type = "b", log = "y", xlab = "Year", ylab = "Number of telephones (1000's)") legend(1951.5, 80000, colnames(WorldPhones), col = 1:6, lty = 1:5, pch = rep(21, 7)) title(main = "World phones data: log scale for response") ``` r None `ToothGrowth` The Effect of Vitamin C on Tooth Growth in Guinea Pigs --------------------------------------------------------------------- ### Description The response is the length of odontoblasts (cells responsible for tooth growth) in 60 guinea pigs. Each animal received one of three dose levels of vitamin C (0.5, 1, and 2 mg/day) by one of two delivery methods, orange juice or ascorbic acid (a form of vitamin C and coded as `VC`). ### Usage ``` ToothGrowth ``` ### Format A data frame with 60 observations on 3 variables. | | | | | | --- | --- | --- | --- | | [,1] | len | numeric | Tooth length | | [,2] | supp | factor | Supplement type (VC or OJ). | | [,3] | dose | numeric | Dose in milligrams/day | ### Source C. I. Bliss (1952). *The Statistics of Bioassay*. Academic Press. ### References McNeil, D. R. (1977). *Interactive Data Analysis*. New York: Wiley. Crampton, E. W. (1947). The growth of the odontoblast of the incisor teeth as a criterion of vitamin C intake of the guinea pig. *The Journal of Nutrition*, **33**(5), 491–504. doi: [10.1093/jn/33.5.491](https://doi.org/10.1093/jn/33.5.491). ### Examples ``` require(graphics) coplot(len ~ dose | supp, data = ToothGrowth, panel = panel.smooth, xlab = "ToothGrowth data: length vs dose, given type of supplement") ``` r None `mtcars` Motor Trend Car Road Tests ------------------------------------ ### Description The data was extracted from the 1974 *Motor Trend* US magazine, and comprises fuel consumption and 10 aspects of automobile design and performance for 32 automobiles (1973–74 models). ### Usage ``` mtcars ``` ### Format A data frame with 32 observations on 11 (numeric) variables. | | | | | --- | --- | --- | | [, 1] | mpg | Miles/(US) gallon | | [, 2] | cyl | Number of cylinders | | [, 3] | disp | Displacement (cu.in.) | | [, 4] | hp | Gross horsepower | | [, 5] | drat | Rear axle ratio | | [, 6] | wt | Weight (1000 lbs) | | [, 7] | qsec | 1/4 mile time | | [, 8] | vs | Engine (0 = V-shaped, 1 = straight) | | [, 9] | am | Transmission (0 = automatic, 1 = manual) | | [,10] | gear | Number of forward gears | | [,11] | carb | Number of carburetors | ### Note Henderson and Velleman (1981) comment in a footnote to Table 1: ‘Hocking [original transcriber]'s noncrucial coding of the Mazda's rotary engine as a straight six-cylinder engine and the Porsche's flat engine as a V engine, as well as the inclusion of the diesel Mercedes 240D, have been retained to enable direct comparisons to be made with previous analyses.’ ### Source Henderson and Velleman (1981), Building multiple regression models interactively. *Biometrics*, **37**, 391–411. ### Examples ``` require(graphics) pairs(mtcars, main = "mtcars data", gap = 1/4) coplot(mpg ~ disp | as.factor(cyl), data = mtcars, panel = panel.smooth, rows = 1) ## possibly more meaningful, e.g., for summary() or bivariate plots: mtcars2 <- within(mtcars, { vs <- factor(vs, labels = c("V", "S")) am <- factor(am, labels = c("automatic", "manual")) cyl <- ordered(cyl) gear <- ordered(gear) carb <- ordered(carb) }) summary(mtcars2) ``` r None `airmiles` Passenger Miles on Commercial US Airlines, 1937–1960 ---------------------------------------------------------------- ### Description The revenue passenger miles flown by commercial airlines in the United States for each year from 1937 to 1960. ### Usage ``` airmiles ``` ### Format A time series of 24 observations; yearly, 1937–1960. ### Source F.A.A. Statistical Handbook of Aviation. ### References Brown, R. G. (1963) *Smoothing, Forecasting and Prediction of Discrete Time Series*. Prentice-Hall. ### Examples ``` require(graphics) plot(airmiles, main = "airmiles data", xlab = "Passenger-miles flown by U.S. commercial airlines", col = 4) ``` r None `morley` Michelson Speed of Light Data --------------------------------------- ### Description A classical data of Michelson (but not this one with Morley) on measurements done in 1879 on the speed of light. The data consists of five experiments, each consisting of 20 consecutive ‘runs’. The response is the speed of light measurement, suitably coded (km/sec, with `299000` subtracted). ### Usage ``` morley ``` ### Format A data frame with 100 observations on the following 3 variables. `Expt` The experiment number, from 1 to 5. `Run` The run number within each experiment. `Speed` Speed-of-light measurement. ### Details The data is here viewed as a randomized block experiment with ‘experiment’ and ‘run’ as the factors. ‘run’ may also be considered a quantitative variate to account for linear (or polynomial) changes in the measurement over the course of a single experiment. ### Note This is the same dataset as `michelson` in package [MASS](https://CRAN.R-project.org/package=MASS). ### Source A. J. Weekes (1986) *A Genstat Primer*. London: Edward Arnold. S. M. Stigler (1977) Do robust estimators work with real data? *Annals of Statistics* **5**, 1055–1098. (See Table 6.) A. A. Michelson (1882) Experimental determination of the velocity of light made at the United States Naval Academy, Annapolis. *Astronomic Papers* **1** 135–8. U.S. Nautical Almanac Office. (See Table 24.) ### Examples ``` require(stats); require(graphics) michelson <- transform(morley, Expt = factor(Expt), Run = factor(Run)) xtabs(~ Expt + Run, data = michelson) # 5 x 20 balanced (two-way) plot(Speed ~ Expt, data = michelson, main = "Speed of Light Data", xlab = "Experiment No.") fm <- aov(Speed ~ Run + Expt, data = michelson) summary(fm) fm0 <- update(fm, . ~ . - Run) anova(fm0, fm) ``` r None `attitude` The Chatterjee–Price Attitude Data ---------------------------------------------- ### Description From a survey of the clerical employees of a large financial organization, the data are aggregated from the questionnaires of the approximately 35 employees for each of 30 (randomly selected) departments. The numbers give the percent proportion of favourable responses to seven questions in each department. ### Usage ``` attitude ``` ### Format A data frame with 30 observations on 7 variables. The first column are the short names from the reference, the second one the variable names in the data frame: | | | | | | --- | --- | --- | --- | | Y | rating | numeric | Overall rating | | X[1] | complaints | numeric | Handling of employee complaints | | X[2] | privileges | numeric | Does not allow special privileges | | X[3] | learning | numeric | Opportunity to learn | | X[4] | raises | numeric | Raises based on performance | | X[5] | critical | numeric | Too critical | | X[6] | advancel | numeric | Advancement | ### Source Chatterjee, S. and Price, B. (1977) *Regression Analysis by Example*. New York: Wiley. (Section 3.7, p.68ff of 2nd ed.(1991).) ### Examples ``` require(stats); require(graphics) pairs(attitude, main = "attitude data") summary(attitude) summary(fm1 <- lm(rating ~ ., data = attitude)) opar <- par(mfrow = c(2, 2), oma = c(0, 0, 1.1, 0), mar = c(4.1, 4.1, 2.1, 1.1)) plot(fm1) summary(fm2 <- lm(rating ~ complaints, data = attitude)) plot(fm2) par(opar) ``` r None `UKDriverDeaths` Road Casualties in Great Britain 1969–84 ---------------------------------------------------------- ### Description `UKDriverDeaths` is a time series giving the monthly totals of car drivers in Great Britain killed or seriously injured Jan 1969 to Dec 1984. Compulsory wearing of seat belts was introduced on 31 Jan 1983. `Seatbelts` is more information on the same problem. ### Usage ``` UKDriverDeaths Seatbelts ``` ### Format `Seatbelts` is a multiple time series, with columns `DriversKilled` car drivers killed. `drivers` same as `UKDriverDeaths`. `front` front-seat passengers killed or seriously injured. `rear` rear-seat passengers killed or seriously injured. `kms` distance driven. `PetrolPrice` petrol price. `VanKilled` number of van (‘light goods vehicle’) drivers. `law` 0/1: was the law in effect that month? ### Source Harvey, A.C. (1989). *Forecasting, Structural Time Series Models and the Kalman Filter*. Cambridge University Press, pp. 519–523. Durbin, J. and Koopman, S. J. (2001). *Time Series Analysis by State Space Methods*. Oxford University Press. <http://www.ssfpack.com/dkbook/> ### References Harvey, A. C. and Durbin, J. (1986). The effects of seat belt legislation on British road casualties: A case study in structural time series modelling. *Journal of the Royal Statistical Society* series A, **149**, 187–227. doi: [10.2307/2981553](https://doi.org/10.2307/2981553). ### Examples ``` require(stats); require(graphics) ## work with pre-seatbelt period to identify a model, use logs work <- window(log10(UKDriverDeaths), end = 1982+11/12) par(mfrow = c(3, 1)) plot(work); acf(work); pacf(work) par(mfrow = c(1, 1)) (fit <- arima(work, c(1, 0, 0), seasonal = list(order = c(1, 0, 0)))) z <- predict(fit, n.ahead = 24) ts.plot(log10(UKDriverDeaths), z$pred, z$pred+2*z$se, z$pred-2*z$se, lty = c(1, 3, 2, 2), col = c("black", "red", "blue", "blue")) ## now see the effect of the explanatory variables X <- Seatbelts[, c("kms", "PetrolPrice", "law")] X[, 1] <- log10(X[, 1]) - 4 arima(log10(Seatbelts[, "drivers"]), c(1, 0, 0), seasonal = list(order = c(1, 0, 0)), xreg = X) ``` r None `npk` Classical N, P, K Factorial Experiment --------------------------------------------- ### Description A classical N, P, K (nitrogen, phosphate, potassium) factorial experiment on the growth of peas conducted on 6 blocks. Each half of a fractional factorial design confounding the NPK interaction was used on 3 of the plots. ### Usage ``` npk ``` ### Format The `npk` data frame has 24 rows and 5 columns: `block` which block (label 1 to 6). `N` indicator (0/1) for the application of nitrogen. `P` indicator (0/1) for the application of phosphate. `K` indicator (0/1) for the application of potassium. `yield` Yield of peas, in pounds/plot (the plots were (1/70) acre). ### Source Imperial College, London, M.Sc. exercise sheet. ### References Venables, W. N. and Ripley, B. D. (2002) *Modern Applied Statistics with S.* Fourth edition. Springer. ### Examples ``` options(contrasts = c("contr.sum", "contr.poly")) npk.aov <- aov(yield ~ block + N*P*K, npk) npk.aov summary(npk.aov) coef(npk.aov) options(contrasts = c("contr.treatment", "contr.poly")) npk.aov1 <- aov(yield ~ block + N + K, data = npk) summary.lm(npk.aov1) se.contrast(npk.aov1, list(N=="0", N=="1"), data = npk) model.tables(npk.aov1, type = "means", se = TRUE) ``` r None `zCO2` Carbon Dioxide Uptake in Grass Plants --------------------------------------------- ### Description The `CO2` data frame has 84 rows and 5 columns of data from an experiment on the cold tolerance of the grass species *Echinochloa crus-galli*. ### Usage ``` CO2 ``` ### Format An object of class `c("nfnGroupedData", "nfGroupedData", "groupedData", "data.frame")` containing the following columns: Plant an ordered factor with levels `Qn1` < `Qn2` < `Qn3` < ... < `Mc1` giving a unique identifier for each plant. Type a factor with levels `Quebec` `Mississippi` giving the origin of the plant Treatment a factor with levels `nonchilled` `chilled` conc a numeric vector of ambient carbon dioxide concentrations (mL/L). uptake a numeric vector of carbon dioxide uptake rates (*umol/m^2* sec). ### Details The *CO2* uptake of six plants from Quebec and six plants from Mississippi was measured at several levels of ambient *CO2* concentration. Half the plants of each type were chilled overnight before the experiment was conducted. This dataset was originally part of package `nlme`, and that has methods (including for `[`, `as.data.frame`, `plot` and `print`) for its grouped-data classes. ### Source Potvin, C., Lechowicz, M. J. and Tardif, S. (1990) “The statistical analysis of ecophysiological response curves obtained from experiments involving repeated measures”, *Ecology*, **71**, 1389–1400. Pinheiro, J. C. and Bates, D. M. (2000) *Mixed-effects Models in S and S-PLUS*, Springer. ### Examples ``` require(stats); require(graphics) coplot(uptake ~ conc | Plant, data = CO2, show.given = FALSE, type = "b") ## fit the data for the first plant fm1 <- nls(uptake ~ SSasymp(conc, Asym, lrc, c0), data = CO2, subset = Plant == "Qn1") summary(fm1) ## fit each plant separately fmlist <- list() for (pp in levels(CO2$Plant)) { fmlist[[pp]] <- nls(uptake ~ SSasymp(conc, Asym, lrc, c0), data = CO2, subset = Plant == pp) } ## check the coefficients by plant print(sapply(fmlist, coef), digits = 3) ``` r None `euro` Conversion Rates of Euro Currencies ------------------------------------------- ### Description Conversion rates between the various Euro currencies. ### Usage ``` euro euro.cross ``` ### Format `euro` is a named vector of length 11, `euro.cross` a matrix of size 11 by 11, with dimnames. ### Details The data set `euro` contains the value of 1 Euro in all currencies participating in the European monetary union (Austrian Schilling ATS, Belgian Franc BEF, German Mark DEM, Spanish Peseta ESP, Finnish Markka FIM, French Franc FRF, Irish Punt IEP, Italian Lira ITL, Luxembourg Franc LUF, Dutch Guilder NLG and Portuguese Escudo PTE). These conversion rates were fixed by the European Union on December 31, 1998. To convert old prices to Euro prices, divide by the respective rate and round to 2 digits. The data set `euro.cross` contains conversion rates between the various Euro currencies, i.e., the result of `outer(1 / euro, euro)`. ### Examples ``` cbind(euro) ## These relations hold: euro == signif(euro, 6) # [6 digit precision in Euro's definition] all(euro.cross == outer(1/euro, euro)) ## Convert 20 Euro to Belgian Franc 20 * euro["BEF"] ## Convert 20 Austrian Schilling to Euro 20 / euro["ATS"] ## Convert 20 Spanish Pesetas to Italian Lira 20 * euro.cross["ESP", "ITL"] require(graphics) dotchart(euro, main = "euro data: 1 Euro in currency unit") dotchart(1/euro, main = "euro data: 1 currency unit in Euros") dotchart(log(euro, 10), main = "euro data: log10(1 Euro in currency unit)") ``` r None `UKgas` UK Quarterly Gas Consumption ------------------------------------- ### Description Quarterly UK gas consumption from 1960Q1 to 1986Q4, in millions of therms. ### Usage ``` UKgas ``` ### Format A quarterly time series of length 108. ### Source Durbin, J. and Koopman, S. J. (2001) *Time Series Analysis by State Space Methods.* Oxford University Press. <http://www.ssfpack.com/dkbook/> ### Examples ``` ## maybe str(UKgas) ; plot(UKgas) ... ```
programming_docs
r None `sleep` Student's Sleep Data ----------------------------- ### Description Data which show the effect of two soporific drugs (increase in hours of sleep compared to control) on 10 patients. ### Usage ``` sleep ``` ### Format A data frame with 20 observations on 3 variables. | | | | | | --- | --- | --- | --- | | [, 1] | extra | numeric | increase in hours of sleep | | [, 2] | group | factor | drug given | | [, 3] | ID | factor | patient ID | ### Details The `group` variable name may be misleading about the data: They represent measurements on 10 persons, not in groups. ### Source Cushny, A. R. and Peebles, A. R. (1905) The action of optical isomers: II hyoscines. *The Journal of Physiology* **32**, 501–510. Student (1908) The probable error of the mean. *Biometrika*, **6**, 20. ### References Scheffé, Henry (1959) *The Analysis of Variance*. New York, NY: Wiley. ### Examples ``` require(stats) ## Student's paired t-test with(sleep, t.test(extra[group == 1], extra[group == 2], paired = TRUE)) ## The sleep *prolongations* sleep1 <- with(sleep, extra[group == 2] - extra[group == 1]) summary(sleep1) stripchart(sleep1, method = "stack", xlab = "hours", main = "Sleep prolongation (n = 10)") boxplot(sleep1, horizontal = TRUE, add = TRUE, at = .6, pars = list(boxwex = 0.5, staplewex = 0.25)) ``` r None `WWWusage` Internet Usage per Minute ------------------------------------- ### Description A time series of the numbers of users connected to the Internet through a server every minute. ### Usage ``` WWWusage ``` ### Format A time series of length 100. ### Source Durbin, J. and Koopman, S. J. (2001) *Time Series Analysis by State Space Methods.* Oxford University Press. <http://www.ssfpack.com/dkbook/> ### References Makridakis, S., Wheelwright, S. C. and Hyndman, R. J. (1998) *Forecasting: Methods and Applications.* Wiley. ### Examples ``` require(graphics) work <- diff(WWWusage) par(mfrow = c(2, 1)); plot(WWWusage); plot(work) ## Not run: require(stats) aics <- matrix(, 6, 6, dimnames = list(p = 0:5, q = 0:5)) for(q in 1:5) aics[1, 1+q] <- arima(WWWusage, c(0, 1, q), optim.control = list(maxit = 500))$aic for(p in 1:5) for(q in 0:5) aics[1+p, 1+q] <- arima(WWWusage, c(p, 1, q), optim.control = list(maxit = 500))$aic round(aics - min(aics, na.rm = TRUE), 2) ## End(Not run) ``` r None `Puromycin` Reaction Velocity of an Enzymatic Reaction ------------------------------------------------------- ### Description The `Puromycin` data frame has 23 rows and 3 columns of the reaction velocity versus substrate concentration in an enzymatic reaction involving untreated cells or cells treated with Puromycin. ### Usage ``` Puromycin ``` ### Format This data frame contains the following columns: `conc` a numeric vector of substrate concentrations (ppm) `rate` a numeric vector of instantaneous reaction rates (counts/min/min) `state` a factor with levels `treated` `untreated` ### Details Data on the velocity of an enzymatic reaction were obtained by Treloar (1974). The number of counts per minute of radioactive product from the reaction was measured as a function of substrate concentration in parts per million (ppm) and from these counts the initial rate (or velocity) of the reaction was calculated (counts/min/min). The experiment was conducted once with the enzyme treated with Puromycin, and once with the enzyme untreated. ### Source Bates, D.M. and Watts, D.G. (1988), *Nonlinear Regression Analysis and Its Applications*, Wiley, Appendix A1.3. Treloar, M. A. (1974), *Effects of Puromycin on Galactosyltransferase in Golgi Membranes*, M.Sc. Thesis, U. of Toronto. ### See Also `[SSmicmen](../../stats/html/ssmicmen)` for other models fitted to this dataset. ### Examples ``` require(stats); require(graphics) plot(rate ~ conc, data = Puromycin, las = 1, xlab = "Substrate concentration (ppm)", ylab = "Reaction velocity (counts/min/min)", pch = as.integer(Puromycin$state), col = as.integer(Puromycin$state), main = "Puromycin data and fitted Michaelis-Menten curves") ## simplest form of fitting the Michaelis-Menten model to these data fm1 <- nls(rate ~ Vm * conc/(K + conc), data = Puromycin, subset = state == "treated", start = c(Vm = 200, K = 0.05)) fm2 <- nls(rate ~ Vm * conc/(K + conc), data = Puromycin, subset = state == "untreated", start = c(Vm = 160, K = 0.05)) summary(fm1) summary(fm2) ## add fitted lines to the plot conc <- seq(0, 1.2, length.out = 101) lines(conc, predict(fm1, list(conc = conc)), lty = 1, col = 1) lines(conc, predict(fm2, list(conc = conc)), lty = 2, col = 2) legend(0.8, 120, levels(Puromycin$state), col = 1:2, lty = 1:2, pch = 1:2) ## using partial linearity fm3 <- nls(rate ~ conc/(K + conc), data = Puromycin, subset = state == "treated", start = c(K = 0.05), algorithm = "plinear") ``` r None `chickwts` Chicken Weights by Feed Type ---------------------------------------- ### Description An experiment was conducted to measure and compare the effectiveness of various feed supplements on the growth rate of chickens. ### Usage ``` chickwts ``` ### Format A data frame with 71 observations on the following 2 variables. `weight` a numeric variable giving the chick weight. `feed` a factor giving the feed type. ### Details Newly hatched chicks were randomly allocated into six groups, and each group was given a different feed supplement. Their weights in grams after six weeks are given along with feed types. ### Source Anonymous (1948) *Biometrika*, **35**, 214. ### References McNeil, D. R. (1977) *Interactive Data Analysis*. New York: Wiley. ### Examples ``` require(stats); require(graphics) boxplot(weight ~ feed, data = chickwts, col = "lightgray", varwidth = TRUE, notch = TRUE, main = "chickwt data", ylab = "Weight at six weeks (gm)") anova(fm1 <- lm(weight ~ feed, data = chickwts)) opar <- par(mfrow = c(2, 2), oma = c(0, 0, 1.1, 0), mar = c(4.1, 4.1, 2.1, 1.1)) plot(fm1) par(opar) ``` r None `Titanic` Survival of passengers on the Titanic ------------------------------------------------ ### Description This data set provides information on the fate of passengers on the fatal maiden voyage of the ocean liner ‘Titanic’, summarized according to economic status (class), sex, age and survival. ### Usage ``` Titanic ``` ### Format A 4-dimensional array resulting from cross-tabulating 2201 observations on 4 variables. The variables and their levels are as follows: | | | | | --- | --- | --- | | No | Name | Levels | | 1 | Class | 1st, 2nd, 3rd, Crew | | 2 | Sex | Male, Female | | 3 | Age | Child, Adult | | 4 | Survived | No, Yes | ### Details The sinking of the Titanic is a famous event, and new books are still being published about it. Many well-known facts—from the proportions of first-class passengers to the ‘women and children first’ policy, and the fact that that policy was not entirely successful in saving the women and children in the third class—are reflected in the survival rates for various classes of passenger. These data were originally collected by the British Board of Trade in their investigation of the sinking. Note that there is not complete agreement among primary sources as to the exact numbers on board, rescued, or lost. Due in particular to the very successful film ‘Titanic’, the last years saw a rise in public interest in the Titanic. Very detailed data about the passengers is now available on the Internet, at sites such as *Encyclopedia Titanica* (<https://www.encyclopedia-titanica.org/>). ### Source Dawson, Robert J. MacG. (1995), The ‘Unusual Episode’ Data Revisited. *Journal of Statistics Education*, **3**. doi: [10.1080/10691898.1995.11910499](https://doi.org/10.1080/10691898.1995.11910499). The source provides a data set recording class, sex, age, and survival status for each person on board of the Titanic, and is based on data originally collected by the British Board of Trade and reprinted in: British Board of Trade (1990), *Report on the Loss of the ‘Titanic’ (S.S.)*. British Board of Trade Inquiry Report (reprint). Gloucester, UK: Allan Sutton Publishing. ### Examples ``` require(graphics) mosaicplot(Titanic, main = "Survival on the Titanic") ## Higher survival rates in children? apply(Titanic, c(3, 4), sum) ## Higher survival rates in females? apply(Titanic, c(2, 4), sum) ## Use loglm() in package 'MASS' for further analysis ... ``` r None `VADeaths` Death Rates in Virginia (1940) ------------------------------------------ ### Description Death rates per 1000 in Virginia in 1940. ### Usage ``` VADeaths ``` ### Format A matrix with 5 rows and 4 columns. ### Details The death rates are measured per 1000 population per year. They are cross-classified by age group (rows) and population group (columns). The age groups are: 50–54, 55–59, 60–64, 65–69, 70–74 and the population groups are Rural/Male, Rural/Female, Urban/Male and Urban/Female. This provides a rather nice 3-way analysis of variance example. ### Source Molyneaux, L., Gilliam, S. K., and Florant, L. C.(1947) Differences in Virginia death rates by color, sex, age, and rural or urban residence. *American Sociological Review*, **12**, 525–535. ### References McNeil, D. R. (1977) *Interactive Data Analysis*. Wiley. ### Examples ``` require(stats); require(graphics) n <- length(dr <- c(VADeaths)) nam <- names(VADeaths) d.VAD <- data.frame( Drate = dr, age = rep(ordered(rownames(VADeaths)), length.out = n), gender = gl(2, 5, n, labels = c("M", "F")), site = gl(2, 10, labels = c("rural", "urban"))) coplot(Drate ~ as.numeric(age) | gender * site, data = d.VAD, panel = panel.smooth, xlab = "VADeaths data - Given: gender") summary(aov.VAD <- aov(Drate ~ .^2, data = d.VAD)) opar <- par(mfrow = c(2, 2), oma = c(0, 0, 1.1, 0)) plot(aov.VAD) par(opar) ``` r None `USAccDeaths` Accidental Deaths in the US 1973–1978 ---------------------------------------------------- ### Description A time series giving the monthly totals of accidental deaths in the USA. The values for the first six months of 1979 are 7798 7406 8363 8460 9217 9316. ### Usage ``` USAccDeaths ``` ### Source P. J. Brockwell and R. A. Davis (1991) *Time Series: Theory and Methods.* Springer, New York. r None `attenu` The Joyner–Boore Attenuation Data ------------------------------------------- ### Description This data gives peak accelerations measured at various observation stations for 23 earthquakes in California. The data have been used by various workers to estimate the attenuating affect of distance on ground acceleration. ### Usage ``` attenu ``` ### Format A data frame with 182 observations on 5 variables. | | | | | | --- | --- | --- | --- | | [,1] | event | numeric | Event Number | | [,2] | mag | numeric | Moment Magnitude | | [,3] | station | factor | Station Number | | [,4] | dist | numeric | Station-hypocenter distance (km) | | [,5] | accel | numeric | Peak acceleration (g) | ### Source Joyner, W.B., D.M. Boore and R.D. Porcella (1981). Peak horizontal acceleration and velocity from strong-motion records including records from the 1979 Imperial Valley, California earthquake. USGS Open File report 81-365. Menlo Park, Ca. ### References Boore, D. M. and Joyner, W. B.(1982). The empirical prediction of ground motion, *Bulletin of the Seismological Society of America*, **72**, S269–S268. Bolt, B. A. and Abrahamson, N. A. (1982). New attenuation relations for peak and expected accelerations of strong ground motion. *Bulletin of the Seismological Society of America*, **72**, 2307–2321. Bolt B. A. and Abrahamson, N. A. (1983). Reply to W. B. Joyner & D. M. Boore's “Comments on: New attenuation relations for peak and expected accelerations for peak and expected accelerations of strong ground motion”, *Bulletin of the Seismological Society of America*, **73**, 1481–1483. Brillinger, D. R. and Preisler, H. K. (1984). An exploratory analysis of the Joyner-Boore attenuation data, *Bulletin of the Seismological Society of America*, **74**, 1441–1449. Brillinger, D. R. and Preisler, H. K. (1984). *Further analysis of the Joyner-Boore attenuation data*. Manuscript. ### Examples ``` require(graphics) ## check the data class of the variables sapply(attenu, data.class) summary(attenu) pairs(attenu, main = "attenu data") coplot(accel ~ dist | as.factor(event), data = attenu, show.given = FALSE) coplot(log(accel) ~ log(dist) | as.factor(event), data = attenu, panel = panel.smooth, show.given = FALSE) ``` r None `uspop` Populations Recorded by the US Census ---------------------------------------------- ### Description This data set gives the population of the United States (in millions) as recorded by the decennial census for the period 1790–1970. ### Usage ``` uspop ``` ### Format A time series of 19 values. ### Source McNeil, D. R. (1977) *Interactive Data Analysis*. New York: Wiley. ### Examples ``` require(graphics) plot(uspop, log = "y", main = "uspop data", xlab = "Year", ylab = "U.S. Population (millions)") ``` r None `quakes` Locations of Earthquakes off Fiji ------------------------------------------- ### Description The data set give the locations of 1000 seismic events of MB > 4.0. The events occurred in a cube near Fiji since 1964. ### Usage ``` quakes ``` ### Format A data frame with 1000 observations on 5 variables. | | | | | | --- | --- | --- | --- | | [,1] | lat | numeric | Latitude of event | | [,2] | long | numeric | Longitude | | [,3] | depth | numeric | Depth (km) | | [,4] | mag | numeric | Richter Magnitude | | [,5] | stations | numeric | Number of stations reporting | ### Details There are two clear planes of seismic activity. One is a major plate junction; the other is the Tonga trench off New Zealand. These data constitute a subsample from a larger dataset of containing 5000 observations. ### Source This is one of the Harvard PRIM-H project data sets. They in turn obtained it from Dr. John Woodhouse, Dept. of Geophysics, Harvard University. ### Examples ``` require(graphics) pairs(quakes, main = "Fiji Earthquakes, N = 1000", cex.main = 1.2, pch = ".") ``` r None `airquality` New York Air Quality Measurements ----------------------------------------------- ### Description Daily air quality measurements in New York, May to September 1973. ### Usage ``` airquality ``` ### Format A data frame with 153 observations on 6 variables. | | | | | | --- | --- | --- | --- | | `[,1]` | `Ozone` | numeric | Ozone (ppb) | | `[,2]` | `Solar.R` | numeric | Solar R (lang) | | `[,3]` | `Wind` | numeric | Wind (mph) | | `[,4]` | `Temp` | numeric | Temperature (degrees F) | | `[,5]` | `Month` | numeric | Month (1--12) | | `[,6]` | `Day` | numeric | Day of month (1--31) | ### Details Daily readings of the following air quality values for May 1, 1973 (a Tuesday) to September 30, 1973. * `Ozone`: Mean ozone in parts per billion from 1300 to 1500 hours at Roosevelt Island * `Solar.R`: Solar radiation in Langleys in the frequency band 4000–7700 Angstroms from 0800 to 1200 hours at Central Park * `Wind`: Average wind speed in miles per hour at 0700 and 1000 hours at LaGuardia Airport * `Temp`: Maximum daily temperature in degrees Fahrenheit at La Guardia Airport. ### Source The data were obtained from the New York State Department of Conservation (ozone data) and the National Weather Service (meteorological data). ### References Chambers, J. M., Cleveland, W. S., Kleiner, B. and Tukey, P. A. (1983) *Graphical Methods for Data Analysis*. Belmont, CA: Wadsworth. ### Examples ``` require(graphics) pairs(airquality, panel = panel.smooth, main = "airquality data") ``` r None `ability.cov` Ability and Intelligence Tests --------------------------------------------- ### Description Six tests were given to 112 individuals. The covariance matrix is given in this object. ### Usage ``` ability.cov ``` ### Details The tests are described as general: a non-verbal measure of general intelligence using Cattell's culture-fair test. picture: a picture-completion test blocks: block design maze: mazes reading: reading comprehension vocab: vocabulary Bartholomew gives both covariance and correlation matrices, but these are inconsistent. Neither are in the original paper. ### Source Bartholomew, D. J. (1987). *Latent Variable Analysis and Factor Analysis*. Griffin. Bartholomew, D. J. and Knott, M. (1990). *Latent Variable Analysis and Factor Analysis*. Second Edition, Arnold. ### References Smith, G. A. and Stanley G. (1983). Clocking *g*: relating intelligence and measures of timed performance. *Intelligence*, **7**, 353–368. doi: [10.1016/0160-2896(83)90010-7](https://doi.org/10.1016/0160-2896(83)90010-7). ### Examples ``` require(stats) (ability.FA <- factanal(factors = 1, covmat = ability.cov)) update(ability.FA, factors = 2) ## The signs of factors and hence the signs of correlations are ## arbitrary with promax rotation. update(ability.FA, factors = 2, rotation = "promax") ``` r None `state` US State Facts and Figures ----------------------------------- ### Description Data sets related to the 50 states of the United States of America. ### Usage ``` state.abb state.area state.center state.division state.name state.region state.x77 ``` ### Details **R** currently contains the following “state” data sets. Note that all data are arranged according to alphabetical order of the state names. `state.abb`: character vector of 2-letter abbreviations for the state names. `state.area`: numeric vector of state areas (in square miles). `state.center`: list with components named `x` and `y` giving the approximate geographic center of each state in negative longitude and latitude. Alaska and Hawaii are placed just off the West Coast. `state.division`: factor giving state divisions (New England, Middle Atlantic, South Atlantic, East South Central, West South Central, East North Central, West North Central, Mountain, and Pacific). `state.name`: character vector giving the full state names. `state.region`: factor giving the region (Northeast, South, North Central, West) that each state belongs to. `state.x77`: matrix with 50 rows and 8 columns giving the following statistics in the respective columns. `Population`: population estimate as of July 1, 1975 `Income`: per capita income (1974) `Illiteracy`: illiteracy (1970, percent of population) `Life Exp`: life expectancy in years (1969–71) `Murder`: murder and non-negligent manslaughter rate per 100,000 population (1976) `HS Grad`: percent high-school graduates (1970) `Frost`: mean number of days with minimum temperature below freezing (1931–1960) in capital or large city `Area`: land area in square miles ### Source U.S. Department of Commerce, Bureau of the Census (1977) *Statistical Abstract of the United States*. U.S. Department of Commerce, Bureau of the Census (1977) *County and City Data Book*. ### References Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) *The New S Language*. Wadsworth & Brooks/Cole. r None `co2` Mauna Loa Atmospheric CO2 Concentration ---------------------------------------------- ### Description Atmospheric concentrations of CO*2* are expressed in parts per million (ppm) and reported in the preliminary 1997 SIO manometric mole fraction scale. ### Usage ``` co2 ``` ### Format A time series of 468 observations; monthly from 1959 to 1997. ### Details The values for February, March and April of 1964 were missing and have been obtained by interpolating linearly between the values for January and May of 1964. ### Source Keeling, C. D. and Whorf, T. P., Scripps Institution of Oceanography (SIO), University of California, La Jolla, California USA 92093-0220. <https://scrippsco2.ucsd.edu/data/atmospheric_co2/>. Note that the data are subject to revision (based on recalibration of standard gases) by the Scripps institute, and hence may not agree exactly with the data provided by **R**. ### References Cleveland, W. S. (1993) *Visualizing Data*. New Jersey: Summit Press. ### Examples ``` require(graphics) plot(co2, ylab = expression("Atmospheric concentration of CO"[2]), las = 1) title(main = "co2 data set") ```
programming_docs
r None `sunspot.year` Yearly Sunspot Data, 1700–1988 ---------------------------------------------- ### Description Yearly numbers of sunspots from 1700 to 1988 (rounded to one digit). Note that monthly numbers are available as `<sunspot.month>`, though starting slightly later. ### Usage ``` sunspot.year ``` ### Format The univariate time series `sunspot.year` contains 289 observations, and is of class `"ts"`. ### Source H. Tong (1996) *Non-Linear Time Series*. Clarendon Press, Oxford, p. 471. ### See Also For *monthly* sunspot numbers, see `<sunspot.month>` and `<sunspots>`. Regularly updated yearly sunspot numbers are available from WDC-SILSO, Royal Observatory of Belgium, at <http://www.sidc.be/silso/datafiles> ### Examples ``` utils::str(sm <- sunspots)# the monthly version we keep unchanged utils::str(sy <- sunspot.year) ## The common time interval (t1 <- c(max(start(sm), start(sy)), 1)) # Jan 1749 (t2 <- c(min( end(sm)[1],end(sy)[1]), 12)) # Dec 1983 s.m <- window(sm, start=t1, end=t2) s.y <- window(sy, start=t1, end=t2[1]) # {irrelevant warning} stopifnot(length(s.y) * 12 == length(s.m), ## The yearly series *is* close to the averages of the monthly one: all.equal(s.y, aggregate(s.m, FUN = mean), tolerance = 0.0020)) ## NOTE: Strangely, correctly weighting the number of days per month ## (using 28.25 for February) is *not* closer than the simple mean: ndays <- c(31, 28.25, rep(c(31,30, 31,30, 31), 2)) all.equal(s.y, aggregate(s.m, FUN = mean)) # 0.0013 all.equal(s.y, aggregate(s.m, FUN = weighted.mean, w = ndays)) # 0.0017 ``` r None `LifeCycleSavings` Intercountry Life-Cycle Savings Data -------------------------------------------------------- ### Description Data on the savings ratio 1960–1970. ### Usage ``` LifeCycleSavings ``` ### Format A data frame with 50 observations on 5 variables. | | | | | | --- | --- | --- | --- | | [,1] | sr | numeric | aggregate personal savings | | [,2] | pop15 | numeric | % of population under 15 | | [,3] | pop75 | numeric | % of population over 75 | | [,4] | dpi | numeric | real per-capita disposable income | | [,5] | ddpi | numeric | % growth rate of dpi | ### Details Under the life-cycle savings hypothesis as developed by Franco Modigliani, the savings ratio (aggregate personal saving divided by disposable income) is explained by per-capita disposable income, the percentage rate of change in per-capita disposable income, and two demographic variables: the percentage of population less than 15 years old and the percentage of the population over 75 years old. The data are averaged over the decade 1960–1970 to remove the business cycle or other short-term fluctuations. ### Source The data were obtained from Belsley, Kuh and Welsch (1980). They in turn obtained the data from Sterling (1977). ### References Sterling, Arnie (1977) Unpublished BS Thesis. Massachusetts Institute of Technology. Belsley, D. A., Kuh. E. and Welsch, R. E. (1980) *Regression Diagnostics*. New York: Wiley. ### Examples ``` require(stats); require(graphics) pairs(LifeCycleSavings, panel = panel.smooth, main = "LifeCycleSavings data") fm1 <- lm(sr ~ pop15 + pop75 + dpi + ddpi, data = LifeCycleSavings) summary(fm1) ``` r None `UCBAdmissions` Student Admissions at UC Berkeley -------------------------------------------------- ### Description Aggregate data on applicants to graduate school at Berkeley for the six largest departments in 1973 classified by admission and sex. ### Usage ``` UCBAdmissions ``` ### Format A 3-dimensional array resulting from cross-tabulating 4526 observations on 3 variables. The variables and their levels are as follows: | | | | | --- | --- | --- | | No | Name | Levels | | 1 | Admit | Admitted, Rejected | | 2 | Gender | Male, Female | | 3 | Dept | A, B, C, D, E, F | ### Details This data set is frequently used for illustrating Simpson's paradox, see Bickel *et al* (1975). At issue is whether the data show evidence of sex bias in admission practices. There were 2691 male applicants, of whom 1198 (44.5%) were admitted, compared with 1835 female applicants of whom 557 (30.4%) were admitted. This gives a sample odds ratio of 1.83, indicating that males were almost twice as likely to be admitted. In fact, graphical methods (as in the example below) or log-linear modelling show that the apparent association between admission and sex stems from differences in the tendency of males and females to apply to the individual departments (females used to apply *more* to departments with higher rejection rates). This data set can also be used for illustrating methods for graphical display of categorical data, such as the general-purpose [mosaicplot](../../graphics/html/mosaicplot) or the [fourfoldplot](../../graphics/html/fourfoldplot) for 2-by-2-by-*k* tables. ### References Bickel, P. J., Hammel, E. A., and O'Connell, J. W. (1975). Sex bias in graduate admissions: Data from Berkeley. *Science*, **187**, 398–403. doi: [10.1126/science.187.4175.398](https://doi.org/10.1126/science.187.4175.398). <https://www.jstor.org/stable/1739581>. ### Examples ``` require(graphics) ## Data aggregated over departments apply(UCBAdmissions, c(1, 2), sum) mosaicplot(apply(UCBAdmissions, c(1, 2), sum), main = "Student admissions at UC Berkeley") ## Data for individual departments opar <- par(mfrow = c(2, 3), oma = c(0, 0, 2, 0)) for(i in 1:6) mosaicplot(UCBAdmissions[,,i], xlab = "Admit", ylab = "Sex", main = paste("Department", LETTERS[i])) mtext(expression(bold("Student admissions at UC Berkeley")), outer = TRUE, cex = 1.5) par(opar) ``` r None `islands` Areas of the World's Major Landmasses ------------------------------------------------ ### Description The areas in thousands of square miles of the landmasses which exceed 10,000 square miles. ### Usage ``` islands ``` ### Format A named vector of length 48. ### Source The World Almanac and Book of Facts, 1975, page 406. ### References McNeil, D. R. (1977) *Interactive Data Analysis*. Wiley. ### Examples ``` require(graphics) dotchart(log(islands, 10), main = "islands data: log10(area) (log10(sq. miles))") dotchart(log(islands[order(islands)], 10), main = "islands data: log10(area) (log10(sq. miles))") ``` r None `pressure` Vapor Pressure of Mercury as a Function of Temperature ------------------------------------------------------------------ ### Description Data on the relation between temperature in degrees Celsius and vapor pressure of mercury in millimeters (of mercury). ### Usage ``` pressure ``` ### Format A data frame with 19 observations on 2 variables. | | | | | | --- | --- | --- | --- | | [, 1] | temperature | numeric | temperature (deg C) | | [, 2] | pressure | numeric | pressure (mm) | ### Source Weast, R. C., ed. (1973) *Handbook of Chemistry and Physics*. CRC Press. ### References McNeil, D. R. (1977) *Interactive Data Analysis*. New York: Wiley. ### Examples ``` require(graphics) plot(pressure, xlab = "Temperature (deg C)", ylab = "Pressure (mm of Hg)", main = "pressure data: Vapor Pressure of Mercury") plot(pressure, xlab = "Temperature (deg C)", log = "y", ylab = "Pressure (mm of Hg)", main = "pressure data: Vapor Pressure of Mercury") ``` r None `austres` Quarterly Time Series of the Number of Australian Residents ---------------------------------------------------------------------- ### Description Numbers (in thousands) of Australian residents measured quarterly from March 1971 to March 1994. The object is of class `"ts"`. ### Usage ``` austres ``` ### Source P. J. Brockwell and R. A. Davis (1996) *Introduction to Time Series and Forecasting.* Springer r None `anscombe` Anscombe's Quartet of ‘Identical’ Simple Linear Regressions ----------------------------------------------------------------------- ### Description Four *x*-*y* datasets which have the same traditional statistical properties (mean, variance, correlation, regression line, etc.), yet are quite different. ### Usage ``` anscombe ``` ### Format A data frame with 11 observations on 8 variables. | | | | --- | --- | | x1 == x2 == x3 | the integers 4:14, specially arranged | | x4 | values 8 and 19 | | y1, y2, y3, y4 | numbers in (3, 12.5) with mean 7.5 and sdev 2.03 | ### Source Tufte, Edward R. (1989). *The Visual Display of Quantitative Information*, 13–14. Graphics Press. ### References Anscombe, Francis J. (1973). Graphs in statistical analysis. *The American Statistician*, **27**, 17–21. doi: [10.2307/2682899](https://doi.org/10.2307/2682899). ### Examples ``` require(stats); require(graphics) summary(anscombe) ##-- now some "magic" to do the 4 regressions in a loop: ff <- y ~ x mods <- setNames(as.list(1:4), paste0("lm", 1:4)) for(i in 1:4) { ff[2:3] <- lapply(paste0(c("y","x"), i), as.name) ## or ff[[2]] <- as.name(paste0("y", i)) ## ff[[3]] <- as.name(paste0("x", i)) mods[[i]] <- lmi <- lm(ff, data = anscombe) print(anova(lmi)) } ## See how close they are (numerically!) sapply(mods, coef) lapply(mods, function(fm) coef(summary(fm))) ## Now, do what you should have done in the first place: PLOTS op <- par(mfrow = c(2, 2), mar = 0.1+c(4,4,1,1), oma = c(0, 0, 2, 0)) for(i in 1:4) { ff[2:3] <- lapply(paste0(c("y","x"), i), as.name) plot(ff, data = anscombe, col = "red", pch = 21, bg = "orange", cex = 1.2, xlim = c(3, 19), ylim = c(3, 13)) abline(mods[[i]], col = "blue") } mtext("Anscombe's 4 Regression data sets", outer = TRUE, cex = 1.5) par(op) ``` r None `EuStockMarkets` Daily Closing Prices of Major European Stock Indices, 1991–1998 --------------------------------------------------------------------------------- ### Description Contains the daily closing prices of major European stock indices: Germany DAX (Ibis), Switzerland SMI, France CAC, and UK FTSE. The data are sampled in business time, i.e., weekends and holidays are omitted. ### Usage ``` EuStockMarkets ``` ### Format A multivariate time series with 1860 observations on 4 variables. The object is of class `"mts"`. ### Source The data were kindly provided by Erste Bank AG, Vienna, Austria. r None `nottem` Average Monthly Temperatures at Nottingham, 1920–1939 --------------------------------------------------------------- ### Description A time series object containing average air temperatures at Nottingham Castle in degrees Fahrenheit for 20 years. ### Usage ``` nottem ``` ### Source Anderson, O. D. (1976) *Time Series Analysis and Forecasting: The Box-Jenkins approach.* Butterworths. Series R. ### Examples ``` require(stats); require(graphics) nott <- window(nottem, end = c(1936,12)) fit <- arima(nott, order = c(1,0,0), list(order = c(2,1,0), period = 12)) nott.fore <- predict(fit, n.ahead = 36) ts.plot(nott, nott.fore$pred, nott.fore$pred+2*nott.fore$se, nott.fore$pred-2*nott.fore$se, gpars = list(col = c(1,1,4,4))) ``` r None `esoph` Smoking, Alcohol and (O)esophageal Cancer -------------------------------------------------- ### Description Data from a case-control study of (o)esophageal cancer in Ille-et-Vilaine, France. ### Usage ``` esoph ``` ### Format A data frame with records for 88 age/alcohol/tobacco combinations. | | | | | | --- | --- | --- | --- | | [,1] | "agegp" | Age group | 1 25--34 years | | | | | 2 35--44 | | | | | 3 45--54 | | | | | 4 55--64 | | | | | 5 65--74 | | | | | 6 75+ | | [,2] | "alcgp" | Alcohol consumption | 1 0--39 gm/day | | | | | 2 40--79 | | | | | 3 80--119 | | | | | 4 120+ | | [,3] | "tobgp" | Tobacco consumption | 1 0-- 9 gm/day | | | | | 2 10--19 | | | | | 3 20--29 | | | | | 4 30+ | | [,4] | "ncases" | Number of cases | | | [,5] | "ncontrols" | Number of controls | | ### Author(s) Thomas Lumley ### Source Breslow, N. E. and Day, N. E. (1980) *Statistical Methods in Cancer Research. Volume 1: The Analysis of Case-Control Studies.* IARC Lyon / Oxford University Press. ### Examples ``` require(stats) require(graphics) # for mosaicplot summary(esoph) ## effects of alcohol, tobacco and interaction, age-adjusted model1 <- glm(cbind(ncases, ncontrols) ~ agegp + tobgp * alcgp, data = esoph, family = binomial()) anova(model1) ## Try a linear effect of alcohol and tobacco model2 <- glm(cbind(ncases, ncontrols) ~ agegp + unclass(tobgp) + unclass(alcgp), data = esoph, family = binomial()) summary(model2) ## Re-arrange data for a mosaic plot ttt <- table(esoph$agegp, esoph$alcgp, esoph$tobgp) o <- with(esoph, order(tobgp, alcgp, agegp)) ttt[ttt == 1] <- esoph$ncases[o] tt1 <- table(esoph$agegp, esoph$alcgp, esoph$tobgp) tt1[tt1 == 1] <- esoph$ncontrols[o] tt <- array(c(ttt, tt1), c(dim(ttt),2), c(dimnames(ttt), list(c("Cancer", "control")))) mosaicplot(tt, main = "esoph data set", color = TRUE) ``` r None `Harman74.cor` Harman Example 7.4 ---------------------------------- ### Description A correlation matrix of 24 psychological tests given to 145 seventh and eight-grade children in a Chicago suburb by Holzinger and Swineford. ### Usage ``` Harman74.cor ``` ### Source Harman, H. H. (1976) *Modern Factor Analysis*, Third Edition Revised, University of Chicago Press, Table 7.4. ### Examples ``` require(stats) (Harman74.FA <- factanal(factors = 1, covmat = Harman74.cor)) for(factors in 2:5) print(update(Harman74.FA, factors = factors)) Harman74.FA <- factanal(factors = 5, covmat = Harman74.cor, rotation = "promax") print(Harman74.FA$loadings, sort = TRUE) ``` r None `multinom` Fit Multinomial Log-linear Models --------------------------------------------- ### Description Fits multinomial log-linear models via neural networks. ### Usage ``` multinom(formula, data, weights, subset, na.action, contrasts = NULL, Hess = FALSE, summ = 0, censored = FALSE, model = FALSE, ...) ``` ### Arguments | | | | --- | --- | | `formula` | a formula expression as for regression models, of the form `response ~ predictors`. The response should be a factor or a matrix with K columns, which will be interpreted as counts for each of K classes. A log-linear model is fitted, with coefficients zero for the first class. An offset can be included: it should be a numeric matrix with K columns if the response is either a matrix with K columns or a factor with K >= 2 classes, or a numeric vector for a response factor with 2 levels. See the documentation of `[formula](../../stats/html/formula)()` for other details. | | `data` | an optional data frame in which to interpret the variables occurring in `formula`. | | `weights` | optional case weights in fitting. | | `subset` | expression saying which subset of the rows of the data should be used in the fit. All observations are included by default. | | `na.action` | a function to filter missing data. | | `contrasts` | a list of contrasts to be used for some or all of the factors appearing as variables in the model formula. | | `Hess` | logical for whether the Hessian (the observed/expected information matrix) should be returned. | | `summ` | integer; if non-zero summarize by deleting duplicate rows and adjust weights. Methods 1 and 2 differ in speed (2 uses `C`); method 3 also combines rows with the same X and different Y, which changes the baseline for the deviance. | | `censored` | If Y is a matrix with `K` columns, interpret the entries as one for possible classes, zero for impossible classes, rather than as counts. | | `model` | logical. If true, the model frame is saved as component `model` of the returned object. | | `...` | additional arguments for `nnet` | ### Details `multinom` calls `<nnet>`. The variables on the rhs of the formula should be roughly scaled to [0,1] or the fit will be slow or may not converge at all. ### Value A `nnet` object with additional components: | | | | --- | --- | | `deviance` | the residual deviance, compared to the full saturated model (that explains individual observations exactly). Also, minus twice log-likelihood. | | `edf` | the (effective) number of degrees of freedom used by the model | | `AIC` | the AIC for this fit. | | `Hessian` | (if `Hess` is true). | | `model` | (if `model` is true). | ### References Venables, W. N. and Ripley, B. D. (2002) *Modern Applied Statistics with S.* Fourth edition. Springer. ### See Also `<nnet>` ### Examples ``` oc <- options(contrasts = c("contr.treatment", "contr.poly")) library(MASS) example(birthwt) (bwt.mu <- multinom(low ~ ., bwt)) options(oc) ``` r None `nnet` Fit Neural Networks --------------------------- ### Description Fit single-hidden-layer neural network, possibly with skip-layer connections. ### Usage ``` nnet(x, ...) ## S3 method for class 'formula' nnet(formula, data, weights, ..., subset, na.action, contrasts = NULL) ## Default S3 method: nnet(x, y, weights, size, Wts, mask, linout = FALSE, entropy = FALSE, softmax = FALSE, censored = FALSE, skip = FALSE, rang = 0.7, decay = 0, maxit = 100, Hess = FALSE, trace = TRUE, MaxNWts = 1000, abstol = 1.0e-4, reltol = 1.0e-8, ...) ``` ### Arguments | | | | --- | --- | | `formula` | A formula of the form `class ~ x1 + x2 + ...` | | `x` | matrix or data frame of `x` values for examples. | | `y` | matrix or data frame of target values for examples. | | `weights` | (case) weights for each example – if missing defaults to 1. | | `size` | number of units in the hidden layer. Can be zero if there are skip-layer units. | | `data` | Data frame from which variables specified in `formula` are preferentially to be taken. | | `subset` | An index vector specifying the cases to be used in the training sample. (NOTE: If given, this argument must be named.) | | `na.action` | A function to specify the action to be taken if `NA`s are found. The default action is for the procedure to fail. An alternative is na.omit, which leads to rejection of cases with missing values on any required variable. (NOTE: If given, this argument must be named.) | | `contrasts` | a list of contrasts to be used for some or all of the factors appearing as variables in the model formula. | | `Wts` | initial parameter vector. If missing chosen at random. | | `mask` | logical vector indicating which parameters should be optimized (default all). | | `linout` | switch for linear output units. Default logistic output units. | | `entropy` | switch for entropy (= maximum conditional likelihood) fitting. Default by least-squares. | | `softmax` | switch for softmax (log-linear model) and maximum conditional likelihood fitting. `linout`, `entropy`, `softmax` and `censored` are mutually exclusive. | | `censored` | A variant on `softmax`, in which non-zero targets mean possible classes. Thus for `softmax` a row of `(0, 1, 1)` means one example each of classes 2 and 3, but for `censored` it means one example whose class is only known to be 2 or 3. | | `skip` | switch to add skip-layer connections from input to output. | | `rang` | Initial random weights on [-`rang`, `rang`]. Value about 0.5 unless the inputs are large, in which case it should be chosen so that `rang` \* max(`|x|`) is about 1. | | `decay` | parameter for weight decay. Default 0. | | `maxit` | maximum number of iterations. Default 100. | | `Hess` | If true, the Hessian of the measure of fit at the best set of weights found is returned as component `Hessian`. | | `trace` | switch for tracing optimization. Default `TRUE`. | | `MaxNWts` | The maximum allowable number of weights. There is no intrinsic limit in the code, but increasing `MaxNWts` will probably allow fits that are very slow and time-consuming. | | `abstol` | Stop if the fit criterion falls below `abstol`, indicating an essentially perfect fit. | | `reltol` | Stop if the optimizer is unable to reduce the fit criterion by a factor of at least `1 - reltol`. | | `...` | arguments passed to or from other methods. | ### Details If the response in `formula` is a factor, an appropriate classification network is constructed; this has one output and entropy fit if the number of levels is two, and a number of outputs equal to the number of classes and a softmax output stage for more levels. If the response is not a factor, it is passed on unchanged to `nnet.default`. Optimization is done via the BFGS method of `[optim](../../stats/html/optim)`. ### Value object of class `"nnet"` or `"nnet.formula"`. Mostly internal structure, but has components | | | | --- | --- | | `wts` | the best set of weights found | | `value` | value of fitting criterion plus weight decay term. | | `fitted.values` | the fitted values for the training data. | | `residuals` | the residuals for the training data. | | `convergence` | `1` if the maximum number of iterations was reached, otherwise `0`. | ### References Ripley, B. D. (1996) *Pattern Recognition and Neural Networks.* Cambridge. Venables, W. N. and Ripley, B. D. (2002) *Modern Applied Statistics with S.* Fourth edition. Springer. ### See Also `<predict.nnet>`, `[nnetHess](nnet.hess)` ### Examples ``` # use half the iris data ir <- rbind(iris3[,,1],iris3[,,2],iris3[,,3]) targets <- class.ind( c(rep("s", 50), rep("c", 50), rep("v", 50)) ) samp <- c(sample(1:50,25), sample(51:100,25), sample(101:150,25)) ir1 <- nnet(ir[samp,], targets[samp,], size = 2, rang = 0.1, decay = 5e-4, maxit = 200) test.cl <- function(true, pred) { true <- max.col(true) cres <- max.col(pred) table(true, cres) } test.cl(targets[-samp,], predict(ir1, ir[-samp,])) # or ird <- data.frame(rbind(iris3[,,1], iris3[,,2], iris3[,,3]), species = factor(c(rep("s",50), rep("c", 50), rep("v", 50)))) ir.nn2 <- nnet(species ~ ., data = ird, subset = samp, size = 2, rang = 0.1, decay = 5e-4, maxit = 200) table(ird$species[-samp], predict(ir.nn2, ird[-samp,], type = "class")) ```
programming_docs
r None `predict.nnet` Predict New Examples by a Trained Neural Net ------------------------------------------------------------ ### Description Predict new examples by a trained neural net. ### Usage ``` ## S3 method for class 'nnet' predict(object, newdata, type = c("raw","class"), ...) ``` ### Arguments | | | | --- | --- | | `object` | an object of class `nnet` as returned by `nnet`. | | `newdata` | matrix or data frame of test examples. A vector is considered to be a row vector comprising a single case. | | `type` | Type of output | | `...` | arguments passed to or from other methods. | ### Details This function is a method for the generic function `predict()` for class `"nnet"`. It can be invoked by calling `predict(x)` for an object `x` of the appropriate class, or directly by calling `predict.nnet(x)` regardless of the class of the object. ### Value If `type = "raw"`, the matrix of values returned by the trained network; if `type = "class"`, the corresponding class (which is probably only useful if the net was generated by `nnet.formula`). ### References Ripley, B. D. (1996) *Pattern Recognition and Neural Networks.* Cambridge. Venables, W. N. and Ripley, B. D. (2002) *Modern Applied Statistics with S.* Fourth edition. Springer. ### See Also `<nnet>`, `<which.is.max>` ### Examples ``` # use half the iris data ir <- rbind(iris3[,,1], iris3[,,2], iris3[,,3]) targets <- class.ind( c(rep("s", 50), rep("c", 50), rep("v", 50)) ) samp <- c(sample(1:50,25), sample(51:100,25), sample(101:150,25)) ir1 <- nnet(ir[samp,], targets[samp,],size = 2, rang = 0.1, decay = 5e-4, maxit = 200) test.cl <- function(true, pred){ true <- max.col(true) cres <- max.col(pred) table(true, cres) } test.cl(targets[-samp,], predict(ir1, ir[-samp,])) # or ird <- data.frame(rbind(iris3[,,1], iris3[,,2], iris3[,,3]), species = factor(c(rep("s",50), rep("c", 50), rep("v", 50)))) ir.nn2 <- nnet(species ~ ., data = ird, subset = samp, size = 2, rang = 0.1, decay = 5e-4, maxit = 200) table(ird$species[-samp], predict(ir.nn2, ird[-samp,], type = "class")) ``` r None `class.ind` Generates Class Indicator Matrix from a Factor ----------------------------------------------------------- ### Description Generates a class indicator function from a given factor. ### Usage ``` class.ind(cl) ``` ### Arguments | | | | --- | --- | | `cl` | factor or vector of classes for cases. | ### Value a matrix which is zero except for the column corresponding to the class. ### References Venables, W. N. and Ripley, B. D. (2002) *Modern Applied Statistics with S.* Fourth edition. Springer. ### Examples ``` # The function is currently defined as class.ind <- function(cl) { n <- length(cl) cl <- as.factor(cl) x <- matrix(0, n, length(levels(cl)) ) x[(1:n) + n*(unclass(cl)-1)] <- 1 dimnames(x) <- list(names(cl), levels(cl)) x } ``` r None `which.is.max` Find Maximum Position in Vector ----------------------------------------------- ### Description Find the maximum position in a vector, breaking ties at random. ### Usage ``` which.is.max(x) ``` ### Arguments | | | | --- | --- | | `x` | a vector | ### Details Ties are broken at random. ### Value index of a maximal value. ### References Venables, W. N. and Ripley, B. D. (2002) *Modern Applied Statistics with S.* Fourth edition. Springer. ### See Also `[max.col](../../base/html/maxcol)`, `[which.max](../../base/html/which.min)` which takes the first of ties. ### Examples ``` ## Not run: ## this is incomplete pred <- predict(nnet, test) table(true, apply(pred, 1, which.is.max)) ## End(Not run) ``` r None `nnet.Hess` Evaluates Hessian for a Neural Network --------------------------------------------------- ### Description Evaluates the Hessian (matrix of second derivatives) of the specified neural network. Normally called via argument `Hess=TRUE` to `nnet` or via `vcov.multinom`. ### Usage ``` nnetHess(net, x, y, weights) ``` ### Arguments | | | | --- | --- | | `net` | object of class `nnet` as returned by `nnet`. | | `x` | training data. | | `y` | classes for training data. | | `weights` | the (case) weights used in the `nnet` fit. | ### Value square symmetric matrix of the Hessian evaluated at the weights stored in the net. ### References Ripley, B. D. (1996) *Pattern Recognition and Neural Networks.* Cambridge. Venables, W. N. and Ripley, B. D. (2002) *Modern Applied Statistics with S.* Fourth edition. Springer. ### See Also `<nnet>`, `<predict.nnet>` ### Examples ``` # use half the iris data ir <- rbind(iris3[,,1], iris3[,,2], iris3[,,3]) targets <- matrix(c(rep(c(1,0,0),50), rep(c(0,1,0),50), rep(c(0,0,1),50)), 150, 3, byrow=TRUE) samp <- c(sample(1:50,25), sample(51:100,25), sample(101:150,25)) ir1 <- nnet(ir[samp,], targets[samp,], size=2, rang=0.1, decay=5e-4, maxit=200) eigen(nnetHess(ir1, ir[samp,], targets[samp,]), TRUE)$values ``` r None `tk_select.list` Select Items from a List ------------------------------------------ ### Description Select item(s) from a character vector using a Tk listbox. ### Usage ``` tk_select.list(choices, preselect = NULL, multiple = FALSE, title = NULL) ``` ### Arguments | | | | --- | --- | | `choices` | a character vector of items. | | `preselect` | a character vector, or `NULL`. If non-null and if the string(s) appear in the list, the item(s) are selected initially. | | `multiple` | logical: can more than one item be selected? | | `title` | optional character string for window title, or `NULL` for no title. | ### Details This is a version of `[select.list](../../utils/html/select.list)` implemented as a Tk list box plus `OK` and `Cancel` buttons. There will be a scrollbar if the list is too long to fit comfortably on the screen. The dialog box is *modal*, so a selection must be made or cancelled before the **R** session can proceed. Double-clicking on an item is equivalent to selecting it and then clicking `OK`. If Tk is version 8.5 or later, themed widgets will be used. ### Value A character vector of selected items. If `multiple` is false and no item was selected (or `Cancel` was used), `""` is returned. If `multiple` is true and no item was selected (or `Cancel` was used) then a character vector of length 0 is returned. ### See Also `[select.list](../../utils/html/select.list)` (a text version except on Windows and the macOS GUI), `[menu](../../utils/html/menu)` (whose `graphics = TRUE` mode uses this on most Unix-alikes). r None `tkpager` Page file using Tk text widget ----------------------------------------- ### Description This plugs into `file.show`, showing files in separate windows. ### Usage ``` tkpager(file, header, title, delete.file) ``` ### Arguments | | | | --- | --- | | `file` | character vector containing the names of the files to be displayed | | `header` | headers to use for each file | | `title` | common title to use for the window(s). Pasted together with the `header` to form actual window title. | | `delete.file` | logical. Should file(s) be deleted after display? | ### Note The `"\b_"` string used for underlining is currently quietly removed. The font and background colour are currently hardcoded to Courier and gray90. ### See Also `[file.show](../../base/html/file.show)` r None `TkWidgetcmds` Tk widget commands ---------------------------------- ### Description These functions interface to Tk widget commands. ### Usage ``` tkactivate(widget, ...) tkadd(widget, ...) tkaddtag(widget, ...) tkbbox(widget, ...) tkcanvasx(widget, ...) tkcanvasy(widget, ...) tkcget(widget, ...) tkcompare(widget, ...) tkconfigure(widget, ...) tkcoords(widget, ...) tkcreate(widget, ...) tkcurselection(widget, ...) tkdchars(widget, ...) tkdebug(widget, ...) tkdelete(widget, ...) tkdelta(widget, ...) tkdeselect(widget, ...) tkdlineinfo(widget, ...) tkdtag(widget, ...) tkdump(widget, ...) tkentrycget(widget, ...) tkentryconfigure(widget, ...) tkfind(widget, ...) tkflash(widget, ...) tkfraction(widget, ...) tkget(widget, ...) tkgettags(widget, ...) tkicursor(widget, ...) tkidentify(widget, ...) tkindex(widget, ...) tkinsert(widget, ...) tkinvoke(widget, ...) tkitembind(widget, ...) tkitemcget(widget, ...) tkitemconfigure(widget, ...) tkitemfocus(widget, ...) tkitemlower(widget, ...) tkitemraise(widget, ...) tkitemscale(widget, ...) tkmark.gravity(widget, ...) tkmark.names(widget, ...) tkmark.next(widget, ...) tkmark.previous(widget, ...) tkmark.set(widget, ...) tkmark.unset(widget, ...) tkmove(widget, ...) tknearest(widget, ...) tkpost(widget, ...) tkpostcascade(widget, ...) tkpostscript(widget, ...) tkscan.mark(widget, ...) tkscan.dragto(widget, ...) tksearch(widget, ...) tksee(widget, ...) tkselect(widget, ...) tkselection.adjust(widget, ...) tkselection.anchor(widget, ...) tkselection.clear(widget, ...) tkselection.from(widget, ...) tkselection.includes(widget, ...) tkselection.present(widget, ...) tkselection.range(widget, ...) tkselection.set(widget, ...) tkselection.to(widget, ...) tkset(widget, ...) tksize(widget, ...) tktoggle(widget, ...) tktag.add(widget, ...) tktag.bind(widget, ...) tktag.cget(widget, ...) tktag.configure(widget, ...) tktag.delete(widget, ...) tktag.lower(widget, ...) tktag.names(widget, ...) tktag.nextrange(widget, ...) tktag.prevrange(widget, ...) tktag.raise(widget, ...) tktag.ranges(widget, ...) tktag.remove(widget, ...) tktype(widget, ...) tkunpost(widget, ...) tkwindow.cget(widget, ...) tkwindow.configure(widget, ...) tkwindow.create(widget, ...) tkwindow.names(widget, ...) tkxview(widget, ...) tkxview.moveto(widget, ...) tkxview.scroll(widget, ...) tkyposition(widget, ...) tkyview(widget, ...) tkyview.moveto(widget, ...) tkyview.scroll(widget, ...) ``` ### Arguments | | | | --- | --- | | `widget` | The widget this applies to | | `...` | Handled via `.Tcl.args` | ### Details There are far too many of these commands to describe them and their arguments in full. Please refer to the Tcl/Tk documentation for details. Except for a few exceptions, the pattern is that Tcl widget commands possibly with subcommands like `.a.b selection clear` are converted to function names like `tkselection.clear` and the widget is given as the first argument. ### See Also `[TclInterface](tclinterface)`, `[TkWidgets](tkwidgets)`, `[TkCommands](tkcommands)` ### Examples ``` ## Not run: ## These cannot be run by examples() but should be OK when pasted ## into an interactive R session with the tcltk package loaded tt <- tktoplevel() tkpack(txt.w <- tktext(tt)) tkinsert(txt.w, "0.0", "plot(1:10)") # callback function eval.txt <- function() eval(str2lang(tclvalue(tkget(txt.w, "0.0", "end")))) tkpack(but.w <- tkbutton(tt, text = "Submit", command = eval.txt)) ## Try pressing the button, edit the text and when finished: tkdestroy(tt) ## End(Not run) ``` r None `TclInterface` Low-level Tcl/Tk Interface ------------------------------------------ ### Description These functions and variables provide the basic glue between **R** and the Tcl interpreter and Tk GUI toolkit. Tk windows may be represented via **R** objects. Tcl variables can be accessed via objects of class `tclVar` and the C level interface to Tcl objects is accessed via objects of class `tclObj`. ### Usage ``` .Tcl(...) .Tcl.objv(objv) .Tcl.args(...) .Tcl.args.objv(...) .Tcl.callback(...) .Tk.ID(win) .Tk.newwin(ID) .Tk.subwin(parent) .TkRoot tkdestroy(win) is.tkwin(x) tclvalue(x) tclvalue(x) <- value tclVar(init = "") ## S3 method for class 'tclVar' as.character(x, ...) ## S3 method for class 'tclVar' tclvalue(x) ## S3 replacement method for class 'tclVar' tclvalue(x) <- value tclArray() ## S3 method for class 'tclArray' x[[...]] ## S3 replacement method for class 'tclArray' x[[...]] <- value ## S3 method for class 'tclArray' x$i ## S3 replacement method for class 'tclArray' x$i <- value ## S3 method for class 'tclArray' names(x) ## S3 method for class 'tclArray' length(x) tclObj(x) tclObj(x) <- value ## S3 method for class 'tclVar' tclObj(x) ## S3 replacement method for class 'tclVar' tclObj(x) <- value as.tclObj(x, drop = FALSE) is.tclObj(x) ## S3 method for class 'tclObj' as.character(x, ...) ## S3 method for class 'tclObj' as.integer(x, ...) ## S3 method for class 'tclObj' as.double(x, ...) ## S3 method for class 'tclObj' as.logical(x, ...) ## S3 method for class 'tclObj' as.raw(x, ...) ## S3 method for class 'tclObj' tclvalue(x) ## Default S3 method: tclvalue(x) ## Default S3 replacement method: tclvalue(x) <- value addTclPath(path = ".") tclRequire(package, warn = TRUE) tclVersion() ``` ### Arguments | | | | --- | --- | | `objv` | a named vector of Tcl objects | | `win` | a window structure | | `x` | an object | | `i` | character or (unquoted) name | | `drop` | logical. Indicates whether a single-element vector should be made into a simple Tcl object or a list of length one | | `value` | For `tclvalue` assignments, a character string. For `tclObj` assignments, an object of class `tclObj` | | `ID` | a window ID | | `parent` | a window which becomes the parent of the resulting window | | `path` | path to a directory containing Tcl packages | | `package` | a Tcl package name | | `warn` | logical. Warn if not found? | | `...` | Additional arguments. See below. | | `init` | initialization value | ### Details Many of these functions are not intended for general use but are used internally by the commands that create and manipulate Tk widgets and Tcl objects. At the lowest level `.Tcl` sends a command as a text string to the Tcl interpreter and returns the result as an object of class `tclObj` (see below). A newer variant `.Tcl.objv` accepts arguments in the form of a named list of `tclObj` objects. `.Tcl.args` converts an R argument list of `tag = value` pairs to the Tcl `-option value` style, thus enabling a simple translation between the two languages. To send a value with no preceding option flag to Tcl, just use an untagged argument. In the rare case one needs an option with no subsequent value `tag = NULL` can be used. Most values are just converted to character mode and inserted in the command string, but window objects are passed using their ID string, and callbacks are passed via the result of `.Tcl.callback`. Tags are converted to option flags simply by prepending a `-` `.Tcl.args.objv` serves a similar purpose as `.Tcl.args` but produces a list of `tclObj` objects suitable for passing to `.Tcl.objv`. The names of the list are converted to Tcl option style internally by `.Tcl.objv`. Callbacks can be either *atomic callbacks* handled by `.Tcl.callback` or expressions. An expression is treated as a list of atomic callbacks, with the following exceptions: if an element is a name, it is first evaluated in the callers frame, and likewise if it is an explicit function definition; the `break` expression is translated directly to the Tcl counterpart. `.Tcl.callback` converts **R** functions and unevaluated calls to Tcl command strings. The argument must be either a function closure or an object of mode `"call"` followed by an environment. The return value in the first case is of the form `R_call 0x408b94d4` in which the hexadecimal number is the memory address of the function. In the second case it will be of the form `R_call_lang 0x8a95904 0x819bfd0`. For expressions, a sequence of similar items is generated, separated by semicolons. `.Tcl.args` takes special precautions to ensure that functions or calls will continue to exist at the specified address by assigning the callback into the relevant window environment (see below). Tk windows are represented as objects of class `tkwin` which are lists containing a `ID` field and an `env` field which is an **R** environments, enclosed in the global environment. The value of the `ID` field is identical to the Tk window name. The `env` environment contains a `parent` variable and a `num.subwin` variable. If the window obtains sub-windows and callbacks, they are added as variables to the environment. `.TkRoot` is the top window with ID "."; this window is not displayed in order to avoid ill effects of closing it via window manager controls. The `parent` variable is undefined for `.TkRoot`. `.Tk.ID` extracts the `ID` of a window, `.Tk.newwin` creates a new window environment with a given ID and `.Tk.subwin` creates a new window which is a sub-window of a given parent window. `tkdestroy` destroys a window and also removes the reference to a window from its parent. `is.tkwin` can be used to test whether a given object is a window environment. `tclVar` creates a new Tcl variable and initializes it to `init`. An R object of class `tclVar` is created to represent it. Using `as.character` on the object returns the Tcl variable name. Accessing the Tcl variable from R is done using the `tclvalue` function, which can also occur on the left-hand side of assignments. If `tclvalue` is passed an argument which is not a `tclVar` object, then it will assume that it is a character string explicitly naming global Tcl variable. Tcl variables created by `tclVar` are uniquely named and automatically unset by the garbage collector when the representing object is no longer in use. `tclArray` creates a new Tcl array and initializes it to the empty array. An R object of class `tclArray` and inheriting from class `tclVar` is created to represent it. You can access elements of the Tcl array using indexing with `[[` or `$`, which also allow replacement forms. Notice that Tcl arrays are associative by nature and hence unordered; indexing with a numeric index `i` refers to the element with the *name* `as.character(i)`. Multiple indices are pasted together separated by commas to form a single name. You can query the length and the set of names in an array using methods for `length` and `names`, respectively; these cannot meaningfully be set so assignment forms exist only to print an error message. It is possible to access Tcl's ‘dual-ported’ objects directly, thus avoiding parsing and deparsing of their string representation. This works by using objects of class `tclObj`. The string representation of such objects can be extracted (but not set) using `tclvalue` and conversion to vectors of mode `"character"`, `"double"`, `"integer"`, `"logical"`, and `"raw"` is performed using the standard coercion functions `as.character`, etc. Conversely, such vectors can be converted using `as.tclObj`. There is an ambiguity as to what should happen for length one vectors, controlled by the `drop` argument; there are cases where the distinction matters to Tcl, although mostly it treats them equivalently. Notice that `tclvalue` and `as.character` differ on an object whose string representation has embedded spaces, the former is sometimes to be preferred, in particular when applied to the result of `tclread`, `tkgetOpenFile`, and similar functions. The `as.raw` method returns a raw vector or a list of raw vectors and can be used to return binary data from Tcl. The object behind a `tclVar` object is extracted using `tclObj(x)` which also allows an assignment form, in which the right hand side of the assignment is automatically converted using `as.tclObj`. There is a print method for `tclObj` objects; it prints `<Tcl>` followed by the string representation of the object. Notice that `as.character` on a `tclVar` object is the *name* of the corresponding Tcl variable and not the value. Tcl packages can be loaded with `tclRequire`; it may be necessary to add the directory where they are found to the Tcl search path with `addTclPath`. The return value is a class `"tclObj"` object if it succeeds, or `FALSE` if it fails (when a warning is issued). To see the current search path as an **R** character vector, use ``` strsplit(tclvalue('auto_path'), " ")[[1]] ``` . The Tcl version (including patchlevel) is returned as a character string (such as `"8.6.3"`). ### Note Strings containing unbalanced braces are currently not handled well in many circumstances. ### See Also `[TkWidgets](tkwidgets)`, `[TkCommands](tkcommands)`, `[TkWidgetcmds](tkwidgetcmds)`. `[capabilities](../../base/html/capabilities)("tcltk")` to see if Tcl/Tk support was compiled into this build of **R**. ### Examples ``` tclVersion() .Tcl("format \"%s\n\" \"Hello, World!\"") f <- function() cat("HI!\n") ## IGNORE_RDIFF_BEGIN .Tcl.callback(f) .Tcl.args(text = "Push!", command = f) # NB: Different address ## IGNORE_RDIFF_END xyzzy <- tclVar(7913) tclvalue(xyzzy) tclvalue(xyzzy) <- "foo" as.character(xyzzy) tcl("set", as.character(xyzzy)) ## Not run: ## These cannot be run by example() but should be OK when pasted ## into an interactive R session with the tcltk package loaded top <- tktoplevel() # a Tk widget, see Tk-widgets ls(envir = top$env, all.names = TRUE) ## End(Not run) ## IGNORE_RDIFF_BEGIN ls(envir = .TkRoot$env, all.names = TRUE) # .Tcl.args put a callback ref in here ## IGNORE_RDIFF_END ```
programming_docs
r None `tclServiceMode` Allow Tcl events to be serviced or not -------------------------------------------------------- ### Description This function controls or reports on the Tcl service mode, i.e., whether Tcl will respond to events. ### Usage ``` tclServiceMode(on = NULL) ``` ### Arguments | | | | --- | --- | | `on` | (logical) Whether event servicing is turned on. | ### Details If called with `on == NULL` (the default), no change is made. Note that this blocks all Tcl/Tk activity, including for widgets from other packages. It may be better to manage mapping of windows individually. ### Value The value of the Tcl service mode before the call. ### Examples ``` ## see demo(tkcanvas) for an example oldmode <- tclServiceMode(FALSE) # Do some work to create a nice picture. # Nothing will be displayed until... tclServiceMode(oldmode) ## another idea is to use tkwm.withdraw() ... tkwm.deiconify() ``` r None `tcltk-package` Tcl/Tk Interface --------------------------------- ### Description Interface and language bindings to Tcl/Tk GUI elements. ### Details This package provides access to the platform-independent Tcl scripting language and Tk GUI elements. See [TkWidgets](tkwidgets) for a list of supported widgets, [TkWidgetcmds](tkwidgetcmds) for commands to work with them, and references in those files for more. The Tcl/Tk documentation is in the system man pages. For a complete list of functions, use `ls("package:tcltk")`. Note that Tk will not be initialized if there is no `DISPLAY` variable set, but Tcl can still be used. This is most useful to allow the loading of a package which depends on tcltk in a session that does not actually use it (e.g., during installation). ### Author(s) R Core Team Maintainer: R Core Team [[email protected]](mailto:[email protected]) r None `TkCommands` Tk non-widget commands ------------------------------------ ### Description These functions interface to Tk non-widget commands, such as the window manager interface commands and the geometry managers. ### Usage ``` tcl(...) tktitle(x) tktitle(x) <- value tkbell(...) tkbind(...) tkbindtags(...) tkfocus(...) tklower(...) tkraise(...) tkclipboard.append(...) tkclipboard.clear(...) tkevent.add(...) tkevent.delete(...) tkevent.generate(...) tkevent.info(...) tkfont.actual(...) tkfont.configure(...) tkfont.create(...) tkfont.delete(...) tkfont.families(...) tkfont.measure(...) tkfont.metrics(...) tkfont.names(...) tkgrab(...) tkgrab.current(...) tkgrab.release(...) tkgrab.set(...) tkgrab.status(...) tkimage.create(...) tkimage.delete(...) tkimage.height(...) tkimage.inuse(...) tkimage.names(...) tkimage.type(...) tkimage.types(...) tkimage.width(...) ## NB: some widgets also have a selection.clear command, ## hence the "X". tkXselection.clear(...) tkXselection.get(...) tkXselection.handle(...) tkXselection.own(...) tkwait.variable(...) tkwait.visibility(...) tkwait.window(...) ## winfo actually has a large number of subcommands, ## but it's rarely used, ## so use tkwinfo("atom", ...) etc. instead. tkwinfo(...) # Window manager interface tkwm.aspect(...) tkwm.client(...) tkwm.colormapwindows(...) tkwm.command(...) tkwm.deiconify(...) tkwm.focusmodel(...) tkwm.frame(...) tkwm.geometry(...) tkwm.grid(...) tkwm.group(...) tkwm.iconbitmap(...) tkwm.iconify(...) tkwm.iconmask(...) tkwm.iconname(...) tkwm.iconposition(...) tkwm.iconwindow(...) tkwm.maxsize(...) tkwm.minsize(...) tkwm.overrideredirect(...) tkwm.positionfrom(...) tkwm.protocol(...) tkwm.resizable(...) tkwm.sizefrom(...) tkwm.state(...) tkwm.title(...) tkwm.transient(...) tkwm.withdraw(...) ### Geometry managers tkgrid(...) tkgrid.bbox(...) tkgrid.columnconfigure(...) tkgrid.configure(...) tkgrid.forget(...) tkgrid.info(...) tkgrid.location(...) tkgrid.propagate(...) tkgrid.rowconfigure(...) tkgrid.remove(...) tkgrid.size(...) tkgrid.slaves(...) tkpack(...) tkpack.configure(...) tkpack.forget(...) tkpack.info(...) tkpack.propagate(...) tkpack.slaves(...) tkplace(...) tkplace.configure(...) tkplace.forget(...) tkplace.info(...) tkplace.slaves(...) ## Standard dialogs tkgetOpenFile(...) tkgetSaveFile(...) tkchooseDirectory(...) tkmessageBox(...) tkdialog(...) tkpopup(...) ## File handling functions tclfile.tail(...) tclfile.dir(...) tclopen(...) tclclose(...) tclputs(...) tclread(...) ``` ### Arguments | | | | --- | --- | | `x` | A window object | | `value` | For `tktitle` assignments, a character string. | | `...` | Handled via `.Tcl.args` | ### Details `tcl` provides a generic interface to calling any Tk or Tcl command by simply running `.Tcl.args.objv` on the argument list and passing the result to `.Tcl.objv`. Most of the other commands simply call `tcl` with a particular first argument and sometimes also a second argument giving the subcommand. `tktitle` and its assignment form provides an alternate interface to Tk's `wm title` There are far too many of these commands to describe them and their arguments in full. Please refer to the Tcl/Tk documentation for details. With a few exceptions, the pattern is that Tk subcommands like `pack configure` are converted to function names like `tkpack.configure`, and Tcl subcommands are like `tclfile.dir`. ### See Also `[TclInterface](tclinterface)`, `[TkWidgets](tkwidgets)`, `[TkWidgetcmds](tkwidgetcmds)` ### Examples ``` ## Not run: ## These cannot be run by examples() but should be OK when pasted ## into an interactive R session with the tcltk package loaded tt <- tktoplevel() tkpack(l1 <- tklabel(tt, text = "Heave"), l2 <- tklabel(tt, text = "Ho")) tkpack.configure(l1, side = "left") ## Try stretching the window and then tkdestroy(tt) ## End(Not run) ``` r None `TkWidgets` Tk widgets ----------------------- ### Description Create Tk widgets and associated **R** objects. ### Usage ``` tkwidget(parent, type, ...) tkbutton(parent, ...) tkcanvas(parent, ...) tkcheckbutton(parent, ...) tkentry(parent, ...) ttkentry(parent, ...) tkframe(parent, ...) tklabel(parent, ...) tklistbox(parent, ...) tkmenu(parent, ...) tkmenubutton(parent, ...) tkmessage(parent, ...) tkradiobutton(parent, ...) tkscale(parent, ...) tkscrollbar(parent, ...) tktext(parent, ...) tktoplevel(parent = .TkRoot, ...) ttkbutton(parent, ...) ttkcheckbutton(parent, ...) ttkcombobox(parent, ...) ttkframe(parent, ...) ttklabel(parent, ...) ttklabelframe(parent, ...) ttkmenubutton(parent, ...) ttknotebook(parent, ...) ttkpanedwindow(parent, ...) ttkprogressbar(parent, ...) ttkradiobutton(parent, ...) ttkscale(parent, ...) ttkscrollbar(parent, ...) ttkseparator(parent, ...) ttksizegrip(parent, ...) ttkspinbox(parent, ...) ttktreeview(parent, ...) ``` ### Arguments | | | | --- | --- | | `parent` | Parent of widget window. | | `type` | string describing the type of widget desired. | | `...` | handled via `[.Tcl.args](tclinterface)`. | ### Details These functions create Tk widgets. `tkwidget` creates a widget of a given type, the others simply call `tkwidget` with the respective `type` argument. The functions starting `ttk` are for the themed widget set for Tk 8.5 or later. A tutorial can be found at <https://tkdocs.com/>. It is not possible to describe the widgets and their arguments in full. Please refer to the Tcl/Tk documentation. ### See Also `[TclInterface](tclinterface)`, `[TkCommands](tkcommands)`, `[TkWidgetcmds](tkwidgetcmds)` ### Examples ``` ## Not run: ## These cannot be run by examples() but should be OK when pasted ## into an interactive R session with the tcltk package loaded 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) # geometry manager # see Tk-commands ## Push the button and then... tkdestroy(tt) ## test for themed widgets if(as.character(tcl("info", "tclversion")) >= "8.5") { # make use of themed widgets # list themes themes <- as.character(tcl("ttk::style", "theme", "names")) themes # select a theme -- for pre-XP windows # tcl("ttk::style", "theme", "use", "winnative") tcl("ttk::style", "theme", "use", themes[1]) } else { # use Tk 8.0 widgets } ## End(Not run) ``` r None `tk_messageBox` Tk Message Box ------------------------------- ### Description An implementation of a generic message box using Tk. ### Usage ``` tk_messageBox(type = c("ok", "okcancel", "yesno", "yesnocancel", "retrycancel", "abortretryignore"), message, caption = "", default = "", ...) ``` ### Arguments | | | | --- | --- | | `type` | character. The type of dialog box. It will have the buttons implied by its name. Can be abbreviated. | | `message` | character. The information field of the dialog box. | | `caption` | the caption on the widget displayed. | | `default` | character. The name of the button to be used as the default. | | `...` | additional named arguments to be passed to the Tk function of this name. An example is `icon = "warning"`. | ### Value A character string giving the name of the button pressed. ### See Also `[tkmessageBox](tkcommands)` for a ‘raw’ interface. r None `tk_choose.files` Choose a List of Files Interactively ------------------------------------------------------- ### Description Use a Tk file dialog to choose a list of zero or more files interactively. ### Usage ``` tk_choose.files(default = "", caption = "Select files", multi = TRUE, filters = NULL, index = 1) ``` ### Arguments | | | | --- | --- | | `default` | which filename to show initially. | | `caption` | the caption on the file selection dialog. | | `multi` | whether to allow multiple files to be selected. | | `filters` | two-column character matrix of filename filters. | | `index` | unused. | ### Details Unlike `[file.choose](../../base/html/file.choose)`, `tk_choose.files` will always attempt to return a character vector giving a list of files. If the user cancels the dialog, then zero files are returned, whereas `[file.choose](../../base/html/file.choose)` would signal an error. The format of `filters` can be seen from the example. File patterns are specified via extensions, with `"*"` meaning any file, and `""` any file without an extension (a filename not containing a period). (Other forms may work on specific platforms.) Note that the way to have multiple extensions for one file type is to have multiple rows with the same name in the first column, and that whether the extensions are named in file chooser widget is platform-specific. **The format may change before release.** ### Value A character vector giving zero or more file paths. ### Note A bug in Tk 8.5.0–8.5.4 prevented multiple selections being used. ### See Also `[file.choose](../../base/html/file.choose)`, `<tk_choose.dir>` ### Examples ``` Filters <- matrix(c("R code", ".R", "R code", ".s", "Text", ".txt", "All files", "*"), 4, 2, byrow = TRUE) Filters if(interactive()) tk_choose.files(filter = Filters) ``` r None `tkStartGUI` Tcl/Tk GUI startup -------------------------------- ### Description Starts up the Tcl/Tk GUI ### Usage ``` tkStartGUI() ``` ### Details Starts a GUI console implemented via a Tk text widget. This should probably be called at most once per session. Also redefines the file pager (as used by `help()`) to be the Tk pager. ### Note `tkStartGUI()` saves its evaluation environment as `.GUIenv`. This means that the user interface elements can be accessed in order to extend the interface. The three main objects are named `Term`, `Menu`, and `Toolbar`, and the various submenus and callback functions can be seen with `ls(envir = .GUIenv)`. ### Author(s) Peter Dalgaard r None `tk_choose.dir` Choose a Folder Interactively ---------------------------------------------- ### Description Use a Tk widget to choose a directory interactively. ### Usage ``` tk_choose.dir(default = "", caption = "Select directory") ``` ### Arguments | | | | --- | --- | | `default` | which directory to show initially. | | `caption` | the caption on the selection dialog. | ### Value A length-one character vector, character `NA` if ‘Cancel’ was selected. ### See Also `<tk_choose.files>` ### Examples ``` if (interactive()) tk_choose.dir(getwd(), "Choose a suitable folder") ``` r None `tkProgressBar` Progress Bars via Tk ------------------------------------- ### Description Put up a Tk progress bar widget. ### Usage ``` tkProgressBar(title = "R progress bar", label = "", min = 0, max = 1, initial = 0, width = 300) getTkProgressBar(pb) setTkProgressBar(pb, value, title = NULL, label = NULL) ## S3 method for class 'tkProgressBar' close(con, ...) ``` ### Arguments | | | | --- | --- | | `title, label` | character strings, giving the window title and the label on the dialog box respectively. | | `min, max` | (finite) numeric values for the extremes of the progress bar. | | `initial, value` | initial or new value for the progress bar. | | `width` | the width of the progress bar in pixels: the dialog box will be 40 pixels wider (plus frame). | | `pb, con` | an object of class `"tkProgressBar"`. | | `...` | for consistency with the generic. | ### Details `tkProgressBar` will display a widget containing a label and progress bar. `setTkProgessBar` will update the value and for non-`NULL` values, the title and label (provided there was one when the widget was created). Missing (`[NA](../../base/html/na)`) and out-of-range values of `value` will be (silently) ignored. The progress bar should be `close`d when finished with. This will use the `ttk::progressbar` widget for Tk version 8.5 or later, otherwise **R**'s copy of BWidget's `progressbar`. ### Value For `tkProgressBar` an object of class `"tkProgressBar"`. For `getTkProgressBar` and `setTkProgressBar`, a length-one numeric vector giving the previous value (invisibly for `setTkProgressBar`). ### See Also `[txtProgressBar](../../utils/html/txtprogressbar)` ### Examples ``` pb <- tkProgressBar("test progress bar", "Some information in %", 0, 100, 50) Sys.sleep(0.5) u <- c(0, sort(runif(20, 0, 100)), 100) for(i in u) { Sys.sleep(0.1) info <- sprintf("%d%% done", round(i)) setTkProgressBar(pb, i, sprintf("test (%s)", info), info) } Sys.sleep(5) close(pb) ``` r None `localeToCharset` Select a Suitable Encoding Name from a Locale Name --------------------------------------------------------------------- ### Description This functions aims to find a suitable coding for the locale named, by default the current locale, and if it is a UTF-8 locale a suitable single-byte encoding. ### Usage ``` localeToCharset(locale = Sys.getlocale("LC_CTYPE")) ``` ### Arguments | | | | --- | --- | | `locale` | character string naming a locale. | ### Details The operation differs by OS. On Windows, a locale is specified like `"English_United Kingdom.1252"`. The final component gives the codepage, and this defines the encoding. On Unix-alikes: Locale names are normally like `es_MX.iso88591`. If final component indicates an encoding and it is not `utf8` we just need to look up the equivalent encoding name. Otherwise, the language (here `es`) is used to choose a primary or fallback encoding. In the `C` locale the answer will be `"ASCII"`. ### Value A character vector naming an encoding and possibly a fallback single-encoding, `NA` if unknown. ### Note The encoding names are those used by `libiconv`, and ought also to work with `glibc` but maybe not with commercial Unixen. ### See Also `[Sys.getlocale](../../base/html/locales)`, `[iconv](../../base/html/iconv)`. ### Examples ``` localeToCharset() ``` r None `INSTALL` Install Add-on Packages ---------------------------------- ### Description Utility for installing add-on packages. ### Usage ``` R CMD INSTALL [options] [-l lib] pkgs ``` ### Arguments | | | | --- | --- | | `pkgs` | a space-separated list with the path names of the packages to be installed. See ‘Details’. | | `lib` | the path name of the **R** library tree to install to. Also accepted in the form --library=lib. Paths including spaces should be quoted, using the conventions for the shell in use. | | `options` | a space-separated list of options through which in particular the process for building the help files can be controlled. Use `R CMD INSTALL --help` for the full current list of options. | ### Details This will stop at the first error, so if you want all the `pkgs` to be tried, call this via a shell loop. If used as `R CMD INSTALL pkgs` without explicitly specifying `lib`, packages are installed into the library tree rooted at the first directory in the library path which would be used by **R** run in the current environment. To install into the library tree `lib`, use `R CMD INSTALL -l lib pkgs`. This prepends `lib` to the library path for duration of the install, so required packages in the installation directory will be found (and used in preference to those in other libraries). Both `lib` and the elements of `pkgs` may be absolute or relative path names of directories. `pkgs` may also contain names of package archive files: these are then extracted to a temporary directory. These are tarballs containing a single directory, optionally compressed by `gzip`, `bzip2`, `xz` or `compress`. Finally, binary package archive files (as created by `R CMD INSTALL --build`) can be supplied. Tarballs are by default unpackaged by the internal `<untar>` function: if needed an external `tar` command can be specified by the environment variable R\_INSTALL\_TAR: please ensure that it can handle the type of compression used on the tarball. (This is sometimes needed for tarballs containing invalid or unsupported sections, and can be faster on very large tarballs. Setting R\_INSTALL\_TAR to tar.exe has been needed to overcome permissions issues on some Windows systems.) The package sources can be cleaned up prior to installation by --preclean or after by --clean: cleaning is essential if the sources are to be used with more than one architecture or platform. Some package sources contain a ‘configure’ script that can be passed arguments or variables via the option --configure-args and --configure-vars, respectively, if necessary. The latter is useful in particular if libraries or header files needed for the package are in non-system directories. In this case, one can use the configure variables `LIBS` and `CPPFLAGS` to specify these locations (and set these via --configure-vars), see section ‘Configuration variables’ in ‘R Installation and Administration’ for more information. (If these are used more than once on the command line they are concatenated.) The configure mechanism can be bypassed using the option --no-configure. If the attempt to install the package fails, leftovers are removed. If the package was already installed, the old version is restored. This happens either if a command encounters an error or if the install is interrupted from the keyboard: after cleaning up the script terminates. For details of the locking which is done, see the section ‘Locking’ in the help for `<install.packages>`. Option --build can be used to tar up the installed package for distribution as a binary package (as used on macOS). This is done by `utils::tar` unless environment variable R\_INSTALL\_TAR is set. By default a package is installed with static HTML help pages if and only if **R** was: use options --html and --no-html to override this. Packages are not by default installed keeping the source formatting (see the `keep.source` argument to `[source](../../base/html/source)`): this can be enabled by the option --with-keep.source or by setting environment variable R\_KEEP\_PKG\_SOURCE to `yes`. Specifying the --install-tests option copies the contents of the ‘tests’ directory into the package installation. If the R\_ALWAYS\_INSTALL\_TESTS environment variable is set to a true value, the tests will be installed even if --install-tests is omitted. Use `R CMD INSTALL --help` for concise usage information, including all the available options. ### Sub-architectures An **R** installation can support more than one sub-architecture: currently this is most commonly used for 32- and 64-bit builds on Windows. For such installations, the default behaviour is to try to install source packages for all installed sub-architectures unless the package has a configure script or a ‘src/Makefile’ (or ‘src/Makefile.win’ on Windows), when only compiled code for the sub-architecture running `R CMD INSTALL` is installed. To install a source package with compiled code only for the sub-architecture used by `R CMD INSTALL`, use --no-multiarch. To install just the compiled code for another sub-architecture, use --libs-only. There are two ways to install for all available sub-architectures. If the configure script is known to work for both Windows architectures, use flag --force-biarch (and packages can specify this *via* a Biarch: yes field in their `DESCRIPTION` files). Second, a single tarball can be installed with ``` R CMD INSTALL --merge-multiarch mypkg_version.tar.gz ``` ### Staged installation The default way to install source packages changed in **R** 3.6.0, so packages are first installed to a temporary location and then (if successful) moved to the destination library directory. Some older packages were written in ways that assume direct installation to the destination library. Staged installation can currently be overridden by having a line StagedInstall: no in the package's ‘DESCRIPTION’ file, *via* flag --no-staged-install or by setting environment variable R\_INSTALL\_STAGED to a false value (e.g. false or no). Staged installation requires either --pkglock or --lock, one of which is used by default. ### Note The options do not have to precede pkgs on the command line, although it will be more legible if they do. All the options are processed before any packages, and where options have conflicting effects the last one will win. Some parts of the operation of `INSTALL` depend on the **R** temporary directory (see `[tempdir](../../base/html/tempfile)`, usually under ‘/tmp’) having both write and execution access to the account running **R**. This is usually the case, but if ‘/tmp’ has been mounted as `noexec`, environment variable TMPDIR may need to be set to a directory from which execution is allowed. ### See Also `[REMOVE](remove)`; `[.libPaths](../../base/html/libpaths)` for information on using several library trees; `<install.packages>` for **R**-level installation of packages; `<update.packages>` for automatic update of packages using the Internet or a local repository. The section on ‘Add-on packages’ in ‘R Installation and Administration’ and the chapter on ‘Creating R packages’ in ‘Writing R Extensions’ *via* `[RShowDoc](rshowdoc)` or in the ‘doc/manual’ subdirectory of the **R** source tree.
programming_docs
r None `bug.report` Send a Bug Report ------------------------------- ### Description Invokes an editor or email program to write a bug report or opens a web page for bug submission. Some standard information on the current version and configuration of **R** are included automatically. ### Usage ``` bug.report(subject = "", address, file = "R.bug.report", package = NULL, lib.loc = NULL, ...) ``` ### Arguments | | | | --- | --- | | `subject` | Subject of the email. | | `address` | Recipient's email address, where applicable: for package bug reports sent by email this defaults to the address of the package maintainer (the first if more than one is listed). | | `file` | filename to use (if needed) for setting up the email. | | `package` | Optional character vector naming a single package which is the subject of the bug report. | | `lib.loc` | A character vector describing the location of **R** library trees in which to search for the package, or `NULL`. The default value of `NULL` corresponds to all libraries currently known. | | `...` | additional named arguments such as `method` and `ccaddress` to pass to `<create.post>`. | ### Details If `package` is `NULL` or a base package, this opens the R bugs tracker at <https://bugs.r-project.org/>. If `package` is specified, it is assumed that the bug report is about that package, and parts of its ‘DESCRIPTION’ file are added to the standard information. If the package has a non-empty `BugReports` field in the ‘DESCRIPTION’ file specifying the URL of a webpage, that URL will be opened using `[browseURL](browseurl)`, otherwise an email directed to the package maintainer will be generated using `<create.post>`. If there is any other form of `BugReports` field or a `Contact` field, this is examined as it may provide a preferred email address. ### Value Nothing useful. ### When is there a bug? If **R** executes an illegal instruction, or dies with an operating system error message that indicates a problem in the program (as opposed to something like “disk full”), then it is certainly a bug. Taking forever to complete a command can be a bug, but you must make certain that it was really **R**'s fault. Some commands simply take a long time. If the input was such that you KNOW it should have been processed quickly, report a bug. If you don't know whether the command should take a long time, find out by looking in the manual or by asking for assistance. If a command you are familiar with causes an **R** error message in a case where its usual definition ought to be reasonable, it is probably a bug. If a command does the wrong thing, that is a bug. But be sure you know for certain what it ought to have done. If you aren't familiar with the command, or don't know for certain how the command is supposed to work, then it might actually be working right. Rather than jumping to conclusions, show the problem to someone who knows for certain. Finally, a command's intended definition may not be best for statistical analysis. This is a very important sort of problem, but it is also a matter of judgement. Also, it is easy to come to such a conclusion out of ignorance of some of the existing features. It is probably best not to complain about such a problem until you have checked the documentation in the usual ways, feel confident that you understand it, and know for certain that what you want is not available. The mailing list `[email protected]` is a better place for discussions of this sort than the bug list. If you are not sure what the command is supposed to do after a careful reading of the manual this indicates a bug in the manual. The manual's job is to make everything clear. It is just as important to report documentation bugs as program bugs. If the online argument list of a function disagrees with the manual, one of them must be wrong, so report the bug. ### How to report a bug When you decide that there is a bug, it is important to report it and to report it in a way which is useful. What is most useful is an exact description of what commands you type, from when you start **R** until the problem happens. Always include the version of **R**, machine, and operating system that you are using; type `version` in **R** to print this. To help us keep track of which bugs have been fixed and which are still open please send a separate report for each bug. The most important principle in reporting a bug is to report FACTS, not hypotheses or categorizations. It is always easier to report the facts, but people seem to prefer to strain to posit explanations and report them instead. If the explanations are based on guesses about how **R** is implemented, they will be useless; we will have to try to figure out what the facts must have been to lead to such speculations. Sometimes this is impossible. But in any case, it is unnecessary work for us. For example, suppose that on a data set which you know to be quite large the command `data.frame(x, y, z, monday, tuesday)` never returns. Do not report that `data.frame()` fails for large data sets. Perhaps it fails when a variable name is a day of the week. If this is so then when we got your report we would try out the `data.frame()` command on a large data set, probably with no day of the week variable name, and not see any problem. There is no way in the world that we could guess that we should try a day of the week variable name. Or perhaps the command fails because the last command you used was a `[` method that had a bug causing **R**'s internal data structures to be corrupted and making the `data.frame()` command fail from then on. This is why we need to know what other commands you have typed (or read from your startup file). It is very useful to try and find simple examples that produce apparently the same bug, and somewhat useful to find simple examples that might be expected to produce the bug but actually do not. If you want to debug the problem and find exactly what caused it, that is wonderful. You should still report the facts as well as any explanations or solutions. Invoking **R** with the --vanilla option may help in isolating a bug. This ensures that the site profile and saved data files are not read. A bug report can be generated using the function `bug.report()`. For reports on **R** this will open the Web page at <https://bugs.r-project.org/>: for a contributed package it will open the package's bug tracker Web page or help you compose an email to the maintainer. Bug reports on **contributed packages** should not be sent to the R bug tracker: rather make use of the `package` argument. ### Author(s) This help page is adapted from the Emacs manual and the R FAQ ### See Also `<help.request>` which you possibly should try *before* `bug.report`. `<create.post>`, which handles emailing reports. The R FAQ, also `[sessionInfo](sessioninfo)()` from which you may add to the bug report. r None `read.table` Data Input ------------------------ ### Description Reads a file in table format and creates a data frame from it, with cases corresponding to lines and variables to fields in the file. ### Usage ``` read.table(file, header = FALSE, sep = "", quote = "\"'", dec = ".", numerals = c("allow.loss", "warn.loss", "no.loss"), row.names, col.names, as.is = !stringsAsFactors, na.strings = "NA", colClasses = NA, nrows = -1, skip = 0, check.names = TRUE, fill = !blank.lines.skip, strip.white = FALSE, blank.lines.skip = TRUE, comment.char = "#", allowEscapes = FALSE, flush = FALSE, stringsAsFactors = FALSE, fileEncoding = "", encoding = "unknown", text, skipNul = FALSE) read.csv(file, header = TRUE, sep = ",", quote = "\"", dec = ".", fill = TRUE, comment.char = "", ...) read.csv2(file, header = TRUE, sep = ";", quote = "\"", dec = ",", fill = TRUE, comment.char = "", ...) read.delim(file, header = TRUE, sep = "\t", quote = "\"", dec = ".", fill = TRUE, comment.char = "", ...) read.delim2(file, header = TRUE, sep = "\t", quote = "\"", dec = ",", fill = TRUE, comment.char = "", ...) ``` ### Arguments | | | | --- | --- | | `file` | the name of the file which the data are to be read from. Each row of the table appears as one line of the file. If it does not contain an *absolute* path, the file name is *relative* to the current working directory, `[getwd](../../base/html/getwd)()`. Tilde-expansion is performed where supported. This can be a compressed file (see `[file](../../base/html/connections)`). Alternatively, `file` can be a readable text-mode [connection](../../base/html/connections) (which will be opened for reading if necessary, and if so `[close](../../base/html/connections)`d (and hence destroyed) at the end of the function call). (If `[stdin](../../base/html/showconnections)()` is used, the prompts for lines may be somewhat confusing. Terminate input with a blank line or an EOF signal, `Ctrl-D` on Unix and `Ctrl-Z` on Windows. Any pushback on `stdin()` will be cleared before return.) `file` can also be a complete URL. (For the supported URL schemes, see the ‘URLs’ section of the help for `[url](../../base/html/connections)`.) | | `header` | a logical value indicating whether the file contains the names of the variables as its first line. If missing, the value is determined from the file format: `header` is set to `TRUE` if and only if the first row contains one fewer field than the number of columns. | | `sep` | the field separator character. Values on each line of the file are separated by this character. If `sep = ""` (the default for `read.table`) the separator is ‘white space’, that is one or more spaces, tabs, newlines or carriage returns. | | `quote` | the set of quoting characters. To disable quoting altogether, use `quote = ""`. See `[scan](../../base/html/scan)` for the behaviour on quotes embedded in quotes. Quoting is only considered for columns read as character, which is all of them unless `colClasses` is specified. | | `dec` | the character used in the file for decimal points. | | `numerals` | string indicating how to convert numbers whose conversion to double precision would lose accuracy, see `<type.convert>`. Can be abbreviated. (Applies also to complex-number inputs.) | | `row.names` | a vector of row names. This can be a vector giving the actual row names, or a single number giving the column of the table which contains the row names, or character string giving the name of the table column containing the row names. If there is a header and the first row contains one fewer field than the number of columns, the first column in the input is used for the row names. Otherwise if `row.names` is missing, the rows are numbered. Using `row.names = NULL` forces row numbering. Missing or `NULL` `row.names` generate row names that are considered to be ‘automatic’ (and not preserved by `[as.matrix](../../base/html/matrix)`). | | `col.names` | a vector of optional names for the variables. The default is to use `"V"` followed by the column number. | | `as.is` | controls conversion of character variables (insofar as they are not converted to logical, numeric or complex) to factors, if not otherwise specified by `colClasses`. Its value is either a vector of logicals (values are recycled if necessary), or a vector of numeric or character indices which specify which columns should not be converted to factors. Note: to suppress all conversions including those of numeric columns, set `colClasses = "character"`. Note that `as.is` is specified per column (not per variable) and so includes the column of row names (if any) and any columns to be skipped. | | `na.strings` | a character vector of strings which are to be interpreted as `[NA](../../base/html/na)` values. Blank fields are also considered to be missing values in logical, integer, numeric and complex fields. Note that the test happens *after* white space is stripped from the input, so `na.strings` values may need their own white space stripped in advance. | | `colClasses` | character. A vector of classes to be assumed for the columns. If unnamed, recycled as necessary. If named, names are matched with unspecified values being taken to be `NA`. Possible values are `NA` (the default, when `<type.convert>` is used), `"NULL"` (when the column is skipped), one of the atomic vector classes (logical, integer, numeric, complex, character, raw), or `"factor"`, `"Date"` or `"POSIXct"`. Otherwise there needs to be an `as` method (from package methods) for conversion from `"character"` to the specified formal class. Note that `colClasses` is specified per column (not per variable) and so includes the column of row names (if any). | | `nrows` | integer: the maximum number of rows to read in. Negative and other invalid values are ignored. | | `skip` | integer: the number of lines of the data file to skip before beginning to read data. | | `check.names` | logical. If `TRUE` then the names of the variables in the data frame are checked to ensure that they are syntactically valid variable names. If necessary they are adjusted (by `[make.names](../../base/html/make.names)`) so that they are, and also to ensure that there are no duplicates. | | `fill` | logical. If `TRUE` then in case the rows have unequal length, blank fields are implicitly added. See ‘Details’. | | `strip.white` | logical. Used only when `sep` has been specified, and allows the stripping of leading and trailing white space from unquoted `character` fields (`numeric` fields are always stripped). See `[scan](../../base/html/scan)` for further details (including the exact meaning of ‘white space’), remembering that the columns may include the row names. | | `blank.lines.skip` | logical: if `TRUE` blank lines in the input are ignored. | | `comment.char` | character: a character vector of length one containing a single character or an empty string. Use `""` to turn off the interpretation of comments altogether. | | `allowEscapes` | logical. Should C-style escapes such as \n be processed or read verbatim (the default)? Note that if not within quotes these could be interpreted as a delimiter (but not as a comment character). For more details see `[scan](../../base/html/scan)`. | | `flush` | logical: if `TRUE`, `scan` will flush to the end of the line after reading the last of the fields requested. This allows putting comments after the last field. | | `stringsAsFactors` | logical: should character vectors be converted to factors? Note that this is overridden by `as.is` and `colClasses`, both of which allow finer control. | | `fileEncoding` | character string: if non-empty declares the encoding used on a file (not a connection) so the character data can be re-encoded. See the ‘Encoding’ section of the help for `[file](../../base/html/connections)`, the ‘R Data Import/Export’ manual and ‘Note’. | | `encoding` | encoding to be assumed for input strings. It is used to mark character strings as known to be in Latin-1 or UTF-8 (see `[Encoding](../../base/html/encoding)`): it is not used to re-encode the input, but allows **R** to handle encoded strings in their native encoding (if one of those two). See ‘Value’ and ‘Note’. | | `text` | character string: if `file` is not supplied and this is, then data are read from the value of `text` via a text connection. Notice that a literal string can be used to include (small) data sets within R code. | | `skipNul` | logical: should nuls be skipped? | | `...` | Further arguments to be passed to `read.table`. | ### Details This function is the principal means of reading tabular data into **R**. Unless `colClasses` is specified, all columns are read as character columns and then converted using `<type.convert>` to logical, integer, numeric, complex or (depending on `as.is`) factor as appropriate. Quotes are (by default) interpreted in all fields, so a column of values like `"42"` will result in an integer column. A field or line is ‘blank’ if it contains nothing (except whitespace if no separator is specified) before a comment character or the end of the field or line. If `row.names` is not specified and the header line has one less entry than the number of columns, the first column is taken to be the row names. This allows data frames to be read in from the format in which they are printed. If `row.names` is specified and does not refer to the first column, that column is discarded from such files. The number of data columns is determined by looking at the first five lines of input (or the whole input if it has less than five lines), or from the length of `col.names` if it is specified and is longer. This could conceivably be wrong if `fill` or `blank.lines.skip` are true, so specify `col.names` if necessary (as in the ‘Examples’). `read.csv` and `read.csv2` are identical to `read.table` except for the defaults. They are intended for reading ‘comma separated value’ files (‘.csv’) or (`read.csv2`) the variant used in countries that use a comma as decimal point and a semicolon as field separator. Similarly, `read.delim` and `read.delim2` are for reading delimited files, defaulting to the TAB character for the delimiter. Notice that `header = TRUE` and `fill = TRUE` in these variants, and that the comment character is disabled. The rest of the line after a comment character is skipped; quotes are not processed in comments. Complete comment lines are allowed provided `blank.lines.skip = TRUE`; however, comment lines prior to the header must have the comment character in the first non-blank column. Quoted fields with embedded newlines are supported except after a comment character. Embedded nuls are unsupported: skipping them (with `skipNul = TRUE`) may work. ### Value A data frame (`[data.frame](../../base/html/data.frame)`) containing a representation of the data in the file. Empty input is an error unless `col.names` is specified, when a 0-row data frame is returned: similarly giving just a header line if `header = TRUE` results in a 0-row data frame. Note that in either case the columns will be logical unless `colClasses` was supplied. Character strings in the result (including factor levels) will have a declared encoding if `encoding` is `"latin1"` or `"UTF-8"`. ### Memory usage These functions can use a surprising amount of memory when reading large files. There is extensive discussion in the ‘R Data Import/Export’ manual, supplementing the notes here. Less memory will be used if `colClasses` is specified as one of the six [atomic](../../base/html/vector) vector classes. This can be particularly so when reading a column that takes many distinct numeric values, as storing each distinct value as a character string can take up to 14 times as much memory as storing it as an integer. Using `nrows`, even as a mild over-estimate, will help memory usage. Using `comment.char = ""` will be appreciably faster than the `read.table` default. `read.table` is not the right tool for reading large matrices, especially those with many columns: it is designed to read *data frames* which may have columns of very different classes. Use `[scan](../../base/html/scan)` instead for matrices. ### Note The columns referred to in `as.is` and `colClasses` include the column of row names (if any). There are two approaches for reading input that is not in the local encoding. If the input is known to be UTF-8 or Latin1, use the `encoding` argument to declare that. If the input is in some other encoding, then it may be translated on input. The `fileEncoding` argument achieves this by setting up a connection to do the re-encoding into the current locale. Note that on Windows or other systems not running in a UTF-8 locale, this may not be possible. ### References Chambers, J. M. (1992) *Data for models.* Chapter 3 of *Statistical Models in S* eds J. M. Chambers and T. J. Hastie, Wadsworth & Brooks/Cole. ### See Also The ‘R Data Import/Export’ manual. `[scan](../../base/html/scan)`, `<type.convert>`, `<read.fwf>` for reading *f*ixed *w*idth *f*ormatted input; `<write.table>`; `[data.frame](../../base/html/data.frame)`. `<count.fields>` can be useful to determine problems with reading files which result in reports of incorrect record lengths (see the ‘Examples’ below). <https://tools.ietf.org/html/rfc4180> for the IANA definition of CSV files (which requires comma as separator and CRLF line endings). ### Examples ``` ## using count.fields to handle unknown maximum number of fields ## when fill = TRUE test1 <- c(1:5, "6,7", "8,9,10") tf <- tempfile() writeLines(test1, tf) read.csv(tf, fill = TRUE) # 1 column ncol <- max(count.fields(tf, sep = ",")) read.csv(tf, fill = TRUE, header = FALSE, col.names = paste0("V", seq_len(ncol))) unlink(tf) ## "Inline" data set, using text= ## Notice that leading and trailing empty lines are auto-trimmed read.table(header = TRUE, text = " a b 1 2 3 4 ") ```
programming_docs
r None `install.packages` Install Packages from Repositories or Local Files --------------------------------------------------------------------- ### Description Download and install packages from CRAN-like repositories or from local files. ### Usage ``` install.packages(pkgs, lib, repos = getOption("repos"), contriburl = contrib.url(repos, type), method, available = NULL, destdir = NULL, dependencies = NA, type = getOption("pkgType"), configure.args = getOption("configure.args"), configure.vars = getOption("configure.vars"), clean = FALSE, Ncpus = getOption("Ncpus", 1L), verbose = getOption("verbose"), libs_only = FALSE, INSTALL_opts, quiet = FALSE, keep_outputs = FALSE, ...) ``` ### Arguments | | | | --- | --- | | `pkgs` | character vector of the names of packages whose current versions should be downloaded from the repositories. If `repos = NULL`, a character vector of file paths, on windows, file paths of ‘.zip’ files containing binary builds of packages. (`http://` and `file://` URLs are also accepted and the files will be downloaded and installed from local copies.) Source directories or file paths or URLs of archives may be specified with `type = "source"`, but some packages need suitable tools installed (see the ‘Details’ section). On Unix-alikes, these file paths can be source directories or archives or binary package archive files (as created by `R CMD build --binary`). (`http://` and `file://` URLs are also accepted and the files will be downloaded and installed from local copies.) On a CRAN build of **R** for macOS these can be ‘.tgz’ files containing binary package archives. Tilde-expansion will be done on file paths. If this is missing, a listbox of available packages is presented where possible in an interactive **R** session. | | `lib` | character vector giving the library directories where to install the packages. Recycled as needed. If missing, defaults to the first element of `[.libPaths](../../base/html/libpaths)()`. | | `repos` | character vector, the base URL(s) of the repositories to use, e.g., the URL of a CRAN mirror such as `"https://cloud.r-project.org"`. For more details on supported URL schemes see `[url](../../base/html/connections)`. Can be `NULL` to install from local files, directories or URLs: this will be inferred by extension from `pkgs` if of length one. | | `contriburl` | URL(s) of the contrib sections of the repositories. Use this argument if your repository mirror is incomplete, e.g., because you burned only the ‘contrib’ section on a CD, or only have binary packages. Overrides argument `repos`. Incompatible with `type = "both"`. | | `method` | download method, see `<download.file>`. Unused if a non-`NULL` `available` is supplied. | | `available` | a matrix as returned by `<available.packages>` listing packages available at the repositories, or `NULL` when the function makes an internal call to `available.packages`. Incompatible with `type = "both"`. | | `destdir` | directory where downloaded packages are stored. If it is `NULL` (the default) a subdirectory `downloaded_packages` of the session temporary directory will be used (and the files will be deleted at the end of the session). | | `dependencies` | logical indicating whether to also install uninstalled packages which these packages depend on/link to/import/suggest (and so on recursively). Not used if `repos = NULL`. Can also be a character vector, a subset of `c("Depends", "Imports", "LinkingTo", "Suggests", "Enhances")`. Only supported if `lib` is of length one (or missing), so it is unambiguous where to install the dependent packages. If this is not the case it is ignored, with a warning. The default, `NA`, means `c("Depends", "Imports", "LinkingTo")`. `TRUE` means to use `c("Depends", "Imports", "LinkingTo", "Suggests")` for `pkgs` and `c("Depends", "Imports", "LinkingTo")` for added dependencies: this installs all the packages needed to run `pkgs`, their examples, tests and vignettes (if the package author specified them correctly). In all of these, `"LinkingTo"` is omitted for binary packages. | | `type` | character, indicating the type of package to download and install. Will be `"source"` except on Windows and some macOS builds: see the section on ‘Binary packages’ for those. | | `configure.args` | (Used only for source installs.) A character vector or a named list. If a character vector with no names is supplied, the elements are concatenated into a single string (separated by a space) and used as the value for the --configure-args flag in the call to `R CMD INSTALL`. If the character vector has names these are assumed to identify values for --configure-args for individual packages. This allows one to specify settings for an entire collection of packages which will be used if any of those packages are to be installed. (These settings can therefore be re-used and act as default settings.) A named list can be used also to the same effect, and that allows multi-element character strings for each package which are concatenated to a single string to be used as the value for --configure-args. | | `configure.vars` | (Used only for source installs.) Analogous to `configure.args` for flag --configure-vars, which is used to set environment variables for the `configure` run. | | `clean` | a logical value indicating whether to add the --clean flag to the call to `R CMD INSTALL`. This is sometimes used to perform additional operations at the end of the package installation in addition to removing intermediate files. | | `Ncpus` | the number of parallel processes to use for a parallel install of more than one source package. Values greater than one are supported if the `make` command specified by `Sys.getenv("MAKE", "make")` accepts argument `-k -j Ncpus`. | | `verbose` | a logical indicating if some “progress report” should be given. | | `libs_only` | a logical value: should the --libs-only option be used to install only additional sub-architectures for source installs? (See also `INSTALL_opts`.) This can also be used on Windows to install just the DLL(s) from a binary package, e.g. to add 64-bit DLLs to a 32-bit install. | | `INSTALL_opts` | an optional character vector of additional option(s) to be passed to `R CMD INSTALL` for a source package install. E.g., `c("--html", "--no-multiarch", "--no-test-load")`. Can also be a named list of character vectors to be used as additional options, with names the respective package names. | | `quiet` | logical: if true, reduce the amount of output. This is *not* passed to `<available.packages>()` in case that is called, on purpose. | | `keep_outputs` | a logical: if true, keep the outputs from installing source packages in the current working directory, with the names of the output files the package names with ‘.out’ appended. Alternatively, a character string giving the directory in which to save the outputs. Ignored when installing from local files. | | `...` | Arguments to be passed to `<download.file>`, `<available.packages>`, or to the functions for binary installs on macOS and Windows (which accept an argument `"lock"`: see the section on ‘Locking’). | ### Details This is the main function to install packages. It takes a vector of names and a destination library, downloads the packages from the repositories and installs them. (If the library is omitted it defaults to the first directory in `.libPaths()`, with a message if there is more than one.) If `lib` is omitted or is of length one and is not a (group) writable directory, in interactive use the code offers to create a personal library tree (the first element of `Sys.getenv("R_LIBS_USER")`) and install there. Detection of a writable directory is problematic on Windows: see the ‘Note’ section. For installs from a repository an attempt is made to install the packages in an order that respects their dependencies. This does assume that all the entries in `lib` are on the default library path for installs (set by environment variable R\_LIBS). You are advised to run `update.packages` before `install.packages` to ensure that any already installed dependencies have their latest versions. ### Value Invisible `NULL`. ### Binary packages This section applies only to platforms where binary packages are available: Windows and CRAN builds for macOS. **R** packages are primarily distributed as *source* packages, but *binary* packages (a packaging up of the installed package) are also supported, and the type most commonly used on Windows and by the CRAN builds for macOS. This function can install either type, either by downloading a file from a repository or from a local file. Possible values of `type` are (currently) `"source"`, `"mac.binary"`, and `"win.binary"`: the appropriate binary type where supported can also be selected as `"binary"`. For a binary install from a repository, the function checks for the availability of a source package on the same repository, and reports if the source package has a later version, or is available but no binary version is. This check can be suppressed by using ``` options(install.packages.check.source = "no") ``` and should be if there is a partial repository containing only binary files. An alternative (and the current default) is `"both"` which means ‘use binary if available and current, otherwise try source’. The action if there are source packages which are preferred but may contain code which needs to be compiled is controlled by `[getOption](../../base/html/options)("install.packages.compile.from.source")`. `type = "both"` will be silently changed to `"binary"` if either `contriburl` or `available` is specified. Using packages with `type = "source"` always works provided the package contains no C/C++/Fortran code that needs compilation. Otherwise, on Windows you will need to have installed the Rtools collection as described in the ‘R for Windows FAQ’ *and* you must have the PATH environment variable set up as required by Rtools. For a 32/64-bit installation of **R** on Windows, a small minority of packages with compiled code need either `INSTALL_opts = "--force-biarch"` or `INSTALL_opts = "--merge-multiarch"` for a source installation. (It is safe to always set the latter when installing from a repository or tarballs, although it will be a little slower.) When installing a package on Windows, `install.packages` will abort the install if it detects that the package is already installed and is currently in use. In some circumstances (e.g., multiple instances of **R** running at the same time and sharing a library) it will not detect a problem, but the installation may fail as Windows locks files in use. On Unix-alikes, when the package contains C/C++/Fortran code that needs compilation, on macOS you need to have installed the ‘Command-line tools for Xcode’ (see the ‘R Installation and Administration’ manual) and if needed by the package a Fortran compiler, and have them in your path. ### Locking There are various options for locking: these differ between source and binary installs. By default for a source install, the library directory is ‘locked’ by creating a directory ‘00LOCK’ within it. This has two purposes: it prevents any other process installing into that library concurrently, and is used to store any previous version of the package to restore on error. A finer-grained locking is provided by the option --pkglock which creates a separate lock for each package: this allows enough freedom for parallel installation. Per-package locking is the default when installing a single package, and for multiple packages when `Ncpus > 1L`. Finally locking (and restoration on error) can be suppressed by --no-lock. For a macOS binary install, no locking is done by default. Setting argument `lock` to `TRUE` (it defaults to the value of `[getOption](../../base/html/options)("install.lock", FALSE)`) will use per-directory locking as described for source installs. For Windows binary install, per-directory locking is used by default (`lock` defaults to the value of `[getOption](../../base/html/options)("install.lock", TRUE)`). If the value is `"pkglock"` per-package locking will be used. If package locking is used on Windows with `libs_only = TRUE` and the installation fails, the package will be restored to its previous state. Note that it is possible for the package installation to fail so badly that the lock directory is not removed: this inhibits any further installs to the library directory (or for `--pkglock`, of the package) until the lock directory is removed manually. ### Parallel installs Parallel installs are attempted if `pkgs` has length greater than one and `Ncpus > 1`. It makes use of a parallel `make`, so the `make` specified (default `make`) when **R** was built must be capable of supporting `make -j n`: GNU make, `dmake` and `pmake` do, but Solaris `make` and older FreeBSD `make` do not: if necessary environment variable MAKE can be set for the current session to select a suitable `make`. `install.packages` needs to be able to compute all the dependencies of `pkgs` from `available`, including if one element of `pkgs` depends indirectly on another. This means that if for example you are installing CRAN packages which depend on Bioconductor packages which in turn depend on CRAN packages, `available` needs to cover both CRAN and Bioconductor packages. ### Timeouts A limit on the elapsed time for each call to `R CMD INSTALL` (so for source installs) can be set *via* environment variable \_R\_INSTALL\_PACKAGES\_ELAPSED\_TIMEOUT\_: in seconds (or in minutes or hours with optional suffix m or h, suffix s being allowed for the default seconds) with `0` meaning no limit. For non-parallel installs this is implemented *via* the `timeout` argument of `[system2](../../base/html/system2)`: for parallel installs *via* the OS's `timeout` command. (The one tested is from GNU coreutils, commonly available on Linux but not other Unix-alikes. If no such command is available the timeout request is ignored, with a warning.) For parallel installs a Error 124 message from `make` indicates that timeout occurred. Timeouts during installation might leave lock directories behind and not restore previous versions. ### Version requirements on source installs If you are not running an up-to-date version of **R** you may see a message like ``` package 'RODBC' is not available (for R version 3.5.3) ``` One possibility is that the package is not available in any of the selected repositories; another is that is available but only for current or recent versions of **R**. For CRAN packages take a look at the package's CRAN page (e.g., <https://cran.r-project.org/package=RODBC>). If that indicates in the Depends field a dependence on a later version of **R** you will need to look in the Old sources section and select the URL of a version of comparable age to your **R**. Then you can supply that URL as the first argument of `install.packages()`: you may need to first manually install its dependencies. For other repositories, using `available.packages(filters = "OS_type")[pkgname, ]` will show if the package is available for any **R** version (for your OS). ### Note On Unix-alikes: Some binary distributions of **R** have `INSTALL` in a separate bundle, e.g. an `R-devel` RPM. `install.packages` will give an error if called with `type = "source"` on such a system. Some binary Linux distributions of **R** can be installed on a machine without the tools needed to install packages: a possible remedy is to do a complete install of **R** which should bring in all those tools as dependencies. On Windows: `install.packages` tries to detect if you have write permission on the library directories specified, but Windows reports unreliably. If there is only one library directory (the default), **R** tries to find out by creating a test directory, but even this need not be the whole story: you may have permission to write in a library directory but lack permission to write binary files (such as ‘.dll’ files) there. See the ‘R for Windows FAQ’ for workarounds. ### See Also `<update.packages>`, `<available.packages>`, `<download.packages>`, `<installed.packages>`, `<contrib.url>`. See `<download.file>` for how to handle proxies and other options to monitor file transfers. `<untar>` for manually unpacking source package tarballs. `[INSTALL](install)`, `[REMOVE](remove)`, `<remove.packages>`, `[library](../../base/html/library)`, `[.packages](../../base/html/zpackages)`, `[read.dcf](../../base/html/dcf)` The ‘R Installation and Administration’ manual for how to set up a repository. ### Examples ``` ## Not run: ## A Linux example for Fedora's layout of udunits2 headers. install.packages(c("ncdf4", "RNetCDF"), configure.args = c(RNetCDF = "--with-netcdf-include=/usr/include/udunits2")) ## End(Not run) ``` r None `COMPILE` Compile Files for Use with R on Unix-alikes ------------------------------------------------------ ### Description Compile given source files so that they can subsequently be collected into a shared object using `R CMD SHLIB` or an executable program using `R CMD LINK`. Not available on Windows. ### Usage ``` R CMD COMPILE [options] srcfiles ``` ### Arguments | | | | --- | --- | | `srcfiles` | A list of the names of source files to be compiled. Currently, C, C++, Objective C, Objective C++ and Fortran are supported; the corresponding files should have the extensions ‘.c’, ‘.cc’ (or ‘.cpp’), ‘.m’, ‘.mm’ (or ‘.M’), ‘.f’ and ‘.f90’ or ‘.f95’, respectively. | | `options` | A list of compile-relevant settings, or for obtaining information about usage and version of the utility. | ### Details `R CMD SHLIB` can both compile and link files into a shared object: since it knows what run-time libraries are needed when passed C++, Fortran and Objective C(++) sources, passing source files to `R CMD SHLIB` is more reliable. Objective C and Objective C++ support is optional and will work only if the corresponding compilers were available at **R** configure time: their main usage is on macOS. Compilation arranges to include the paths to the **R** public C/C++ headers. As this compiles code suitable for incorporation into a shared object, it generates PIC code: that might occasionally be undesirable for the main code of an executable program. This is a `make`-based facility, so will not compile a source file if a newer corresponding ‘.o’ file is present. ### Note Some binary distributions of **R** have `COMPILE` in a separate bundle, e.g. an `R-devel` RPM. This is not available on Windows. ### See Also `[LINK](link)`, `[SHLIB](shlib)`, `[dyn.load](../../base/html/dynload)`; the section on “Customizing compilation under Unix” in “R Administration and Installation” (see the ‘doc/manual’ subdirectory of the **R** source tree). r None `close.socket` Close a Socket ------------------------------ ### Description Closes the socket and frees the space in the file descriptor table. The port may not be freed immediately. ### Usage ``` close.socket(socket, ...) ``` ### Arguments | | | | --- | --- | | `socket` | a `socket` object | | `...` | further arguments passed to or from other methods. | ### Value logical indicating success or failure ### Author(s) Thomas Lumley ### See Also `<make.socket>`, `<read.socket>` Compiling in support for sockets was optional prior to **R** 3.3.0: see `[capabilities](../../base/html/capabilities)("sockets")` to see if it is available. r None `help.request` Send a Post to R-help ------------------------------------- ### Description Prompts the user to check they have done all that is expected of them before sending a post to the R-help mailing list, provides a template for the post with session information included and optionally sends the email (on Unix systems). ### Usage ``` help.request(subject = "", address = "[email protected]", file = "R.help.request", ...) ``` ### Arguments | | | | --- | --- | | `subject` | subject of the email. Please do not use single quotes (`'`) in the subject! Post separate help requests for multiple queries. | | `address` | recipient's email address. | | `file` | filename to use (if needed) for setting up the email. | | `...` | additional named arguments such as `method` and `ccaddress` to pass to `<create.post>`. | ### Details This function is not intended to replace the posting guide. Please read the guide before posting to R-help or using this function (see <https://www.r-project.org/posting-guide.html>). The `help.request` function: * asks whether the user has consulted relevant resources, stopping and opening the relevant URL if a negative response if given. * checks whether the current version of **R** is being used and whether the add-on packages are up-to-date, giving the option of updating where necessary. * asks whether the user has prepared appropriate (minimal, reproducible, self-contained, commented) example code ready to paste into the post. Once this checklist has been completed a template post is prepared including current session information, and passed to `<create.post>`. ### Value Nothing useful. ### Author(s) Heather Turner, based on the then current code and help page of `<bug.report>()`. ### See Also The posting guide (<https://www.r-project.org/posting-guide.html>), also `[sessionInfo](sessioninfo)()` from which you may add to the help request. `<create.post>`.
programming_docs
r None `cite` Cite a Bibliography Entry --------------------------------- ### Description Cite a `bibentry` object in text. The `cite()` function uses the `cite()` function from the default `[bibstyle](../../tools/html/bibstyle)` if present, or `citeNatbib()` if not. `citeNatbib()` uses a style similar to that used by the LaTeX package natbib. ### Usage ``` cite(keys, bib, ...) citeNatbib(keys, bib, textual = FALSE, before = NULL, after = NULL, mode = c("authoryear", "numbers", "super"), abbreviate = TRUE, longnamesfirst = TRUE, bibpunct = c("(", ")", ";", "a", "", ","), previous) ``` ### Arguments | | | | --- | --- | | `keys` | A character vector of keys of entries to cite. May contain multiple keys in a single entry, separated by commas. | | `bib` | A `"<bibentry>"` object containing the list of documents in which to find the keys. | | `...` | Additional arguments to pass to the `cite()` function for the default style. | | `textual` | Produce a “textual” style of citation, i.e. what `\citet` would produce in LaTeX. | | `before` | Optional text to display before the citation. | | `after` | Optional text to display after the citation. | | `mode` | The “mode” of citation. | | `abbreviate` | Whether to abbreviate long author lists. | | `longnamesfirst` | If `abbreviate == TRUE`, whether to leave the first citation long. | | `bibpunct` | A vector of punctuation to use in the citation, as used in natbib. See the Details section. | | `previous` | A list of keys that have been previously cited, to be used when `abbreviate == TRUE` and `longnamesfirst == TRUE` | ### Details Argument names are chosen based on the documentation for the LaTeX natbib package. See that documentation for the interpretation of the `bibpunct` entries. The entries in `bibpunct` are as follows: 1. The left delimiter. 2. The right delimiter. 3. The separator between references within a citation. 4. An indicator of the “mode”: `"n"` for numbers, `"s"` for superscripts, anything else for author-year. 5. Punctuation to go between the author and year. 6. Punctuation to go between years when authorship is suppressed. Note that if `mode` is specified, it overrides the mode specification in `bibpunct[4]`. Partial matching is used for `mode`. The defaults for `citeNatbib` have been chosen to match the JSS style, and by default these are used in `cite`. See `[bibstyle](../../tools/html/bibstyle)` for how to set a different default style. ### Value A single element character string is returned, containing the citation. ### Author(s) Duncan Murdoch ### Examples ``` ## R reference rref <- bibentry( bibtype = "Manual", title = "R: A Language and Environment for Statistical Computing", author = person("R Core Team"), organization = "R Foundation for Statistical Computing", address = "Vienna, Austria", year = 2013, url = "https://www.R-project.org/", key = "R") ## References for boot package and associated book bref <- c( bibentry( bibtype = "Manual", title = "boot: Bootstrap R (S-PLUS) Functions", author = c( person("Angelo", "Canty", role = "aut", comment = "S original"), person(c("Brian", "D."), "Ripley", role = c("aut", "trl", "cre"), comment = "R port, author of parallel support", email = "[email protected]") ), year = "2012", note = "R package version 1.3-4", url = "https://CRAN.R-project.org/package=boot", key = "boot-package" ), bibentry( bibtype = "Book", title = "Bootstrap Methods and Their Applications", author = as.person("Anthony C. Davison [aut], David V. Hinkley [aut]"), year = "1997", publisher = "Cambridge University Press", address = "Cambridge", isbn = "0-521-57391-2", url = "http://statwww.epfl.ch/davison/BMA/", key = "boot-book" ) ) ## Combine and cite refs <- c(rref, bref) cite("R, boot-package", refs) ## Cite numerically savestyle <- tools::getBibstyle() tools::bibstyle("JSSnumbered", .init = TRUE, fmtPrefix = function(paper) paste0("[", paper$.index, "]"), cite = function(key, bib, ...) citeNatbib(key, bib, mode = "numbers", bibpunct = c("[", "]", ";", "n", "", ","), ...) ) cite("R, boot-package", refs, textual = TRUE) refs ## restore the old style tools::bibstyle(savestyle, .default = TRUE) ``` r None `promptPackage` Generate a Shell for Documentation of a Package ---------------------------------------------------------------- ### Description Generates a shell of documentation for an installed or source package. ### Usage ``` promptPackage(package, lib.loc = NULL, filename = NULL, name = NULL, final = FALSE) ``` ### Arguments | | | | --- | --- | | `package` | a `[character](../../base/html/character)` string with the name of an *installed* or *source* package to be documented. | | `lib.loc` | a character vector describing the location of **R** library trees to search through, or `NULL`. The default value of `NULL` corresponds to all libraries currently known. For a source package this should specify the parent directory of the package's sources. | | `filename` | usually, a [connection](../../base/html/connections) or a character string giving the name of the file to which the documentation shell should be written. The default corresponds to a file whose name is `name` followed by `".Rd"`. Can also be `NA` (see below). | | `name` | a character string specifying the name of the help topic, typically of the form <pkg>-package. | | `final` | a logical value indicating whether to attempt to create a usable version of the help topic, rather than just a shell. | ### Details Unless `filename` is `NA`, a documentation shell for `package` is written to the file specified by `filename`, and a message about this is given. If `filename` is `NA`, a list-style representation of the documentation shell is created and returned. Writing the shell to a file amounts to `cat(unlist(x), file = filename, sep = "\n")`, where `x` is the list-style representation. If `final` is `TRUE`, the generated documentation will not include the place-holder slots for manual editing, it will be usable as-is. In most cases a manually edited file is preferable (but `final = TRUE` is certainly less work). ### Value If `filename` is `NA`, a list-style representation of the documentation shell. Otherwise, the name of the file written to is returned invisibly. ### See Also `<prompt>`, `<package.skeleton>` ### Examples ``` filename <- tempfile() promptPackage("utils", filename = filename) file.show(filename) unlink(filename) ``` r None `download.packages` Download Packages from CRAN-like Repositories ------------------------------------------------------------------ ### Description These functions can be used to automatically compare the version numbers of installed packages with the newest available version on the repositories and update outdated packages on the fly. ### Usage ``` download.packages(pkgs, destdir, available = NULL, repos = getOption("repos"), contriburl = contrib.url(repos, type), method, type = getOption("pkgType"), ...) ``` ### Arguments | | | | --- | --- | | `pkgs` | character vector of the names of packages whose latest available versions should be downloaded from the repositories. | | `destdir` | directory where downloaded packages are to be stored. | | `available` | an object as returned by `<available.packages>` listing packages available at the repositories, or `NULL` which makes an internal call to `available.packages`. | | `repos` | character vector, the base URL(s) of the repositories to use, i.e., the URL of the CRAN master such as `"https://cran.r-project.org"` or its Statlib mirror, `"http://lib.stat.cmu.edu/R/CRAN"`. | | `contriburl` | URL(s) of the contrib sections of the repositories. Use this argument only if your repository mirror is incomplete, e.g., because you burned only the ‘contrib’ section on a CD. Overrides argument `repos`. | | `method` | Download method, see `<download.file>`. | | `type` | character string, indicate which type of packages: see `<install.packages>` and ‘Details’. | | `...` | additional arguments to be passed to `<download.file>` and `<available.packages>`. | ### Details `download.packages` takes a list of package names and a destination directory, downloads the newest versions and saves them in `destdir`. If the list of available packages is not given as argument, it is obtained from repositories. If a repository is local, i.e. the URL starts with `"file:"`, then the packages are not downloaded but used directly. Both `"file:"` and `"file:///"` are allowed as prefixes to a file path. Use the latter only for URLs: see `[url](../../base/html/connections)` for their interpretation. (Other forms of file:// URLs are not supported.) For `download.packages`, `type = "both"` looks at source packages only. ### Value A two-column matrix of names and destination file names of those packages successfully downloaded. If packages are not available or there is a problem with the download, suitable warnings are given. ### See Also `<available.packages>`, `<contrib.url>`. The main use is by `<install.packages>`. See `<download.file>` for how to handle proxies and other options to monitor file transfers. The ‘R Installation and Administration’ manual for how to set up a repository. r None `Rprofmem` Enable Profiling of R's Memory Use ---------------------------------------------- ### Description Enable or disable reporting of memory allocation in R. ### Usage ``` Rprofmem(filename = "Rprofmem.out", append = FALSE, threshold = 0) ``` ### Arguments | | | | --- | --- | | `filename` | The file to be used for recording the memory allocations. Set to `NULL` or `""` to disable reporting. | | `append` | logical: should the file be over-written or appended to? | | `threshold` | numeric: allocations on R's "large vector" heap larger than this number of bytes will be reported. | ### Details Enabling profiling automatically disables any existing profiling to another or the same file. Profiling writes the call stack to the specified file every time `malloc` is called to allocate a large vector object or to allocate a page of memory for small objects. The size of a page of memory and the size above which `malloc` is used for vectors are compile-time constants, by default 2000 and 128 bytes respectively. The profiler tracks allocations, some of which will be to previously used memory and will not increase the total memory use of R. ### Value None ### Note The memory profiler slows down R even when not in use, and so is a compile-time option. (It is enabled in a standard Windows build of **R**.) The memory profiler can be used at the same time as other **R** and C profilers. ### See Also The R sampling profiler, `[Rprof](rprof)` also collects memory information. `[tracemem](../../base/html/tracemem)` traces duplications of specific objects. The "Writing R Extensions" manual section on "Tidying and profiling R code" ### Examples ``` ## Not run: ## not supported unless R is compiled to support it. Rprofmem("Rprofmem.out", threshold = 1000) example(glm) Rprofmem(NULL) noquote(readLines("Rprofmem.out", n = 5)) ## End(Not run) ``` r None `page` Invoke a Pager on an R Object ------------------------------------- ### Description Displays a representation of the object named by `x` in a pager *via* `[file.show](../../base/html/file.show)`. ### Usage ``` page(x, method = c("dput", "print"), ...) ``` ### Arguments | | | | --- | --- | | `x` | An **R** object, or a character string naming an object. | | `method` | The default method is to dump the object *via* `[dput](../../base/html/dput)`. An alternative is to use `print` and capture the output to be shown in the pager. Can be abbreviated. | | `...` | additional arguments for `[dput](../../base/html/dput)`, `[print](../../base/html/print)` or `[file.show](../../base/html/file.show)` (such as `title`). | ### Details If `x` is a length-one character vector, it is used as the name of an object to look up in the environment from which `page` is called. All other objects are displayed directly. A default value of `title` is passed to `file.show` if one is not supplied in `...`. ### See Also `[file.show](../../base/html/file.show)`, `<edit>`, `<fix>`. To go to a new page when graphing, see `[frame](../../graphics/html/frame)`. ### Examples ``` ## Not run: ## four ways to look at the code of 'page' page(page) # as an object page("page") # a character string v <- "page"; page(v) # a length-one character vector page(utils::page) # a call ## End(Not run) ``` r None `arrangeWindows` Rearrange Windows on MS Windows ------------------------------------------------- ### Description This function allows you to tile or cascade windows, or to minimize or restore them (on Windows, i.e. when `([.Platform](../../base/html/platform)$OS.type == "windows")`). This may include windows not “belonging” to **R**. ### Usage ``` arrangeWindows(action, windows, preserve = TRUE, outer = FALSE) ``` ### Arguments | | | | --- | --- | | `action` | a character string, the action to perform on the windows. The choices are `c("vertical", "horizontal", "cascade", "minimize", "restore")` with default `"vertical"`; see the ‘Details’ for the interpretation. Abbreviations may be used. | | `windows` | a `[list](../../base/html/list)` of window handles, by default produced by `[getWindowsHandles](getwindowshandles)()`. | | `preserve` | If `TRUE`, when tiling preserve the outer boundary of the collection of windows; otherwise make them as large as will fit. | | `outer` | This argument is only used in MDI mode. If `TRUE`, tile the windows on the system desktop. Otherwise, tile them within the MDI frame. | ### Details The actions are as follows: `"vertical"` Tile vertically. `"horizontal"` Tile horizontally. `"cascade"` Cascade the windows. `"minimize"` Minimize all of the windows. `"restore"` Restore all of the windows to normal size (not minimized, not maximized). The tiling and cascading are done by the standard Windows API functions, but unlike those functions, they will apply to all of the windows in the `windows` list. By default, `windows` is set to the result of `[getWindowsHandles](getwindowshandles)()` (with one exception described below). This will select windows belonging to the current **R** process. However, if the global environment contains a variable named `.arrangeWindowsDefaults`, it will be used as the argument list instead. See the `[getWindowsHandles](getwindowshandles)` man page for a discussion of the optional arguments to that function. When `action = "restore"` is used with `windows` unspecified, `minimized = TRUE` is added to the argument list of `[getWindowsHandles](getwindowshandles)` so that minimized windows will be restored. In MDI mode, by default tiling and cascading will happen within the **R** GUI frame. However, if `outer = TRUE`, tiling is done on the system desktop. This will generally not give desirable results if any **R** child windows are included within `windows`. ### Value This function is called for the side effect of arranging the windows. The list of window handles is returned invisibly. ### Note This is only available on Windows. ### Author(s) Duncan Murdoch ### See Also `[getWindowsHandles](getwindowshandles)` ### Examples ``` ## Not run: ## Only available on Windows : arrangeWindows("v") # This default is useful only in SDI mode: it will tile any Firefox window # along with the R windows .arrangeWindowsDefaults <- list(c("R", "all"), pattern = c("", "Firefox")) arrangeWindows("v") ## End(Not run) ``` r None `format` Format Unordered and Ordered Lists -------------------------------------------- ### Description Format unordered (itemize) and ordered (enumerate) lists. ### Usage ``` formatUL(x, label = "*", offset = 0, width = 0.9 * getOption("width")) formatOL(x, type = "arabic", offset = 0, start = 1, width = 0.9 * getOption("width")) ``` ### Arguments | | | | --- | --- | | `x` | a character vector of list items. | | `label` | a character string used for labelling the items. | | `offset` | a non-negative integer giving the offset (indentation) of the list. | | `width` | a positive integer giving the target column for wrapping lines in the output. | | `type` | a character string specifying the ‘type’ of the labels in the ordered list. If `"arabic"` (default), arabic numerals are used. For `"Alph"` or `"alph"`, single upper or lower case letters are employed (in this case, the number of the last item must not exceed 26). Finally, for `"Roman"` or `"roman"`, the labels are given as upper or lower case roman numerals (with the number of the last item maximally 3899). `type` can be given as a unique abbreviation of the above, or as one of the HTML style tokens `"1"` (arabic), `"A"`/`"a"` (alphabetic), or `"I"`/`"i"` (roman), respectively. | | `start` | a positive integer specifying the starting number of the first item in an ordered list. | ### Value A character vector with the formatted entries. ### See Also `[formatDL](../../base/html/formatdl)` for formatting description lists. ### Examples ``` ## A simpler recipe. x <- c("Mix dry ingredients thoroughly.", "Pour in wet ingredients.", "Mix for 10 minutes.", "Bake for one hour at 300 degrees.") ## Format and output as an unordered list. writeLines(formatUL(x)) ## Format and output as an ordered list. writeLines(formatOL(x)) ## Ordered list using lower case roman numerals. writeLines(formatOL(x, type = "i")) ## Ordered list using upper case letters and some offset. writeLines(formatOL(x, type = "A", offset = 5)) ``` r None `changedFiles` Detect which Files Have Changed ----------------------------------------------- ### Description `fileSnapshot` takes a snapshot of a selection of files, recording summary information about each. `changedFiles` compares two snapshots, or compares one snapshot to the current state of the file system. The snapshots need not be the same directory; this could be used to compare two directories. ### Usage ``` fileSnapshot(path = ".", file.info = TRUE, timestamp = NULL, md5sum = FALSE, digest = NULL, full.names = length(path) > 1, ...) changedFiles(before, after, path = before$path, timestamp = before$timestamp, check.file.info = c("size", "isdir", "mode", "mtime"), md5sum = before$md5sum, digest = before$digest, full.names = before$full.names, ...) ## S3 method for class 'fileSnapshot' print(x, verbose = FALSE, ...) ## S3 method for class 'changedFiles' print(x, verbose = FALSE, ...) ``` ### Arguments | | | | --- | --- | | `path` | character vector; the path(s) to record. | | `file.info` | logical; whether to record `[file.info](../../base/html/file.info)` values for each file. | | `timestamp` | character string or `NULL`; the name of a file to write at the time the snapshot is taken. This gives a quick test for modification, but may be unreliable; see the Details. | | `md5sum` | logical; whether MD5 summaries of each file should be taken as part of the snapshot. | | `digest` | a function or `NULL`; a function with header `function(filename)` which will take a vector of filenames and produce a vector of values of the same length, or a matrix with that number of rows. | | `full.names` | logical; whether full names (as in `[list.files](../../base/html/list.files)`) should be recorded. Must be `TRUE` if `length(path) > 1`. | | `...` | additional parameters to pass to `[list.files](../../base/html/list.files)` to control the set of files in the snapshots. | | `before, after` | objects produced by `fileSnapshot`; two snapshots to compare. If `after` is missing, a new snapshot of the current file system will be produced for comparison, using arguments recorded in `before` as defaults. | | `check.file.info` | character vector; which columns from `[file.info](../../base/html/file.info)` should be compared. | | `x` | the object to print. | | `verbose` | logical; whether to list all data when printing. | ### Details The `fileSnapshot` function uses `[list.files](../../base/html/list.files)` to obtain a list of files, and depending on the `file.info`, `md5sum`, and `digest` arguments, records information about each file. The `changedFiles` function compares two snapshots. If the `timestamp` argument to `fileSnapshot` is length 1, a file with that name is created. If it is length 1 in `changedFiles`, the `[file\_test](filetest)` function is used to compare the age of all files common to both `before` and `after` to it. This test may be unreliable: it compares the current modification time of the `after` files to the timestamp; that may not be the same as the modification time when the `after` snapshot was taken. It may also give incorrect results if the clock on the file system holding the timestamp differs from the one holding the snapshot files. If the `check.file.info` argument contains a non-empty character vector, the indicated columns from the result of a call to `[file.info](../../base/html/file.info)` will be compared. If `md5sum` is `TRUE`, `fileSnapshot` will call the `tools::[md5sum](../../tools/html/md5sum)` function to record the 32 byte MD5 checksum for each file, and `changedFiles` will compare the values. The `digest` argument allows users to provide their own digest function. ### Value `fileSnapshot` returns an object of class `"fileSnapshot"`. This is a list containing the fields | | | | --- | --- | | `info` | a data frame whose rownames are the filenames, and whose columns contain the requested snapshot data | | `path` | the normalized `path` from the call | | `timestamp, file.info, md5sum, digest, full.names` | a record of the other arguments from the call | | `args` | other arguments passed via `...` to `[list.files](../../base/html/list.files)`. | `changedFiles` produces an object of class `"changedFiles"`. This is a list containing | | | | --- | --- | | `added, deleted, changed, unchanged` | character vectors of filenames from the before and after snapshots, with obvious meanings | | `changes` | a logical matrix with a row for each common file, and a column for each comparison test. `TRUE` indicates a change in that test. | `[print](../../base/html/print)` methods are defined for each of these types. The `[print](../../base/html/print)` method for `"fileSnapshot"` objects displays the arguments used to produce them, while the one for `"changedFiles"` displays the `added`, `deleted` and `changed` fields if non-empty, and a submatrix of the `changes` matrix containing all of the `TRUE` values. ### Author(s) Duncan Murdoch, using suggestions from Karl Millar and others. ### See Also `[file.info](../../base/html/file.info)`, `[file\_test](filetest)`, `[md5sum](../../tools/html/md5sum)`. ### Examples ``` # Create some files in a temporary directory dir <- tempfile() dir.create(dir) writeBin(1L, file.path(dir, "file1")) writeBin(2L, file.path(dir, "file2")) dir.create(file.path(dir, "dir")) # Take a snapshot snapshot <- fileSnapshot(dir, timestamp = tempfile("timestamp"), md5sum=TRUE) # Change one of the files. writeBin(3L:4L, file.path(dir, "file2")) # Display the detected changes. We may or may not see mtime change... changedFiles(snapshot) changedFiles(snapshot)$changes ```
programming_docs
r None `SHLIB` Build Shared Object/DLL for Dynamic Loading ---------------------------------------------------- ### Description Compile the given source files and then link all specified object files into a shared object aka DLL which can be loaded into **R** using `dyn.load` or `library.dynam`. ### Usage ``` R CMD SHLIB [options] [-o dllname] files ``` ### Arguments | | | | --- | --- | | `files` | a list specifying the object files to be included in the shared object/DLL. You can also include the name of source files (for which the object files are automagically made from their sources) and library linking commands. | | `dllname` | the full name of the shared object/DLL to be built, including the extension (typically ‘.so’ on Unix systems, and ‘.dll’ on Windows). If not given, the basename of the object/DLL is taken from the basename of the first file. | | `options` | Further options to control the processing. Use `R CMD SHLIB --help` for a current list. | ### Details `R CMD SHLIB` is the mechanism used by `[INSTALL](install)` to compile source code in packages. It will generate suitable compilation commands for C, C++, Objective C(++) and Fortran sources: Fortran 90/95 sources can also be used but it may not be possible to mix these with other languages (on most platforms it is possible to mix with C, but mixing with C++ rarely works). Please consult section ‘Creating shared objects’ in the manual ‘Writing R Extensions’ for how to customize it (for example to add `cpp` flags and to add libraries to the link step) and for details of some of its quirks. Items in `files` with extensions ‘.c’, ‘.cpp’, ‘.cc’, ‘.C’, ‘.f’, ‘.f90’, ‘.f95’, ‘.m’ (ObjC), ‘.M’ and ‘.mm’ (ObjC++) are regarded as source files, and those with extension ‘.o’ as object files. All other items are passed to the linker. Objective C(++) support is optional when **R** was configured: their main usage is on macOS. Note that the appropriate run-time libraries will be used when linking if C++, Fortran or Objective C(++) sources are supplied, but not for compiled object files from these languages. Option -n (also known as --dry-run) will show the commands that would be run without actually executing them. ### Note Some binary distributions of **R** have `SHLIB` in a separate bundle, e.g., an `R-devel` RPM. ### See Also `[COMPILE](compile)`, `[dyn.load](../../base/html/dynload)`, `[library.dynam](../../base/html/library.dynam)`. The ‘R Installation and Administration’ and ‘Writing R Extensions’ manuals, including the section on ‘Customizing compilation’ in the former. ### Examples ``` ## Not run: # To link against a library not on the system library paths: R CMD SHLIB -o mylib.so a.f b.f -L/opt/acml3.5.0/gnu64/lib -lacml ## End(Not run) ``` r None `PkgUtils` Utilities for Building and Checking Add-on Packages --------------------------------------------------------------- ### Description Utilities for checking whether the sources of an **R** add-on package work correctly, and for building a source package from them. ### Usage ``` R CMD check [options] pkgdirs R CMD build [options] pkgdirs ``` ### Arguments | | | | --- | --- | | `pkgdirs` | a list of names of directories with sources of **R** add-on packages. For `check` these can also be the filenames of compressed `tar` archives with extension ‘.tar.gz’, ‘.tgz’, ‘.tar.bz2’ or ‘.tar.xz’. | | `options` | further options to control the processing, or for obtaining information about usage and version of the utility. | ### Details `R CMD check` checks **R** add-on packages from their sources, performing a wide variety of diagnostic checks. `R CMD build` builds **R** source tarballs. The name(s) of the packages are taken from the ‘DESCRIPTION’ files and not from the directory names. This works entirely on a copy of the supplied source directories. Use `R CMD foo --help` to obtain usage information on utility `foo`. The defaults for some of the options to `R CMD build` can be set by environment variables \_R\_BUILD\_RESAVE\_DATA\_ and \_R\_BUILD\_COMPACT\_VIGNETTES\_: see ‘Writing R Extensions’. Many of the checks in `R CMD check` can be turned off or on by environment variables: see Chapter ‘Tools’ of the ‘R Internals’ manual. By default `R CMD build` uses the `"internal"` option to `<tar>` to prepare the tarball. An external `tar` program can be specified by the R\_BUILD\_TAR environment variable. This may be substantially faster for very large packages, and can be needed for packages with long path names (over 100 bytes) or very large files (over 8GB): however, the resulting tarball may not be portable. `R CMD check` by default unpacks tarballs by the internal `<untar>` function: if needed an external `tar` command can be specified by the environment variable R\_INSTALL\_TAR: please ensure that it can handle the type of compression used on the tarball. (This is sometimes needed for tarballs containing invalid or unsupported sections, and can be faster on very large tarballs. Setting R\_INSTALL\_TAR to tar.exe has been needed to overcome permissions issues on some Windows systems.) ### Note Only on Windows: They make use of a temporary directory specified by the environment variable `TMPDIR` and defaulting to c:/TEMP. Do ensure that if set forward slashes are used. ### See Also The sections on ‘Checking and building packages’ and ‘Processing Rd format’ in ‘Writing R Extensions’ (see on Unix-alikes the ‘doc/manual’ subdirectory of the **R** source tree, on Windows, see the Manuals sub-menu of the Help menu on the console). r None `maintainer` Show Package Maintainer ------------------------------------- ### Description Show the name and email address of the maintainer of a package. ### Usage ``` maintainer(pkg) ``` ### Arguments | | | | --- | --- | | `pkg` | Character string. The name of a single package. | ### Details Accesses the package description to return the name and email address of the maintainer. Questions about contributed packages should often be addressed to the package maintainer; questions about base packages should usually be addressed to the R-help or R-devel mailing lists. Bug reports should be submitted using the `<bug.report>` function. ### Value A character string giving the name and email address of the maintainer of the package, or `NA` if no such package is installed. ### Author(s) David Scott <[email protected]> from code on R-help originally due to Charlie Sharpsteen <[email protected]>; multiple corrections by R-core. ### References <https://stat.ethz.ch/pipermail/r-help/2010-February/230027.html> ### See Also `[packageDescription](packagedescription)`, `<bug.report>` ### Examples ``` maintainer("MASS") ``` r None `read.fwf` Read Fixed Width Format Files ----------------------------------------- ### Description Read a table of **f**ixed **w**idth **f**ormatted data into a `[data.frame](../../base/html/data.frame)`. ### Usage ``` read.fwf(file, widths, header = FALSE, sep = "\t", skip = 0, row.names, col.names, n = -1, buffersize = 2000, fileEncoding = "", ...) ``` ### Arguments | | | | --- | --- | | `file` | the name of the file which the data are to be read from. Alternatively, `file` can be a [connection](../../base/html/connections), which will be opened if necessary, and if so closed at the end of the function call. | | `widths` | integer vector, giving the widths of the fixed-width fields (of one line), or list of integer vectors giving widths for multiline records. | | `header` | a logical value indicating whether the file contains the names of the variables as its first line. If present, the names must be delimited by `sep`. | | `sep` | character; the separator used internally; should be a character that does not occur in the file (except in the header). | | `skip` | number of initial lines to skip; see `<read.table>`. | | `row.names` | see `<read.table>`. | | `col.names` | see `<read.table>`. | | `n` | the maximum number of records (lines) to be read, defaulting to no limit. | | `buffersize` | Maximum number of lines to read at one time | | `fileEncoding` | character string: if non-empty declares the encoding used on a file (not a connection) so the character data can be re-encoded. See the ‘Encoding’ section of the help for `[file](../../base/html/connections)`, the ‘R Data Import/Export’ manual and ‘Note’. | | `...` | further arguments to be passed to `<read.table>`. Useful such arguments include `as.is`, `na.strings`, `colClasses` and `strip.white`. | ### Details Multiline records are concatenated to a single line before processing. Fields that are of zero-width or are wholly beyond the end of the line in `file` are replaced by `NA`. Negative-width fields are used to indicate columns to be skipped, e.g., `-5` to skip 5 columns. These fields are not seen by `read.table` and so should not be included in a `col.names` or `colClasses` argument (nor in the header line, if present). Reducing the `buffersize` argument may reduce memory use when reading large files with long lines. Increasing `buffersize` may result in faster processing when enough memory is available. Note that `read.fwf` (not `read.table`) reads the supplied file, so the latter's argument `encoding` will not be useful. ### Value A `[data.frame](../../base/html/data.frame)` as produced by `<read.table>` which is called internally. ### Author(s) Brian Ripley for **R** version: originally in `Perl` by Kurt Hornik. ### See Also `[scan](../../base/html/scan)` and `<read.table>`. `<read.fortran>` for another style of fixed-format files. ### Examples ``` ff <- tempfile() cat(file = ff, "123456", "987654", sep = "\n") read.fwf(ff, widths = c(1,2,3)) #> 1 23 456 \ 9 87 654 read.fwf(ff, widths = c(1,-2,3)) #> 1 456 \ 9 654 unlink(ff) cat(file = ff, "123", "987654", sep = "\n") read.fwf(ff, widths = c(1,0, 2,3)) #> 1 NA 23 NA \ 9 NA 87 654 unlink(ff) cat(file = ff, "123456", "987654", sep = "\n") read.fwf(ff, widths = list(c(1,0, 2,3), c(2,2,2))) #> 1 NA 23 456 98 76 54 unlink(ff) ``` r None `LINK` Create Executable Programs on Unix-alikes ------------------------------------------------- ### Description Front-end for creating executable programs on unix-alikes, i.e., not on Windows. ### Usage ``` R CMD LINK [options] linkcmd ``` ### Arguments | | | | --- | --- | | `linkcmd` | a list of commands to link together suitable object files (include library objects) to create the executable program. | | `options` | further options to control the linking, or for obtaining information about usage and version. | ### Details The linker front-end is useful in particular when linking against the **R** shared or static library: see the examples. The actual linking command is constructed by the version of `libtool` installed at ‘R\_HOME/bin’. `R CMD LINK --help` gives usage information. ### Note Some binary distributions of **R** have `LINK` in a separate bundle, e.g. an `R-devel` RPM. This is not available on Windows. ### See Also `[COMPILE](compile)`. ### Examples ``` ## Not run: ## examples of front-ends linked against R. ## First a C program CC=`R CMD config CC` R CMD LINK $CC -o foo foo.o `R CMD config --ldflags` ## if Fortran code has been compiled into ForFoo.o FLIBS=`R CMD config FLIBS` R CMD LINK $CC -o foo foo.o ForFoo.o `R CMD config --ldflags` $FLIBS ## And for a C++ front-end CXX=`R CMD config CXX` R CMD COMPILE foo.cc R CMD LINK $CXX -o foo foo.o `R CMD config --ldflags` ## End(Not run) ``` r None `aspell-utils` Spell Check Utilities ------------------------------------- ### Description Utilities for spell checking packages via Aspell, Hunspell or Ispell. ### Usage ``` aspell_package_Rd_files(dir, drop = c("\\author", "\\references"), control = list(), program = NULL, dictionaries = character()) aspell_package_vignettes(dir, control = list(), program = NULL, dictionaries = character()) aspell_package_R_files(dir, ignore = character(), control = list(), program = NULL, dictionaries = character()) aspell_package_C_files(dir, ignore = character(), control = list(), program = NULL, dictionaries = character()) aspell_write_personal_dictionary_file(x, out, language = "en", program = NULL) ``` ### Arguments | | | | --- | --- | | `dir` | a character string specifying the path to a package's root directory. | | `drop` | a character vector naming additional Rd sections to drop when selecting text via `[RdTextFilter](../../tools/html/rdtextfilter)`. | | `control` | a list or character vector of control options for the spell checker. | | `program` | a character string giving the name (if on the system path) or full path of the spell check program to be used, or `NULL` (default). By default, the system path is searched for `aspell`, `hunspell` and `ispell` (in that order), and the first one found is used. | | `dictionaries` | a character vector of names or file paths of additional R level dictionaries to use. See `<aspell>`. | | `ignore` | a character vector with regular expressions to be replaced by blanks when filtering the message strings. | | `x` | a character vector, or the result of a call to `<aspell>()`. | | `out` | a character string naming the personal dictionary file to write to. | | `language` | a character string indicating a language as used by Aspell. | ### Details Functions `aspell_package_Rd_files`, `aspell_package_vignettes`, `aspell_package_R_files` and `aspell_package_C_files` perform spell checking on the Rd files, vignettes, R files, and C-level messages of the package with root directory `dir`. They determine the respective files, apply the appropriate filters, and run the spell checker. See `<aspell>` for details on filters. The C-level message string are obtained from the ‘po/PACKAGE.pot’ message catalog file, with PACKAGE the basename of `dir`. See the section on ‘C-level messages’ in ‘Writing R Extensions’ for more information. When using Aspell, the vignette checking skips parameters and/or options of commands `\Sexpr`, `\citep`, `\code`, `\pkg`, `\proglang` and `\samp`. Further commands can be skipped by adding `--add-tex-command` options to the `control` argument. E.g., to skip both option and parameter of `\mycmd`, add `--add-tex-command='mycmd op'`. Suitable values for `control`, `program`, `dictionaries`, `drop` and `ignore` can also be specified using a package defaults file which should go as ‘defaults.R’ into the ‘.aspell’ subdirectory of `dir`, and provides defaults via assignments of suitable named lists, e.g., ``` vignettes <- list(control = "--add-tex-command='mycmd op'") ``` for vignettes (when using Aspell) and similarly assigning to `Rd_files`, `R_files` and `C_files` for Rd files, R files and C level message defaults. Maintainers of packages using both English and American spelling will find it convenient to pass control options --master=en\_US and --add-extra-dicts=en\_GB to Aspell and control options -d en\_US,en\_GB to Hunspell (provided that the corresponding dictionaries are installed). Older versions of **R** had no support for R level dictionaries, and hence provided the function `aspell_write_personal_dictionary_file` to create (spell check) program-specific personal dictionary files from words to be accepted. The new mechanism is to use R level dictionaries, i.e., ‘.rds’ files obtained by serializing character vectors of such words using `[saveRDS](../../base/html/readrds)`. For such dictionaries specified via the package defaults mechanism, elements with no path separator can be R system dictionaries or dictionaries in the ‘.aspell’ subdirectory. ### See Also `<aspell>` r None `help` Documentation --------------------- ### Description `help` is the primary interface to the help systems. ### Usage ``` help(topic, package = NULL, lib.loc = NULL, verbose = getOption("verbose"), try.all.packages = getOption("help.try.all.packages"), help_type = getOption("help_type")) ``` ### Arguments | | | | --- | --- | | `topic` | usually, a [name](../../base/html/name) or character string specifying the topic for which help is sought. A character string (enclosed in explicit single or double quotes) is always taken as naming a topic. If the value of `topic` is a length-one character vector the topic is taken to be the value of the only element. Otherwise `topic` must be a name or a [reserved](../../base/html/reserved) word (if syntactically valid) or character string. See ‘Details’ for what happens if this is omitted. | | `package` | a name or character vector giving the packages to look into for documentation, or `NULL`. By default, all packages whose namespaces are loaded are used. To avoid a name being deparsed use e.g. `(pkg_ref)` (see the examples). | | `lib.loc` | a character vector of directory names of **R** libraries, or `NULL`. The default value of `NULL` corresponds to all libraries currently known. If the default is used, the loaded packages are searched before the libraries. This is not used for HTML help (see ‘Details’). | | `verbose` | logical; if `TRUE`, the file name is reported. | | `try.all.packages` | logical; see `Note`. | | `help_type` | character string: the type of help required. Possible values are `"text"`, `"html"` and `"pdf"`. Case is ignored, and partial matching is allowed. | ### Details The following types of help are available: * Plain text help * HTML help pages with hyperlinks to other topics, shown in a browser by `[browseURL](browseurl)`. (On Unix-alikes, where possible an existing browser window is re-used: the macOS GUI uses its own browser window.) If for some reason HTML help is unavailable (see `[startDynamicHelp](../../tools/html/startdynamichelp)`), plain text help will be used instead. * For `help` only, typeset as PDF – see the section on ‘Offline help’. On Unix-alikes: The ‘factory-fresh’ default is text help except from the macOS GUI, which uses HTML help displayed in its own browser window. On Windows: The default for the type of help is selected when **R** is installed – the ‘factory-fresh’ default is HTML help. The rendering of text help will use directional quotes in suitable locales (UTF-8 and single-byte Windows locales): sometimes the fonts used do not support these quotes so this can be turned off by setting `[options](../../base/html/options)(useFancyQuotes = FALSE)`. `topic` is not optional: if it is omitted **R** will give * If a package is specified, (text or, in interactive use only, HTML) information on the package, including hints/links to suitable help topics. * If `lib.loc` only is specified, a (text) list of available packages. * Help on `help` itself if none of the first three arguments is specified. Some topics need to be quoted (by [backtick](../../base/html/quotes)s) or given as a character string. These include those which cannot syntactically appear on their own such as unary and binary operators, `function` and control-flow [reserved](../../base/html/reserved) words (including `if`, `else` `for`, `in`, `repeat`, `while`, `break` and `next`). The other `reserved` words can be used as if they were names, for example `TRUE`, `NA` and `Inf`. If multiple help files matching `topic` are found, in interactive use a menu is presented for the user to choose one: in batch use the first on the search path is used. (For HTML help the menu will be an HTML page, otherwise a graphical menu if possible if `[getOption](../../base/html/options)("menu.graphics")` is true, the default.) Note that HTML help does not make use of `lib.loc`: it will always look first in the loaded packages and then along `.libPaths()`. ### Offline help Typeset documentation is produced by running the LaTeX version of the help page through `pdflatex`: this will produce a PDF file. The appearance of the output can be customized through a file ‘Rhelp.cfg’ somewhere in your LaTeX search path: this will be input as a LaTeX style file after `Rd.sty`. Some [environment variables](../../base/html/envvar) are consulted, notably R\_PAPERSIZE (*via* `getOption("papersize")`) and R\_RD4PDF (see ‘Making manuals’ in the ‘R Installation and Administration’ manual). If there is a function `offline_help_helper` in the workspace or further down the search path it is used to do the typesetting, otherwise the function of that name in the `utils` namespace (to which the first paragraph applies). It should accept at least two arguments, the name of the LaTeX file to be typeset and the type (which is nowadays ignored). It accepts a third argument, `texinputs`, which will give the graphics path when the help document contains figures, and will otherwise not be supplied. ### Note Unless `lib.loc` is specified explicitly, the loaded packages are searched before those in the specified libraries. This ensures that if a library is loaded from a library not in the known library trees, then the help from the loaded library is used. If `lib.loc` is specified explicitly, the loaded packages are *not* searched. If this search fails and argument `try.all.packages` is `TRUE` and neither `packages` nor `lib.loc` is specified, then all the packages in the known library trees are searched for help on `topic` and a list of (any) packages where help may be found is displayed (with hyperlinks for `help_type = "html"`). **NB:** searching all packages can be slow, especially the first time (caching of files by the OS can expedite subsequent searches dramatically). ### References Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) *The New S Language*. Wadsworth & Brooks/Cole. ### See Also `[?](question)` for shortcuts to help topics. `<help.search>()` or `[??](help.search)` for finding help pages on a vague topic; `<help.start>()` which opens the HTML version of the **R** help pages; `[library](../../base/html/library)()` for listing available packages and the help objects they contain; `<data>()` for listing available data sets; `<methods>()`. Use `<prompt>()` to get a prototype for writing `help` pages of your own package. ### Examples ``` help() help(help) # the same help(lapply) help("for") # or ?"for", but quotes/backticks are needed try({# requires working TeX installation: help(dgamma, help_type = "pdf") ## -> nicely formatted pdf -- including math formula -- for help(dgamma): system2(getOption("pdfviewer"), "dgamma.pdf", wait = FALSE) }) help(package = "splines") # get help even when package is not loaded topi <- "women" help(topi) try(help("bs", try.all.packages = FALSE)) # reports not found (an error) help("bs", try.all.packages = TRUE) # reports can be found # in package 'splines' ## For programmatic use: topic <- "family"; pkg_ref <- "stats" help((topic), (pkg_ref)) ```
programming_docs
r None `chooseBioCmirror` Select a Bioconductor Mirror ------------------------------------------------ ### Description Interact with the user to choose a Bioconductor mirror. ### Usage ``` chooseBioCmirror(graphics = getOption("menu.graphics"), ind = NULL, local.only = FALSE) ``` ### Arguments | | | | --- | --- | | `graphics` | Logical. If true, use a graphical list: on Windows or the macOS GUI use a list box, and on a Unix-alike use a Tk widget if package tcltk and an X server are available. Otherwise use a text `<menu>`. | | `ind` | Optional numeric value giving which entry to select. | | `local.only` | Logical, try to get most recent list from the Bioconductor master or use file on local disk only. | ### Details This sets the [option](../../base/html/options) `"BioC_mirror"`: it is used before a call to `[setRepositories](setrepositories)`. The out-of-the-box default for that option is `NULL`, which currently corresponds to the mirror <https://bioconductor.org>. The ‘Bioconductor (World-wide)’ ‘mirror’ is a network of mirrors providing reliable world-wide access; other mirrors may provide faster access on a geographically local scale. `ind` chooses a row in ‘[R\_HOME](../../base/html/rhome)/doc/BioC\_mirrors.csv’, by number. ### Value None: this function is invoked for its side effect of updating `options("BioC_mirror")`. ### See Also `[setRepositories](setrepositories)`, `[chooseCRANmirror](choosecranmirror)`. r None `strcapture` Capture String Tokens into a data.frame ----------------------------------------------------- ### Description Given a character vector and a regular expression containing capture expressions, `strcapture` will extract the captured tokens into a tabular data structure, such as a data.frame, the type and structure of which is specified by a prototype object. The assumption is that the same number of tokens are captured from every input string. ### Usage ``` strcapture(pattern, x, proto, perl = FALSE, useBytes = FALSE) ``` ### Arguments | | | | --- | --- | | `pattern` | The regular expression with the capture expressions. | | `x` | A character vector in which to capture the tokens. | | `proto` | A `data.frame` or S4 object that behaves like one. See details. | | `perl,useBytes` | Arguments passed to `[regexec](../../base/html/grep)`. | ### Details The `proto` argument is typically a `data.frame`, with a column corresponding to each capture expression, in order. The captured character vector is coerced to the type of the column, and the column names are carried over to the return value. Any data in the prototype are ignored. See the examples. ### Value A tabular data structure of the same type as `proto`, so typically a `data.frame`, containing a column for each capture expression. The column types and names are inherited from `proto`. Cases in `x` that do not match `pattern` have `NA` in every column. ### See Also `[regexec](../../base/html/grep)` and `[regmatches](../../base/html/regmatches)` for related low-level utilities. ### Examples ``` x <- "chr1:1-1000" pattern <- "(.*?):([[:digit:]]+)-([[:digit:]]+)" proto <- data.frame(chr=character(), start=integer(), end=integer()) strcapture(pattern, x, proto) ``` r None `utils-deprecated` Deprecated Functions in Package utils --------------------------------------------------------- ### Description (Currently none) These functions are provided for compatibility with older versions of **R** only, and may be defunct as soon as of the next release. ### See Also `[Deprecated](../../base/html/deprecated)`, `[Defunct](../../base/html/defunct)` r None `RweaveLatex` R/LaTeX Driver for Sweave ---------------------------------------- ### Description A driver for `[Sweave](sweave)` that translates **R** code chunks in LaTeX files by “running them”, i.e., `[parse](../../base/html/parse)()` and `[eval](../../base/html/eval)()` each. ### Usage ``` RweaveLatex() RweaveLatexSetup(file, syntax, output = NULL, quiet = FALSE, debug = FALSE, stylepath, ...) ``` ### Arguments | | | | --- | --- | | `file` | Name of Sweave source file. See the description of the corresponding argument of `[Sweave](sweave)`. | | `syntax` | An object of class `SweaveSyntax`. | | `output` | Name of output file. The default is to remove extension ‘.nw’, ‘.Rnw’ or ‘.Snw’ and to add extension ‘.tex’. Any directory paths in `file` are also removed such that the output is created in the current working directory. | | `quiet` | If `TRUE` all progress messages are suppressed. | | `debug` | If `TRUE`, input and output of all code chunks is copied to the console. | | `stylepath` | See ‘Details’. | | `...` | named values for the options listed in ‘Supported Options’. | ### Details The LaTeX file generated needs to contain the line \usepackage{Sweave}, and if this is not present in the Sweave source file (possibly in a comment), it is inserted by the `RweaveLatex` driver. If `stylepath = TRUE`, a hard-coded path to the file ‘Sweave.sty’ in the **R** installation is set in place of `Sweave`. The hard-coded path makes the LaTeX file less portable, but avoids the problem of installing the current version of ‘Sweave.sty’ to some place in your TeX input path. However, TeX may not be able to process the hard-coded path if it contains spaces (as it often will under Windows) or TeX special characters. The default for `stylepath` is now taken from the environment variable SWEAVE\_STYLEPATH\_DEFAULT, or is `FALSE` it that is unset or empty. If set, it should be exactly `TRUE` or `FALSE`: any other values are taken as `FALSE`. The simplest way for frequent Sweave users to ensure that ‘Sweave.sty’ is in the TeX input path is to add ‘R\_HOME/share/texmf’ as a ‘texmf tree’ (‘root directory’ in the parlance of the ‘MiKTeX settings’ utility). By default, ‘Sweave.sty’ sets the width of all included graphics to: \setkeys{Gin}{width=0.8\textwidth}. This setting affects the width size option passed to the \includegraphics{} directive for each plot file and in turn impacts the scaling of your plot files as they will appear in your final document. Thus, for example, you may set `width=3` in your figure chunk and the generated graphics files will be set to 3 inches in width. However, the width of your graphic in your final document will be set to 0.8\textwidth and the height dimension will be scaled accordingly. Fonts and symbols will be similarly scaled in the final document. You can adjust the default value by including the \setkeys{Gin}{width=...} directive in your ‘.Rnw’ file after the \begin{document} directive and changing the `width` option value as you prefer, using standard LaTeX measurement values. If you wish to override this default behavior entirely, you can add a \usepackage[nogin]{Sweave} directive in your preamble. In this case, no size/scaling options will be passed to the \includegraphics{} directive and the `height` and `width` options will determine both the runtime generated graphic file sizes and the size of the graphics in your final document. ‘Sweave.sty’ also supports the [noae] option, which suppresses the use of the ae package, the use of which may interfere with certain encoding and typeface selections. If you have problems in the rendering of certain character sets, try this option. It also supports the [inconsolata] option, to render monospaced text in `inconsolata`, the font used by default for **R** help pages. The use of fancy quotes (see `[sQuote](../../base/html/squote)`) can cause problems when setting **R** output. Either set `[options](../../base/html/options)(useFancyQuotes = FALSE)` or arrange that LaTeX is aware of the encoding used (by a \usepackage[utf8]{inputenc} declaration: Windows users of `Sweave` from `Rgui.exe` will need to replace utf8 by cp1252 or similar) and ensure that typewriter fonts containing directional quotes are used. Some LaTeX graphics drivers do not include .png or .jpg in the list of known extensions. To enable them, add something like \DeclareGraphicsExtensions{.png,.pdf,.jpg} to the preamble of your document or check the behavior of your graphics driver. When both `pdf` and `png` are `TRUE` both files will be produced by `Sweave`, and their order in the DeclareGraphicsExtensions list determines which will be used by `pdflatex`. ### Supported Options `RweaveLatex` supports the following options for code chunks (the values in parentheses show the default values). Character string values should be quoted when passed from `[Sweave](sweave)` through `...` but not when use in the header of a code chunk. engine: character string (`"R"`). Only chunks with `engine` equal to `"R"` or `"S"` are processed. echo: logical (`TRUE`). Include **R** code in the output file? keep.source: logical (`TRUE`). When echoing, if `TRUE` the original source is copied to the file. Otherwise, deparsed source is echoed. eval: logical (`TRUE`). If `FALSE`, the code chunk is not evaluated, and hence no text nor graphical output produced. results: character string (`"verbatim"`). If `"verbatim"`, the output of **R** commands is included in the verbatim-like Soutput environment. If `"tex"`, the output is taken to be already proper LaTeX markup and included as is. If `"hide"` then all output is completely suppressed (but the code executed during the weave). Values can be abbreviated. print: logical (`FALSE`). If `TRUE`, this forces auto-printing of all expressions. term: logical (`TRUE`). If `TRUE`, visibility of values emulates an interactive **R** session: values of assignments are not printed, values of single objects are printed. If `FALSE`, output comes only from explicit `[print](../../base/html/print)` or similar statements. split: logical (`FALSE`). If `TRUE`, text output is written to separate files for each code chunk. strip.white: character string (`"true"`). If `"true"`, blank lines at the beginning and end of output are removed. If `"all"`, then all blank lines are removed from the output. If `"false"` then blank lines are retained. A ‘blank line’ is one that is empty or includes only whitespace (spaces and tabs). Note that blank lines in a code chunk will usually produce a prompt string rather than a blank line on output. prefix: logical (`TRUE`). If `TRUE` generated filenames of figures and output all have the common prefix given by the `prefix.string` option: otherwise only unlabelled chunks use the prefix. prefix.string: a character string, default is the name of the source file (without extension). Note that this is used as part of filenames, so needs to be portable. include: logical (`TRUE`), indicating whether input statements for text output (if `split = TRUE`) and \includegraphics statements for figures should be auto-generated. Use `include = FALSE` if the output should appear in a different place than the code chunk (by placing the input line manually). fig: logical (`FALSE`), indicating whether the code chunk produces graphical output. Note that only one figure per code chunk can be processed this way. The labels for figure chunks are used as part of the file names, so should preferably be alphanumeric. eps: logical (`FALSE`), indicating whether EPS figures should be generated. Ignored if `fig = FALSE`. pdf: logical (`TRUE`), indicating whether PDF figures should be generated. Ignored if `fig = FALSE`. pdf.version, pdf.encoding, pdf.compress: passed to `[pdf](../../grdevices/html/pdf)` to set the version, encoding and compression (or not). Defaults taken from `pdf.options()`. png: logical (`FALSE`), indicating whether PNG figures should be generated. Ignored if `fig = FALSE`. Only available in *R >= 2.13.0*. jpeg: logical (`FALSE`), indicating whether JPEG figures should be generated. Ignored if `fig = FALSE`. Only available in *R >= 2.13.0*. grdevice: character (`NULL`): see section ‘Custom Graphics Devices’. Ignored if `fig = FALSE`. Only available in *R >= 2.13.0*. width: numeric (6), width of figures in inches. See ‘Details’. height: numeric (6), height of figures in inches. See ‘Details’. resolution: numeric (300), resolution in pixels per inch: used for PNG and JPEG graphics. Note that the default is a fairly high value, appropriate for high-quality plots. Something like `100` is a better choice for package vignettes. concordance: logical (`FALSE`). Write a concordance file to link the input line numbers to the output line numbers. This is an experimental feature; see the source code for the output format, which is subject to change in future releases. figs.only: logical (`FALSE`). By default each figure chunk is run once, then re-run for each selected type of graphics. That will open a default graphics device for the first figure chunk and use that device for the first evaluation of all subsequent chunks. If this option is true, the figure chunk is run only for each selected type of graphics, for which a new graphics device is opened and then closed. In addition, users can specify further options, either in the header of an individual code section or in a \SweaveOpts{} line in the document. For unknown options, their type is set at first use. ### Custom Graphics Devices If option `grdevice` is supplied for a code chunk with both `fig` and `eval` true, the following call is made ``` get(options$grdevice, envir = .GlobalEnv)(name=, width=, height=, options) ``` which should open a graphics device. The chunk's code is then evaluated and `[dev.off](../../grdevices/html/dev)` is called. Normally a function of the name given will have been defined earlier in the Sweave document, e.g. ``` <<results=hide>>= my.Swd <- function(name, width, height, ...) grDevices::png(filename = paste(name, "png", sep = "."), width = width, height = height, res = 100, units = "in", type = "quartz", bg = "transparent") @ ``` Alternatively for **R** >= 3.4.0, if the function exists in a package (rather than the `.GlobalEnv`) it can be used by setting `grdevice = "pkg::my.Swd"` (or with ::: instead of :: if the function is not exported). Currently only one custom device can be used for each chunk, but different devices can be used for different chunks. A replacement for `[dev.off](../../grdevices/html/dev)` can be provided as a function with suffix `.off`, e.g. `my.Swd.off()` or `pkg::my.Swd.off()`, respectively. ### Hook Functions Before each code chunk is evaluated, zero or more hook functions can be executed. If `getOption("SweaveHooks")` is set, it is taken to be a named list of hook functions. For each *logical* option of a code chunk (`echo`, `print`, ...) a hook can be specified, which is executed if and only if the respective option is `TRUE`. Hooks must be named elements of the list returned by `getOption("SweaveHooks")` and be functions taking no arguments. E.g., if option `"SweaveHooks"` is defined as `list(fig = foo)`, and `foo` is a function, then it would be executed before the code in each figure chunk. This is especially useful to set defaults for the graphical parameters in a series of figure chunks. Note that the user is free to define new Sweave logical options and associate arbitrary hooks with them. E.g., one could define a hook function for a new option called `clean` that removes all objects in the workspace. Then all code chunks specified with `clean = TRUE` would start operating on an empty workspace. ### Author(s) Friedrich Leisch and R-core ### See Also ‘Sweave User Manual’, a vignette in the utils package. `[Sweave](sweave)`, `[Rtangle](rtangle)` r None `globalVariables` Declarations Used in Checking a Package ---------------------------------------------------------- ### Description For `globalVariables`, the names supplied are of functions or other objects that should be regarded as defined globally when the `check` tool is applied to this package. The call to `globalVariables` will be included in the package's source. Repeated calls in the same package accumulate the names of the global variables. Typical examples are the fields and methods in reference classes, which appear to be global objects to `codetools`. (This case is handled automatically by `[setRefClass](../../methods/html/refclass)()` and friends, using the supplied field and method names.) For `suppressForeignCheck`, the names supplied are of variables used as `.NAME` in foreign function calls which should not be checked by `[checkFF](../../tools/html/checkff)(registration = TRUE)`. Without this declaration, expressions other than simple character strings are assumed to evaluate to registered native symbol objects. The type of call (`.Call`, `.External`, etc.) and argument counts will be checked. With this declaration, checks on those names will usually be suppressed. (If the code uses an expression that should only be evaluated at runtime, the message can be suppressed by wrapping it in a `[dontCheck](../../base/html/dontcheck)` function call, or by saving it to a local variable, and suppressing messages about that variable. See the example below.) ### Usage ``` globalVariables(names, package, add = TRUE) suppressForeignCheck(names, package, add = TRUE) ``` ### Arguments | | | | --- | --- | | `names` | The character vector of object names. If omitted, the current list of global variables declared in the package will be returned, unchanged. | | `package` | The relevant package, usually the character string name of the package but optionally its corresponding namespace environment. When the call to `globalVariables` or `suppressForeignCheck` comes in the package's source file, the argument is normally omitted, as in the example below. | | `add` | Should the contents of `names` be added to the current global variables or replace it? | ### Details The lists of declared global variables and native symbol objects are stored in a metadata object in the package's namespace, assuming the `globalVariables` or `suppressForeignCheck` call(s) occur as top-level calls in the package's source code. The check command, as implemented in package `tools`, queries the list before checking the **R** source code in the package for possible problems. `globalVariables` was introduced in **R** 2.15.1 and `suppressForeignCheck` was introduced in **R** 3.1.0 so both should be used conditionally: see the example. ### Value `globalVariables` returns the current list of declared global variables, possibly modified by this call. `suppressForeignCheck` returns the current list of native symbol objects which are not to be checked. ### Note The global variables list really belongs to a restricted scope (a function or a group of method definitions, for example) rather than the package as a whole. However, implementing finer control would require changes in `check` and/or in `codetools`, so in this version the information is stored at the package level. ### Author(s) John Chambers and Duncan Murdoch ### See Also `dontCheck`. ### Examples ``` ## Not run: ## assume your package has some code that assigns ".obj1" and ".obj2" ## but not in a way that codetools can find. ## In the same source file (to remind you that you did it) add: if(getRversion() >= "2.15.1") utils::globalVariables(c(".obj1", "obj2")) ## To suppress messages about a run-time calculated native symbol, ## save it to a local variable. ## At top level, put this: if(getRversion() >= "3.1.0") utils::suppressForeignCheck("localvariable") ## Within your function, do the call like this: localvariable <- if (condition) entry1 else entry2 .Call(localvariable, 1, 2, 3) ## HOWEVER, it is much better practice to write code ## that can be checked thoroughly, e.g. if(condition) .Call(entry1, 1, 2, 3) else .Call(entry2, 1, 2, 3) ## End(Not run) ```
programming_docs
r None `ls_str` List Objects and their Structure ------------------------------------------ ### Description `ls.str` and `lsf.str` are variations of `[ls](../../base/html/ls)` applying `<str>()` to each matched name: see section Value. ### Usage ``` ls.str(pos = -1, name, envir, all.names = FALSE, pattern, mode = "any") lsf.str(pos = -1, envir, ...) ## S3 method for class 'ls_str' print(x, max.level = 1, give.attr = FALSE, ..., digits = max(1, getOption("str")$digits.d)) ``` ### Arguments | | | | --- | --- | | `pos` | integer indicating `[search](../../base/html/search)` path position, or `-1` for the current environment. | | `name` | optional name indicating `[search](../../base/html/search)` path position, see `[ls](../../base/html/ls)`. | | `envir` | environment to use, see `[ls](../../base/html/ls)`. | | `all.names` | logical indicating if names which begin with a `.` are omitted; see `[ls](../../base/html/ls)`. | | `pattern` | a [regular expression](../../base/html/regex) passed to `[ls](../../base/html/ls)`. Only names matching `pattern` are considered. | | `max.level` | maximal level of nesting which is applied for displaying nested structures, e.g., a list containing sub lists. Default 1: Display only the first nested level. | | `give.attr` | logical; if `TRUE` (default), show attributes as sub structures. | | `mode` | character specifying the `[mode](../../base/html/mode)` of objects to consider. Passed to `[exists](../../base/html/exists)` and `[get](../../base/html/get)`. | | `x` | an object of class `"ls_str"`. | | `...` | further arguments to pass. `lsf.str` passes them to `ls.str` which passes them on to `[ls](../../base/html/ls)`. The (non-exported) print method `print.ls_str` passes them to `<str>`. | | `digits` | the number of significant digits to use for printing. | ### Value `ls.str` and `lsf.str` return an object of class `"ls_str"`, basically the character vector of matching names (functions only for `lsf.str`), similarly to `[ls](../../base/html/ls)`, with a `print()` method that calls `<str>()` on each object. ### Author(s) Martin Maechler ### See Also `<str>`, `[summary](../../base/html/summary)`, `[args](../../base/html/args)`. ### Examples ``` require(stats) lsf.str() #- how do the functions look like which I am using? ls.str(mode = "list") #- what are the structured objects I have defined? ## create a few objects example(glm, echo = FALSE) ll <- as.list(LETTERS) print(ls.str(), max.level = 0)# don't show details ## which base functions have "file" in their name ? lsf.str(pos = length(search()), pattern = "file") ## demonstrating that ls.str() works inside functions ## ["browser/debug mode"]: tt <- function(x, y = 1) { aa <- 7; r <- x + y; ls.str() } (nms <- sapply(strsplit(capture.output(tt(2))," *: *"), `[`, 1)) stopifnot(nms == c("aa", "r","x","y")) ``` r None `Rprof` Enable Profiling of R's Execution ------------------------------------------ ### Description Enable or disable profiling of the execution of **R** expressions. ### Usage ``` Rprof(filename = "Rprof.out", append = FALSE, interval = 0.02, memory.profiling = FALSE, gc.profiling = FALSE, line.profiling = FALSE, filter.callframes = FALSE, numfiles = 100L, bufsize = 10000L) ``` ### Arguments | | | | --- | --- | | `filename` | The file to be used for recording the profiling results. Set to `NULL` or `""` to disable profiling. | | `append` | logical: should the file be over-written or appended to? | | `interval` | real: time interval between samples. | | `memory.profiling` | logical: write memory use information to the file? | | `gc.profiling` | logical: record whether GC is running? | | `line.profiling` | logical: write line locations to the file? | | `filter.callframes` | logical: filter out intervening call frames of the call tree. See the filtering out call frames section. | | `numfiles, bufsize` | integers: line profiling memory allocation | ### Details Enabling profiling automatically disables any existing profiling to another or the same file. Profiling works by writing out the call stack every `interval` seconds, to the file specified. Either the `[summaryRprof](summaryrprof)` function or the wrapper script `R CMD Rprof` can be used to process the output file to produce a summary of the usage; use `R CMD Rprof --help` for usage information. How time is measured varies by platform: On Windows: Exactly what the time interval measures is subtle: it is time that the **R** process is running and executing an **R** command. It is not however just CPU time, for if `readline()` is waiting for input, that counts (on Windows, but not on a Unix-alike). Note that the timing interval cannot be too small, for the time spent in each profiling step is added to the interval. What is feasible is machine-dependent, but 10ms seemed as small as advisable on a 1GHz machine. On Unix-alikes it is the CPU time of the **R** process, so for example excludes time when **R** is waiting for input or for processes run by `[system](../../base/html/system)` to return. Note that the timing interval cannot usefully be too small: once the timer goes off, the information is not recorded until the next timing click (probably in the range 1–10 ms). Functions will only be recorded in the profile log if they put a context on the call stack (see `[sys.calls](../../base/html/sys.parent)`). Some [primitive](../../base/html/primitive) functions do not do so: specifically those which are of [type](../../base/html/typeof) `"special"` (see the ‘R Internals’ manual for more details). Individual statements will be recorded in the profile log if `line.profiling` is `TRUE`, and if the code being executed was parsed with source references. See `[parse](../../base/html/parse)` for a discussion of source references. By default the statement locations are not shown in `[summaryRprof](summaryrprof)`, but see that help page for options to enable the display. ### Filtering Out Call Frames Lazy evaluation makes the call stack more complex because intervening call frames are created between the time arguments are applied to a function, and the time they are effectively evaluated. When the call stack is represented as a tree, these intervening frames appear as sibling nodes. For instance, evaluating `try(EXPR)` produces the following call tree, at the time `EXPR` gets evaluated: ``` 1. +-base::try(EXPR) 2. | \-base::tryCatch(...) 3. | \-base:::tryCatchList(expr, classes, parentenv, handlers) 4. | \-base:::tryCatchOne(expr, names, parentenv, handlers[[1L]]) 5. | \-base:::doTryCatch(return(expr), name, parentenv, handler) 6. \-EXPR ``` Lines 2 to 5 are intervening call frames, the last of which finally triggered evaluation of `EXPR`. Setting `filter.callframes` to `TRUE` simplifies the profiler output by removing all sibling nodes of intervening frames. The same kind of call frame filtering is applied with `eval()` frames. When you call `eval()`, two frames are pushed on the stack to ensure a continuity between frames. Say we have these definitions: ``` calling <- function() evaluator(quote(called()), environment()) evaluator <- function(expr, env) eval(expr, env) called <- function() EXPR() ``` `calling()` calls `called()` in its own environment, via `eval()`. The latter is called indirectly through `evaluator()`. The net effect of this code is identical to just calling `called()` directly, without the intermediaries. However, the full call stack looks like this: ``` 1. calling() 2. \-evaluator(quote(called()), environment()) 3. \-base::eval(expr, env) 4. \-base::eval(expr, env) 5. \-called() 6. \-EXPR() ``` When call frame filtering is turned on, the true calling environment of `called()` is looked up, and the filtered call stack looks like this: ``` 1. calling() 5. \-called() 6. \-EXPR() ``` If the calling environment is not on the stack, the function called by `eval()` becomes a root node. Say we have: ``` calling <- function() evaluator(quote(called()), new.env()) ``` With call frame filtering we then get the following filtered call stack: ``` 5. called() 6. \-EXPR() ``` ### Note On Unix-alikes: Profiling is not available on all platforms. By default, support for profiling is compiled in if possible – configure **R** with --disable-R-profiling to change this. As **R** profiling uses the same mechanisms as C profiling, the two cannot be used together, so do not use `Rprof` in an executable built for C-level profiling. On Windows: `filename` can be a UTF-8-encoded filepath that cannot be translated to the current locale. The profiler interrupts R asynchronously, and it cannot allocate memory to store results as it runs. This affects line profiling, which needs to store an unknown number of file pathnames. The `numfiles` and `bufsize` arguments control the size of pre-allocated buffers to hold these results: the former counts the maximum number of paths, the latter counts the numbers of bytes in them. If the profiler runs out of space it will skip recording the line information for new files, and issue a warning when `Rprof(NULL)` is called to finish profiling. ### See Also The chapter on “Tidying and profiling R code” in ‘Writing R Extensions’ (see the ‘doc/manual’ subdirectory of the **R** source tree). `[summaryRprof](summaryrprof)` to analyse the output file. `[tracemem](../../base/html/tracemem)`, `[Rprofmem](rprofmem)` for other ways to track memory use. ### Examples ``` ## Not run: Rprof() ## some code to be profiled Rprof(NULL) ## some code NOT to be profiled Rprof(append = TRUE) ## some code to be profiled Rprof(NULL) ## ... ## Now post-process the output as described in Details ## End(Not run) ``` r None `download.file` Download File from the Internet ------------------------------------------------ ### Description This function can be used to download a file from the Internet. ### Usage ``` download.file(url, destfile, method, quiet = FALSE, mode = "w", cacheOK = TRUE, extra = getOption("download.file.extra"), headers = NULL, ...) ``` ### Arguments | | | | --- | --- | | `url` | a `[character](../../base/html/character)` string (or longer vector e.g., for the `"libcurl"` method) naming the URL of a resource to be downloaded. | | `destfile` | a character string (or vector, see `url`) with the name where the downloaded file is saved. Tilde-expansion is performed. | | `method` | Method to be used for downloading files. Current download methods are `"internal"`, `"wininet"` (Windows only) `"libcurl"`, `"wget"` and `"curl"`, and there is a value `"auto"`: see ‘Details’ and ‘Note’. The method can also be set through the option `"download.file.method"`: see `[options](../../base/html/options)()`. | | `quiet` | If `TRUE`, suppress status messages (if any), and the progress bar. | | `mode` | character. The mode with which to write the file. Useful values are `"w"`, `"wb"` (binary), `"a"` (append) and `"ab"`. Not used for methods `"wget"` and `"curl"`. See also ‘Details’, notably about using `"wb"` for Windows. | | `cacheOK` | logical. Is a server-side cached value acceptable? | | `extra` | character vector of additional command-line arguments for the `"wget"` and `"curl"` methods. | | `headers` | named character vector of HTTP headers to use in HTTP requests. It is ignored for non-HTTP URLs. The `User-Agent` header, coming from the `HTTPUserAgent` option (see `[options](../../base/html/options)`) is used as the first header, automatically. | | `...` | allow additional arguments to be passed, unused. | ### Details The function `download.file` can be used to download a single file as described by `url` from the internet and store it in `destfile`. The `url` must start with a scheme such as http://, https://, ftp:// or file://. If `method = "auto"` is chosen (the default), the behavior depends on the platform: * On a Unix-alike method `"libcurl"` is used except `"internal"` for file:// URLs, where `"libcurl"` uses the library of that name (<https://curl.se/libcurl/>). * On Windows the `"wininet"` method is used apart from for ftps:// URLs where `"libcurl"` is tried. The `"wininet"` method uses the WinINet functions (part of the OS). Support for method `"libcurl"` is optional on Windows: use `[capabilities](../../base/html/capabilities)("libcurl")` to see if it is supported on your build. It uses an external library of that name (<https://curl.se/libcurl/>) against which **R** can be compiled. When method `"libcurl"` is used, it provides (non-blocking) access to https:// and (usually) ftps:// URLs. There is support for simultaneous downloads, so `url` and `destfile` can be character vectors of the same length greater than one (but the method has to be specified explicitly and not *via* `"auto"`). For a single URL and `quiet = FALSE` a progress bar is shown in interactive use. For methods `"wget"` and `"curl"` a system call is made to the tool given by `method`, and the respective program must be installed on your system and be in the search path for executables. They will block all other activity on the **R** process until they complete: this may make a GUI unresponsive. `cacheOK = FALSE` is useful for http:// and https:// URLs: it will attempt to get a copy directly from the site rather than from an intermediate cache. It is used by `<available.packages>`. The `"libcurl"` and `"wget"` methods follow http:// and https:// redirections to any scheme they support: the `"internal"` method follows http:// to http:// redirections only. (For method `"curl"` use argument `extra = "-L"`. To disable redirection in `wget`, use `extra = "--max-redirect=0"`.) The `"wininet"` method supports some redirections but not all. (For method `"libcurl"`, messages will quote the endpoint of redirections.) Note that https:// URLs are not supported by the `"internal"` method but are supported by the `"libcurl"` method and the `"wininet"` method on Windows. See `[url](../../base/html/connections)` for how file:// URLs are interpreted, especially on Windows. The `"internal"` and `"wininet"` methods do not percent-decode file:// URLs, but the `"libcurl"` and `"curl"` methods do: method `"wget"` does not support them. Most methods do not percent-encode special characters such as spaces in URLs (see `[URLencode](urlencode)`), but it seems the `"wininet"` method does. The remaining details apply to the `"internal"`, `"wininet"` and `"libcurl"` methods only. The timeout for many parts of the transfer can be set by the option `timeout` which defaults to 60 seconds. This is often insufficient for downloads of large files (50MB or more) and so should be increased when `download.file` is used in packages to do so. Note that the user can set the default timeout by the environment variable R\_DEFAULT\_INTERNET\_TIMEOUT in recent versions of **R**, so to ensure that this is not decreased packages should use something like ``` options(timeout = max(300, getOption("timeout"))) ``` (It is unrealistic to require download times of less than 1s/MB.) The level of detail provided during transfer can be set by the `quiet` argument and the `internet.info` option: the details depend on the platform and scheme. For the `"internal"` method setting option `internet.info` to 0 gives all available details, including all server responses. Using 2 (the default) gives only serious messages, and 3 or more suppresses all messages. For the `"libcurl"` method values of the option less than 2 give verbose output. A progress bar tracks the transfer platform specifically: On Windows If the file length is known, the full width of the bar is the known length. Otherwise the initial width represents 100 Kbytes and is doubled whenever the current width is exceeded. (In non-interactive use this uses a text version. If the file length is known, an equals sign represents 2% of the transfer completed: otherwise a dot represents 10Kb.) On a unix-alike If the file length is known, an equals sign represents 2% of the transfer completed: otherwise a dot represents 10Kb. The choice of binary transfer (`mode = "wb"` or `"ab"`) is important on Windows, since unlike Unix-alikes it does distinguish between text and binary files and for text transfers changes `\n` line endings to `\r\n` (aka ‘CRLF’). On Windows, if `mode` is not supplied (`[missing](../../base/html/missing)()`) and `url` ends in one of `.gz`, `.bz2`, `.xz`, `.tgz`, `.zip`, `.jar`, `.rda`, `.rds` or `.RData`, `mode = "wb"` is set so that a binary transfer is done to help unwary users. Code written to download binary files must use `mode = "wb"` (or `"ab"`), but the problems incurred by a text transfer will only be seen on Windows. ### Value An (invisible) integer code, `0` for success and non-zero for failure. For the `"wget"` and `"curl"` methods this is the status code returned by the external program. The `"internal"` method can return `1`, but will in most cases throw an error. What happens to the destination file(s) in the case of error depends on the method and **R** version. Currently the `"internal"`, `"wininet"` and `"libcurl"` methods will remove the file if there the URL is unavailable except when `mode` specifies appending when the file should be unchanged. ### Setting Proxies For the Windows-only method `"wininet"`, the ‘Internet Options’ of the system are used to choose proxies and so on; these are set in the Control Panel and are those used for system browsers. The next two paragraphs apply to the internal code only. Proxies can be specified via environment variables. Setting no\_proxy to `*` stops any proxy being tried. Otherwise the setting of http\_proxy or ftp\_proxy (or failing that, the all upper-case version) is consulted and if non-empty used as a proxy site. For FTP transfers, the username and password on the proxy can be specified by ftp\_proxy\_user and ftp\_proxy\_password. The form of http\_proxy should be `http://proxy.dom.com/` or `http://proxy.dom.com:8080/` where the port defaults to `80` and the trailing slash may be omitted. For ftp\_proxy use the form `ftp://proxy.dom.com:3128/` where the default port is `21`. These environment variables must be set before the download code is first used: they cannot be altered later by calling `[Sys.setenv](../../base/html/sys.setenv)`. Usernames and passwords can be set for HTTP proxy transfers via environment variable http\_proxy\_user in the form `user:passwd`. Alternatively, http\_proxy can be of the form `http://user:[email protected]:8080/` for compatibility with `wget`. Only the HTTP/1.0 basic authentication scheme is supported. Under Windows, if http\_proxy\_user is set to `ask` then a dialog box will come up for the user to enter the username and password. **NB:** you will be given only one opportunity to enter this, but if proxy authentication is required and fails there will be one further prompt per download. Much the same scheme is supported by `method = "libcurl"`, including no\_proxy, http\_proxy and ftp\_proxy, and for the last two a contents of `[user:password@]machine[:port]` where the parts in brackets are optional. See <https://curl.se/libcurl/c/libcurl-tutorial.html> for details. ### Secure URLs Methods which access https:// and ftps:// URLs should try to verify the site certificates. This is usually done using the CA root certificates installed by the OS (although we have seen instances in which these got removed rather than updated). For further information see <https://curl.se/docs/sslcerts.html>. This is an issue for `method = "libcurl"` on Windows, where the OS does not provide a suitable CA certificate bundle, so by default on Windows certificates are not verified. To turn verification on, set environment variable CURL\_CA\_BUNDLE to the path to a certificate bundle file, usually named ‘ca-bundle.crt’ or ‘curl-ca-bundle.crt’. (This is normally done for a binary installation of **R**, which installs ‘R\_HOME/etc/curl-ca-bundle.crt’ and sets CURL\_CA\_BUNDLE to point to it if that environment variable is not already set.) For an updated certificate bundle, see <https://curl.se/docs/sslcerts.html>. Currently one can download a copy from <https://raw.githubusercontent.com/bagder/ca-bundle/master/ca-bundle.crt> and set CURL\_CA\_BUNDLE to the full path to the downloaded file. Note that the root certificates used by **R** may or may not be the same as used in a browser, and indeed different browsers may use different certificate bundles (there is typically a build option to choose either their own or the system ones). ### FTP sites ftp: URLs are accessed using the FTP protocol which has a number of variants. One distinction is between ‘active’ and ‘(extended) passive’ modes: which is used is chosen by the client. The `"internal"` and `"libcurl"` methods use passive mode, and that is almost universally used by browsers. The `"wininet"` method first tries passive and then active. ### Good practice Setting the `method` should be left to the end user. Neither of the `wget` nor `curl` commands is widely available: you can check if one is available *via* `[Sys.which](../../base/html/sys.which)`, and should do so in a package or script. If you use `download.file` in a package or script, you must check the return value, since it is possible that the download will fail with a non-zero status but not an **R** error. The supported `method`s do change: method `libcurl` was introduced in **R** 3.2.0 and is still optional on Windows – use `[capabilities](../../base/html/capabilities)("libcurl")` in a program to see if it is available. ### Note Files of more than 2GB are supported on 64-bit builds of **R**; they may be truncated on some 32-bit builds. Methods `"wget"` and `"curl"` are mainly for historical compatibility but provide may provide capabilities not supported by the `"libcurl"` or `"wininet"` methods. Method `"wget"` can be used with proxy firewalls which require user/password authentication if proper values are stored in the configuration file for `wget`. `wget` (<https://www.gnu.org/software/wget/>) is commonly installed on Unix-alikes (but not macOS). Windows binaries are available from Cygwin, gnuwin32 and elsewhere. `curl` (<https://curl.se/>) is installed on macOS and commonly on Unix-alikes. Windows binaries are available at that URL. ### See Also `[options](../../base/html/options)` to set the `HTTPUserAgent`, `timeout` and `internet.info` options used by some of the methods. `[url](../../base/html/connections)` for a finer-grained way to read data from URLs. `<url.show>`, `<available.packages>`, `<download.packages>` for applications. Contributed packages [RCurl](https://CRAN.R-project.org/package=RCurl) and [curl](https://CRAN.R-project.org/package=curl) provide more comprehensive facilities to download from URLs.
programming_docs
r None `findLineNum` Find the Location of a Line of Source Code, or Set a Breakpoint There ------------------------------------------------------------------------------------ ### Description These functions locate objects containing particular lines of source code, using the information saved when the code was parsed with `keep.source = TRUE`. ### Usage ``` findLineNum(srcfile, line, nameonly = TRUE, envir = parent.frame(), lastenv) setBreakpoint(srcfile, line, nameonly = TRUE, envir = parent.frame(), lastenv, verbose = TRUE, tracer, print = FALSE, clear = FALSE, ...) ``` ### Arguments | | | | --- | --- | | `srcfile` | The name of the file containing the source code. | | `line` | The line number within the file. See Details for an alternate way to specify this. | | `nameonly` | If `TRUE` (the default), we require only a match to `basename(srcfile)`, not to the full path. | | `envir` | Where do we start looking for function objects? | | `lastenv` | Where do we stop? See the Details. | | `verbose` | Should we print information on where breakpoints were set? | | `tracer` | An optional `tracer` function to pass to `[trace](../../base/html/trace)`. By default, a call to `[browser](../../base/html/browser)` is inserted. | | `print` | The `print` argument to pass to `[trace](../../base/html/trace)`. | | `clear` | If `TRUE`, call `[untrace](../../base/html/trace)` rather than `[trace](../../base/html/trace)`. | | `...` | Additional arguments to pass to `[trace](../../base/html/trace)`. | ### Details The `findLineNum` function searches through all objects in environment `envir`, its parent, grandparent, etc., all the way back to `lastenv`. `lastenv` defaults to the global environment if `envir` is not specified, and to the root environment `[emptyenv](../../base/html/environment)()` if `envir` is specified. (The first default tends to be quite fast, and will usually find all user code other than S4 methods; the second one is quite slow, as it will typically search all attached system libraries.) For convenience, `envir` may be specified indirectly: if it is not an environment, it will be replaced with `environment(envir)`. `setBreakpoint` is a simple wrapper function for `[trace](../../base/html/trace)` and `[untrace](../../base/html/trace)`. It will set or clear breakpoints at the locations found by `findLineNum`. The `srcfile` is normally a filename entered as a character string, but it may be a `"[srcfile](../../base/html/srcfile)"` object, or it may include a suffix like `"filename.R#nn"`, in which case the number `nn` will be used as a default value for `line`. As described in the description of the `where` argument on the man page for `[trace](../../base/html/trace)`, the **R** package system uses a complicated scheme that may include more than one copy of a function in a package. The user will typically see the public one on the search path, while code in the package will see a private one in the package namespace. If you set `envir` to the environment of a function in the package, by default `findLineNum` will find both versions, and `setBreakpoint` will set the breakpoint in both. (This can be controlled using `lastenv`; e.g., `envir = environment(foo)`, `lastenv = globalenv()` will find only the private copy, as the search is stopped before seeing the public copy.) S version 4 methods are also somewhat tricky to find. They are stored with the generic function, which may be in the base or other package, so it is usually necessary to have `lastenv = emptyenv()` in order to find them. In some cases transformations are done by **R** when storing them and `findLineNum` may not be able to find the original code. Many special cases, e.g. methods on primitive generics, are not yet supported. ### Value `findLineNum` returns a list of objects containing location information. A `print` method is defined for them. `setBreakpoint` has no useful return value; it is called for the side effect of calling `[trace](../../base/html/trace)` or `[untrace](../../base/html/trace)`. ### Author(s) Duncan Murdoch ### See Also `[trace](../../base/html/trace)` ### Examples ``` ## Not run: # Find what function was defined in the file mysource.R at line 100: findLineNum("mysource.R#100") # Set a breakpoint in both copies of that function, assuming one is in the # same namespace as myfunction and the other is on the search path setBreakpoint("mysource.R#100", envir = myfunction) ## End(Not run) ``` r None `removeSource` Remove Stored Source from a Function or Language Object ----------------------------------------------------------------------- ### Description When `options("keep.source")` is `TRUE`, a copy of the original source code to a function is stored with it. Similarly, `[parse](../../base/html/parse)()` may keep formatted source for an expression. Such source reference attributes are removed from the object by `removeSource()`. ### Usage ``` removeSource(fn) ``` ### Arguments | | | | --- | --- | | `fn` | a `[function](../../base/html/function)` or another language object (fulfilling `[is.language](../../base/html/is.language)`) from which to remove the source. | ### Details This removes the `"srcref"` and related attributes, via *recursive* cleaning of `body(fn)` in the case of a function or the recursive language parts, otherwise. ### Value A copy of the `fn` object with the source removed. ### See Also `[is.language](../../base/html/is.language)` about language objects. `[srcref](../../base/html/srcfile)` for a description of source reference records, `[deparse](../../base/html/deparse)` for a description of how functions are deparsed. ### Examples ``` ## to make this act independently of the global 'options()' setting: op <- options(keep.source = TRUE) fn <- function(x) { x + 1 # A comment, kept as part of the source } fn names(attributes(fn)) # "srcref" (only) names(attributes(body(fn))) # "srcref" "srcfile" "wholeSrcref" f2 <- removeSource(fn) f2 stopifnot(length(attributes(fn)) > 0, is.null(attributes(f2)), is.null(attributes(body(f2)))) ## Source attribute of parse()d expressions, ## have {"srcref", "srcfile", "wholeSrcref"} : E <- parse(text ="a <- x^y # power") ; names(attributes(E )) E. <- removeSource(E) ; names(attributes(E.)) stopifnot(length(attributes(E )) > 0, is.null(attributes(E.))) options(op) # reset to previous state ``` r None `promptData` Generate Outline Documentation for a Data Set ----------------------------------------------------------- ### Description Generates a shell of documentation for a data set. ### Usage ``` promptData(object, filename = NULL, name = NULL) ``` ### Arguments | | | | --- | --- | | `object` | an **R** object to be documented as a data set. | | `filename` | usually, a [connection](../../base/html/connections) or a character string giving the name of the file to which the documentation shell should be written. The default corresponds to a file whose name is `name` followed by `".Rd"`. Can also be `NA` (see below). | | `name` | a character string specifying the name of the object. | ### Details Unless `filename` is `NA`, a documentation shell for `object` is written to the file specified by `filename`, and a message about this is given. If `filename` is `NA`, a list-style representation of the documentation shell is created and returned. Writing the shell to a file amounts to `cat(unlist(x), file = filename, sep = "\n")`, where `x` is the list-style representation. Currently, only data frames are handled explicitly by the code. ### Value If `filename` is `NA`, a list-style representation of the documentation shell. Otherwise, the name of the file written to is returned invisibly. ### See Also `<prompt>` ### Examples ``` promptData(sunspots) unlink("sunspots.Rd") ``` r None `recover` Browsing after an Error ---------------------------------- ### Description This function allows the user to browse directly on any of the currently active function calls, and is suitable as an error option. The expression `options(error = recover)` will make this the error option. ### Usage ``` recover() ``` ### Details When called, `recover` prints the list of current calls, and prompts the user to select one of them. The standard **R** `[browser](../../base/html/browser)` is then invoked from the corresponding environment; the user can type ordinary **R** language expressions to be evaluated in that environment. When finished browsing in this call, type `c` to return to `recover` from the browser. Type another frame number to browse some more, or type `0` to exit `recover`. The use of `recover` largely supersedes `[dump.frames](debugger)` as an error option, unless you really want to wait to look at the error. If `recover` is called in non-interactive mode, it behaves like `dump.frames`. For computations involving large amounts of data, `recover` has the advantage that it does not need to copy out all the environments in order to browse in them. If you do decide to quit interactive debugging, call `[dump.frames](debugger)` directly while browsing in any frame (see the examples). ### Value Nothing useful is returned. However, you *can* invoke `recover` directly from a function, rather than through the error option shown in the examples. In this case, execution continues after you type `0` to exit `recover`. ### Compatibility Note The **R** `recover` function can be used in the same way as the S function of the same name; therefore, the error option shown is a compatible way to specify the error action. However, the actual functions are essentially unrelated and interact quite differently with the user. The navigating commands `up` and `down` do not exist in the **R** version; instead, exit the browser and select another frame. ### References John M. Chambers (1998). *Programming with Data*; Springer. See the compatibility note above, however. ### See Also `[browser](../../base/html/browser)` for details about the interactive computations; `[options](../../base/html/options)` for setting the error option; `[dump.frames](debugger)` to save the current environments for later debugging. ### Examples ``` ## Not run: options(error = recover) # setting the error option ### Example of interaction > myFit <- lm(y ~ x, data = xy, weights = w) Error in lm.wfit(x, y, w, offset = offset, ...) : missing or negative weights not allowed Enter a frame number, or 0 to exit 1:lm(y ~ x, data = xy, weights = w) 2:lm.wfit(x, y, w, offset = offset, ...) Selection: 2 Called from: eval(expr, envir, enclos) Browse[1]> objects() # all the objects in this frame [1] "method" "n" "ny" "offset" "tol" "w" [7] "x" "y" Browse[1]> w [1] -0.5013844 1.3112515 0.2939348 -0.8983705 -0.1538642 [6] -0.9772989 0.7888790 -0.1919154 -0.3026882 Browse[1]> dump.frames() # save for offline debugging Browse[1]> c # exit the browser Enter a frame number, or 0 to exit 1:lm(y ~ x, data = xy, weights = w) 2:lm.wfit(x, y, w, offset = offset, ...) Selection: 0 # exit recover > ## End(Not run) ``` r None `summaryRprof` Summarise Output of R Sampling Profiler ------------------------------------------------------- ### Description Summarise the output of the `[Rprof](rprof)` function to show the amount of time used by different **R** functions. ### Usage ``` summaryRprof(filename = "Rprof.out", chunksize = 5000, memory = c("none", "both", "tseries", "stats"), lines = c("hide", "show", "both"), index = 2, diff = TRUE, exclude = NULL, basenames = 1) ``` ### Arguments | | | | --- | --- | | `filename` | Name of a file produced by `Rprof()`. | | `chunksize` | Number of lines to read at a time. | | `memory` | Summaries for memory information. See ‘Memory profiling’ below. Can be abbreviated. | | `lines` | Summaries for line information. See ‘Line profiling’ below. Can be abbreviated. | | `index` | How to summarize the stack trace for memory information. See ‘Details’ below. | | `diff` | If `TRUE` memory summaries use change in memory rather than current memory. | | `exclude` | Functions to exclude when summarizing the stack trace for memory summaries. | | `basenames` | Number of components of the path to filenames to display. | ### Details This function provides the analysis code for `[Rprof](rprof)` files used by `R CMD Rprof`. As the profiling output file could be larger than available memory, it is read in blocks of `chunksize` lines. Increasing `chunksize` will make the function run faster if sufficient memory is available. ### Value If `memory = "none"` and `lines = "hide"`, a list with components | | | | --- | --- | | `by.self` | A data frame of timings sorted by ‘self’ time. | | `by.total` | A data frame of timings sorted by ‘total’ time. | | `sample.interval` | The sampling interval. | | `sampling.time` | Total time of profiling run. | The first two components have columns self.time, self.pct, total.time and total.pct, the times in seconds and percentages of the total time spent executing code in that function and code in that function or called from that function, respectively. If `lines = "show"`, an additional component is added to the list: | | | | --- | --- | | `by.line` | A data frame of timings sorted by source location. | If `memory = "both"` the same list but with memory consumption in Mb in addition to the timings. If `memory = "tseries"` a data frame giving memory statistics over time. Memory usage is in bytes. If `memory = "stats"` a `[by](../../base/html/by)` object giving memory statistics by function. Memory usage is in bytes. If no events were recorded, a zero-row data frame is returned. ### Memory profiling Options other than `memory = "none"` apply only to files produced by `[Rprof](rprof)(memory.profiling = TRUE)`. When called with `memory.profiling = TRUE`, the profiler writes information on three aspects of memory use: vector memory in small blocks on the R heap, vector memory in large blocks (from `malloc`), memory in nodes on the R heap. It also records the number of calls to the internal function `duplicate` in the time interval. `duplicate` is called by C code when arguments need to be copied. Note that the profiler does not track which function actually allocated the memory. With `memory = "both"` the change in total memory (truncated at zero) is reported in addition to timing data. With `memory = "tseries"` or `memory = "stats"` the `index` argument specifies how to summarize the stack trace. A positive number specifies that many calls from the bottom of the stack; a negative number specifies the number of calls from the top of the stack. With `memory = "tseries"` the index is used to construct labels and may be a vector to give multiple sets of labels. With `memory = "stats"` the index must be a single number and specifies how to aggregate the data to the maximum and average of the memory statistics. With both `memory = "tseries"` and `memory = "stats"` the argument `diff = TRUE` asks for summaries of the increase in memory use over the sampling interval and `diff = FALSE` asks for the memory use at the end of the interval. ### Line profiling If the code being run has source reference information retained (via `keep.source = TRUE` in `[source](../../base/html/source)` or `KeepSource = TRUE` in a package ‘DESCRIPTION’ file or some other way), then information about the origin of lines is recorded during profiling. By default this is not displayed, but the `lines` parameter can enable the display. If `lines = "show"`, line locations will be used in preference to the usual function name information, and the results will be displayed ordered by location in addition to the other orderings. If `lines = "both"`, line locations will be mixed with function names in a combined display. ### See Also The chapter on ‘Tidying and profiling R code’ in ‘Writing R Extensions’ (see the ‘doc/manual’ subdirectory of the **R** source tree). `[Rprof](rprof)` `[tracemem](../../base/html/tracemem)` traces copying of an object via the C function `duplicate`. `[Rprofmem](rprofmem)` is a non-sampling memory-use profiler. <https://developer.r-project.org/memory-profiling.html> ### Examples ``` ## Not run: ## Rprof() is not available on all platforms Rprof(tmp <- tempfile()) example(glm) Rprof() summaryRprof(tmp) unlink(tmp) ## End(Not run) ``` r None `package.skeleton` Create a Skeleton for a New Source Package -------------------------------------------------------------- ### Description `package.skeleton` automates some of the setup for a new source package. It creates directories, saves functions, data, and R code files to appropriate places, and creates skeleton help files and a ‘Read-and-delete-me’ file describing further steps in packaging. ### Usage ``` package.skeleton(name = "anRpackage", list, environment = .GlobalEnv, path = ".", force = FALSE, code_files = character(), encoding = "unknown") ``` ### Arguments | | | | --- | --- | | `name` | character string: the package name and directory name for your package. Must be a valid package name. | | `list` | character vector naming the **R** objects to put in the package. Usually, at most one of `list`, `environment`, or `code_files` will be supplied. See ‘Details’. | | `environment` | an environment where objects are looked for. See ‘Details’. | | `path` | path to put the package directory in. | | `force` | If `FALSE` will not overwrite an existing directory. | | `code_files` | a character vector with the paths to R code files to build the package around. See ‘Details’. | | `encoding` | optionally a `[character](../../base/html/character)` string with an encoding for an optional `Encoding:` line in ‘DESCRIPTION’ when non-ASCII characters will be used; typically one of `"latin1"`, `"latin2"`, or `"UTF-8"`; see the WRE manual. | ### Details The arguments `list`, `environment`, and `code_files` provide alternative ways to initialize the package. If `code_files` is supplied, the files so named will be sourced to form the environment, then used to generate the package skeleton. Otherwise `list` defaults to the objects in `environment` (including those whose names start with `.`), but can be supplied to select a subset of the objects in that environment. Stubs of help files are generated for functions, data objects, and S4 classes and methods, using the `<prompt>`, `[promptClass](../../methods/html/promptclass)`, and `[promptMethods](../../methods/html/promptmethods)` functions. If an object from another package is intended to be imported and re-exported without changes, the `[promptImport](prompt)` function should be used after `package.skeleton` to generate a simple help file linking to the original one. The package sources are placed in subdirectory `name` of `path`. If `code_files` is supplied, these files are copied; otherwise, objects will be dumped into individual source files. The file names in `code_files` should have suffix `".R"` and be in the current working directory. The filenames created for source and documentation try to be valid for all OSes known to run **R**. Invalid characters are replaced by \_, invalid names are preceded by zz, names are converted to lower case (to avoid case collisions on case-insensitive file systems) and finally the converted names are made unique by `[make.unique](../../base/html/make.unique)(sep = "_")`. This can be done for code and help files but not data files (which are looked for by name). Also, the code and help files should have names starting with an ASCII letter or digit, and this is checked and if necessary `z` prepended. Functions with names starting with a dot are placed in file ‘R/name-internal.R’. When you are done, delete the ‘Read-and-delete-me’ file, as it should not be distributed. ### Value Used for its side-effects. ### References Read the ‘Writing R Extensions’ manual for more details. Once you have created a *source* package you need to install it: see the ‘R Installation and Administration’ manual, `[INSTALL](install)` and `<install.packages>`. ### See Also `<prompt>`, `[promptClass](../../methods/html/promptclass)`, and `[promptMethods](../../methods/html/promptmethods)`. `[package\_native\_routine\_registration\_skeleton](../../tools/html/package_native_routine_registration_skeleton)` for helping in preparing packages with compiled code. ### Examples ``` require(stats) ## two functions and two "data sets" : f <- function(x, y) x+y g <- function(x, y) x-y d <- data.frame(a = 1, b = 2) e <- rnorm(1000) package.skeleton(list = c("f","g","d","e"), name = "mypkg") ```
programming_docs
r None `read.fortran` Read Fixed-Format Data in a Fortran-like Style -------------------------------------------------------------- ### Description Read fixed-format data files using Fortran-style format specifications. ### Usage ``` read.fortran(file, format, ..., as.is = TRUE, colClasses = NA) ``` ### Arguments | | | | --- | --- | | `file` | File or [connection](../../base/html/connections) to read from. | | `format` | Character vector or list of vectors. See ‘Details’ below. | | `...` | Other arguments for `<read.fwf>`. | | `as.is` | Keep characters as characters? | | `colClasses` | Variable classes to override defaults. See `<read.table>` for details. | ### Details The format for a field is of one of the following forms: `rFl.d`, `rDl.d`, `rXl`, `rAl`, `rIl`, where `l` is the number of columns, `d` is the number of decimal places, and `r` is the number of repeats. `F` and `D` are numeric formats, `A` is character, `I` is integer, and `X` indicates columns to be skipped. The repeat code `r` and decimal place code `d` are always optional. The length code `l` is required except for `X` formats when `r` is present. For a single-line record, `format` should be a character vector. For a multiline record it should be a list with a character vector for each line. Skipped (`X`) columns are not passed to `read.fwf`, so `colClasses`, `col.names`, and similar arguments passed to `read.fwf` should not reference these columns. ### Value A data frame ### Note `read.fortran` does not use actual Fortran input routines, so the formats are at best rough approximations to the Fortran ones. In particular, specifying `d > 0` in the `F` or `D` format will shift the decimal `d` places to the left, even if it is explicitly specified in the input file. ### See Also `<read.fwf>`, `<read.table>`, `[read.csv](read.table)` ### Examples ``` ff <- tempfile() cat(file = ff, "123456", "987654", sep = "\n") read.fortran(ff, c("F2.1","F2.0","I2")) read.fortran(ff, c("2F1.0","2X","2A1")) unlink(ff) cat(file = ff, "123456AB", "987654CD", sep = "\n") read.fortran(ff, list(c("2F3.1","A2"), c("3I2","2X"))) unlink(ff) # Note that the first number is read differently than Fortran would # read it: cat(file = ff, "12.3456", "1234567", sep = "\n") read.fortran(ff, "F7.4") unlink(ff) ``` r None `Sweave` Automatic Generation of Reports ----------------------------------------- ### Description `Sweave` provides a flexible framework for mixing text and R/S code for automatic report generation. The basic idea is to replace the code with its output, such that the final document only contains the text and the output of the statistical analysis: however, the source code can also be included. ### Usage ``` Sweave(file, driver = RweaveLatex(), syntax = getOption("SweaveSyntax"), encoding = "", ...) Stangle(file, driver = Rtangle(), syntax = getOption("SweaveSyntax"), encoding = "", ...) ``` ### Arguments | | | | --- | --- | | `file` | Path to Sweave source file. Note that this can be supplied without the extension, but the function will only proceed if there is exactly one Sweave file in the directory whose basename matches `file`. | | `driver` | the actual workhorse, (a function returning) a named `[list](../../base/html/list)` of five functions, see ‘Details’ or the Sweave manual vignette. | | `syntax` | `NULL` or an object of class `SweaveSyntax` or a character string with its name. See the section ‘Syntax Definition’. | | `encoding` | The default encoding to assume for `file`. | | `...` | further arguments passed to the driver's setup function: see section ‘Details’, or specifically the arguments of the `R...Setup()` function in `[RweaveLatex](rweavelatex)` and `[Rtangle](rtangle)`, respectively. | ### Details Automatic generation of reports by mixing word processing markup (like latex) and S code. The S code gets replaced by its output (text or graphs) in the final markup file. This allows a report to be re-generated if the input data change and documents the code to reproduce the analysis in the same file that also produces the report. `Sweave` combines the documentation and code chunks together (or their output) into a single document. `Stangle` extracts only the code from the Sweave file creating an S source file that can be run using `[source](../../base/html/source)`. (Code inside `\Sexpr{}` statements is ignored by `Stangle`.) `Stangle` is just a wrapper to `Sweave` specifying a different default driver. Alternative drivers can be used: the former CRAN package [cacheSweave](https://CRAN.R-project.org/package=cacheSweave) and the Bioconductor package weaver provide drivers based on the default driver `[RweaveLatex](rweavelatex)` which incorporate ideas of *caching* the results of computations on code chunks. Environment variable SWEAVE\_OPTIONS can be used to override the initial options set by the driver: it should be a comma-separated set of `key=value` items, as would be used in a \SweaveOpts statement in a document. Non-ASCII source files must contain a line of the form ``` \usepackage[foo]{inputenc} ``` (where foo is typically latin1, latin2, utf8 or cp1252 or cp1250) or they will give an error. Re-encoding can be turned off completely with argument `encoding = "bytes"`. ### Syntax Definition Sweave allows a flexible syntax framework for marking documentation and text chunks. The default is a noweb-style syntax, as alternative a latex-style syntax can be used. (See the user manual for further details.) If `syntax = NULL` (the default) then the available syntax objects are consulted in turn, and selected if their `extension` component matches (as a regexp) the file name. Objects `SweaveSyntaxNoweb` (with `extension = "[.][rsRS]nw$"`) and `SweaveSyntaxLatex` (with `extension = "[.][rsRS]tex$"`) are supplied, but users or packages can supply others with names matching the pattern `SweaveSyntax.*`. ### Author(s) Friedrich Leisch and R-core. ### References Friedrich Leisch (2002) Dynamic generation of statistical reports using literate data analysis. In W. Härdle and B. Rönz, editors, *Compstat 2002 - Proceedings in Computational Statistics*, pages 575–580. Physika Verlag, Heidelberg, Germany, ISBN 3-7908-1517-9. ### See Also ‘Sweave User Manual’, a vignette in the utils package. `[RweaveLatex](rweavelatex)`, `[Rtangle](rtangle)`. Packages [cacheSweave](https://CRAN.R-project.org/package=cacheSweave) (archived), weaver (Bioconductor) and [SweaveListingUtils](https://CRAN.R-project.org/package=SweaveListingUtils) (archived). Further Sweave drivers are in, for example, packages [R2HTML](https://CRAN.R-project.org/package=R2HTML), [ascii](https://CRAN.R-project.org/package=ascii), [odfWeave](https://CRAN.R-project.org/package=odfWeave) (archived) and [pgfSweave](https://CRAN.R-project.org/package=pgfSweave) (archived). Non-Sweave vignettes may be built with `tools::[buildVignette](../../tools/html/buildvignette)`. ### Examples ``` testfile <- system.file("Sweave", "Sweave-test-1.Rnw", package = "utils") ## enforce par(ask = FALSE) options(device.ask.default = FALSE) ## create a LaTeX file - in the current working directory, getwd(): Sweave(testfile) ## This can be compiled to PDF by ## tools::texi2pdf("Sweave-test-1.tex") ## or outside R by ## ## R CMD texi2pdf Sweave-test-1.tex ## on Unix-alikes which sets the appropriate TEXINPUTS path. ## ## On Windows, ## Rcmd texify --pdf Sweave-test-1.tex ## if MiKTeX is available. ## create an R source file from the code chunks Stangle(testfile) ## which can be sourced, e.g. source("Sweave-test-1.R") ``` r None `help.start` Hypertext Documentation ------------------------------------- ### Description Start the hypertext (currently HTML) version of **R**'s online documentation. ### Usage ``` help.start(update = FALSE, gui = "irrelevant", browser = getOption("browser"), remote = NULL) ``` ### Arguments | | | | --- | --- | | `update` | logical: should this attempt to update the package index to reflect the currently available packages. (Not attempted if `remote` is non-`NULL`.) | | `gui` | just for compatibility with S-PLUS. | | `browser` | the name of the program to be used as hypertext browser. It should be in the PATH, or a full path specified. Alternatively, it can be an **R** function which will be called with a URL as its only argument. This option is normally unset on Windows, when the file-association mechanism will be used. | | `remote` | A character string giving a valid URL for the ‘[R\_HOME](../../base/html/rhome)’ directory on a remote location. | ### Details Unless `remote` is specified this requires the HTTP server to be available (it will be started if possible: see `[startDynamicHelp](../../tools/html/startdynamichelp)`). One of the links on the index page is the HTML package index, ‘R.home("docs")/html/packages.html’, which can be remade by `<make.packages.html>()`. For local operation, the HTTP server will remake a temporary version of this list when the link is first clicked, and each time thereafter check if updating is needed (if `[.libPaths](../../base/html/libpaths)` has changed or any of the directories has been changed). This can be slow, and using `update = TRUE` will ensure that the packages list is updated before launching the index page. Argument `remote` can be used to point to HTML help published by another **R** installation: it will typically only show packages from the main library of that installation. ### See Also `<help>()` for on- and off-line help in other formats. `[browseURL](browseurl)` for how the help file is displayed. `[RSiteSearch](rsitesearch)` to access an on-line search of **R** resources. ### Examples ``` help.start() ## Not run: if(.Platform$OS.type == "unix") # includes Mac ## the 'remote' arg can be tested by help.start(remote = paste0("file://", R.home())) ## End(Not run) ``` r None `choose.dir` Choose a Folder Interactively on MS Windows --------------------------------------------------------- ### Description Use a Windows shell folder widget to choose a folder interactively. ### Usage ``` choose.dir(default = "", caption = "Select folder") ``` ### Arguments | | | | --- | --- | | `default` | which folder to show initially. | | `caption` | the caption on the selection dialog. | ### Details This brings up the Windows shell folder selection widget. With the default `default = ""`, ‘My Computer’ (or similar) is initially selected. To workaround a bug, on Vista and later only folders under ‘Computer’ are accessible via the widget. ### Value A length-one character vector, character `NA` if ‘Cancel’ was selected. ### Note This is only available on Windows. ### See Also `<choose.files>` (on Windows) and `[file.choose](../../base/html/file.choose)` (on all platforms). ### Examples ``` if (interactive() && .Platform$OS.type == "windows") choose.dir(getwd(), "Choose a suitable folder") ``` r None `capture.output` Send Output to a Character String or File ----------------------------------------------------------- ### Description Evaluates its arguments with the output being returned as a character string or sent to a file. Related to `[sink](../../base/html/sink)` similarly to how `[with](../../base/html/with)` is related to `[attach](../../base/html/attach)`. ### Usage ``` capture.output(..., file = NULL, append = FALSE, type = c("output", "message"), split = FALSE) ``` ### Arguments | | | | --- | --- | | `...` | Expressions to be evaluated. | | `file` | A file name or a [connection](../../base/html/connections), or `NULL` to return the output as a character vector. If the connection is not open, it will be opened initially and closed on exit. | | `append` | logical. If `file` a file name or unopened connection, append or overwrite? | | `type, split` | are passed to `[sink](../../base/html/sink)()`, see there. | ### Details It works via `[sink](../../base/html/sink)(<file connection>)` and hence the **R** code in `dots` must *not* interfere with the connection (e.g., by calling `[closeAllConnections](../../base/html/showconnections)()`). An attempt is made to write output as far as possible to `file` if there is an error in evaluating the expressions, but for `file = NULL` all output will be lost. Messages sent to `[stderr](../../base/html/showconnections)()` (including those from `[message](../../base/html/message)`, `[warning](../../base/html/warning)` and `[stop](../../base/html/stop)`) are captured by `type = "message"`. Note that this can be “unsafe” and should only be used with care. ### Value A character string (if `file = NULL`), or invisible `NULL`. ### See Also `[sink](../../base/html/sink)`, `[textConnection](../../base/html/textconnections)` ### Examples ``` require(stats) glmout <- capture.output(summary(glm(case ~ spontaneous+induced, data = infert, family = binomial()))) glmout[1:5] capture.output(1+1, 2+2) capture.output({1+1; 2+2}) ## Not run: ## on Unix-alike with a2ps available op <- options(useFancyQuotes=FALSE) pdf <- pipe("a2ps -o - | ps2pdf - tempout.pdf", "w") capture.output(example(glm), file = pdf) close(pdf); options(op) ; system("evince tempout.pdf &") ## End(Not run) ``` r None `read.DIF` Data Input from Spreadsheet --------------------------------------- ### Description Reads a file in Data Interchange Format (DIF) and creates a data frame from it. DIF is a format for data matrices such as single spreadsheets. ### Usage ``` read.DIF(file, header = FALSE, dec = ".", numerals = c("allow.loss", "warn.loss", "no.loss"), row.names, col.names, as.is = !stringsAsFactors, na.strings = "NA", colClasses = NA, nrows = -1, skip = 0, check.names = TRUE, blank.lines.skip = TRUE, stringsAsFactors = FALSE, transpose = FALSE, fileEncoding = "") ``` ### Arguments | | | | --- | --- | | `file` | the name of the file which the data are to be read from, or a [connection](../../base/html/connections), or a complete URL. The name `"clipboard"` may also be used on Windows, in which case `read.DIF("clipboard")` will look for a DIF format entry in the Windows clipboard. | | `header` | a logical value indicating whether the spreadsheet contains the names of the variables as its first line. If missing, the value is determined from the file format: `header` is set to `TRUE` if and only if the first row contains only character values and the top left cell is empty. | | `dec` | the character used in the file for decimal points. | | `numerals` | string indicating how to convert numbers whose conversion to double precision would lose accuracy, see `<type.convert>`. | | `row.names` | a vector of row names. This can be a vector giving the actual row names, or a single number giving the column of the table which contains the row names, or character string giving the name of the table column containing the row names. If there is a header and the first row contains one fewer field than the number of columns, the first column in the input is used for the row names. Otherwise if `row.names` is missing, the rows are numbered. Using `row.names = NULL` forces row numbering. | | `col.names` | a vector of optional names for the variables. The default is to use `"V"` followed by the column number. | | `as.is` | controls conversion of character variables (insofar as they are not converted to logical, numeric or complex) to factors, if not otherwise specified by `colClasses`. Its value is either a vector of logicals (values are recycled if necessary), or a vector of numeric or character indices which specify which columns should not be converted to factors. Note: In releases prior to **R** 2.12.1, cells marked as being of character type were converted to logical, numeric or complex using `<type.convert>` as in `<read.table>`. Note: to suppress all conversions including those of numeric columns, set `colClasses = "character"`. Note that `as.is` is specified per column (not per variable) and so includes the column of row names (if any) and any columns to be skipped. | | `na.strings` | a character vector of strings which are to be interpreted as `[NA](../../base/html/na)` values. Blank fields are also considered to be missing values in logical, integer, numeric and complex fields. | | `colClasses` | character. A vector of classes to be assumed for the columns. Recycled as necessary, or if the character vector is named, unspecified values are taken to be `NA`. Possible values are `NA` (when `<type.convert>` is used), `"NULL"` (when the column is skipped), one of the atomic vector classes (logical, integer, numeric, complex, character, raw), or `"factor"`, `"Date"` or `"POSIXct"`. Otherwise there needs to be an `as` method (from package methods) for conversion from `"character"` to the specified formal class. Note that `colClasses` is specified per column (not per variable) and so includes the column of row names (if any). | | `nrows` | the maximum number of rows to read in. Negative values are ignored. | | `skip` | the number of lines of the data file to skip before beginning to read data. | | `check.names` | logical. If `TRUE` then the names of the variables in the data frame are checked to ensure that they are syntactically valid variable names. If necessary they are adjusted (by `[make.names](../../base/html/make.names)`) so that they are, and also to ensure that there are no duplicates. | | `blank.lines.skip` | logical: if `TRUE` blank lines in the input are ignored. | | `stringsAsFactors` | logical: should character vectors be converted to factors? | | `transpose` | logical, indicating if the row and column interpretation should be transposed. Microsoft's Excel has been known to produce (non-standard conforming) DIF files which would need `transpose = TRUE` to be read correctly. | | `fileEncoding` | character string: if non-empty declares the encoding used on a file (not a connection or clipboard) so the character data can be re-encoded. See the ‘Encoding’ section of the help for `[file](../../base/html/connections)`, the ‘R Data Import/Export’ manual and ‘Note’. | ### Value A data frame (`[data.frame](../../base/html/data.frame)`) containing a representation of the data in the file. Empty input is an error unless `col.names` is specified, when a 0-row data frame is returned: similarly giving just a header line if `header = TRUE` results in a 0-row data frame. ### Note The columns referred to in `as.is` and `colClasses` include the column of row names (if any). Less memory will be used if `colClasses` is specified as one of the six atomic vector classes. ### Author(s) R Core; `transpose` option by Christoph Buser, ETH Zurich ### References The DIF format specification can be found by searching on <http://www.wotsit.org/>; the optional header fields are ignored. See also <https://en.wikipedia.org/wiki/Data_Interchange_Format>. The term is likely to lead to confusion: Windows will have a ‘Windows Data Interchange Format (DIF) data format’ as part of its WinFX system, which may or may not be compatible. ### See Also The *R Data Import/Export* manual. `[scan](../../base/html/scan)`, `<type.convert>`, `<read.fwf>` for reading *f*ixed *w*idth *f*ormatted input; `<read.table>`; `[data.frame](../../base/html/data.frame)`. ### Examples ``` ## read.DIF() may need transpose = TRUE for a file exported from Excel udir <- system.file("misc", package = "utils") dd <- read.DIF(file.path(udir, "exDIF.dif"), header = TRUE, transpose = TRUE) dc <- read.csv(file.path(udir, "exDIF.csv"), header = TRUE) stopifnot(identical(dd, dc), dim(dd) == c(4,2)) ``` r None `tar` Create a Tar Archive --------------------------- ### Description Create a tar archive. ### Usage ``` tar(tarfile, files = NULL, compression = c("none", "gzip", "bzip2", "xz"), compression_level = 6, tar = Sys.getenv("tar"), extra_flags = "") ``` ### Arguments | | | | --- | --- | | `tarfile` | The pathname of the tar file: tilde expansion (see `[path.expand](../../base/html/path.expand)`) will be performed. Alternatively, a [connection](../../base/html/connections) that can be used for binary writes. | | `files` | A character vector of filepaths to be archived: the default is to archive all files under the current directory. | | `compression` | character string giving the type of compression to be used (default none). Can be abbreviated. | | `compression_level` | integer: the level of compression. Only used for the internal method. | | `tar` | character string: the path to the command to be used. If the command itself contains spaces it needs to be quoted (e.g., by `[shQuote](../../base/html/shquote)`) – but argument `tar` may also contain flags separated from the command by spaces. | | `extra_flags` | Any extra flags for an external `tar`. | ### Details This is either a wrapper for a `tar` command or uses an internal implementation in **R**. The latter is used if `tarfile` is a connection or if the argument `tar` is `"internal"` or `""` (the ‘factory-fresh’ default). Note that whereas Unix-alike versions of **R** set the environment variable TAR, its value is not the default for this function. Argument `extra_flags` is passed to an external `tar` and so is platform-dependent. Possibly useful values include -h (follow symbolic links, also -L on some platforms), --acls, --exclude-backups, --exclude-vcs (and similar) and on Windows --force-local (so drives can be included in filepaths: however, this is the default for the `Rtools` `tar`). For GNU `tar`, --format=ustar forces a more portable format. (The default is set at compilation and will be shown at the end of the output from `tar --help`: for version 1.30 ‘out-of-the-box’ it is --format=gnu, but the manual says the intention is to change to --format=posix which is the same as `pax` – it was never part of the POSIX standard for `tar` and should not be used.) For libarchive's `bsdtar`, --format=ustar is more portable than the default. One issue which can cause an external command to fail is a command line too long for the system shell: as from **R** 3.5.0 this is worked around if the external command is detected to be GNU `tar` or libarchive `tar` (aka `bsdtar`). Note that `files = '.'` will usually not work with an external `tar` as that would expand the list of files after `tarfile` is created. (It does work with the default internal method.) ### Value The return code from `[system](../../base/html/system)` or `0` for the internal version, invisibly. ### Portability The ‘tar’ format no longer has an agreed standard! ‘Unix Standard Tar’ was part of POSIX 1003.1:1998 but has been removed in favour of `pax`, and in any case many common implementations diverged from the former standard. Many **R** platforms use a version of GNU `tar` (including `Rtools` on Windows), but the behaviour seems to be changed with each version. macOS >= 10.6 and FreeBSD use `bsdtar` from the libarchive project (but for macOS a version from 2017 or earlier, 2010 for High Sierra), and commercial Unixes will have their own versions. `bsdtar` is available for many other platforms: macOS up to at least 10.9 had GNU `tar` as `gnutar` and other platforms, e.g. Solaris, have it as `gtar`: on a Unix-alike `configure` will try `gnutar` and `gtar` before `tar`. Known problems arise from * The handling of file paths of more than 100 bytes. These were unsupported in early versions of `tar`, and supported in one way by POSIX `tar` and in another by GNU `tar` and yet another by the POSIX `pax` command which recent `tar` programs often support. The internal implementation warns on paths of more than 100 bytes, uses the ‘ustar’ way from the 1998 POSIX standard which supports up to 256 bytes (depending on the path: in particular the final component is limited to 100 bytes) if possible, otherwise the GNU way (which is widely supported, including by `<untar>`). Most formats do not record the encoding of file paths. * (File) links. `tar` was developed on an OS that used hard links, and physical files that were referred to more than once in the list of files to be included were included only once, the remaining instances being added as links. Later a means to include symbolic links was added. The internal implementation supports symbolic links (on OSes that support them), only. Of course, the question arises as to how links should be unpacked on OSes that do not support them: for regular files file copies can be used. Names of links in the ‘ustar’ format are restricted to 100 bytes. There is an GNU extension for arbitrarily long link names, but `bsdtar` ignores it. The internal method uses the GNU extension, with a warning. * Header fields, in particular the padding to be used when fields are not full or not used. POSIX did define the correct behaviour but commonly used implementations did (and still do) not comply. * File sizes. The ‘ustar’ format is restricted to 8GB per (uncompressed) file. For portability, avoid file paths of more than 100 bytes and all links (especially hard links and symbolic links to directories). The internal implementation writes only the blocks of 512 bytes required (including trailing blocks of nuls), unlike GNU `tar` which by default pads with nul to a multiple of 20 blocks (10KB). Implementations which pad differ on whether the block padding should occur before or after compression (or both): padding was designed for improved performance on physical tape drives. The ‘ustar’ format records file modification times to a resolution of 1 second: on file systems with higher resolution it is conventional to discard fractional seconds. ### Compression When an external `tar` command is used, compressing the tar archive requires that `tar` supports the -z, -j or -J flag, and may require the appropriate command (`gzip`, `bzip2` or `xz`) to be available. For GNU `tar`, further compression programs can be specified by e.g. `extra_flags = "-I lz4"`. Some versions of `bsdtar` accept options such as --lz4, --lzop and --lrzip or an external compressor *via* `--use-compress-program lz4`: these could be supplied in `extra_flags`. NetBSD prior to 8.0 used flag --xz rather than -J, so this should be used *via* `extra_flags = "--xz"` rather than `compression = "xz"`. The commands from OpenBSD and the Heirloom Toolchest are not documented to support `xz`. The `tar` programs in commercial Unixen such as AIX and Solaris do not support compression. ### Note For users of macOS. Apple's file systems have a legacy concept of ‘resource forks’ dating from classic Mac OS and rarely used nowadays. Apple's version of `tar` stores these as separate files in the tarball with names prefixed by ‘.\_’, and unpacks such files into resource forks (if possible): other ways of unpacking (including `<untar>` in **R**) unpack them as separate files. When argument `tar` is set to the command `tar` on macOS, environment variable COPYFILE\_DISABLE=1 is set, which for the system version of `tar` prevents these separate files being included in the tarball. ### See Also <https://en.wikipedia.org/wiki/Tar_(file_format)>, <https://pubs.opengroup.org/onlinepubs/9699919799/utilities/pax.html#tag_20_92_13_06> for the way the POSIX utility `pax` handles `tar` formats. <https://github.com/libarchive/libarchive/wiki/FormatTar>. `<untar>`.
programming_docs
r None `aregexec` Approximate String Match Positions ---------------------------------------------- ### Description Determine positions of approximate string matches. ### Usage ``` aregexec(pattern, text, max.distance = 0.1, costs = NULL, ignore.case = FALSE, fixed = FALSE, useBytes = FALSE) ``` ### Arguments | | | | --- | --- | | `pattern` | a non-empty character string or a character string containing a regular expression (for `fixed = FALSE`) to be matched. Coerced by `[as.character](../../base/html/character)` to a string if possible. | | `text` | character vector where matches are sought. Coerced by `[as.character](../../base/html/character)` to a character vector if possible. | | `max.distance` | maximum distance allowed for a match. See `[agrep](../../base/html/agrep)`. | | `costs` | cost of transformations. See `[agrep](../../base/html/agrep)`. | | `ignore.case` | a logical. If `TRUE`, case is ignored for computing the distances. | | `fixed` | If `TRUE`, the pattern is matched literally (as is). Otherwise (default), it is matched as a regular expression. | | `useBytes` | a logical. If `TRUE` comparisons are byte-by-byte rather than character-by-character. | ### Details `aregexec` provides a different interface to approximate string matching than `[agrep](../../base/html/agrep)` (along the lines of the interfaces to exact string matching provided by `[regexec](../../base/html/grep)` and `[grep](../../base/html/grep)`). Note that by default, `[agrep](../../base/html/agrep)` performs literal matches, whereas `aregexec` performs regular expression matches. See `[agrep](../../base/html/agrep)` and `<adist>` for more information about approximate string matching and distances. Comparisons are byte-by-byte if `pattern` or any element of `text` is marked as `"bytes"`. ### Value A list of the same length as `text`, each element of which is either *-1* if there is no match, or a sequence of integers with the starting positions of the match and all substrings corresponding to parenthesized subexpressions of `pattern`, with attribute `"match.length"` an integer vector giving the lengths of the matches (or *-1* for no match). ### See Also `[regmatches](../../base/html/regmatches)` for extracting the matched substrings. ### Examples ``` ## Cf. the examples for agrep. x <- c("1 lazy", "1", "1 LAZY") aregexec("laysy", x, max.distance = 2) aregexec("(lay)(sy)", x, max.distance = 2) aregexec("(lay)(sy)", x, max.distance = 2, ignore.case = TRUE) m <- aregexec("(lay)(sy)", x, max.distance = 2) regmatches(x, m) ``` r None `setWindowTitle` Set the Window Title or the Statusbar of the RGui in Windows ------------------------------------------------------------------------------ ### Description Set or get the title of the **R** (i.e. `RGui`) window which will appear in the task bar, or set the statusbar (if in use). ### Usage ``` setWindowTitle(suffix, title = paste(getIdentification(), suffix)) getWindowTitle() getIdentification() setStatusBar(text) ``` ### Arguments | | | | --- | --- | | `suffix` | a character string to form part of the title | | `title` | a character string forming the complete new title | | `text` | a character string of up to 255 characters, to be displayed in the status bar. | ### Details `setWindowTitle` appends `suffix` to the normal window identification (`RGui`, `R Console` or `Rterm`). Use `suffix = ""` to reset the title. `getWindowTitle` gets the current title. This sets the title of the frame in MDI mode, the title of the console for `RGui --sdi`, and the title of the window from which it was launched for `Rterm`. It has no effect in embedded uses of **R**. `getIdentification` returns the normal window identification. `setStatusBar` sets the text in the statusbar of an MDI frame: if this is not currently shown it is selected and shown. ### Value The first three functions return a length 1 character vector. `setWindowTitle` returns the previous window title (invisibly). `getWindowTitle` and `getIdentification` return the current window title and the normal window identification, respectively. ### Note These functions are only available on Windows and only make sense when using the `Rgui`. E.g., in `Rterm` (and hence in `ESS`) the title is not visible (but can be set and gotten), and in a version of `RStudio` it has been `""`, invariably. ### Examples ``` if(.Platform$OS.type == "windows") withAutoprint({ ## show the current working directory in the title, saving the old one oldtitle <- setWindowTitle(getwd()) Sys.sleep(0.5) ## reset the title setWindowTitle("") Sys.sleep(0.5) ## restore the original title setWindowTitle(title = oldtitle) }) ``` r None `RShowDoc` Show R Manuals and Other Documentation -------------------------------------------------- ### Description Utility function to find and display **R** documentation. ### Usage ``` RShowDoc(what, type = c("pdf", "html", "txt"), package) ``` ### Arguments | | | | --- | --- | | `what` | a character string: see ‘Details’. | | `type` | an optional character string giving the preferred format. Can be abbreviated. | | `package` | an optional character string specifying the name of a package within which to look for documentation. | ### Details `what` can specify one of several different sources of documentation, including the **R** manuals (`R-admin`, `R-data`, `R-exts`, `R-intro`, `R-ints`, `R-lang`), `NEWS`, `COPYING` (the GPL licence), any of the licenses in ‘share/licenses’, `FAQ` (also available as `R-FAQ`), and the files in ‘[R\_HOME](../../base/html/rhome)/doc’. Only on Windows, the **R** for Windows FAQ is specified by `rw-FAQ`. If `package` is supplied, documentation is looked for in the ‘doc’ and top-level directories of an installed package of that name. If `what` is missing a brief usage message is printed. The documentation types are tried in turn starting with the first specified in `type` (or `"pdf"` if none is specified). ### Value A invisible character string given the path to the file found. ### See Also For displaying regular help files, `<help>` (or `[?](question)`) and `<help.start>`. For `type = "txt"`, `[file.show](../../base/html/file.show)` is used. `<vignette>`s are nicely viewed via `RShowDoc(*, package= . )`. ### Examples ``` RShowDoc("R-lang") RShowDoc("FAQ", type = "html") RShowDoc("frame", package = "grid") RShowDoc("changes.txt", package = "grid") RShowDoc("NEWS", package = "MASS") ``` r None `create.post` Ancillary Function for Preparing Emails and Postings ------------------------------------------------------------------- ### Description An ancillary function used by `<bug.report>` and `<help.request>` to prepare emails for submission to package maintainers or to **R** mailing lists. ### Usage ``` create.post(instructions = character(), description = "post", subject = "", method = getOption("mailer"), address = "the relevant mailing list", ccaddress = getOption("ccaddress", ""), filename = "R.post", info = character()) ``` ### Arguments | | | | --- | --- | | `instructions` | Character vector of instructions to put at the top of the template email. | | `description` | Character string: a description to be incorporated into messages. | | `subject` | Subject of the email. Optional except for the `"mailx"` method. | | `method` | Submission method, one of `"none"`, `"mailto"`, `"gnudoit"`, `"ess"` or (Unix only) `"mailx"`. See ‘Details’. | | `address` | Recipient's email address, where applicable: for package bug reports sent by email this defaults to the address of the package maintainer (the first if more than one is listed). | | `ccaddress` | Optional email address for copies with the `"mailx"` and `"mailto"` methods. Use `ccaddress = ""` for no copy. | | `filename` | Filename to use for setting up the email (or storing it when method is `"none"` or sending mail fails). | | `info` | character vector of information to include in the template email below the ‘please do not edit the information below’ line. | ### Details What this does depends on the `method`. The function first creates a template email body. `none` A file editor (see `<file.edit>`) is opened with instructions and the template email. When this returns, the completed email is in file `file` ready to be read/pasted into an email program. `mailto` This opens the default email program with a template email (including address, Cc: address and subject) for you to edit and send. This works where default mailers are set up (usual on macOS and Windows, and where `xdg-open` is available and configured on other Unix-alikes: if that fails it tries the browser set by R\_BROWSER). This is the ‘factory-fresh’ default method. `mailx` (Unix-alikes only.) A file editor (see `<file.edit>`) is opened with instructions and the template email. When this returns, it is mailed using a Unix command line mail utility such as `mailx`, to the address (and optionally, the Cc: address) given. `gnudoit` An (X)emacs mail buffer is opened for the email to be edited and sent: this requires the `gnudoit` program to be available. Currently `subject` is ignored. `ess` The body of the template email is sent to `stdout`. ### Value Invisible `NULL`. ### See Also `<bug.report>`, `<help.request>`. r None `askYesNo` Ask a Yes/No Question --------------------------------- ### Description `askYesNo` provides a standard way to ask the user a yes/no question. It provides a way for front-ends to substitute their own dialogs. ### Usage ``` askYesNo(msg, default = TRUE, prompts = getOption("askYesNo", gettext(c("Yes", "No", "Cancel"))), ...) ``` ### Arguments | | | | --- | --- | | `msg` | The prompt message for the user. | | `default` | The default response. | | `prompts` | Any of: a character vector containing 3 prompts corresponding to return values of `TRUE`, `FALSE`, or `NA`, or a single character value containing the prompts separated by `/` characters, or a function to call. | | `...` | Additional parameters, ignored by the default function. | ### Details `askYesNo` will accept case-independent partial matches to the prompts. If no response is given the value of `default` will be returned; if a non-empty string that doesn't match any of the prompts is entered, an error will be raised. If a function or single character string naming a function is given for `prompts`, it will be called as `fn(msg = msg, default = default, prompts = prompts, ...)`. On Windows, the GUI uses the unexported `utils:::askYesNoWinDialog` function for this purpose. If strings (or a string such as `"Y/N/C"`) are given as `prompts`, the choices will be mapped to lowercase for the non-default choices, and left as-is for the default choice. ### Value `TRUE` for yes, `FALSE` for no, and `NA` for cancel. ### See Also `readline` for more general user input. ### Examples ``` if (interactive()) askYesNo("Do you want to use askYesNo?") ``` r None `choose.files` Choose a List of Files Interactively on MS Windows ------------------------------------------------------------------ ### Description Use a Windows file dialog to choose a list of zero or more files interactively. ### Usage ``` choose.files(default = "", caption = "Select files", multi = TRUE, filters = Filters, index = nrow(Filters)) Filters ``` ### Arguments | | | | --- | --- | | `default` | which filename to show initially | | `caption` | the caption on the file selection dialog | | `multi` | whether to allow multiple files to be selected | | `filters` | a matrix of filename filters (see Details) | | `index` | which row of filters to use by default | ### Details Unlike `[file.choose](../../base/html/file.choose)`, `choose.files` will always attempt to return a character vector giving a list of files. If the user cancels the dialog, then zero files are returned, whereas `[file.choose](../../base/html/file.choose)` would signal an error. `choose.dir` chooses a directory. Windows file dialog boxes include a list of ‘filters’, which allow the file selection to be limited to files of specific types. The `filters` argument to `choose.files` allows the list of filters to be set. It should be an `n` by `2` character matrix. The first column gives, for each filter, the description the user will see, while the second column gives the mask(s) to select those files. If more than one mask is used, separate them by semicolons, with no spaces. The `index` argument chooses which filter will be used initially. `Filters` is a matrix giving the descriptions and masks for the file types that **R** knows about. Print it to see typical formats for filter specifications. The examples below show how particular filters may be selected. If you would like to display files in a particular directory, give a fully qualified file mask (e.g., `"c:\\*.*"`) in the `default` argument. If a directory is not given, the dialog will start in the current directory the first time, and remember the last directory used on subsequent invocations. There is a buffer limit on the total length of the selected filenames: it is large but this function is not intended to select thousands of files, when the limit might be reached. ### Value A character vector giving zero or more file paths. ### Note This is only available on Windows. ### See Also `[file.choose](../../base/html/file.choose)`, `<choose.dir>`. `[Sys.glob](../../base/html/sys.glob)` or `[list.files](../../base/html/list.files)` to select multiple files by pattern. ### Examples ``` if (interactive() && .Platform$OS.type == "windows") choose.files(filters = Filters[c("zip", "All"),]) ``` r None `flush.console` Flush Output to a Console ------------------------------------------ ### Description This does nothing except on console-based versions of **R**. On the macOS and Windows GUIs, it ensures that the display of output in the console is current, even if output buffering is on. ### Usage ``` flush.console() ``` r None `mirrorAdmin` Managing Repository Mirrors ------------------------------------------ ### Description Functions helping to maintain CRAN, some of them may also be useful for administrators of other repository networks. ### Usage ``` mirror2html(mirrors = NULL, file = "mirrors.html", head = "mirrors-head.html", foot = "mirrors-foot.html") checkCRAN(method) ``` ### Arguments | | | | --- | --- | | `mirrors` | A data frame, by default the CRAN list of mirrors is used. | | `file` | A [connection](../../base/html/connections) or a character string. | | `head` | Name of optional header file. | | `foot` | Name of optional footer file. | | `method` | Download method, see `download.file`. | ### Details `mirror2html` creates the HTML file for the CRAN list of mirrors and invisibly returns the HTML text. `checkCRAN` performs a sanity checks on all CRAN mirrors. r None `remove.packages` Remove Installed Packages -------------------------------------------- ### Description Removes installed packages/bundles and updates index information as necessary. ### Usage ``` remove.packages(pkgs, lib) ``` ### Arguments | | | | --- | --- | | `pkgs` | a character vector with the names of the packages to be removed. | | `lib` | a character vector giving the library directories to remove the packages from. If missing, defaults to the first element in `[.libPaths](../../base/html/libpaths)()`. | ### See Also On Unix-alikes, `[REMOVE](remove)` for a command line version; `<install.packages>` for installing packages. r None `REMOVE` Remove Add-on Packages -------------------------------- ### Description Utility for removing add-on packages. ### Usage ``` R CMD REMOVE [options] [-l lib] pkgs ``` ### Arguments | | | | --- | --- | | `pkgs` | a space-separated list with the names of the packages to be removed. | | `lib` | the path name of the **R** library tree to remove from. May be absolute or relative. Also accepted in the form --library=lib. | | `options` | further options for help or version. | ### Details If used as `R CMD REMOVE pkgs` without explicitly specifying `lib`, packages are removed from the library tree rooted at the first directory in the library path which would be used by **R** run in the current environment. To remove from the library tree `lib` instead of the default one, use `R CMD REMOVE -l lib pkgs`. Use `R CMD REMOVE --help` for more usage information. ### Note Some binary distributions of **R** have `REMOVE` in a separate bundle, e.g. an `R-devel` RPM. ### See Also `[INSTALL](install)`, `<remove.packages>` r None `winMenus` User Menus under MS Windows (Rgui) ---------------------------------------------- ### Description Enables users to add, delete and program menus for the `Rgui` in MS Windows. ### Usage ``` winMenuAdd(menuname) winMenuAddItem(menuname, itemname, action) winMenuDel(menuname) winMenuDelItem(menuname, itemname) winMenuNames() winMenuItems(menuname) ``` ### Arguments | | | | --- | --- | | `menuname` | a character string naming a menu. | | `itemname` | a character string naming a menu item on an existing menu. | | `action` | a character string describing the action when that menu is selected, or `"enable"` or `"disable"`. | ### Details User menus are added to the right of existing menus, and items are added at the bottom of the menu. By default the action character string is treated as **R** input, being echoed on the command line and parsed and executed as usual. If the `menuname` parameter of `winMenuAddItem` does not already exist, it will be created automatically. Normally new submenus and menu items are added to the main console menu. They may be added elsewhere using the following special names: `$ConsoleMain` The console menu (the default) `$ConsolePopup` The console popup menu `$Graph<n>Main` The menu for graphics window `<n>` `$Graph<n>Popup` The popup menu for graphics window `<n>` Specifying an existing item in `winMenuAddItem` enables the action to be changed. Submenus can be specified by separating the elements in `menuname` by slashes: as a consequence menu names may not contain slashes. If the `action` is specified as `"none"` no action is taken: this can be useful to reserve items for future expansion. The function `winMenuNames` can be used to find out what menus have been created by the user and returns a vector of the existing menu names. The `winMenuItems` function will take the name of a menu and return the items that exist in that menu. The return value is a named vector where the names correspond to the names of the items and the values of the vector are the corresponding actions. The `winMenuDel` function will delete a menu and all of its items and submenus. `winMenuDelItem` just deletes one menu item. The total path to an item (menu string plus item string) cannot exceed 1000 bytes, and the menu string cannot exceed 500 bytes. ### Value `NULL`, invisibly. If an error occurs, an informative error message will be given. ### Note These functions are only available on Windows and only when using the `Rgui`, hence not in `ESS` nor `RStudio`. ### See Also `[winDialog](windialog)` ### Examples ``` ## Not run: winMenuAdd("Testit") winMenuAddItem("Testit", "one", "aaaa") winMenuAddItem("Testit", "two", "bbbb") winMenuAdd("Testit/extras") winMenuAddItem("Testit", "-", "") winMenuAddItem("Testit", "two", "disable") winMenuAddItem("Testit", "three", "cccc") winMenuAddItem("Testit/extras", "one more", "ddd") winMenuAddItem("Testit/extras", "and another", "eee") winMenuAdd("$ConsolePopup/Testit") winMenuAddItem("$ConsolePopup/Testit", "six", "fff") winMenuNames() winMenuItems("Testit") ## End(Not run) ```
programming_docs
r None `BATCH` Batch Execution of R ----------------------------- ### Description Run **R** non-interactively with input from `infile` and send output (stdout/stderr) to another file. ### Usage ``` R CMD BATCH [options] infile [outfile] ``` ### Arguments | | | | --- | --- | | `infile` | the name of a file with **R** code to be executed. | | `options` | a list of **R** command line options, e.g., for setting the amount of memory available and controlling the load/save process. If `infile` starts with a -, use -- as the final option. The default options are --restore --save --no-readline. (Without --no-readline on Windows.) | | `outfile` | the name of a file to which to write output. If not given, the name used is that of `infile`, with a possible ‘.R’ extension stripped, and ‘.Rout’ appended. | ### Details Use `R CMD BATCH --help` to be reminded of the usage. By default, the input commands are printed along with the output. To suppress this behavior, add `options(echo = FALSE)` at the beginning of `infile`, or use option --no-echo. The `infile` can have end of line marked by LF or CRLF (but not just CR), and files with an incomplete last line (missing end of line (EOL) mark) are processed correctly. A final expression proc.time() will be executed after the input script unless the latter calls `[q](../../base/html/quit)(runLast = FALSE)` or is aborted. This can be suppressed by the option --no-timing. Additional options can be set by the environment variable R\_BATCH\_OPTIONS: these come after the default options (see the description of the `options` argument) and before any options given on the command line. ### Note On Unix-alikes only: Unlike `Splus BATCH`, this does not run the **R** process in the background. In most shells, ``` R CMD BATCH [options] infile [outfile] & ``` will do so. r None `available.packages` List Available Packages at CRAN-like Repositories ----------------------------------------------------------------------- ### Description `available.packages` returns a matrix of details corresponding to packages currently available at one or more repositories. The current list of packages is downloaded over the internet (or copied from a local mirror). ### Usage ``` available.packages(contriburl = contrib.url(repos, type), method, fields = NULL, type = getOption("pkgType"), filters = NULL, repos = getOption("repos"), ignore_repo_cache = FALSE, max_repo_cache_age, quiet = TRUE, ...) ``` ### Arguments | | | | --- | --- | | `contriburl` | URL(s) of the ‘contrib’ sections of the repositories. Specify this argument only if your repository mirror is incomplete, e.g., because you burned only the ‘contrib’ section on a CD. | | `method` | download method, see `<download.file>`. | | `type` | character string, indicate which type of packages: see `<install.packages>`. If `type = "both"` this will use the source repository. | | `fields` | a character vector giving the fields to extract from the ‘PACKAGES’ file(s) in addition to the default ones, or `NULL` (default). Unavailable fields result in `NA` values. | | `filters` | a character vector or list or `NULL` (default). See ‘Details’. | | `repos` | character vector, the base URL(s) of the repositories to use. | | `ignore_repo_cache` | logical. If true, the repository cache is never used (see ‘Details’). | | `max_repo_cache_age` | any cached values older than this in seconds will be ignored. See ‘Details’. | | `quiet` | logical, passed to `<download.file>()`; change only if you know what you are doing. | | `...` | allow additional arguments to be passed from callers (which might be arguments to future versions of this function). Currently these are all passed to `<download.file>()`. | ### Details The list of packages is either copied from a local mirror (specified by a file:// URI) or downloaded. If downloaded and `ignore_repo_cache` is false (the default), the list is cached for the **R** session in a per-repository file in `[tempdir](../../base/html/tempfile)()` with a name like ``` repos_http%3a%2f%2fcran.r-project.org%2fsrc%2fcontrib.rds ``` The cached values are renewed when found to be too old, with the age limit controlled *via* argument `max_repo_cache_age`. This defaults to the current value of the environment variable R\_AVAILABLE\_PACKAGES\_CACHE\_CONTROL\_MAX\_AGE, or if unset, to `3600` (one hour). By default, the return value includes only packages whose version and OS requirements are met by the running version of **R**, and only gives information on the latest versions of packages. Argument `filters` can be used to select which of the packages on the repositories are reported. It is called with its default value (`NULL`) by functions such as `install.packages`: this value corresponds to `[getOption](../../base/html/options)("available_packages_filters")` and to `c("R_version", "OS_type", "subarch", "duplicates")` if that is unset or set to `NULL`. The built-in filters are `"R_version"` Exclude packages whose **R** version requirements are not met. `"OS_type"` Exclude packages whose OS requirement is incompatible with this version of **R**: that is exclude Windows-only packages on a Unix-alike platform and *vice versa*. `"subarch"` For binary packages, exclude those with compiled code that is not available for the current sub-architecture, e.g. exclude packages only compiled for 32-bit Windows on a 64-bit Windows **R**. `"duplicates"` Only report the latest version where more than one version is available, and only report the first-named repository (in `contriburl`) with the latest version if that is in more than one repository. `"license/FOSS"` Include only packages for which installation can proceed solely based on packages which can be verified as Free or Open Source Software (FOSS, e.g., <https://en.wikipedia.org/wiki/FOSS>) employing the available license specifications. Thus both the package and any packages that it depends on to load need to be *known to be* FOSS. Note that this does depend on the repository supplying license information. `"license/restricts_use"` Include only packages for which installation can proceed solely based on packages which are known not to restrict use. `"CRAN"` Use CRAN versions in preference to versions from other repositories (even if these have a higher version number). This needs to be applied *before* the default `"duplicates"` filter, so cannot be used with `add = TRUE`. If all the filters are from this set, then they can be specified as a character vector; otherwise `filters` should be a list with elements which are character strings, user-defined functions or `add = TRUE` (see below). User-defined filters are functions which take a single argument, a matrix of the form returned by `available.packages`, and return a matrix consisting of a subset of the rows of the argument. The special ‘filter’ `add = TRUE` appends the other elements of the filter list to the default filters. ### Value A matrix with one row per package, row names the package names and column names including `"Package"`, `"Version"`, `"Priority"`, `"Depends"`, `"Imports"`, `"LinkingTo"`, `"Suggests"`, `"Enhances"`, `"File"` and `"Repository"`. Additional columns can be specified using the `fields` argument. Where provided by the repository, fields `"OS_type"`, `"License"`, `"License_is_FOSS"`, `"License_restricts_use"`, `"Archs"`, `"MD5sum"` and `"NeedsCompilation"` are reported for use by the filters and package management tools, including `<install.packages>`. ### See Also `<install.packages>`, `<download.packages>`, `<contrib.url>`. The ‘R Installation and Administration’ manual for how to set up a repository. ### Examples ``` ## Not run: ## Count package licenses db <- available.packages(filters = "duplicates") table(db[,"License"]) ## Use custom filter function to only keep recommended packages ## which do not require compilation available.packages(filters = list( add = TRUE, function (db) db[db[,"Priority"] %in% "recommended" & db[,"NeedsCompilation"] == "no", ] )) ## Restrict install.packages() (etc) to known-to-be-FOSS packages options(available_packages_filters = c("R_version", "OS_type", "subarch", "duplicates", "license/FOSS")) ## or options(available_packages_filters = list(add = TRUE, "license/FOSS")) ## Give priority to released versions on CRAN, rather than development ## versions on R-Forge etc. options(available_packages_filters = c("R_version", "OS_type", "subarch", "CRAN", "duplicates")) ## End(Not run) ``` r None `sourceutils` Source Reference Utilities ----------------------------------------- ### Description These functions extract information from source references. ### Usage ``` getSrcFilename(x, full.names = FALSE, unique = TRUE) getSrcDirectory(x, unique = TRUE) getSrcref(x) getSrcLocation(x, which = c("line", "column", "byte", "parse"), first = TRUE) ``` ### Arguments | | | | --- | --- | | `x` | An object (typically a function) containing source references. | | `full.names` | Whether to include the full path in the filename result. | | `unique` | Whether to list only unique filenames/directories. | | `which` | Which part of a source reference to extract. Can be abbreviated. | | `first` | Whether to show the first (or last) location of the object. | ### Details Each statement of a function will have its own source reference if the `"keep.source"` option is `TRUE`. These functions retrieve all of them. The components are as follows: line The line number where the object starts or ends. column The column number where the object starts or ends. byte As for `"column"`, but counting bytes, which may differ in case of multibyte characters. parse As for `"line"`, but this ignores `#line` directives. ### Value `getSrcFilename` and `getSrcDirectory` return character vectors holding the filename/directory. `getSrcref` returns a list of `"srcref"` objects or `NULL` if there are none. `getSrcLocation` returns an integer vector of the requested type of locations. ### See Also `[srcref](../../base/html/srcfile)`, `[getParseData](getparsedata)` ### Examples ``` fn <- function(x) { x + 1 # A comment, kept as part of the source } # Show the temporary file directory # where the example was saved getSrcDirectory(fn) getSrcLocation(fn, "line") ``` r None `menu` Menu Interaction Function --------------------------------- ### Description `menu` presents the user with a menu of choices labelled from 1 to the number of choices. To exit without choosing an item one can select 0. ### Usage ``` menu(choices, graphics = FALSE, title = NULL) ``` ### Arguments | | | | --- | --- | | `choices` | a character vector of choices | | `graphics` | a logical indicating whether a graphics menu should be used if available. | | `title` | a character string to be used as the title of the menu. `NULL` is also accepted. | ### Details If `graphics = TRUE` and a windowing system is available (Windows, macOS or X11 *via* Tcl/Tk) a listbox widget is used, otherwise a text menu. It is an error to use `menu` in a non-interactive session. Ten or fewer items will be displayed in a single column, more in multiple columns if possible within the current display width. No title is displayed if `title` is `NULL` or `""`. ### Value The number corresponding to the selected item, or 0 if no choice was made. ### References Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) *The New S Language*. Wadsworth & Brooks/Cole. ### See Also `<select.list>`, which is used to implement the graphical menu, and allows multiple selections. ### Examples ``` ## Not run: switch(menu(c("List letters", "List LETTERS")) + 1, cat("Nothing done\n"), letters, LETTERS) ## End(Not run) ``` r None `select.list` Select Items from a List --------------------------------------- ### Description Select item(s) from a character vector. ### Usage ``` select.list(choices, preselect = NULL, multiple = FALSE, title = NULL, graphics = getOption("menu.graphics")) ``` ### Arguments | | | | --- | --- | | `choices` | a character vector of items. | | `preselect` | a character vector, or `NULL`. If non-null and if the string(s) appear in the list, the item(s) are selected initially. | | `multiple` | logical: can more than one item be selected? | | `title` | optional character string for window title, or `NULL` for no title. | | `graphics` | logical: should a graphical widget be used? | ### Details The normal default is `graphics = TRUE`. On Windows, this brings up a modal dialog box with a (scrollable) list of items, which can be selected by the mouse. If `multiple` is true, further items can be selected or deselected by holding the control key down whilst selecting, and shift-clicking can be used to select ranges. Normal termination is via the ‘OK’ button or by hitting Enter or double-clicking an item. Selection can be aborted via the ‘Cancel’ button or pressing Escape. Under the macOS GUI, this brings up a modal dialog box with a (scrollable) list of items, which can be selected by the mouse. On other Unix-like platforms it will use a Tcl/Tk listbox widget if possible. If `graphics` is FALSE or no graphical widget is available it displays a text list from which the user can choose by number(s). The `multiple = FALSE` case uses `<menu>`. Preselection is only supported for `multiple = TRUE`, where it is indicated by a `"+"` preceding the item. It is an error to use `select.list` in a non-interactive session. ### Value A character vector of selected items. If `multiple` is false and no item was selected (or `Cancel` was used), `""` is returned. If `multiple` is true and no item was selected (or `Cancel` was used) then a character vector of length 0 is returned. ### See Also `<menu>`, `[tk\_select.list](../../tcltk/html/tk_select.list)` for a graphical version using Tcl/Tk. ### Examples ``` ## Not run: select.list(sort(.packages(all.available = TRUE))) ## End(Not run) ``` r None `str` Compactly Display the Structure of an Arbitrary R Object --------------------------------------------------------------- ### Description Compactly display the internal **str**ucture of an **R** object, a diagnostic function and an alternative to `[summary](../../base/html/summary)` (and to some extent, `[dput](../../base/html/dput)`). Ideally, only one line for each ‘basic’ structure is displayed. It is especially well suited to compactly display the (abbreviated) contents of (possibly nested) lists. The idea is to give reasonable output for **any** **R** object. It calls `[args](../../base/html/args)` for (non-primitive) function objects. `strOptions()` is a convenience function for setting `[options](../../base/html/options)(str = .)`, see the examples. ### Usage ``` str(object, ...) ## S3 method for class 'data.frame' str(object, ...) ## Default S3 method: str(object, max.level = NA, vec.len = strO$vec.len, digits.d = strO$digits.d, nchar.max = 128, give.attr = TRUE, drop.deparse.attr = strO$drop.deparse.attr, give.head = TRUE, give.length = give.head, width = getOption("width"), nest.lev = 0, indent.str = paste(rep.int(" ", max(0, nest.lev + 1)), collapse = ".."), comp.str = "$ ", no.list = FALSE, envir = baseenv(), strict.width = strO$strict.width, formatNum = strO$formatNum, list.len = strO$list.len, deparse.lines = strO$deparse.lines, ...) strOptions(strict.width = "no", digits.d = 3, vec.len = 4, list.len = 99, deparse.lines = NULL, drop.deparse.attr = TRUE, formatNum = function(x, ...) format(x, trim = TRUE, drop0trailing = TRUE, ...)) ``` ### Arguments | | | | --- | --- | | `object` | any **R** object about which you want to have some information. | | `max.level` | maximal level of nesting which is applied for displaying nested structures, e.g., a list containing sub lists. Default NA: Display all nesting levels. | | `vec.len` | numeric (>= 0) indicating how many ‘first few’ elements are displayed of each vector. The number is multiplied by different factors (from .5 to 3) depending on the kind of vector. Defaults to the `vec.len` component of option `"str"` (see `[options](../../base/html/options)`) which defaults to 4. | | `digits.d` | number of digits for numerical components (as for `[print](../../base/html/print)`). Defaults to the `digits.d` component of option `"str"` which defaults to 3. | | `nchar.max` | maximal number of characters to show for `[character](../../base/html/character)` strings. Longer strings are truncated, see `longch` example below. | | `give.attr` | logical; if `TRUE` (default), show attributes as sub structures. | | `drop.deparse.attr` | logical; if `TRUE` (default), `[deparse](../../base/html/deparse)(control = <S>)` will not have `"showAttributes"` in `<S>`. Used to be hard coded to `FALSE` and hence can be set via `strOptions()` for back compatibility. | | `give.length` | logical; if `TRUE` (default), indicate length (as `[1:...]`). | | `give.head` | logical; if `TRUE` (default), give (possibly abbreviated) mode/class and length (as `<type>[1:...]`). | | `width` | the page width to be used. The default is the currently active `[options](../../base/html/options)("width")`; note that this has only a weak effect, unless `strict.width` is not `"no"`. | | `nest.lev` | current nesting level in the recursive calls to `str`. | | `indent.str` | the indentation string to use. | | `comp.str` | string to be used for separating list components. | | `no.list` | logical; if true, no ‘list of ...’ nor the class are printed. | | `envir` | the environment to be used for *promise* (see `[delayedAssign](../../base/html/delayedassign)`) objects only. | | `strict.width` | string indicating if the `width` argument's specification should be followed strictly, one of the values `c("no", "cut", "wrap")`, which can be abbreviated. Defaults to the `strict.width` component of option `"str"` (see `[options](../../base/html/options)`) which defaults to `"no"` for back compatibility reasons; `"wrap"` uses `[strwrap](../../base/html/strwrap)(*, width = width)` whereas `"cut"` cuts directly to `width`. Note that a small `vec.length` may be better than setting `strict.width = "wrap"`. | | `formatNum` | a function such as `[format](../../base/html/format)` for formatting numeric vectors. It defaults to the `formatNum` component of option `"str"`, see “Usage” of `strOptions()` above, which is almost back compatible to **R** <= 2.7.x, however, using `[formatC](../../base/html/formatc)` may be slightly better. | | `list.len` | numeric; maximum number of list elements to display within a level. | | `deparse.lines` | numeric or `NULL` as by default, determining the `nlines` argument to `[deparse](../../base/html/deparse)()` when `object` is a `[call](../../base/html/call)`. When `NULL`, the `nchar.max` and `width` arguments are used to determine a smart default. | | `...` | potential further arguments (required for Method/Generic reasons). | ### Value `str` does not return anything, for efficiency reasons. The obvious side effect is output to the terminal. ### Note See the extensive annotated ‘Examples’ below. The default method tries to “work always”, but needs to make some assumptions for the case when `object` has a `[class](../../base/html/class)` but no own `str()` method which is *the typical* case: There it relies on `"[[](../../base/html/extract)"` and `"[[[](../../base/html/extract)"` subsetting methods to be compatible with `[length](../../base/html/length)()`. When this is not the case, or when `is.list(object)` is `TRUE`, but `length(object)` differs from `length([unclass](../../base/html/class)(object))` it treats it as “irregular” and reports the contents of `unclass(object)` as “hidden list”. ### Author(s) Martin Maechler [[email protected]](mailto:[email protected]) since 1990. ### See Also `[ls.str](ls_str)` for *listing* objects with their structure; `[summary](../../base/html/summary)`, `[args](../../base/html/args)`. ### Examples ``` require(stats); require(grDevices); require(graphics) ## The following examples show some of 'str' capabilities str(1:12) str(ls) str(args) #- more useful than args(args) ! str(freeny) str(str) str(.Machine, digits.d = 20) # extra digits for identification of binary numbers str( lsfit(1:9, 1:9)) str( lsfit(1:9, 1:9), max.level = 1) str( lsfit(1:9, 1:9), width = 60, strict.width = "cut") str( lsfit(1:9, 1:9), width = 60, strict.width = "wrap") op <- options(); str(op) # save first; # otherwise internal options() is used. need.dev <- !exists(".Device") || is.null(.Device) || .Device == "null device" { if(need.dev) postscript() str(par()) if(need.dev) graphics.off() } ch <- letters[1:12]; is.na(ch) <- 3:5 str(ch) # character NA's str(list(a = "A", L = as.list(1:100)), list.len = 9) ## ------------ ## " .. [list output truncated] " ## Long strings, 'nchar.max'; 'strict.width' : nchar(longch <- paste(rep(letters,100), collapse = "")) str(longch) str(longch, nchar.max = 52) str(longch, strict.width = "wrap") ## Multibyte characters in strings (in multibyte locales): oloc <- Sys.getlocale("LC_CTYPE") mbyte.lc <- if(.Platform$OS.type == "windows") "English_United States.28605" else "en_GB.UTF-8" try(Sys.setlocale("LC_CTYPE", mbyte.lc)) ## Truncation behavior (<-> correct width measurement) for "long" non-ASCII: idx <- c(65313:65338, 65345:65350) fwch <- intToUtf8(idx) # full width character string: each has width 2 ch <- strtrim(paste(LETTERS, collapse="._"), 64) (ncc <- c(c.ch = nchar(ch), w.ch = nchar(ch, "w"), c.fw = nchar(fwch), w.fw = nchar(fwch, "w"))) stopifnot(unname(ncc) == c(64,64, 32, 64)) ## nchar.max: 1st line needs an increase of 2 in order to see 1 (in UTF-8!): invisible(lapply(60:66, function(N) str(fwch, nchar.max = N))) invisible(lapply(60:66, function(N) str( ch , nchar.max = N))) # "1 is 1" here ## revert locale to previous: Sys.setlocale("LC_CTYPE", oloc) ## Settings for narrow transcript : op <- options(width = 60, str = strOptions(strict.width = "wrap")) str(lsfit(1:9,1:9)) str(options()) ## reset to previous: options(op) str(quote( { A+B; list(C, D) } )) ## S4 classes : require(stats4) x <- 0:10; y <- c(26, 17, 13, 12, 20, 5, 9, 8, 5, 4, 8) ll <- function(ymax = 15, xh = 6) -sum(dpois(y, lambda=ymax/(1+x/xh), log=TRUE)) fit <- mle(ll) str(fit) ```
programming_docs
r None `methods` List Methods for S3 Generic Functions or Classes ----------------------------------------------------------- ### Description List all available methods for a S3 and S4 generic function, or all methods for an S3 or S4 class. ### Usage ``` methods(generic.function, class) .S3methods(generic.function, class, envir=parent.frame()) ## S3 method for class 'MethodsFunction' format(x, byclass = attr(x, "byclass"), ...) ## S3 method for class 'MethodsFunction' print(x, byclass = attr(x, "byclass"), ...) ``` ### Arguments | | | | --- | --- | | `generic.function` | a generic function, or a character string naming a generic function. | | `class` | a symbol or character string naming a class: only used if `generic.function` is not supplied. | | `envir` | the environment in which to look for the definition of the generic function, when the generic function is passed as a character string. | | `x` | typically the result of `methods(..)`, an **R** object of S3 class `"MethodsFunction"`, see ‘Value’ below. | | `byclass` | an optional `[logical](../../base/html/logical)` allowing to override the `"byclass"` attribute determining how the result is printed, see ‘Details’. | | `...` | potentially further arguments passed to and from methods; unused currently. | ### Details `methods()` finds S3 and S4 methods associated with either the `generic.function` or `class` argument. Methods are found in all packages on the current `search()` path. `.S3methods()` finds only S3 methods, `.S4methods()` finds only only S4 methods. When invoked with the `generic.function` argument, the `"byclass"` attribute (see Details) is `FALSE`, and the `print` method by default displays the signatures (full names) of S3 and S4 methods. S3 methods are printed by pasting the generic function and class together, separated by a ‘.’, as `generic.class`. The S3 method name is followed by an asterisk `*` if the method definition is not exported from the package namespace in which the method is defined. S4 method signatures are printed as `generic,class-method`; S4 allows for multiple dispatch, so there may be several classes in the signature `generic,A,B-method`. When invoked with the `class` argument, `"byclass"` is `TRUE`, and the `print` method by default displays the names of the generic functions associated with the class, `generic`. The source code for all functions is available. For S3 functions exported from the namespace, enter the method at the command line as `generic.class`. For S3 functions not exported from the namespace, see `getAnywhere` or `getS3method`. For S4 methods, see `getMethod`. Help is available for each method, in addition to each generic. For interactive help, use the documentation shortcut `?` with the name of the generic and tab completion, `?"generic<tab>"` to select the method for which help is desired. The S3 functions listed are those which *are named like methods* and may not actually be methods (known exceptions are discarded in the code). ### Value An object of class `"MethodsFunction"`, a character vector of method names with `"byclass"` and `"info"` attributes. The `"byclass"` attribute is a `[logical](../../base/html/logical)` indicating if the results were obtained with argument `class` defined. The `"info"` attribute is a data frame with columns: generic `[character](../../base/html/character)` vector of the names of the generic. visible logical(), is the method exported from the namespace of the package in which it is defined? isS4 logical(), true when the method is an S4 method. from a `[factor](../../base/html/factor)`, the location or package name where the method was found. ### Note The original `methods` function was written by Martin Maechler. ### References Chambers, J. M. (1992) *Classes and methods: object-oriented programming in S.* Appendix A of *Statistical Models in S* eds J. M. Chambers and T. J. Hastie, Wadsworth & Brooks/Cole. ### See Also `[S3Methods](../../base/html/usemethod)`, `[class](../../base/html/class)`, `[getS3method](gets3method)`. For S4, `[getMethod](../../methods/html/getmethod)`, `[showMethods](../../methods/html/showmethods)`, [Introduction](../../methods/html/introduction) or `[Methods\_Details](../../methods/html/methods_details)`. ### Examples ``` methods(class = "MethodsFunction") # format and print require(stats) methods(summary) methods(class = "aov") # S3 class ## The same, with more details and more difficult to read: print(methods(class = "aov"), byclass=FALSE) methods("[[") # uses C-internal dispatching methods("$") methods("$<-") # replacement function methods("+") # binary operator methods("Math") # group generic require(graphics) methods(axis) # looks like a generic, but is not mf <- methods(format) # quite a few; ... the last few : tail(cbind(meth = format(mf))) if(require(Matrix)) { print(methods(class = "Matrix")) # S4 class m <- methods(dim) # S3 and S4 methods print(m) print(attr(m, "info")) # more extensive information ## --> help(showMethods) for related examples } ``` r None `clipboard` Read/Write to/from the Clipboard in MS Windows ----------------------------------------------------------- ### Description Transfer text between a character vector and the Windows clipboard in MS Windows (only). ### Usage ``` getClipboardFormats(numeric = FALSE) readClipboard(format = 1, raw = FALSE) writeClipboard(str, format = 1) ``` ### Arguments | | | | --- | --- | | `numeric` | logical: should the result be in human-readable form (the default) or raw numbers? | | `format` | an integer giving the desired format. | | `raw` | should the value be returned as a raw vector rather than as a character vector? | | `str` | a character vector or a raw vector. | ### Details The Windows clipboard offers data in a number of formats: see e.g. <https://docs.microsoft.com/en-gb/windows/desktop/dataxchg/clipboard-formats>. The standard formats include | | | | | --- | --- | --- | | CF\_TEXT | 1 | Text in the machine's locale | | CF\_BITMAP | 2 | | | CF\_METAFILEPICT | 3 | Metafile picture | | CF\_SYLK | 4 | Symbolic link | | CF\_DIF | 5 | Data Interchange Format | | CF\_TIFF | 6 | Tagged-Image File Format | | CF\_OEMTEXT | 7 | Text in the OEM codepage | | CF\_DIB | 8 | Device-Independent Bitmap | | CF\_PALETTE | 9 | | | CF\_PENDATA | 10 | | | CF\_RIFF | 11 | Audio data | | CF\_WAVE | 12 | Audio data | | CF\_UNICODETEXT | 13 | Text in Unicode (UCS-2) | | CF\_ENHMETAFILE | 14 | Enhanced metafile | | CF\_HDROP | 15 | Drag-and-drop data | | CF\_LOCALE | 16 | Locale for the text on the clipboard | | CF\_MAX | 17 | Shell-oriented formats | | | Applications normally make data available in one or more of these and possibly additional private formats. Use `raw = TRUE` to read binary formats, `raw = FALSE` (the default) for text formats. The current codepage is used to convert text to Unicode text, and information on that is contained in the `CF_LOCALE` format. (Take care if you are running R in a different locale from Windows.) The `writeClipboard` function will write a character vector as text or Unicode text with standard CR-LF line terminators. It will copy a raw vector directly to the clipboard without any changes. ### Value For `getClipboardFormats`, a character or integer vector of available formats, in numeric order. If non human-readable character representation is known, the number is returned. For `readClipboard`, a character vector by default, a raw vector if `raw` is `TRUE`, or `NULL`, if the format is unavailable. For `writeClipboard` an invisible logical indicating success or failure. ### Note This is only available on Windows. ### See Also `[file](../../base/html/connections)` which can be used to set up a connection to a clipboard. r None `apropos` Find Objects by (Partial) Name ----------------------------------------- ### Description `apropos()` returns a character vector giving the names of objects in the search list matching (as a regular expression) `what`. `find()` returns where objects of a given name can be found. ### Usage ``` apropos(what, where = FALSE, ignore.case = TRUE, mode = "any") find(what, mode = "any", numeric = FALSE, simple.words = TRUE) ``` ### Arguments | | | | --- | --- | | `what` | character string. For `simple.words = FALSE` the name of an object; otherwise a [regular expression](../../base/html/regex) to match object names against. | | `where, numeric` | a logical indicating whether positions in the search list should also be returned | | `ignore.case` | logical indicating if the search should be case-insensitive, `TRUE` by default. | | `mode` | character; if not `"any"`, only objects whose `[mode](../../base/html/mode)` equals `mode` are searched. | | `simple.words` | logical; if `TRUE`, the `what` argument is only searched as a whole word. | ### Details If `mode != "any"` only those objects which are of mode `mode` are considered. `find` is a different user interface for a similar task to `apropos`. By default (`simple.words == TRUE`), only whole names are matched. Unlike `apropos`, matching is always case-sensitive. Unlike the default behaviour of `[ls](../../base/html/ls)`, names which begin with a . are included (and these are often ‘internal’ objects — as from **R** 3.4.0 most such are excluded). ### Value For `apropos`, a character vector sorted by name. For `where = TRUE` this has names giving the (numerical) positions on the search path. For `find`, either a character vector of environment names or (for `numeric = TRUE`) a numerical vector of positions on the search path with names the names of the corresponding environments. ### Author(s) Originally, Kurt Hornik and Martin Maechler (May 1997). ### See Also `<glob2rx>` to convert wildcard patterns to regular expressions. `[objects](../../base/html/ls)` for listing objects from one place, `<help.search>` for searching the help system, `[search](../../base/html/search)` for the search path. ### Examples ``` require(stats) ## Not run: apropos("lm") apropos("GLM") # several apropos("GLM", ignore.case = FALSE) # not one apropos("lq") cor <- 1:pi find("cor") #> ".GlobalEnv" "package:stats" find("cor", numeric = TRUE) # numbers with these names find("cor", numeric = TRUE, mode = "function") # only the second one rm(cor) ## Not run: apropos(".", mode="list") # a long list # need a DOUBLE backslash '\\' (in case you don't see it anymore) apropos("\\[") # everything % not diff-able length(apropos(".")) # those starting with 'pr' apropos("^pr") # the 1-letter things apropos("^.$") # the 1-2-letter things apropos("^..?$") # the 2-to-4 letter things apropos("^.{2,4}$") # the 8-and-more letter things apropos("^.{8,}$") table(nchar(apropos("^.{8,}$"))) ``` r None `hasName` Check for Name ------------------------- ### Description `hasName` is a convenient way to test for one or more names in an R object. ### Usage ``` hasName(x, name) ``` ### Arguments | | | | --- | --- | | `x` | Any object. | | `name` | One or more character values to look for. | ### Details `hasName(x, name)` is defined to be equivalent to `name %in% names(x)`, though it will evaluate slightly more quickly. It is intended to replace the common idiom `!is.null(x$name)`. The latter can be unreliable due to partial name matching; see the example below. ### Value A logical vector of the same length as `name` containing `TRUE` if the corresponding entry is in `names(x)`. ### See Also `[%in%](../../base/html/match)`, `[exists](../../base/html/exists)` ### Examples ``` x <- list(abc = 1, def = 2) !is.null(x$abc) # correct !is.null(x$a) # this is the wrong test! hasName(x, "abc") hasName(x, "a") ``` r None `getWindowsHandles` Get handles of Windows in the MS Windows RGui ------------------------------------------------------------------ ### Description This function gets the Windows handles of visible top level windows or windows within the **R** MDI frame (when using the `Rgui`). ### Usage ``` getWindowsHandles(which = "R", pattern = "", minimized = FALSE) ``` ### Arguments | | | | --- | --- | | `which` | A vector of strings "R" or "all" (possibly with repetitions). See the Details section. | | `pattern` | A vector of patterns that the titles of the windows must match. | | `minimized` | A logical vector indicating whether minimized windows should be considered. | ### Details This function will search for Windows handles, for passing to external GUIs or to the `[arrangeWindows](arrangewindows)` function. Each of the arguments may be a vector of values. These will be treated as follows: * The arguments will all be recycled to the same length. * The corresponding elements of each argument will be applied in separate searches. * The final result will be the union of the windows identified in each of the searches. If an element of `which` is `"R"`, only windows belonging to the current **R** process will be returned. In MDI mode, those will be the child windows within the **R** GUI (`Rgui`) frame. In SDI mode, all windows belonging to the process will be included. If the element is `"all"`, then top level windows will be returned. The elements of `pattern` will be used to make a subset of windows whose title text matches (according to `[grep](../../base/html/grep)`) the pattern. If `minimized = FALSE`, minimized windows will be ignored. ### Value A list of external pointers containing the window handles. ### Note This is only available on Windows. ### Author(s) Duncan Murdoch ### See Also `[arrangeWindows](arrangewindows)`, `[getWindowsHandle](getwindowshandle)` (singular). ### Examples ``` if(.Platform$OS.type == "windows") withAutoprint({ getWindowsHandles() getWindowsHandles("all") }) ``` r None `getAnywhere` Retrieve an R Object, Including from a Namespace --------------------------------------------------------------- ### Description These functions locate all objects with name matching their argument, whether visible on the search path, registered as an S3 method or in a namespace but not exported. `getAnywhere()` returns the objects and `argsAnywhere()` returns the arguments of any objects that are functions. ### Usage ``` getAnywhere(x) argsAnywhere(x) ``` ### Arguments | | | | --- | --- | | `x` | a character string or name. | ### Details These functions look at all loaded namespaces, whether or not they are associated with a package on the search list. They do not search literally “anywhere”: for example, local evaluation frames and namespaces that are not loaded will not be searched. Where functions are found as registered S3 methods, an attempt is made to find which namespace registered them. This may not be correct, especially if namespaces have been unloaded. ### Value For `getAnywhere()` an object of class `"getAnywhere"`. This is a list with components | | | | --- | --- | | `name` | the name searched for | | `objs` | a list of objects found | | `where` | a character vector explaining where the object(s) were found | | `visible` | logical: is the object visible | | `dups` | logical: is the object identical to one earlier in the list. | In computing whether objects are identical, their environments are ignored. Normally the structure will be hidden by the `print` method. There is a `[` method to extract one or more of the objects found. For `argsAnywhere()` one or more argument lists as returned by `[args](../../base/html/args)`. ### See Also `[getS3method](gets3method)` to find the method which would be used: this might not be the one of those returned by `getAnywhere` since it might have come from a namespace which was unloaded or be registered under another name. `[get](../../base/html/get)`, `[getFromNamespace](getfromnamespace)`, `[args](../../base/html/args)` ### Examples ``` getAnywhere("format.dist") getAnywhere("simpleLoess") # not exported from stats argsAnywhere(format.dist) ``` r None `zip` Create Zip Archives -------------------------- ### Description A wrapper for an external `zip` command to create zip archives. ### Usage ``` zip(zipfile, files, flags = "-r9X", extras = "", zip = Sys.getenv("R_ZIPCMD", "zip")) ``` ### Arguments | | | | --- | --- | | `zipfile` | The pathname of the zip file: tilde expansion (see `[path.expand](../../base/html/path.expand)`) will be performed. | | `files` | A character vector of recorded filepaths to be included. | | `flags` | A character string of flags to be passed to the command: see ‘Details’. | | `extras` | An optional character vector: see ‘Details’. | | `zip` | A character string specifying the external command to be used. | ### Details On a Unix-alike, the default for `zip` will use the value of R\_ZIPCMD, whose default is set in ‘etc/Renviron’ to the `zip` command found during configuration. On Windows, the default relies on a `zip` program (for example that from Rtools) being in the path. The default for `flags` is that appropriate for zipping up a directory tree in a portable way: see the system-specific help for the `zip` command for other possibilities. Argument `extras` can be used to specify `-x` or `-i` followed by a list of filepaths to exclude or include. Since `extras` will be treated as if passed to `[system](../../base/html/system)`, if the filepaths contain spaces they must be quoted e.g. by `[shQuote](../../base/html/shquote)`. ### Value The status value returned by the external command, invisibly. ### See Also `<unzip>`, `[unz](../../base/html/connections)`; further, `<tar>` and `<untar>` for (un)packing tar archives. r None `vignette` View, List or Get R Source of Package Vignettes ----------------------------------------------------------- ### Description View a specified package vignette, or list the available ones; display it rendered in a viewer, and get or edit its **R** source file. ### Usage ``` vignette(topic, package = NULL, lib.loc = NULL, all = TRUE) ## S3 method for class 'vignette' print(x, ...) ## S3 method for class 'vignette' edit(name, ...) ``` ### Arguments | | | | --- | --- | | `topic` | a character string giving the (base) name of the vignette to view. If omitted, all vignettes from all installed packages are listed. | | `package` | a character vector with the names of packages to search through, or `NULL` in which ‘all’ packages (as defined by argument `all`) are searched. | | `lib.loc` | a character vector of directory names of **R** libraries, or `NULL`. The default value of `NULL` corresponds to all libraries currently known. | | `all` | logical; if `TRUE` search all available packages in the library trees specified by `lib.loc`, and if `FALSE`, search only attached packages. | | `x, name` | object of class `vignette`. | | `...` | ignored by the `print` method, passed on to `<file.edit>` by the `edit` method. | ### Details Function `vignette` returns an object of the same class, the print method opens a viewer for it. On Unix-alikes, The program specified by the `pdfviewer` option is used for viewing PDF versions of vignettes. If several vignettes have PDF/HTML versions with base name identical to `topic`, the first one found is used. If no topics are given, all available vignettes are listed. The corresponding information is returned in an object of class `"packageIQR"`. ### See Also `[browseVignettes](browsevignettes)` for an HTML-based vignette browser; `[RShowDoc](rshowdoc)(<basename>, package = "<pkg>")` displays a “rendered” vignette (pdf or html). ### Examples ``` ## List vignettes from all *attached* packages vignette(all = FALSE) ## List vignettes from all *installed* packages (can take a long time!): vignette(all = TRUE) ## The grid intro vignette -- open it ## Not run: vignette("grid") # calling print() ## The same (conditional on existence of the vignettte). ## Note that 'package = *' is much faster in the case of many installed packages: if(!is.null(v1 <- vignette("grid", package="grid"))) { ## Not run: v1 # calling print(.) str(v1) ## Now let us have a closer look at the code ## Not run: edit(v1) # e.g., to send lines ... }# if( has vignette "installed") ## A package can have more than one vignette (package grid has several): vignette(package = "grid") if(interactive()) { ## vignette("rotated") ## The same, but without searching for it: vignette("rotated", package = "grid") } ```
programming_docs
r None `aspell` Spell Check Interface ------------------------------- ### Description Spell check given files via Aspell, Hunspell or Ispell. ### Usage ``` aspell(files, filter, control = list(), encoding = "unknown", program = NULL, dictionaries = character()) ``` ### Arguments | | | | --- | --- | | `files` | a character vector with the names of files to be checked. | | `filter` | an optional filter for processing the files before spell checking, given as either a function (with formals `ifile` and `encoding`), or a character string specifying a built-in filter, or a list with the name of a built-in filter and additional arguments to be passed to it. See **Details** for available filters. If missing or `NULL`, no filtering is performed. | | `control` | a list or character vector of control options for the spell checker. | | `encoding` | the encoding of the files. Recycled as needed. | | `program` | a character string giving the name (if on the system path) or full path of the spell check program to be used, or `NULL` (default). By default, the system path is searched for `aspell`, `hunspell` and `ispell` (in that order), and the first one found is used. | | `dictionaries` | a character vector of names or file paths of additional R level dictionaries to use. Elements with no path separator specify R system dictionaries (in subdirectory ‘share/dictionaries’ of the R home directory). The file extension (currently, only ‘.rds’) can be omitted. | ### Details The spell check programs employed must support the so-called Ispell pipe interface activated via command line option -a. In addition to the programs, suitable dictionaries need to be available. See <http://aspell.net>, <https://hunspell.github.io/> and <https://www.cs.hmc.edu/~geoff/ispell.html>, respectively, for obtaining the Aspell, Hunspell and (International) Ispell programs and dictionaries. The currently available built-in filters are `"Rd"` (corresponding to `[RdTextFilter](../../tools/html/rdtextfilter)`), `"Sweave"` (corresponding to `[SweaveTeXFilter](../../tools/html/sweavetexfilter)`), `"R"`, `"pot"`, `"dcf"` and `"md"`. Filter `"R"` is for R code and extracts the message string constants in calls to `[message](../../base/html/message)`, `[warning](../../base/html/warning)`, `[stop](../../base/html/stop)`, `[packageStartupMessage](../../base/html/message)`, `[gettext](../../base/html/gettext)`, `[gettextf](../../base/html/sprintf)`, and `[ngettext](../../base/html/gettext)` (the unnamed string constants for the first five, and `fmt` and `msg1`/`msg2` string constants, respectively, for the latter two). Filter `"pot"` is for message string catalog ‘.pot’ files. Both have an argument `ignore` allowing to give regular expressions for parts of message strings to be ignored for spell checking: e.g., using `"[ \t]'[^']*'[ \t[:punct:]]"` ignores all text inside single quotes. Filter `"dcf"` is for files in Debian Control File format. The fields to keep can be controlled by argument `keep` (a character vector with the respective field names). By default, Title and Description fields are kept. Filter `"md"` is for files in [Markdown](https://en.wikipedia.org/wiki/Markdown) format (‘.md’ and ‘.Rmd’ files), and needs packages [commonmark](https://CRAN.R-project.org/package=commonmark) and [xml2](https://CRAN.R-project.org/package=xml2) to be available. The print method for the objects returned by `aspell` has an `indent` argument controlling the indentation of the positions of possibly mis-spelled words. The default is 2; Emacs users may find it useful to use an indentation of 0 and visit output in grep-mode. It also has a `verbose` argument: when this is true, suggestions for replacements are shown as well. It is possible to employ additional R level dictionaries. Currently, these are files with extension ‘.rds’ obtained by serializing character vectors of word lists using `[saveRDS](../../base/html/readrds)`. If such dictionaries are employed, they are combined into a single word list file which is then used as the spell checker's personal dictionary (option -p): hence, the default personal dictionary is not used in this case. ### Value A data frame inheriting from `aspell` (which has a useful print method) with the information about possibly mis-spelled words. ### References Kurt Hornik and Duncan Murdoch (2011). “Watch your spelling!” *The R Journal*, **3**(2), 22–28. doi: [10.32614/RJ-2011-014](https://doi.org/10.32614/RJ-2011-014). ### See Also <aspell-utils> for utilities for spell checking packages. ### Examples ``` ## Not run: ## To check all Rd files in a directory, (additionally) skipping the ## \references sections. files <- Sys.glob("*.Rd") aspell(files, filter = list("Rd", drop = "\\references")) ## To check all Sweave files files <- Sys.glob(c("*.Rnw", "*.Snw", "*.rnw", "*.snw")) aspell(files, filter = "Sweave", control = "-t") ## To check all Texinfo files (Aspell only) files <- Sys.glob("*.texi") aspell(files, control = "--mode=texinfo") ## End(Not run) ## List the available R system dictionaries. Sys.glob(file.path(R.home("share"), "dictionaries", "*.rds")) ``` r None `browseURL` Load URL into an HTML Browser ------------------------------------------ ### Description Load a given URL into an HTML browser. ### Usage ``` browseURL(url, browser = getOption("browser"), encodeIfNeeded = FALSE) ``` ### Arguments | | | | --- | --- | | `url` | a non-empty character string giving the URL to be loaded. Some platforms also accept file paths. | | `browser` | a non-empty character string giving the name of the program to be used as the HTML browser. It should be in the PATH, or a full path specified. Alternatively, an **R** function to be called to invoke the browser. Under Windows `NULL` is also allowed (and is the default), and implies that the file association mechanism will be used. | | `encodeIfNeeded` | Should the URL be encoded by `[URLencode](urlencode)` before passing to the browser? This is not needed (and might be harmful) if the `browser` program/function itself does encoding, and can be harmful for file:// URLs on some systems and for http:// URLs passed to some CGI applications. Fortunately, most URLs do not need encoding. | ### Details On Unix-alikes: The default browser is set by option `"browser"`, in turn set by the environment variable R\_BROWSER which is by default set in file ‘[R\_HOME](../../base/html/rhome)/etc/Renviron’ to a choice made manually or automatically when **R** was configured. (See `[Startup](../../base/html/startup)` for where to override that default value.) To suppress showing URLs altogether, use the value `"false"`. On many platforms it is best to set option `"browser"` to a generic program/script and let that invoke the user's choice of browser. For example, on macOS use `open` and on many other Unix-alikes use `xdg-open`. If `browser` supports remote control and **R** knows how to perform it, the URL is opened in any already-running browser or a new one if necessary. This mechanism currently is available for browsers which support the `"-remote openURL(...)"` interface (which includes Mozilla and Opera), Galeon, KDE konqueror (*via* kfmclient) and the GNOME interface to Mozilla. (Firefox has dropped support, but defaults to using an already-running browser.) Note that the type of browser is determined from its name, so this mechanism will only be used if the browser is installed under its canonical name. Because `"-remote"` will use any browser displaying on the X server (whatever machine it is running on), the remote control mechanism is only used if `DISPLAY` points to the local host. This may not allow displaying more than one URL at a time from a remote host. It is the caller's responsibility to encode `url` if necessary (see `[URLencode](urlencode)`). To suppress showing URLs altogether, set `browser = "false"`. The behaviour for arguments `url` which are not URLs is platform-dependent. Some platforms accept absolute file paths; fewer accept relative file paths. On Windows: The default browser is set by option `"browser"`, in turn set by the environment variable R\_BROWSER if that is set, otherwise to `NULL`. To suppress showing URLs altogether, use the value `"false"`. Some browsers have required `:` be replaced by `|` in file paths: others do not accept that. All seem to accept `\` as a path separator even though the RFC1738 standard requires `/`. To suppress showing URLs altogether, set `browser = "false"`. ### URL schemes Which URL schemes are accepted is platform-specific: expect http://, https:// and ftp:// to work, but mailto: may or may not (and if it does may not use the user's preferred email client). For the file:// scheme the format accepted (if any) can depend on both browser and OS. ### Examples ``` ## Not run: ## for KDE users who want to open files in a new tab options(browser = "kfmclient newTab") browseURL("https://www.r-project.org") ## On Windows-only, something like browseURL("file://d:/R/R-2.5.1/doc/html/index.html", browser = "C:/Program Files/Mozilla Firefox/firefox.exe") ## End(Not run) ``` r None `data` Data Sets ----------------- ### Description Loads specified data sets, or list the available data sets. ### Usage ``` data(..., list = character(), package = NULL, lib.loc = NULL, verbose = getOption("verbose"), envir = .GlobalEnv, overwrite = TRUE) ``` ### Arguments | | | | --- | --- | | `...` | literal character strings or names. | | `list` | a character vector. | | `package` | a character vector giving the package(s) to look in for data sets, or `NULL`. By default, all packages in the search path are used, then the ‘data’ subdirectory (if present) of the current working directory. | | `lib.loc` | a character vector of directory names of **R** libraries, or `NULL`. The default value of `NULL` corresponds to all libraries currently known. | | `verbose` | a logical. If `TRUE`, additional diagnostics are printed. | | `envir` | the [environment](../../base/html/environment) where the data should be loaded. | | `overwrite` | logical: should existing objects of the same name in envir be replaced? | ### Details Currently, four formats of data files are supported: 1. files ending ‘.R’ or ‘.r’ are `[source](../../base/html/source)()`d in, with the **R** working directory changed temporarily to the directory containing the respective file. (`data` ensures that the utils package is attached, in case it had been run *via* `utils::data`.) 2. files ending ‘.RData’ or ‘.rda’ are `[load](../../base/html/load)()`ed. 3. files ending ‘.tab’, ‘.txt’ or ‘.TXT’ are read using `<read.table>(..., header = TRUE, as.is=FALSE)`, and hence result in a data frame. 4. files ending ‘.csv’ or ‘.CSV’ are read using `<read.table>(..., header = TRUE, sep = ";", as.is=FALSE)`, and also result in a data frame. If more than one matching file name is found, the first on this list is used. (Files with extensions ‘.txt’, ‘.tab’ or ‘.csv’ can be compressed, with or without further extension ‘.gz’, ‘.bz2’ or ‘.xz’.) The data sets to be loaded can be specified as a set of character strings or names, or as the character vector `list`, or as both. For each given data set, the first two types (‘.R’ or ‘.r’, and ‘.RData’ or ‘.rda’ files) can create several variables in the load environment, which might all be named differently from the data set. The third and fourth types will always result in the creation of a single variable with the same name (without extension) as the data set. If no data sets are specified, `data` lists the available data sets. It looks for a new-style data index in the ‘Meta’ or, if this is not found, an old-style ‘00Index’ file in the ‘data’ directory of each specified package, and uses these files to prepare a listing. If there is a ‘data’ area but no index, available data files for loading are computed and included in the listing, and a warning is given: such packages are incomplete. The information about available data sets is returned in an object of class `"packageIQR"`. The structure of this class is experimental. Where the datasets have a different name from the argument that should be used to retrieve them the index will have an entry like `beaver1 (beavers)` which tells us that dataset `beaver1` can be retrieved by the call `data(beaver)`. If `lib.loc` and `package` are both `NULL` (the default), the data sets are searched for in all the currently loaded packages then in the ‘data’ directory (if any) of the current working directory. If `lib.loc = NULL` but `package` is specified as a character vector, the specified package(s) are searched for first amongst loaded packages and then in the default library/ies (see `[.libPaths](../../base/html/libpaths)`). If `lib.loc` *is* specified (and not `NULL`), packages are searched for in the specified library/ies, even if they are already loaded from another library. To just look in the ‘data’ directory of the current working directory, set `package = character(0)` (and `lib.loc = NULL`, the default). ### Value A character vector of all data sets specified (whether found or not), or information about all available data sets in an object of class `"packageIQR"` if none were specified. ### Good practice There is no requirement for `data(foo)` to create an object named `foo` (nor to create one object), although it much reduces confusion if this convention is followed (and it is enforced if datasets are lazy-loaded). `data()` was originally intended to allow users to load datasets from packages for use in their examples, and as such it loaded the datasets into the workspace `[.GlobalEnv](../../base/html/environment)`. This avoided having large datasets in memory when not in use: that need has been almost entirely superseded by lazy-loading of datasets. The ability to specify a dataset by name (without quotes) is a convenience: in programming the datasets should be specified by character strings (with quotes). Use of `data` within a function without an `envir` argument has the almost always undesirable side-effect of putting an object in the user's workspace (and indeed, of replacing any object of that name already there). It would almost always be better to put the object in the current evaluation environment by `data(..., envir = environment())`. However, two alternatives are usually preferable, both described in the ‘Writing R Extensions’ manual. * For sets of data, set up a package to use lazy-loading of data. * For objects which are system data, for example lookup tables used in calculations within the function, use a file ‘R/sysdata.rda’ in the package sources or create the objects by **R** code at package installation time. A sometimes important distinction is that the second approach places objects in the namespace but the first does not. So if it is important that the function sees `mytable` as an object from the package, it is system data and the second approach should be used. In the unusual case that a package uses a lazy-loaded dataset as a default argument to a function, that needs to be specified by `[::](../../base/html/ns-dblcolon)`, e.g., `survival::survexp.us`. ### Warning This function creates objects in the `envir` environment (by default the user's workspace) replacing any which already existed. `data("foo")` can silently create objects other than `foo`: there have been instances in published packages where it created/replaced `[.Random.seed](../../base/html/random)` and hence change the seed for the session. ### Note One can take advantage of the search order and the fact that a ‘.R’ file will change directory. If raw data are stored in ‘mydata.txt’ then one can set up ‘mydata.R’ to read ‘mydata.txt’ and pre-process it, e.g., using `[transform](../../base/html/transform)()`. For instance one can convert numeric vectors to factors with the appropriate labels. Thus, the ‘.R’ file can effectively contain a metadata specification for the plaintext formats. In older versions of **R**, up to 3.6.x, both `package = "base"` and `package = "stats"` were using `package = "datasets"`, (with a warning), as before 2004, (most of) the datasets in datasets were either in base or stats. For these packages, the result is now empty as they contain no data sets. ### See Also `<help>` for obtaining documentation on data sets, `[save](../../base/html/save)` for *creating* the second (‘.rda’) kind of data, typically the most efficient one. The ‘Writing R Extensions’ for considerations in preparing the ‘data’ directory of a package. ### Examples ``` require(utils) data() # list all available data sets try(data(package = "rpart") ) # list the data sets in the rpart package data(USArrests, "VADeaths") # load the data sets 'USArrests' and 'VADeaths' ## Not run: ## Alternatively ds <- c("USArrests", "VADeaths"); data(list = ds) ## End(Not run) help(USArrests) # give information on data set 'USArrests' ``` r None `browseVignettes` List Vignettes in an HTML Browser ---------------------------------------------------- ### Description List available vignettes in an HTML browser with links to PDF, LaTeX/noweb source, and (tangled) R code (if available). ### Usage ``` browseVignettes(package = NULL, lib.loc = NULL, all = TRUE) ## S3 method for class 'browseVignettes' print(x, ...) ``` ### Arguments | | | | --- | --- | | `package` | a character vector with the names of packages to search through, or `NULL` in which "all" packages (as defined by argument `all`) are searched. | | `lib.loc` | a character vector of directory names of **R** libraries, or `NULL`. The default value of `NULL` corresponds to all libraries currently known. | | `all` | logical; if `TRUE` search all available packages in the library trees specified by `lib.loc`, and if `FALSE`, search only attached packages. | | `x` | Object of class `browseVignettes`. | | `...` | Further arguments, ignored by the `print` method. | ### Details Function `browseVignettes` returns an object of the same class; the print method displays it as an HTML page in a browser (using `[browseURL](browseurl)`). ### See Also `[browseURL](browseurl)`, `<vignette>` ### Examples ``` ## List vignettes from all *attached* packages browseVignettes(all = FALSE) ## List vignettes from a specific package browseVignettes("grid") ``` r None `combn` Generate All Combinations of n Elements, Taken m at a Time ------------------------------------------------------------------- ### Description Generate all combinations of the elements of `x` taken `m` at a time. If `x` is a positive integer, returns all combinations of the elements of `seq(x)` taken `m` at a time. If argument `FUN` is not `NULL`, applies a function given by the argument to each point. If simplify is FALSE, returns a list; otherwise returns an `[array](../../base/html/array)`, typically a `[matrix](../../base/html/matrix)`. `...` are passed unchanged to the `FUN` function, if specified. ### Usage ``` combn(x, m, FUN = NULL, simplify = TRUE, ...) ``` ### Arguments | | | | --- | --- | | `x` | vector source for combinations, or integer `n` for `x <- [seq\_len](../../base/html/seq)(n)`. | | `m` | number of elements to choose. | | `FUN` | function to be applied to each combination; default `NULL` means the identity, i.e., to return the combination (vector of length `m`). | | `simplify` | logical indicating if the result should be simplified to an `[array](../../base/html/array)` (typically a `[matrix](../../base/html/matrix)`); if FALSE, the function returns a `[list](../../base/html/list)`. Note that when `simplify = TRUE` as by default, the dimension of the result is simply determined from `FUN(1st combination)` (for efficiency reasons). This will badly fail if `FUN(u)` is not of constant length. | | `...` | optionally, further arguments to `FUN`. | ### Details Factors `x` are accepted. ### Value A `[list](../../base/html/list)` or `[array](../../base/html/array)`, see the `simplify` argument above. In the latter case, the identity `dim(combn(n, m)) == c(m, choose(n, m))` holds. ### Author(s) Scott Chasalow wrote the original in 1994 for S; R package [combinat](https://CRAN.R-project.org/package=combinat) and documentation by Vince Carey [[email protected]](mailto:[email protected]); small changes by the R core team, notably to return an array in all cases of `simplify = TRUE`, e.g., for `combn(5,5)`. ### References Nijenhuis, A. and Wilf, H.S. (1978) *Combinatorial Algorithms for Computers and Calculators*; Academic Press, NY. ### See Also `[choose](../../base/html/special)` for fast computation of the *number* of combinations. `[expand.grid](../../base/html/expand.grid)` for creating a data frame from all combinations of factors or vectors. ### Examples ``` combn(letters[1:4], 2) (m <- combn(10, 5, min)) # minimum value in each combination mm <- combn(15, 6, function(x) matrix(x, 2, 3)) stopifnot(round(choose(10, 5)) == length(m), is.array(m), # 1-dimensional c(2,3, round(choose(15, 6))) == dim(mm)) ## Different way of encoding points: combn(c(1,1,1,1,2,2,2,3,3,4), 3, tabulate, nbins = 4) ## Compute support points and (scaled) probabilities for a ## Multivariate-Hypergeometric(n = 3, N = c(4,3,2,1)) p.f.: # table.mat(t(combn(c(1,1,1,1,2,2,2,3,3,4), 3, tabulate, nbins = 4))) ## Assuring the identity for(n in 1:7) for(m in 0:n) stopifnot(is.array(cc <- combn(n, m)), dim(cc) == c(m, choose(n, m)), identical(cc, combn(n, m, identity)) || m == 1) ```
programming_docs
r None `glob2rx` Change Wildcard or Globbing Pattern into Regular Expression ---------------------------------------------------------------------- ### Description Change *wildcard* aka *globbing* patterns into the corresponding regular expressions (`[regexp](../../base/html/regex)`). ### Usage ``` glob2rx(pattern, trim.head = FALSE, trim.tail = TRUE) ``` ### Arguments | | | | --- | --- | | `pattern` | character vector | | `trim.head` | logical specifying if leading `"^.*"` should be trimmed from the result. | | `trim.tail` | logical specifying if trailing `".*$"` should be trimmed from the result. | ### Details This takes a wildcard as used by most shells and returns an equivalent regular expression. `?` is mapped to `.` (match a single character), `*` to `.*` (match any string, including an empty one), and the pattern is anchored (it must start at the beginning and end at the end). Optionally, the resulting regexp is simplified. Note that now even `(`, `[` and `{` can be used in `pattern`, but `glob2rx()` may not work correctly with arbitrary characters in `pattern`. ### Value A character vector of the same length as the input `pattern` where each wildcard is translated to the corresponding regular expression. ### Author(s) Martin Maechler, Unix/sed based version, 1991; current: 2004 ### See Also `[regexp](../../base/html/regex)` about regular expression, `[sub](../../base/html/grep)`, etc about substitutions using regexps. ### Examples ``` stopifnot(glob2rx("abc.*") == "^abc\\.", glob2rx("a?b.*") == "^a.b\\.", glob2rx("a?b.*", trim.tail = FALSE) == "^a.b\\..*$", glob2rx("*.doc") == "^.*\\.doc$", glob2rx("*.doc", trim.head = TRUE) == "\\.doc$", glob2rx("*.t*") == "^.*\\.t", glob2rx("*.t??") == "^.*\\.t..$", glob2rx("*[*") == "^.*\\[" ) ``` r None `isS3stdGen` Check if a Function Acts as an S3 Generic ------------------------------------------------------- ### Description Determines whether `f` acts as a standard S3-style generic function. ### Usage ``` isS3stdGeneric(f) ``` ### Arguments | | | | --- | --- | | `f` | a function object | ### Details A closure is considered a standard S3 generic if the first expression in its body calls `[UseMethod](../../base/html/usemethod)`. Functions which perform operations before calling `UseMethod` will not be considered “standard” S3 generics. If `f` is currently being traced, i.e., inheriting from class `"traceable"`, the definition of the original untraced version of the function is used instead. ### Value If `f` is an S3 generic, a logical containing `TRUE` with the name of the S3 generic (the string passed to `UseMethod`). Otherwise, `FALSE` (unnamed). r None `isS3method` Is 'method' the Name of an S3 Method? --------------------------------------------------- ### Description Checks if `method` is the name of a valid / registered S3 method. Alternatively, when `f` and `class` are specified, it is checked if `f` is the name of an S3 generic function and `paste(f, class, sep=".")` is a valid S3 method. ### Usage ``` isS3method(method, f, class, envir = parent.frame()) ``` ### Arguments | | | | --- | --- | | `method` | a character string, typically of the form `"<fn>.<class>"`. If omitted, `f` and `class` have to be specified instead. | | `f` | optional character string, typically specifying an S3 generic function. Used, when `method` is not specified. | | `class` | optional character string, typically specifying an S3 class name. Used, when `method` is not specified. | | `envir` | the `[environment](../../base/html/environment)` in which the method and its generic are searched first, as in `[getS3method](gets3method)()`. | ### Value `[logical](../../base/html/logical)` `TRUE` or `FALSE` ### See Also `<methods>`, `[getS3method](gets3method)`. ### Examples ``` isS3method("t") # FALSE - it is an S3 generic isS3method("t.default") # TRUE isS3method("t.ts") # TRUE isS3method("t.test") # FALSE isS3method("t.data.frame")# TRUE isS3method("t.lm") # FALSE - not existing isS3method("t.foo.bar") # FALSE - not existing ## S3 methods with "4 parts" in their name: ff <- c("as.list", "as.matrix", "is.na", "row.names", "row.names<-") for(m in ff) if(isS3method(m)) stop("wrongly declared an S3 method: ", m) (m4 <- paste(ff, "data.frame", sep=".")) for(m in m4) if(!isS3method(m)) stop("not an S3 method: ", m) ``` r None `news` Build and Query R or Package News Information ----------------------------------------------------- ### Description Build and query the news data base for **R** or add-on packages. ### Usage ``` news(query, package = "R", lib.loc = NULL, format = NULL, reader = NULL, db = NULL) ## S3 method for class 'news_db' print(x, doBrowse = interactive(), browser = getOption("browser"), ...) ``` ### Arguments | | | | --- | --- | | `query` | an expression for selecting news entries | | `package` | a character string giving the name of an installed add-on package, or `"R"` or `"R-3"` or `"R-2"` | . | | | | --- | --- | | `lib.loc` | a character vector of directory names of R libraries, or `NULL`. The default value of `NULL` corresponds to all libraries currently known. | | `format` | Not yet used. | | `reader` | Not yet used. | | `db, x` | a news db obtained from `news()`. | | `doBrowse` | logical specifying that the news should be opened in the browser (by `[browseURL](browseurl)`, accessible as via `<help.start>`) instead of printed to the console. | | `browser` | the browser to be used, see `[browseURL](browseurl)`. | | `...` | potentially further arguments passed to `print()`. | ### Details If `package` is `"R"` (default), a news db is built with the news since the 4.0.0 release of **R** (corresponding to **R**'s top-level ‘NEWS’ file). For `"R-3"` or `"R-2"`. news for **R** 3.x.y or **R** 2.x.y respectively. Otherwise, if the given add-on package can be found in the given libraries, it is attempted to read its news in structured form from files ‘inst/NEWS.Rd’, ‘NEWS.md’ (since **R** version 3.6.0, needs packages [commonmark](https://CRAN.R-project.org/package=commonmark) and [xml2](https://CRAN.R-project.org/package=xml2) to be available), ‘NEWS’ or ‘inst/NEWS’ (in that order). File ‘inst/NEWS.Rd’ should be an Rd file given the entries as Rd `\itemize` lists, grouped according to version using `section` elements with names starting with a suitable prefix (e.g. “Changes in version”) followed by a space and the version number, and optionally followed by a space and a parenthesized ISO 8601 (%Y-%m-%d, see `[strptime](../../base/html/strptime)`) format date, and possibly further grouped according to categories using `\subsection` elements named as the categories. At the very end of `\section{..}`, the date may also be specified as `(%Y-%m-%d, <note>)`, i.e., including parentheses. File ‘NEWS.md’ should contain the news in Markdown (following the CommonMark (<https://commonmark.org/>) specification), with the primary heading level giving the version number after a prefix followed by a space, and optionally followed by a space and a parenthesized ISO 8601 format date. Where available, secondary heading are taken to indicate categories. To accommodate for common practice, news entries are only split down to the category level. The plain text ‘NEWS’ files in add-on packages use a variety of different formats; the default news reader should be capable to extract individual news entries from a majority of packages from the standard repositories, which use (slight variations of) the following format: * Entries are grouped according to version, with version header “Changes in version” at the beginning of a line, followed by a version number, optionally followed by an ISO 8601 format date, possibly parenthesized. * Entries may be grouped according to category, with a category header (different from a version header) starting at the beginning of a line. * Entries are written as itemize-type lists, using one of o, \*, - or + as item tag. Entries must be indented, and ideally use a common indentation for the item texts. Additional formats and readers may be supported in the future. Package tools provides an (internal) utility function `news2Rd` to convert plain text ‘NEWS’ files to Rd. For ‘NEWS’ files in a format which can successfully be handled by the default reader, package maintainers can use `tools:::news2Rd(dir, "NEWS.Rd")`, possibly with additional argument `codify = TRUE`, with `dir` a character string specifying the path to a package's root directory. Upon success, the ‘NEWS.Rd’ file can further be improved and then be moved to the ‘inst’ subdirectory of the package source directory. The news db built is a character data frame inheriting from `"news_db"` with variables `Version`, `Category`, `Date` and `Text`, where the last contains the entry texts read, and the other variables may be `NA` if they were missing or could not be determined. Using `query`, one can select news entries from the db. If missing or `NULL`, the complete db is returned. Otherwise, `query` should be an expression involving (a subset of) the variables `Version`, `Category`, `Date` and `Text`, and when evaluated within the db returning a logical vector with length the number of entries in the db. The entries for which evaluation gave `TRUE` are selected. When evaluating, `Version` and `Date` are coerced to `[numeric\_version](../../base/html/numeric_version)` and `[Date](../../base/html/dates)` objects, respectively, so that the comparison operators for these classes can be employed. ### Value A data frame inheriting from class `"news_db"`, with `[attributes](../../base/html/attributes)` `"package"` (and `"subset"` if the `query` lead to proper subsetting). ### Examples ``` ## Build a db of all R news entries. db <- news() ## Bug fixes with PR number in 4.0.0. db4 <- news(Version == "4.0.0" & grepl("^BUG", Category) & grepl("PR#", Text), db = db) nrow(db4) ## print db4 to show in an HTML browser. ## News from a date range ('Matrix' is there in a regular R installation): if(length(iM <- find.package("Matrix", quiet = TRUE)) && nzchar(iM)) { dM <- news(package="Matrix") stopifnot(identical(dM, news(db=dM))) dM2014 <- news("2014-01-01" <= Date & Date <= "2014-12-31", db = dM) stopifnot(paste0("1.1-", 2:4) %in% dM2014[,"Version"]) } ## Which categories have been in use? % R-core maybe should standardize a bit more sort(table(db[, "Category"]), decreasing = TRUE) ## Entries with version >= 4.0.0 table(news(Version >= "4.0.0", db = db)$Version) ## do the same for R 3.x.y, more slowly db3 <- news(package = "R-3") sort(table(db3[, "Category"]), decreasing = TRUE) ## Entries with version >= 3.6.0 table(news(Version >= "3.6.0", db = db3)$Version) ``` r None `url.show` Display a Text URL ------------------------------ ### Description Extension of `[file.show](../../base/html/file.show)` to display text files from a remote server. ### Usage ``` url.show(url, title = url, file = tempfile(), delete.file = TRUE, method, ...) ``` ### Arguments | | | | --- | --- | | `url` | The URL to read from. | | `title` | Title for the browser. | | `file` | File to copy to. | | `delete.file` | Delete the file afterwards? | | `method` | File transfer method: see `<download.file>` | | `...` | Arguments to pass to `[file.show](../../base/html/file.show)`. | ### Note Since this is for text files, it will convert to CRLF line endings on Windows. ### See Also `[url](../../base/html/connections)`, `[file.show](../../base/html/file.show)`, `<download.file>` ### Examples ``` ## Not run: url.show("https://www.stats.ox.ac.uk/pub/datasets/csb/ch3a.txt") ``` r None `URLencode` Encode or Decode (partial) URLs -------------------------------------------- ### Description Functions to percent-encode or decode characters in URLs. ### Usage ``` URLencode(URL, reserved = FALSE, repeated = FALSE) URLdecode(URL) ``` ### Arguments | | | | --- | --- | | `URL` | a character vector. | | `reserved` | logical: should ‘reserved’ characters be encoded? See ‘Details’. | | `repeated` | logical: should apparently already-encoded URLs be encoded again? | ### Details Characters in a URL other than the English alphanumeric characters and - \_ . ~ should be encoded as `%` plus a two-digit hexadecimal representation, and any single-byte character can be so encoded. (Multi-byte characters are encoded byte-by-byte.) The standard refers to this as ‘percent-encoding’. In addition, ! $ & ' ( ) \* + , ; = : / ? @ # [ ] are reserved characters, and should be encoded unless used in their reserved sense, which is scheme specific. The default in `URLencode` is to leave them alone, which is appropriate for file:// URLs, but probably not for http:// ones. An ‘apparently already-encoded URL’ is one containing `%xx` for two hexadecimal digits. ### Value A character vector. ### References Internet STD 66 (formerly RFC 3986), <https://tools.ietf.org/html/std66> ### Examples ``` (y <- URLencode("a url with spaces and / and @")) URLdecode(y) (y <- URLencode("a url with spaces and / and @", reserved = TRUE)) URLdecode(y) URLdecode(z <- "ab%20cd") c(URLencode(z), URLencode(z, repeated = TRUE)) # first is usually wanted ## both functions support character vectors of length > 1 y <- URLdecode(URLencode(c("url with space", "another one"))) ``` r None `write.table` Data Output -------------------------- ### Description `write.table` prints its required argument `x` (after converting it to a data frame if it is not one nor a matrix) to a file or [connection](../../base/html/connections). ### Usage ``` write.table(x, file = "", append = FALSE, quote = TRUE, sep = " ", eol = "\n", na = "NA", dec = ".", row.names = TRUE, col.names = TRUE, qmethod = c("escape", "double"), fileEncoding = "") write.csv(...) write.csv2(...) ``` ### Arguments | | | | --- | --- | | `x` | the object to be written, preferably a matrix or data frame. If not, it is attempted to coerce `x` to a data frame. | | `file` | either a character string naming a file or a [connection](../../base/html/connections) open for writing. `""` indicates output to the console. | | `append` | logical. Only relevant if `file` is a character string. If `TRUE`, the output is appended to the file. If `FALSE`, any existing file of the name is destroyed. | | `quote` | a logical value (`TRUE` or `FALSE`) or a numeric vector. If `TRUE`, any character or factor columns will be surrounded by double quotes. If a numeric vector, its elements are taken as the indices of columns to quote. In both cases, row and column names are quoted if they are written. If `FALSE`, nothing is quoted. | | `sep` | the field separator string. Values within each row of `x` are separated by this string. | | `eol` | the character(s) to print at the end of each line (row). For example, `eol = "\r\n"` will produce Windows' line endings on a Unix-alike OS, and `eol = "\r"` will produce files as expected by Excel:mac 2004. | | `na` | the string to use for missing values in the data. | | `dec` | the string to use for decimal points in numeric or complex columns: must be a single character. | | `row.names` | either a logical value indicating whether the row names of `x` are to be written along with `x`, or a character vector of row names to be written. | | `col.names` | either a logical value indicating whether the column names of `x` are to be written along with `x`, or a character vector of column names to be written. See the section on ‘CSV files’ for the meaning of `col.names = NA`. | | `qmethod` | a character string specifying how to deal with embedded double quote characters when quoting strings. Must be one of `"escape"` (default for `write.table`), in which case the quote character is escaped in C style by a backslash, or `"double"` (default for `write.csv` and `write.csv2`), in which case it is doubled. You can specify just the initial letter. | | `fileEncoding` | character string: if non-empty declares the encoding to be used on a file (not a connection) so the character data can be re-encoded as they are written. See `[file](../../base/html/connections)`. | | `...` | arguments to `write.table`: `append`, `col.names`, `sep`, `dec` and `qmethod` cannot be altered. | ### Details If the table has no columns the rownames will be written only if `row.names = TRUE`, and *vice versa*. Real and complex numbers are written to the maximal possible precision. If a data frame has matrix-like columns these will be converted to multiple columns in the result (*via* `[as.matrix](../../base/html/matrix)`) and so a character `col.names` or a numeric `quote` should refer to the columns in the result, not the input. Such matrix-like columns are unquoted by default. Any columns in a data frame which are lists or have a class (e.g., dates) will be converted by the appropriate `as.character` method: such columns are unquoted by default. On the other hand, any class information for a matrix is discarded and non-atomic (e.g., list) matrices are coerced to character. Only columns which have been converted to character will be quoted if specified by `quote`. The `dec` argument only applies to columns that are not subject to conversion to character because they have a class or are part of a matrix-like column (or matrix), in particular to columns protected by `[I](../../base/html/asis)()`. Use `[options](../../base/html/options)("OutDec")` to control such conversions. In almost all cases the conversion of numeric quantities is governed by the option `"scipen"` (see `[options](../../base/html/options)`), but with the internal equivalent of `digits = 15`. For finer control, use `[format](../../base/html/format)` to make a character matrix/data frame, and call `write.table` on that. These functions check for a user interrupt every 1000 lines of output. If `file` is a non-open connection, an attempt is made to open it and then close it after use. To write a Unix-style file on Windows, use a binary connection e.g. `file = file("filename", "wb")`. ### CSV files By default there is no column name for a column of row names. If `col.names = NA` and `row.names = TRUE` a blank column name is added, which is the convention used for CSV files to be read by spreadsheets. Note that such CSV files can be read in **R** by ``` read.csv(file = "<filename>", row.names = 1) ``` `write.csv` and `write.csv2` provide convenience wrappers for writing CSV files. They set `sep` and `dec` (see below), `qmethod = "double"`, and `col.names` to `NA` if `row.names = TRUE` (the default) and to `TRUE` otherwise. `write.csv` uses `"."` for the decimal point and a comma for the separator. `write.csv2` uses a comma for the decimal point and a semicolon for the separator, the Excel convention for CSV files in some Western European locales. These wrappers are deliberately inflexible: they are designed to ensure that the correct conventions are used to write a valid file. Attempts to change `append`, `col.names`, `sep`, `dec` or `qmethod` are ignored, with a warning. CSV files do not record an encoding, and this causes problems if they are not ASCII for many other applications. Windows Excel 2007/10 will open files (e.g., by the file association mechanism) correctly if they are ASCII or UTF-16 (use `fileEncoding = "UTF-16LE"`) or perhaps in the current Windows codepage (e.g., `"CP1252"`), but the ‘Text Import Wizard’ (from the ‘Data’ tab) allows far more choice of encodings. Excel:mac 2004/8 can *import* only ‘Macintosh’ (which seems to mean Mac Roman), ‘Windows’ (perhaps Latin-1) and ‘PC-8’ files. OpenOffice 3.x asks for the character set when opening the file. There is an IETF RFC4180 (<https://tools.ietf.org/html/rfc4180>) for CSV files, which mandates comma as the separator and CRLF line endings. `write.csv` writes compliant files on Windows: use `eol = "\r\n"` on other platforms. ### Note `write.table` can be slow for data frames with large numbers (hundreds or more) of columns: this is inevitable as each column could be of a different class and so must be handled separately. If they are all of the same class, consider using a matrix instead. ### See Also The ‘R Data Import/Export’ manual. `<read.table>`, `[write](../../base/html/write)`. `[write.matrix](../../mass/html/write.matrix)` in package [MASS](https://CRAN.R-project.org/package=MASS). ### Examples ``` ## Not run: ## To write a CSV file for input to Excel one might use x <- data.frame(a = I("a \" quote"), b = pi) write.table(x, file = "foo.csv", sep = ",", col.names = NA, qmethod = "double") ## and to read this file back into R one needs read.table("foo.csv", header = TRUE, sep = ",", row.names = 1) ## NB: you do need to specify a separator if qmethod = "double". ### Alternatively write.csv(x, file = "foo.csv") read.csv("foo.csv", row.names = 1) ## or without row names write.csv(x, file = "foo.csv", row.names = FALSE) read.csv("foo.csv") ## To write a file in Mac Roman for simple use in Mac Excel 2004/8 write.csv(x, file = "foo.csv", fileEncoding = "macroman") ## or for Windows Excel 2007/10 write.csv(x, file = "foo.csv", fileEncoding = "UTF-16LE") ## End(Not run) ```
programming_docs
r None `browseEnv` Browse Objects in Environment ------------------------------------------ ### Description The `browseEnv` function opens a browser with list of objects currently in `sys.frame()` environment. ### Usage ``` browseEnv(envir = .GlobalEnv, pattern, excludepatt = "^last\\.warning", html = .Platform$GUI != "AQUA", expanded = TRUE, properties = NULL, main = NULL, debugMe = FALSE) ``` ### Arguments | | | | --- | --- | | `envir` | an `[environment](../../base/html/environment)` the objects of which are to be browsed. | | `pattern` | a [regular expression](../../base/html/regex) for object subselection is passed to the internal `[ls](../../base/html/ls)()` call. | | `excludepatt` | a regular expression for *dropping* objects with matching names. | | `html` | is used to display the workspace on a HTML page in your favorite browser. The default except when running from `R.app` on macOS. | | `expanded` | whether to show one level of recursion. It can be useful to switch it to `FALSE` if your workspace is large. This option is ignored if `html` is set to `FALSE`. | | `properties` | a named list of global properties (of the objects chosen) to be showed in the browser; when `NULL` (as per default), user, date, and machine information is used. | | `main` | a title string to be used in the browser; when `NULL` (as per default) a title is constructed. | | `debugMe` | logical switch; if true, some diagnostic output is produced. | ### Details Very experimental code: displays a static HTML page on all platforms except `R.app` on macOS. Only allows one level of recursion into object structures. It can be generalized. See sources for details. Most probably, this should rather work through using the tkWidget package (from <https://www.bioconductor.org>). ### See Also `<str>`, `[ls](../../base/html/ls)`. ### Examples ``` if(interactive()) { ## create some interesting objects : ofa <- ordered(4:1) ex1 <- expression(1+ 0:9) ex3 <- expression(u, v, 1+ 0:9) example(factor, echo = FALSE) example(table, echo = FALSE) example(ftable, echo = FALSE) example(lm, echo = FALSE, ask = FALSE) example(str, echo = FALSE) ## and browse them: browseEnv() ## a (simple) function's environment: af12 <- approxfun(1:2, 1:2, method = "const") browseEnv(envir = environment(af12)) } ``` r None `utils-package` The R Utils Package ------------------------------------ ### Description R utility functions ### Details This package contains a collection of utility functions. For a complete list, use `library(help = "utils")`. ### Author(s) R Core Team and contributors worldwide Maintainer: R Core Team [[email protected]](mailto:[email protected]) r None `Question` Documentation Shortcuts ----------------------------------- ### Description These functions provide access to documentation. Documentation on a topic with name `name` (typically, an **R** object or a data set) can be displayed by either `help("name")` or `?name`. ### Usage ``` ?topic type?topic ``` ### Arguments | | | | --- | --- | | `topic` | Usually, a [name](../../base/html/name) or character string specifying the topic for which help is sought. Alternatively, a function call to ask for documentation on a corresponding S4 method: see the section on S4 method documentation. The calls `pkg::topic` and `pkg:::topic` are treated specially, and look for help on `topic` in package pkg. | | `type` | the special type of documentation to use for this topic; for example, if the type is `class`, documentation is provided for the class with name `topic`. See the Section ‘S4 Method Documentation’ for the uses of `type` to get help on formal methods, including `methods?function` and `method?call`. | ### Details This is a shortcut to `<help>` and uses its default type of help. Some topics need to be quoted (by [backtick](../../base/html/quotes)s) or given as a character string. There include those which cannot syntactically appear on their own such as unary and binary operators, `function` and control-flow [reserved](../../base/html/reserved) words (including `if`, `else` `for`, `in`, `repeat`, `while`, `break` and `next`). The other `reserved` words can be used as if they were names, for example `TRUE`, `NA` and `Inf`. ### S4 Method Documentation Authors of formal (‘S4’) methods can provide documentation on specific methods, as well as overall documentation on the methods of a particular function. The `"?"` operator allows access to this documentation in three ways. The expression `methods?f` will look for the overall documentation methods for the function `f`. Currently, this means the documentation file containing the alias `f-methods`. There are two different ways to look for documentation on a particular method. The first is to supply the `topic` argument in the form of a function call, omitting the `type` argument. The effect is to look for documentation on the method that would be used if this function call were actually evaluated. See the examples below. If the function is not a generic (no S4 methods are defined for it), the help reverts to documentation on the function name. The `"?"` operator can also be called with `doc_type` supplied as `method`; in this case also, the `topic` argument is a function call, but the arguments are now interpreted as specifying the class of the argument, not the actual expression that will appear in a real call to the function. See the examples below. The first approach will be tedious if the actual call involves complicated expressions, and may be slow if the arguments take a long time to evaluate. The second approach avoids these issues, but you do have to know what the classes of the actual arguments will be when they are evaluated. Both approaches make use of any inherited methods; the signature of the method to be looked up is found by using `selectMethod` (see the documentation for `[getMethod](../../methods/html/getmethod)`). A limitation is that methods in packages (as opposed to regular functions) will only be found if the package exporting them is on the search list, even if it is specified explicitly using the `?package::generic()` notation. ### References Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) *The New S Language*. Wadsworth & Brooks/Cole. ### See Also `<help>` `[??](help.search)` for finding help pages on a vague topic. ### Examples ``` ?lapply ?"for" # but quotes/backticks are needed ?`+` ?women # information about data set "women" ## Not run: require(methods) ## define a S4 generic function and some methods combo <- function(x, y) c(x, y) setGeneric("combo") setMethod("combo", c("numeric", "numeric"), function(x, y) x+y) ## assume we have written some documentation ## for combo, and its methods .... ?combo # produces the function documentation methods?combo # looks for the overall methods documentation method?combo("numeric", "numeric") # documentation for the method above ?combo(1:10, rnorm(10)) # ... the same method, selected according to # the arguments (one integer, the other numeric) ?combo(1:10, letters) # documentation for the default method ## End(Not run) ``` r None `edit.data.frame` Edit Data Frames and Matrices ------------------------------------------------ ### Description Use data editor on data frame or matrix contents. ### Usage ``` ## S3 method for class 'data.frame' edit(name, factor.mode = c("character", "numeric"), edit.row.names = any(row.names(name) != 1:nrow(name)), ...) ## S3 method for class 'matrix' edit(name, edit.row.names = !is.null(dn[[1]]), ...) ``` ### Arguments | | | | --- | --- | | `name` | A data frame or (numeric, logical or character) matrix. | | `factor.mode` | How to handle factors (as integers or using character levels) in a data frame. Can be abbreviated. | | `edit.row.names` | logical. Show the row names (if they exist) be displayed as a separate editable column? It is an error to ask for this on a matrix with `NULL` row names. | | `...` | further arguments passed to or from other methods. | ### Details At present, this only works on simple data frames containing numeric, logical or character vectors and factors, and numeric, logical or character matrices. Any other mode of matrix will give an error, and a warning is given when the matrix has a class (which will be discarded). Data frame columns are coerced on input to *character* unless numeric (in the sense of `is.numeric`), logical or factor. A warning is given when classes are discarded. Special characters (tabs, non-printing ASCII, etc.) will be displayed as escape sequences. Factors columns are represented in the spreadsheet as either numeric vectors (which are more suitable for data entry) or character vectors (better for browsing). After editing, vectors are padded with `NA` to have the same length and factor attributes are restored. The set of factor levels can not be changed by editing in numeric mode; invalid levels are changed to `NA` and a warning is issued. If new factor levels are introduced in character mode, they are added at the end of the list of levels in the order in which they encountered. It is possible to use the data-editor's facilities to select the mode of columns to swap between numerical and factor columns in a data frame. Changing any column in a numerical matrix to character will cause the result to be coerced to a character matrix. Changing the mode of logical columns is not supported. For a data frame, the row names will be taken from the original object if `edit.row.names = FALSE` and the number of rows is unchanged, and from the edited output if `edit.row.names = TRUE` and there are no duplicates. (If the `row.names` column is incomplete, it is extended by entries like `row223`.) In all other cases the row names are replaced by `seq(length = nrows)`. For a matrix, colnames will be added (of the form `col7`) if needed. The rownames will be taken from the original object if `edit.row.names = FALSE` and the number of rows is unchanged (otherwise `NULL`), and from the edited output if `edit.row.names = TRUE`. (If the `row.names` column is incomplete, it is extended by entries like `row223`.) Editing a matrix or data frame will lose all attributes apart from the row and column names. ### Value The edited data frame or matrix. ### Note `fix(dataframe)` works for in-place editing by calling this function. If the data editor is not available, a dump of the object is presented for editing using the default method of `edit`. At present the data editor is limited to 65535 rows. ### Author(s) Peter Dalgaard ### See Also `[data.entry](dataentry)`, `<edit>` ### Examples ``` ## Not run: edit(InsectSprays) edit(InsectSprays, factor.mode = "numeric") ## End(Not run) ``` r None `warnErrList` Collect and Summarize Errors From List ----------------------------------------------------- ### Description Collect errors (class `"error"`, typically from `[tryCatch](../../base/html/conditions)`) from a list `x` into a “summary warning”, by default produce a `[warning](../../base/html/warning)` and keep that message as `"warningMsg"` attribute. ### Usage ``` warnErrList(x, warn = TRUE, errValue = NULL) ``` ### Arguments | | | | --- | --- | | `x` | a `[list](../../base/html/list)`, typically from applying models to a list of data (sub)sets, e.g., using `[tryCatch](../../base/html/conditions)(*, error = identity)`. | | `warn` | logical indicating if `[warning](../../base/html/warning)()` should be called. | | `errValue` | the value with which errors should be replaced. | ### Value a `[list](../../base/html/list)` of the same length and names as the `x` argument, with the error components replaced by `errValue`, `[NULL](../../base/html/null)` by default, and summarized in the `"warningMsg"` attribute. ### See Also The `warnErrList()` utility has been used in `[lmList](../../nlme/html/lmlist)()` and `[nlsList](../../nlme/html/nlslist)()` in recommended package [nlme](https://CRAN.R-project.org/package=nlme) forever. ### Examples ``` ## Regression for each Chick: ChWtgrps <- split(ChickWeight, ChickWeight[,"Chick"]) sapply(ChWtgrps, nrow)# typically 12 obs. nlis1 <- lapply(ChWtgrps, function(DAT) tryCatch(error = identity, lm(weight ~ (Time + I(Time^2)) * Diet, data = DAT))) nl1 <- warnErrList(nlis1) #-> warning : ## 50 times the same error (as Diet has only one level in each group) stopifnot(sapply(nl1, is.null)) ## all errors --> all replaced by NULL nlis2 <- lapply(ChWtgrps, function(DAT) tryCatch(error = identity, lm(weight ~ Time + I(Time^2), data = DAT))) nl2 <- warnErrList(nlis2) stopifnot(identical(nl2, nlis2)) # because there was *no* error at all nlis3 <- lapply(ChWtgrps, function(DAT) tryCatch(error = identity, lm(weight ~ poly(Time, 3), data = DAT))) nl3 <- warnErrList(nlis3) # 1 error caught: stopifnot(inherits(nlis3[[1]], "error") , identical(nl3[-1], nlis3[-1]) , is.null(nl3[[1]]) ) ## With different error messages if(requireNamespace("nlme")) { # almost always, as it is recommended data(Soybean, package="nlme") attr(Soybean, "formula") #-> weight ~ Time | Plot => split by "Plot": L <- lapply(split(Soybean, Soybean[,"Plot"]), function(DD) tryCatch(error = identity, nls(weight ~ SSlogis(Time, Asym, xmid, scal), data = DD))) Lw <- warnErrList(L) } # if <nlme> ``` r None `unzip` Extract or List Zip Archives ------------------------------------- ### Description Extract files from or list a zip archive. ### Usage ``` unzip(zipfile, files = NULL, list = FALSE, overwrite = TRUE, junkpaths = FALSE, exdir = ".", unzip = "internal", setTimes = FALSE) ``` ### Arguments | | | | --- | --- | | `zipfile` | The pathname of the zip file: tilde expansion (see `[path.expand](../../base/html/path.expand)`) will be performed. | | `files` | A character vector of recorded filepaths to be extracted: the default is to extract all files. | | `list` | If `TRUE`, list the files and extract none. The equivalent of `unzip -l`. | | `overwrite` | If `TRUE`, overwrite existing files (the equivalent of `unzip -o`), otherwise ignore such files (the equivalent of `unzip -n`). | | `junkpaths` | If `TRUE`, use only the basename of the stored filepath when extracting. The equivalent of `unzip -j`. | | `exdir` | The directory to extract files to (the equivalent of `unzip -d`). It will be created if necessary. | | `unzip` | The method to be used. An alternative is to use `getOption("unzip")`, which on a Unix-alike may be set to the path to a `unzip` program. | | `setTimes` | logical. For the internal method only, should the file times be set based on the times in the zip file? (NB: this applies to included files, not to directories.) | ### Value If `list = TRUE`, a data frame with columns `Name` (character) `Length` (the size of the uncompressed file, numeric) and `Date` (of class `"[POSIXct](../../base/html/datetimeclasses)"`). Otherwise for the `"internal"` method, a character vector of the filepaths extracted to, invisibly. ### Note The default internal method is a minimal implementation, principally designed for Windows' users to be able to unpack Windows binary packages without external software. It does not (for example) support Unicode filenames as introduced in `zip 3.0`: for that use `unzip = "unzip"` with `unzip 6.00` or later. It does have some support for `bzip2` compression and > 2GB zip files (but not >= 4GB files pre-compression contained in a zip file: like many builds of `unzip` it may truncate these, in **R**'s case with a warning if possible). If `unzip` specifies a program, the format of the dates listed with `list = TRUE` is unknown (on Windows it can even depend on the current locale) and the return values could be `NA` or expressed in the wrong time zone or misinterpreted (the latter being far less likely as from `unzip 6.00`). File times in zip files are stored in the style of MS-DOS, as local times to an accuracy of 2 seconds. This is not very useful when transferring zip files between machines (even across continents), so we chose not to restore them by default. ### Source The internal C code uses `zlib` and is in particular based on the contributed minizip application in the `zlib` sources (from <https://zlib.net/>) by Gilles Vollant. ### See Also `[unz](../../base/html/connections)` to read a single component from a zip file. `<zip>` for packing, i.e., the “inverse” of `unzip()`; further `<untar>` and `<tar>`, the corresponding pair for (un)packing tar archives (“tarballs”) such as **R** source packages. r None `charClass` Character Classification ------------------------------------- ### Description An interface to the (C99) wide character classification functions in use. ### Usage ``` charClass(x, class) ``` ### Arguments | | | | --- | --- | | `x` | **Either** a UTF-8-encoded length-1 character vector **or** an integer vector of Unicode points (or a vector coercible to integer). | | `class` | A character string, one of those given in the ‘Details’ section. | ### Details The classification into character classes is platform-dependent. The classes are determined by internal tables on Windows and (optionally but by default) on macOS and AIX. The character classes are interpreted as follows: `"alnum"` Alphabetic or numeric. `"alpha"` Alphabetic. `"blank"` Space or tab. `"cntrl"` Control characters. `"digit"` Digits `0-9`. `"graph"` Graphical characters (printable characters except whitespace). `"lower"` Lower-case alphabetic. `"print"` Printable characters. `"punct"` Punctuation characters. Some platforms treat all non-alphanumeric graphical characters as punctuation. `"space"` Whitespace, including tabs, form and line feeds and carriage returns. Some OSes include non-breaking spaces, some exclude them. `"upper"` Upper-case alphabetic. `"xdigit"` Hexadecimal character, one of `0-9A-fa-f`. Alphabetic characters contain all lower- and upper-case ones and some others (for example, those in ‘title case’). Whether a character is printable is used to decide whether to escape it when printing – see the help for `[print.default](../../base/html/print.default)`. If `x` is a character string it should either be ASCII or declared as UTF-8 – see `[Encoding](../../base/html/encoding)`. `charClass` was added in **R** 4.1.0. A less direct way to examine character classes which also worked in earlier versions is to use something like `grepl("[[:print:]]", intToUtf8(x))` – however, the regular-expression code might not use the same classification functions as printing and on macOS used not to. ### Value A logical vector of the length the number of characters or integers in `x`. ### Note Non-ASCII digits are excluded by the C99 standard from the class `"digit"`: most platforms will have them as alphabetic. It is an assumption that the system's wide character classification functions are coded in Unicode points, but this is known to be true for all recent platforms. In principle the classification could depend on the locale even on one platform, but that seems no longer to be seen. ### See Also Character classes are used in [regular expression](../../base/html/regex)s. The OS's `man` pages for `iswctype` and `wctype`. ### Examples ``` x <- c(48:70, 32, 0xa0) # Last is non-breaking space cl <- c("alnum", "alpha", "blank", "digit", "graph", "punct", "upper", "xdigit") X <- lapply(cl, function(y) charClass(x,y)); names(X) <- cl X <- as.data.frame(X); row.names(X) <- sQuote(intToUtf8(x, multiple = TRUE)) X charClass("ABC123", "alpha") ## Some accented capital Greek characters (x <- "\u0386\u0388\u0389") charClass(x, "upper") ## How many printable characters are there? (Around 280,000 in Unicode 13.) ## There are 2^21-1 possible Unicode points (most not yet assigned). pr <- charClass(1:0x1fffff, "print") table(pr) ```
programming_docs
r None `type.convert` Convert Data to Appropriate Type ------------------------------------------------ ### Description Convert a data object to logical, integer, numeric, complex, character or factor as appropriate. ### Usage ``` type.convert(x, ...) ## Default S3 method: type.convert(x, na.strings = "NA", as.is, dec = ".", numerals = c("allow.loss", "warn.loss", "no.loss"), ...) ## S3 method for class 'data.frame' type.convert(x, ...) ## S3 method for class 'list' type.convert(x, ...) ``` ### Arguments | | | | --- | --- | | `x` | a vector, matrix, array, data frame, or list. | | `na.strings` | a vector of strings which are to be interpreted as `[NA](../../base/html/na)` values. Blank fields are also considered to be missing values in logical, integer, numeric or complex vectors. | | `as.is` | whether convert to `[factor](../../base/html/factor)`s. When false (was default before **R** 4.0.0), convert character vectors to factors. See ‘Details’. | | `dec` | the character to be assumed for decimal points. | | `numerals` | string indicating how to convert numbers whose conversion to double precision would lose accuracy, typically when `x` has more digits than can be stored in a `[double](../../base/html/double)`. Can be abbreviated. Possible values are `numerals = "allow.loss"`, default: the conversion happens with some accuracy loss. This was the behavior of **R** versions 3.0.3 and earlier, and the default from 3.1.1 onwards. `numerals = "warn.loss"`: a `[warning](../../base/html/warning)` about accuracy loss is signalled and the conversion happens as with `numerals = "allow.loss"`. `numerals = "no.loss"`: `x` is *not* converted to a number, but to a `[factor](../../base/html/factor)` or `character`, depending on `as.is`. This was the behavior of **R** version 3.1.0. | | `...` | arguments to be passed to or from methods. | ### Details This helper function is used by `<read.table>`. When the data object `x` is a data frame or list, the function is called recursively for each column or list element. Given a vector, the function attempts to convert it to logical, integer, numeric or complex, and when additionally `as.is = FALSE` (no longer the default!), converts a character vector to `[factor](../../base/html/factor)`. The first type that can accept all the non-missing values is chosen. Vectors which are entirely missing values are converted to logical, since `NA` is primarily logical. Vectors containing just `F`, `T`, `FALSE`, `TRUE` and values from `na.strings` are converted to logical. Vectors containing optional whitespace followed by decimal constants representable as **R** integers or values from `na.strings` are converted to integer. Other vectors containing optional whitespace followed by other decimal or hexadecimal constants (see [NumericConstants](../../base/html/numericconstants)), or `NaN`, `Inf` or `infinity` (ignoring case) or values from `na.strings` are converted to numeric. Where converting inputs to numeric or complex would result in loss of accuracy they can optionally be returned as strings or (for `as.is = FALSE`) factors. Since this is a helper function, the caller should always pass an appropriate value of `as.is`. ### Value An object like `x` but using another storage mode when appropriate. ### Author(s) R Core, with a contribution by Arni Magnusson ### See Also `<read.table>`, `[class](../../base/html/class)`, `[storage.mode](../../base/html/mode)`. ### Examples ``` ## Numeric to integer class(rivers) x <- type.convert(rivers) class(x) ## Convert many columns auto <- type.convert(mtcars) str(mtcars) str(auto) ## Convert matrix phones <- type.convert(WorldPhones) storage.mode(WorldPhones) storage.mode(phones) ## Factor or character chr <- c("A", "B", "B", "A") fac <- factor(c("A", "B", "B", "A")) type.convert(chr) # -> factor type.convert(fac) # -> factor type.convert(chr, as.is = TRUE) # -> character type.convert(fac, as.is = TRUE) # -> character ``` r None `debugcall` Debug a Call ------------------------- ### Description Set or unset debugging flags based on a call to a function. Takes into account S3/S4 method dispatch based on the classes of the arguments in the call. ### Usage ``` debugcall(call, once = FALSE) undebugcall(call) ``` ### Arguments | | | | --- | --- | | `call` | An R expression calling a function. The called function will be debugged. See Details. | | `once` | logical; if `TRUE`, debugging only occurs once, as via `debugonce`. Defaults to `FALSE` | ### Details `debugcall` debugs the non-generic function, S3 method or S4 method that would be called by evaluating `call`. Thus, the user does not need to specify the signature when debugging methods. Although the call is actually to the generic, it is the method that is debugged, not the generic, except for non-standard S3 generics (see `[isS3stdGeneric](iss3stdgen)`). ### Value `debugcall` invisibly returns the debugged call expression. ### Note Non-standard evaluation is used to retrieve the `call` (via `[substitute](../../base/html/substitute)`). For this reason, passing a variable containing a call expression, rather than the call expression itself, will not work. ### See Also `[debug](../../base/html/debug)` for the primary debugging interface ### Examples ``` ## Not run: ## Evaluate call after setting debugging ## f <- factor(1:10) res <- eval(debugcall(summary(f))) ## End(Not run) ``` r None `getFromNamespace` Utility Functions for Developing Namespaces --------------------------------------------------------------- ### Description Utility functions to access and replace the non-exported functions in a namespace, for use in developing packages with namespaces. They should not be used in production code (except perhaps `assignInMyNamespace`, but see the ‘Note’). ### Usage ``` getFromNamespace(x, ns, pos = -1, envir = as.environment(pos)) assignInNamespace(x, value, ns, pos = -1, envir = as.environment(pos)) assignInMyNamespace(x, value) fixInNamespace(x, ns, pos = -1, envir = as.environment(pos), ...) ``` ### Arguments | | | | --- | --- | | `x` | an object name (given as a character string). | | `value` | an **R** object. | | `ns` | a namespace, or character string giving the namespace. | | `pos` | where to look for the object: see `[get](../../base/html/get)`. | | `envir` | an alternative way to specify an environment to look in. | | `...` | arguments to pass to the editor: see `<edit>`. | ### Details `assignInMyNamespace` is intended to be called from functions within a package, and chooses the namespace as the environment of the function calling it. The namespace can be specified in several ways. Using, for example, `ns = "stats"` is the most direct, but a loaded package can be specified via any of the methods used for `[get](../../base/html/get)`: `ns` can also be the environment printed as `<namespace:foo>`. `getFromNamespace` is similar to (but predates) the `[:::](../../base/html/ns-dblcolon)` operator: it is more flexible in how the namespace is specified. `fixInNamespace` invokes `<edit>` on the object named `x` and assigns the revised object in place of the original object. For compatibility with `fix`, `x` can be unquoted. ### Value `getFromNamespace` returns the object found (or gives an error). `assignInNamespace`, `assignInMyNamespace` and `fixInNamespace` are invoked for their side effect of changing the object in the namespace. ### Warning `assignInNamespace` should not be used in final code, and will in future throw an error if called from a package. Already certain uses are disallowed. ### Note `assignInNamespace`, `assignInMyNamespace` and `fixInNamespace` change the copy in the namespace, but not any copies already exported from the namespace, in particular an object of that name in the package (if already attached) and any copies already imported into other namespaces. They are really intended to be used *only* for objects which are not exported from the namespace. They do attempt to alter a copy registered as an S3 method if one is found. They can only be used to change the values of objects in the namespace, not to create new objects. ### See Also `[get](../../base/html/get)`, `<fix>`, `[getS3method](gets3method)` ### Examples ``` getFromNamespace("findGeneric", "utils") ## Not run: fixInNamespace("predict.ppr", "stats") stats:::predict.ppr getS3method("predict", "ppr") ## alternatively fixInNamespace("predict.ppr", pos = 3) fixInNamespace("predict.ppr", pos = "package:stats") ## End(Not run) ``` r None `nsl` Look up the IP Address by Hostname (on Unix-alikes) ---------------------------------------------------------- ### Description Interface to the system `gethostbyname`, currently available only on unix-alikes, i.e., not on Windows. ### Usage ``` nsl(hostname) ``` ### Arguments | | | | --- | --- | | `hostname` | the name of the host. | ### Details This was included as a test of internet connectivity, to fail if the node running **R** is not connected. It will also return `NULL` if BSD networking is not supported, including the header file ‘arpa/inet.h’. This function is not available on Windows. ### Value The IP address, as a character string, or `NULL` if the call fails. ### Examples ``` if(.Platform$OS.type == "unix") # includes Mac print( nsl("www.r-project.org") ) ``` r None `person` Persons ----------------- ### Description A class and utility methods for holding information about persons like name and email address. ### Usage ``` person(given = NULL, family = NULL, middle = NULL, email = NULL, role = NULL, comment = NULL, first = NULL, last = NULL) ## Default S3 method: as.person(x) ## S3 method for class 'person' format(x, include = c("given", "family", "email", "role", "comment"), braces = list(given = "", family = "", email = c("<", ">"), role = c("[", "]"), comment = c("(", ")")), collapse = list(given = " ", family = " ", email = ", ", role = ", ", comment = ", "), ..., style = c("text", "R") ) ``` ### Arguments | | | | --- | --- | | `given` | a character vector with the *given* names, or a list thereof. | | `family` | a character string with the *family* name, or a list thereof. | | `middle` | a character string with the collapsed middle name(s). Deprecated, see **Details**. | | `email` | a character string (or vector) giving an e-mail address (each), or a list thereof. | | `role` | a character vector specifying the role(s) of the person (see **Details**), or a list thereof. | | `comment` | a character string (or vector) providing comments, or a list thereof. | | `first` | a character string giving the first name. Deprecated, see **Details**. | | `last` | a character string giving the last name. Deprecated, see **Details**. | | `x` | a character string for the `as.person` default method; an object of class `"person"` otherwise. | | `include` | a character vector giving the fields to be included when formatting. | | `braces` | a list of characters (see **Details**). | | `collapse` | a list of characters (see **Details**). | | `...` | currently not used. | | `style` | a character string specifying the print style, with `"R"` yielding formatting as R code. | ### Details Objects of class `"person"` can hold information about an arbitrary positive number of persons. These can be obtained by one call to `person()` with list arguments, or by first creating objects representing single persons and combining these via `c()`. The `format()` method collapses information about persons into character vectors (one string for each person): the fields in `include` are selected, each collapsed to a string using the respective element of `collapse` and subsequently “embraced” using the respective element of `braces`, and finally collapsed into one string separated by white space. If `braces` and/or `collapse` do not specify characters for all fields, the defaults shown in the usage are imputed. If `collapse` is `FALSE` or `NA` the corresponding field is not collapsed but only the first element is used. The `print()` method calls the `format()` method and prints the result, the `toBibtex()` method creates a suitable BibTeX representation. Person objects can be subscripted by fields (using `$`) or by position (using `[`). `as.person()` is a generic function. Its default method tries to reverse the default person formatting, and can also handle formatted person entries collapsed by comma or `"and"` (with appropriate white space). Personal names are rather tricky, e.g., <https://en.wikipedia.org/wiki/Personal_name>. The current implementation (starting from R 2.12.0) of the `"person"` class uses the notions of *given* (including middle names) and *family* names, as specified by `given` and `family` respectively. Earlier versions used a scheme based on first, middle and last names, as appropriate for most of Western culture where the given name precedes the family name, but not universal, as some other cultures place it after the family name, or use no family name. To smooth the transition to the new scheme, arguments `first`, `middle` and `last` are still supported, but their use is deprecated and they must not be given in combination with the corresponding new style arguments. For persons which are not natural persons (e.g., institutions, companies, etc.) it is appropriate to use `given` (but not `family`) for the name, e.g., `person("R Core Team", role = "aut")`. The new scheme also adds the possibility of specifying *roles* based on a subset of the MARC Code List for Relators (<https://www.loc.gov/marc/relators/relaterm.html>). When giving the roles of persons in the context of authoring **R** packages, the following usage is suggested. `"aut"` (Author) Use for full authors who have made substantial contributions to the package and should show up in the package citation. `"com"` (Compiler) Use for persons who collected code (potentially in other languages) but did not make further substantial contributions to the package. `"cph"` (Copyright holder) Use for all copyright holders. This is a legal concept so should use the legal name of an institution or corporate body. `"cre"` (Creator) Use for the package maintainer. `"ctb"` (Contributor) Use for authors who have made smaller contributions (such as code patches etc.) but should not show up in the package citation. `"ctr"` (Contractor) Use for authors who have been contracted to write (parts of) the package and hence do not own intellectual property. `"dtc"` (Data contributor) Use for persons who contributed data sets for the package. `"fnd"` (Funder) Use for persons or organizations that furnished financial support for the development of the package. `"rev"` (Reviewer) Use for persons or organizations responsible for reviewing (parts of) the package. `"ths"` (Thesis advisor) If the package is part of a thesis, use for the thesis advisor. `"trl"` (Translator) If the R code is a translation from another language (typically S), use for the translator to R. In the old scheme, person objects were used for single persons, and a separate `"personList"` class with corresponding creator `personList()` for collections of these. The new scheme employs a single class for information about an arbitrary positive number of persons, eliminating the need for the `personList` mechanism. The `comment` field can be used for “arbitrary” additional information about persons. Elements named `"ORCID"` will be taken to give ORCID identifiers (see <https://orcid.org/> for more information), and be displayed as the corresponding URIs by the `print()` and `format()` methods (see **Examples** below). ### Value `person()` and `as.person()` return objects of class `"person"`. ### See Also `<citation>` ### Examples ``` ## Create a person object directly ... p1 <- person("Karl", "Pearson", email = "[email protected]") ## ... or convert a string. p2 <- as.person("Ronald Aylmer Fisher") ## Combining and subsetting. p <- c(p1, p2) p[1] p[-1] ## Extracting fields. p$family p$email p[1]$email ## Specifying package authors, example from "boot": ## AC is the first author [aut] who wrote the S original. ## BR is the second author [aut], who translated the code to R [trl], ## and maintains the package [cre]. b <- c(person("Angelo", "Canty", role = "aut", comment = "S original, <http://statwww.epfl.ch/davison/BMA/library.html>"), person(c("Brian", "D."), "Ripley", role = c("aut", "trl", "cre"), comment = "R port", email = "[email protected]") ) b ## Formatting. format(b) format(b, include = c("family", "given", "role"), braces = list(family = c("", ","), role = c("(Role(s): ", ")"))) ## Conversion to BibTeX author field. paste(format(b, include = c("given", "family")), collapse = " and ") toBibtex(b) ## ORCID identifiers. (p3 <- person("Achim", "Zeileis", comment = c(ORCID = "0000-0003-0918-3766"))) ``` r None `edit` Invoke a Text Editor ---------------------------- ### Description Invoke a text editor on an **R** object. ### Usage ``` ## Default S3 method: edit(name = NULL, file = "", title = NULL, editor = getOption("editor"), ...) vi(name = NULL, file = "") emacs(name = NULL, file = "") pico(name = NULL, file = "") xemacs(name = NULL, file = "") xedit(name = NULL, file = "") ``` ### Arguments | | | | --- | --- | | `name` | a named object that you want to edit. If name is missing then the file specified by `file` is opened for editing. | | `file` | a string naming the file to write the edited version to. | | `title` | a display name for the object being edited. | | `editor` | usually a character string naming (or giving the path to) the text editor you want to use. On Unix the default is set from the environment variables EDITOR or VISUAL if either is set, otherwise `vi` is used. On Windows it defaults to `"internal"`, the script editor. On the macOS GUI the argument is ignored and the document editor is always used. `editor` can also be an **R** function, in which case it is called with the arguments `name`, `file`, and `title`. Note that such a function will need to independently implement all desired functionality. | | `...` | further arguments to be passed to or from methods. | ### Details `edit` invokes the text editor specified by `editor` with the object `name` to be edited. It is a generic function, currently with a default method and one for data frames and matrices. `data.entry` can be used to edit data, and is used by `edit` to edit matrices and data frames on systems for which `data.entry` is available. It is important to realize that `edit` does not change the object called `name`. Instead, a copy of name is made and it is that copy which is changed. Should you want the changes to apply to the object `name` you must assign the result of `edit` to `name`. (Try `<fix>` if you want to make permanent changes to an object.) In the form `edit(name)`, `edit` deparses `name` into a temporary file and invokes the editor `editor` on this file. Quitting from the editor causes `file` to be parsed and that value returned. Should an error occur in parsing, possibly due to incorrect syntax, no value is returned. Calling `edit()`, with no arguments, will result in the temporary file being reopened for further editing. Note that deparsing is not perfect, and the object recreated after editing can differ in subtle ways from that deparsed: see `[dput](../../base/html/dput)` and `[.deparseOpts](../../base/html/deparseopts)`. (The deparse options used are the same as the defaults for `dump`.) Editing a function will preserve its environment. See `<edit.data.frame>` for further changes that can occur when editing a data frame or matrix. Currently only the internal editor in Windows makes use of the `title` option; it displays the given name in the window header. ### Note The functions `vi`, `emacs`, `pico`, `xemacs`, `xedit` rely on the corresponding editor being available and being on the path. This is system-dependent. ### See Also `<edit.data.frame>`, `[data.entry](dataentry)`, `<fix>`. ### Examples ``` ## Not run: # use xedit on the function mean and assign the changes mean <- edit(mean, editor = "xedit") # use vi on mean and write the result to file mean.out vi(mean, file = "mean.out") ## End(Not run) ```
programming_docs
r None `example` Run an Examples Section from the Online Help ------------------------------------------------------- ### Description Run all the **R** code from the **Examples** part of **R**'s online help topic `topic` with possible exceptions `dontrun`, `dontshow`, and `donttest`, see ‘Details’ below. ### Usage ``` example(topic, package = NULL, lib.loc = NULL, character.only = FALSE, give.lines = FALSE, local = FALSE, echo = TRUE, verbose = getOption("verbose"), setRNG = FALSE, ask = getOption("example.ask"), prompt.prefix = abbreviate(topic, 6), run.dontrun = FALSE, run.donttest = interactive()) ``` ### Arguments | | | | --- | --- | | `topic` | name or literal character string: the online `<help>` topic the examples of which should be run. | | `package` | a character vector giving the package names to look into for the topic, or `NULL` (the default), when all packages on the [search](../../base/html/search) path are used. | | `lib.loc` | a character vector of directory names of **R** libraries, or `NULL`. The default value of `NULL` corresponds to all libraries currently known. If the default is used, the loaded packages are searched before the libraries. | | `character.only` | a logical indicating whether `topic` can be assumed to be a character string. | | `give.lines` | logical: if true, the *lines* of the example source code are returned as a character vector. | | `local` | logical: if `TRUE` evaluate locally, if `FALSE` evaluate in the workspace. | | `echo` | logical; if `TRUE`, show the **R** input when sourcing. | | `verbose` | logical; if `TRUE`, show even more when running example code. | | `setRNG` | logical or expression; if not `FALSE`, the random number generator state is saved, then initialized to a specified state, the example is run and the (saved) state is restored. `setRNG = TRUE` sets the same state as `R CMD [check](pkgutils)` does for running a package's examples. This is currently equivalent to `setRNG = {RNGkind("default", "default", "default"); set.seed(1)}`. | | `ask` | logical (or `"default"`) indicating if `[devAskNewPage](../../grdevices/html/devasknewpage)(ask = TRUE)` should be called before graphical output happens from the example code. The value `"default"` (the factory-fresh default) means to ask if `echo == TRUE` and the graphics device appears to be interactive. This parameter applies both to any currently opened device and to any devices opened by the example code. | | `prompt.prefix` | character; prefixes the prompt to be used if `echo = TRUE`. | | `run.dontrun` | logical indicating that `\dontrun` should be ignored. | | `run.donttest` | logical indicating that `\donttest` should be ignored. | ### Details If `lib.loc` is not specified, the packages are searched for amongst those already loaded, then in the libraries given by `[.libPaths](../../base/html/libpaths)()`. If `lib.loc` is specified, packages are searched for only in the specified libraries, even if they are already loaded from another library. The search stops at the first package found that has help on the topic. An attempt is made to load the package before running the examples, but this will not replace a package loaded from another location. If `local = TRUE` objects are not created in the workspace and so not available for examination after `example` completes: on the other hand they cannot overwrite objects of the same name in the workspace. As detailed in the manual *Writing **R** Extensions*, the author of the help page can markup parts of the examples for exception rules `dontrun` encloses code that should not be run. `dontshow` encloses code that is invisible on help pages, but will be run both by the package checking tools, and the `example()` function. This was previously `testonly`, and that form is still accepted. `donttest` encloses code that typically should be run, but not during package checking. The default `run.donttest = [interactive](../../base/html/interactive)()` leads `example()` use in other help page examples to skip `\donttest` sections appropriately. ### Value The value of the last evaluated expression, unless `give.lines` is true, where a `[character](../../base/html/character)` vector is returned. ### Author(s) Martin Maechler and others ### See Also `<demo>` ### Examples ``` example(InsectSprays) ## force use of the standard package 'stats': example("smooth", package = "stats", lib.loc = .Library) ## set RNG *before* example as when R CMD check is run: r1 <- example(quantile, setRNG = TRUE) x1 <- rnorm(1) u <- runif(1) ## identical random numbers r2 <- example(quantile, setRNG = TRUE) x2 <- rnorm(1) stopifnot(identical(r1, r2)) ## but x1 and x2 differ since the RNG state from before example() ## differs and is restored! x1; x2 ## Exploring examples code: ## How large are the examples of "lm...()" functions? lmex <- sapply(apropos("^lm", mode = "function"), example, character.only = TRUE, give.lines = TRUE) sapply(lmex, length) ``` r None `shortPathName` Express File Paths in Short Form on Windows ------------------------------------------------------------ ### Description Convert file paths to the short form. This is an interface to the Windows API call `GetShortPathNameW`. ### Usage ``` shortPathName(path) ``` ### Arguments | | | | --- | --- | | `path` | character vector of file paths. | ### Details For most file systems, the short form is the ‘DOS’ form with 8+3 path components and no spaces, and this used to be guaranteed. But some file systems on recent versions of Windows do not have short path names when the long-name path will be returned instead. ### Value A character vector. The path separator will be `\`. If a file path does not exist, the supplied path will be returned with slashes replaced by backslashes. ### Note This is only available on Windows. ### See Also `[normalizePath](../../base/html/normalizepath)`. ### Examples ``` if(.Platform$OS.type == "windows") withAutoprint({ cat(shortPathName(c(R.home(), tempdir())), sep = "\n") }) ``` r None `getS3method` Get an S3 Method ------------------------------- ### Description Get a method for an S3 generic, possibly from a namespace or the generic's registry. ### Usage ``` getS3method(f, class, optional = FALSE, envir = parent.frame()) ``` ### Arguments | | | | --- | --- | | `f` | a character string giving the name of the generic. | | `class` | a character string giving the name of the class. | | `optional` | logical: should failure to find the generic or a method be allowed? | | `envir` | the `[environment](../../base/html/environment)` in which the method and its generic are searched first. | ### Details S3 methods may be hidden in namespaces, and will not then be found by `[get](../../base/html/get)`: this function can retrieve such functions, primarily for debugging purposes. Further, S3 methods can be registered on the generic when a namespace is loaded, and the registered method will be used if none is visible (using namespace scoping rules). It is possible that which S3 method will be used may depend on where the generic `f` is called from: `getS3method` returns the method found if `f` were called from the same environment. ### Value The function found, or `NULL` if no function is found and `optional = TRUE`. ### See Also `<methods>`, `[get](../../base/html/get)`, `[getAnywhere](getanywhere)` ### Examples ``` require(stats) exists("predict.ppr") # false getS3method("predict", "ppr") ``` r None `make.socket` Create a Socket Connection ----------------------------------------- ### Description With `server = FALSE` attempts to open a client socket to the specified port and host. With `server = TRUE` the **R** process listens on the specified port for a connection and then returns a server socket. It is a good idea to use `[on.exit](../../base/html/on.exit)` to ensure that a socket is closed, as you only get 64 of them. ### Usage ``` make.socket(host = "localhost", port, fail = TRUE, server = FALSE) ``` ### Arguments | | | | --- | --- | | `host` | name of remote host | | `port` | port to connect to/listen on | | `fail` | failure to connect is an error? | | `server` | a server socket? | ### Value An object of class `"socket"`, a list with components: | | | | --- | --- | | `socket` | socket number. This is for internal use. On a Unix-alike it is a file descriptor. | | `port` | port number of the connection. | | `host` | name of remote computer. | ### Warning I don't know if the connecting host name returned when `server = TRUE` can be trusted. I suspect not. ### Author(s) Thomas Lumley ### References Adapted from Luke Tierney's code for `XLISP-Stat`, in turn based on code from Robbins and Robbins “Practical UNIX Programming”. ### See Also `<close.socket>`, `<read.socket>`. Compiling in support for sockets was optional prior to **R** 3.3.0: see `[capabilities](../../base/html/capabilities)("sockets")` to see if it is available. ### Examples ``` daytime <- function(host = "localhost"){ a <- make.socket(host, 13) on.exit(close.socket(a)) read.socket(a) } ## Official time (UTC) from US Naval Observatory ## Not run: daytime("tick.usno.navy.mil") ``` r None `setRepositories` Select Package Repositories ---------------------------------------------- ### Description Interact with the user to choose the package repositories to be used. ### Usage ``` setRepositories(graphics = getOption("menu.graphics"), ind = NULL, addURLs = character()) ``` ### Arguments | | | | --- | --- | | `graphics` | Logical. If true, use a graphical list: on Windows or macOS GUI use a list box, and on a Unix-alike if tcltk and an X server are available, use Tk widget. Otherwise use a text `<menu>`. | | `ind` | `NULL` or a vector of integer indices, which have the same effect as if they were entered at the prompt for `graphics = FALSE`. | | `addURLs` | A character vector of additional URLs: it is often helpful to use a named vector. | ### Details The default list of known repositories is stored in the file ‘[R\_HOME](../../base/html/rhome)/etc/repositories’. That file can be edited for a site, or a user can have a personal copy in the file pointed to by the environment variable R\_REPOSITORIES, or if this is unset or does not exist, in ‘HOME/.R/repositories’, which will take precedence. A Bioconductor mirror can be selected by setting `[options](../../base/html/options)("BioC_mirror")`, e.g. via `[chooseBioCmirror](choosebiocmirror)` — the default value is "https://bioconductor.org". The items that are preselected are those that are currently in `options("repos")` plus those marked as default in the list of known repositories. The list of repositories offered depends on the setting of option `"pkgType"` as some repositories only offer a subset of types (e.g., only source packages or not macOS binary packages). Further, for binary packages some repositories (notably R-Forge) only offer packages for the current or recent versions of **R**. (Type `"both"` is equivalent to `"source"`.) Repository CRAN is treated specially: the value is taken from the current setting of `getOption("repos")` if this has an element `"CRAN"`: this ensures mirror selection is sticky. This function requires the **R** session to be interactive unless `ind` is supplied. ### Value This function is invoked mainly for its side effect of updating `options("repos")`. It returns (invisibly) the previous `repos` options setting (as a `[list](../../base/html/list)` with component `repos`) or `[NULL](../../base/html/null)` if no changes were applied. ### Note This does **not** set the list of repositories at startup: to do so set `[options](../../base/html/options)(repos =)` in a start up file (see help topic [Startup](../../base/html/startup)). ### See Also `[chooseCRANmirror](choosecranmirror)`, `[chooseBioCmirror](choosebiocmirror)`, `<install.packages>`. ### Examples ``` ## Not run: setRepositories(addURLs = c(CRANxtras = "https://www.stats.ox.ac.uk/pub/RWin")) ## End(Not run) ``` r None `process.events` Trigger Event Handling ---------------------------------------- ### Description R front ends like the Windows GUI handle key presses and mouse clicks through “events” generated by the OS. These are processed automatically by R at intervals during computations, but in some cases it may be desirable to trigger immediate event handling. The `process.events` function does that. ### Usage ``` process.events() ``` ### Details This is a simple wrapper for the C API function `R_ProcessEvents`. As such, it is possible that it will not return if the user has signalled to interrupt the calculation. ### Value `NULL` is returned invisibly. ### Author(s) Duncan Murdoch ### See Also See ‘Writing R Extensions’ and the ‘R for Windows FAQ’ for more discussion of the `R_ProcessEvents` function. r None `fix` Fix an Object -------------------- ### Description `fix` invokes `<edit>` on `x` and then assigns the new (edited) version of `x` in the user's workspace. ### Usage ``` fix(x, ...) ``` ### Arguments | | | | --- | --- | | `x` | the name of an **R** object, as a name or a character string. | | `...` | arguments to pass to editor: see `<edit>`. | ### Details The name supplied as `x` need not exist as an **R** object, in which case a function with no arguments and an empty body is supplied for editing. Editing an **R** object may change it in ways other than are obvious: see the comment under `<edit>`. See `<edit.data.frame>` for changes that can occur when editing a data frame or matrix. ### See Also `<edit>`, `<edit.data.frame>` ### Examples ``` ## Not run: ## Assume 'my.fun' is a user defined function : fix(my.fun) ## now my.fun is changed ## Also, fix(my.data.frame) # calls up data editor fix(my.data.frame, factor.mode="char") # use of ... ## End(Not run) ``` r None `memory.size` Report on Memory Allocation (on Windows) ------------------------------------------------------- ### Description On MS Windows, `memory.size()` reports the current or maximum memory allocation of the `malloc` function used in this version of **R**. `memory.limit()` reports or increases the limit in force on the total allocation. On non-Windows platforms these are stubs which report infinity (`[Inf](../../base/html/is.finite)`) with a warning. ### Usage ``` memory.size(max = FALSE) memory.limit(size = NA) ``` ### Arguments | | | | --- | --- | | `max` | logical. If `TRUE` the maximum amount of memory obtained from the OS is reported, if `FALSE` the amount currently in use, if `NA` the memory limit. | | `size` | numeric. If `NA` report the memory limit, otherwise request a new limit, in Mb. Only values of up to 4095 are allowed on 32-bit **R** builds, but see ‘Details’. | ### Details Command-line flag --max-mem-size sets the maximum value of obtainable memory (including a very small amount of housekeeping overhead). This cannot exceed 3Gb on 32-bit Windows, and most versions are limited to 2Gb. The minimum is currently 32Mb. If 32-bit **R** is run on most 64-bit versions of Windows the maximum value of obtainable memory is just under 4Gb. For a 64-bit versions of **R** under 64-bit Windows the limit is currently 8Tb. Memory limits can only be increased. Environment variable R\_MAX\_MEM\_SIZE provides another way to specify the initial limit. ### Value A number: On Windows, size in Mb (1048576 bytes), rounded to 0.01 Mb for `memory.size` and rounded down for `memory.limit`. On other platforms: `[Inf](../../base/html/is.finite)` always. ### Note These functions exist on all platforms, but on non-Windows always report infinity as **R** does itself provide limits on memory allocation—the OS's own facilities can be used. ### See Also [Memory-limits](../../base/html/memory-limits) for other limits. On Windows: The rw-FAQ for more details and references. ### Examples ``` if(.Platform$OS.type == "windows") withAutoprint({ memory.size() memory.size(TRUE) memory.limit() }) ``` r None `toLatex` Converting R Objects to BibTeX or LaTeX -------------------------------------------------- ### Description These methods convert **R** objects to character vectors with BibTeX or LaTeX markup. ### Usage ``` toBibtex(object, ...) toLatex(object, ...) ## S3 method for class 'Bibtex' print(x, prefix = "", ...) ## S3 method for class 'Latex' print(x, prefix = "", ...) ``` ### Arguments | | | | --- | --- | | `object` | object of a class for which a `toBibtex` or `toLatex` method exists. | | `x` | object of class `"Bibtex"` or `"Latex"`. | | `prefix` | a character string which is printed at the beginning of each line, mostly used to insert whitespace for indentation. | | `...` | in the print methods, passed to `[writeLines](../../base/html/writelines)`. | ### Details Objects of class `"Bibtex"` or `"Latex"` are simply character vectors where each element holds one line of the corresponding BibTeX or LaTeX file. ### See Also `[citEntry](citentry)` and `[sessionInfo](sessioninfo)` for examples r None `DLL.version` DLL Version Information on MS Windows ---------------------------------------------------- ### Description On MS Windows only, return the version of the package and the version of **R** used to build the DLL, if available. ### Usage ``` DLL.version(path) ``` ### Arguments | | | | --- | --- | | `path` | character vector of length one giving the complete path to the DLL. | ### Value If the DLL does not exist, `NULL`. A character vector of length two, giving the DLL version and the version of **R** used to build the DLL. If the information is not available, the corresponding string is empty. ### Note This is only available on Windows. ### Examples ``` if(.Platform$OS.type == "windows") withAutoprint({ DLL.version(file.path(R.home("bin"), "R.dll")) DLL.version(file.path(R.home(), "library/stats/libs", .Platform$r_arch, "stats.dll")) }) ``` r None `Rscript` Scripting Front-End for R ------------------------------------ ### Description This is an alternative front end for use in #! scripts and other scripting applications. ### Usage ``` Rscript [options] [-e expr [-e expr2 ...] | file] [args] ``` ### Arguments | | | | --- | --- | | `options` | a list of options, all beginning with --. These can be any of the options of the standard **R** front-end, and also those described in the details. | | `expr, expr2` | **R** expression(s), properly quoted. | | `file` | the name of a file containing **R** commands. - indicates ‘stdin’. | | `args` | arguments to be passed to the script in `file`. | ### Details `Rscript --help` gives details of usage, and `Rscript --version` gives the version of `Rscript`. Other invocations invoke the **R** front-end with selected options. This front-end is convenient for writing #! scripts since it is an executable and takes `file` directly as an argument. Options --no-echo --no-restore are always supplied: these imply --no-save. Arguments that contain spaces cannot be specified directly on the #! line, because spaces and tabs are interpreted as delimiters and there is no way to protect them from this interpretation on the #! line. (The standard Windows command line has no concept of #! scripts, but Cygwin shells do.) *Either* one or more -e options or `file` should be supplied. When using -e options be aware of the quoting rules in the shell used: see the examples. Additional options accepted (before `file` or `args`) are --verbose gives details of what `Rscript` is doing. Also passed on to **R**. --default-packages=list where `list` is a comma-separated list of package names or `NULL`. Sets the environment variable R\_DEFAULT\_PACKAGES which determines the packages loaded on startup. Spaces are allowed in `expression` and `file` (but will need to be protected from the shell in use, if any, for example by enclosing the argument in quotes). If --default-packages is not used, then `Rscript` checks the environment variable R\_SCRIPT\_DEFAULT\_PACKAGES. If this is set, then it takes precedence over R\_DEFAULT\_PACKAGES. Normally the version of **R** is determined at installation, but this can be overridden by setting the environment variable RHOME. `[stdin](../../base/html/showconnections)()` refers to the input file, and `[file](../../base/html/connections)("stdin")` to the `stdin` file stream of the process. ### Note `Rscript` is only supported on systems with the `execv` system call. ### Examples ``` ## Not run: Rscript -e 'date()' -e 'format(Sys.time(), "%a %b %d %X %Y")' # Get the same initial packages in the same order as default R: Rscript --default-packages=methods,datasets,utils,grDevices,graphics,stats -e 'sessionInfo()' ## example #! script for a Unix-alike #! /path/to/Rscript --vanilla --default-packages=utils args <- commandArgs(TRUE) res <- try(install.packages(args)) if(inherits(res, "try-error")) q(status=1) else q() ## End(Not run) ```
programming_docs
r None `getWindowsHandle` Get a Windows Handle ---------------------------------------- ### Description Get the Windows handle of a window or of the **R** process in MS Windows. ### Usage ``` getWindowsHandle(which = "Console") ``` ### Arguments | | | | --- | --- | | `which` | a string (see below), or the number of a graphics device window (which must a `[windows](../../grdevices/html/windows)` one). | ### Details `getWindowsHandle` gets the Windows handle. Possible choices for `which` are: | | | | --- | --- | | `"Console"` | The console window handle. | | `"Frame"` | The MDI frame window handle. | | `"Process"` | The process pseudo-handle. | | A device number | The window handle of a graphics device | These values are not normally useful to users, but may be used by developers making add-ons to **R**. `NULL` is returned for the Frame handle if not running in MDI mode, for the Console handle when running Rterm, for any unrecognized string for `which`, or for a graphics device with no corresponding window. Other windows (help browsers, etc.) are not accessible through this function. ### Value An external pointer holding the Windows handle, or `NULL`. ### Note This is only available on Windows. ### See Also `[getIdentification](setwindowtitle)`, `[getWindowsHandles](getwindowshandles)` ### Examples ``` if(.Platform$OS.type == "windows") print( getWindowsHandle() ) ``` r None `prompt` Produce Prototype of an R Documentation File ------------------------------------------------------ ### Description Facilitate the constructing of files documenting **R** objects. ### Usage ``` prompt(object, filename = NULL, name = NULL, ...) ## Default S3 method: prompt(object, filename = NULL, name = NULL, force.function = FALSE, ...) ## S3 method for class 'data.frame' prompt(object, filename = NULL, name = NULL, ...) promptImport(object, filename = NULL, name = NULL, importedFrom = NULL, importPage = name, ...) ``` ### Arguments | | | | --- | --- | | `object` | an **R** object, typically a function for the default method. Can be `[missing](../../base/html/missing)` when `name` is specified. | | `filename` | usually, a [connection](../../base/html/connections) or a character string giving the name of the file to which the documentation shell should be written. The default corresponds to a file whose name is `name` followed by `".Rd"`. Can also be `NA` (see below). | | `name` | a character string specifying the name of the object. | | `force.function` | a logical. If `TRUE`, treat `object` as function in any case. | | `...` | further arguments passed to or from other methods. | | `importedFrom` | a character string naming the package from which `object` was imported. Defaults to the environment of `object` if `object` is a function. | | `importPage` | a character string naming the help page in the package from which `object` was imported. | ### Details Unless `filename` is `NA`, a documentation shell for `object` is written to the file specified by `filename`, and a message about this is given. For function objects, this shell contains the proper function and argument names. R documentation files thus created still need to be edited and moved into the ‘man’ subdirectory of the package containing the object to be documented. If `filename` is `NA`, a list-style representation of the documentation shell is created and returned. Writing the shell to a file amounts to `cat(unlist(x), file = filename, sep = "\n")`, where `x` is the list-style representation. When `prompt` is used in `[for](../../base/html/control)` loops or scripts, the explicit `name` specification will be useful. The `importPage` argument for `promptImport` needs to give the base of the name of the help file of the original help page. For example, the `[approx](../../stats/html/approxfun)` function is documented in ‘approxfun.Rd’ in the stats package, so if it were imported and re-exported it should have `importPage = "approxfun"`. Objects that are imported from other packages are not normally documented unless re-exported. ### Value If `filename` is `NA`, a list-style representation of the documentation shell. Otherwise, the name of the file written to is returned invisibly. ### Warning The default filename may not be a valid filename under limited file systems (e.g., those on Windows). Currently, calling `prompt` on a non-function object assumes that the object is in fact a data set and hence documents it as such. This may change in future versions of **R**. Use `[promptData](promptdata)` to create documentation skeletons for data sets. ### Note The documentation file produced by `prompt.data.frame` does not have the same format as many of the data frame documentation files in the base package. We are trying to settle on a preferred format for the documentation. ### Author(s) Douglas Bates for `prompt.data.frame` ### References Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) *The New S Language*. Wadsworth & Brooks/Cole. ### See Also `[promptData](promptdata)`, `<help>` and the chapter on ‘Writing R documentation’ in ‘Writing R Extensions’ (see the ‘doc/manual’ subdirectory of the **R** source tree). For creation of many help pages (for a package), see `<package.skeleton>`. To prompt the user for input, see `[readline](../../base/html/readline)`. ### Examples ``` require(graphics) prompt(plot.default) prompt(interactive, force.function = TRUE) unlink("plot.default.Rd") unlink("interactive.Rd") prompt(women) # data.frame unlink("women.Rd") prompt(sunspots) # non-data.frame data unlink("sunspots.Rd") ## Not run: ## Create a help file for each function in the .GlobalEnv: for(f in ls()) if(is.function(get(f))) prompt(name = f) ## End(Not run) ``` r None `View` Invoke a Data Viewer ---------------------------- ### Description Invoke a spreadsheet-style data viewer on a matrix-like **R** object. ### Usage ``` View(x, title) ``` ### Arguments | | | | --- | --- | | `x` | an **R** object which can be coerced to a data frame with non-zero numbers of rows and columns. | | `title` | title for viewer window. Defaults to name of `x` prefixed by `Data:`. | ### Details Object `x` is coerced (if possible) to a data frame, then columns are converted to character using `[format.data.frame](../../base/html/format)`. The object is then viewed in a spreadsheet-like data viewer, a read-only version of `[data.entry](dataentry)`. If there are row names on the data frame that are not `1:nrow`, they are displayed in a separate first column called `row.names`. Objects with zero columns or zero rows are not accepted. On Unix-alikes, the array of cells can be navigated by the cursor keys and Home, End, Page Up and Page Down (where supported by X11) as well as Enter and Tab. On Windows, the array of cells can be navigated *via* the scrollbars and by the cursor keys, Home, End, Page Up and Page Down. On Windows, the initial size of the data viewer window is taken from the default dimensions of a pager (see `[Rconsole](rconsole)`), but adjusted downwards to show a whole number of rows and columns. ### Value Invisible `NULL`. The functions puts up a window and returns immediately: the window can be closed via its controls or menus. ### See Also `<edit.data.frame>`, `[data.entry](dataentry)`. r None `untar` Extract or List Tar Archives ------------------------------------- ### Description Extract files from or list the contents of a tar archive. ### Usage ``` untar(tarfile, files = NULL, list = FALSE, exdir = ".", compressed = NA, extras = NULL, verbose = FALSE, restore_times = TRUE, support_old_tars = Sys.getenv("R_SUPPORT_OLD_TARS", FALSE), tar = Sys.getenv("TAR")) ``` ### Arguments | | | | --- | --- | | `tarfile` | The pathname of the tar file: tilde expansion (see `[path.expand](../../base/html/path.expand)`) will be performed. Alternatively, a [connection](../../base/html/connections) that can be used for binary reads. For a *compressed* `tarfile`, and if a connection is to be used, that should be created by `[gzfile](../../base/html/connections)(.)` (or `[gzcon](../../base/html/gzcon)(.)` which currently only works for `"gzip"`, whereas `gzfile()` works for all compressions available in `<tar>()`). | | `files` | A character vector of recorded filepaths to be extracted: the default is to extract all files. | | `list` | If `TRUE`, list the files (the equivalent of `tar -tf`). Otherwise extract the files (the equivalent of `tar -xf`). | | `exdir` | The directory to extract files to (the equivalent of `tar -C`). It will be created if necessary. | | `compressed` | (Deprecated in favour of auto-detection, used only for an external `tar` command.) Logical or character string. Values `"gzip"`, `"bzip2"` and `"xz"` select that form of compression (and may be abbreviated to the first letter). `TRUE` indicates `gzip` compression, `FALSE` no known compression, and `NA` (the default) indicates that the type is to be inferred from the file header. The external command may ignore the selected compression type but detect a type automagically. | | `extras` | `NULL` or a character string: further command-line flags such as -p to be passed to an external `tar` program. | | `verbose` | logical: if true echo the command used for an external `tar` program. | | `restore_times` | logical. If true (default) restore file modification times. If false, the equivalent of the -m flag. Times in tarballs are supposed to be in UTC, but tarballs have been submitted to CRAN with times in the future or far past: this argument allows such times to be discarded. Note that file times in a tarball are stored with a resolution of 1 second, and can only be restored to the resolution supported by the file system (which on a FAT system is 2 seconds). | | | | | --- | --- | | `support_old_tars` | logical. If false (the default), the external `tar` command is assumed to be able handle compressed tarfiles and if `compressed` does not specify it, to automagically detect the type of compression. (The major implementations have done so since 2009; for GNU `tar` since version 1.22.) If true, the **R** code calls an appropriate decompressor and pipes the output to `tar`, for `compressed = NA` examining the tarfile header to determine the type of compression. | | `tar` | character string: the path to the command to be used or `"internal"`. If the command itself contains spaces it needs to be quoted – but `tar` can also contain flags separated from the command by spaces. | ### Details This is either a wrapper for a `tar` command or for an internal implementation written in **R**. The latter is used if `tarfile` is a connection or if the argument `tar` is `"internal"` or `""` (except on Windows, when `tar.exe` is tried first). Unless otherwise stated three types of compression of the tar file are supported: `gzip`, `bzip2` and `xz`. What options are supported will depend on the `tar` implementation used: the `"internal"` one is intended to provide support for most in a platform-independent way. GNU tar: Modern GNU `tar` versions support compressed archives and since 1.15 are able to detect the type of compression automatically: version 1.22 added support for `xz` compression. On a Unix-alike, `configure` will set environment variable TAR, preferring GNU tar if found. `bsdtar`: macOS 10.6 and later (and FreeBSD and some other OSes) have a `tar` from the libarchive project which detects all three forms of compression automagically (even if undocumented in macOS). NetBSD: It is undocumented if NetBSD's `tar` can detect compression automagically: for versions before 8 the flag for `xz` compression was --xz not -J. So `support_old_tars = TRUE` is recommended (or use `bsdtar` if installed). OpenBSD: OpenBSD's `tar` does not detect compression automagically. It has no support for `xz` beyond reporting that the file is `xz`-compressed. So `support_old_tars = TRUE` is recommended. Heirloom Toolchest: This `tar` does automagically detect `gzip` and `bzip2` compression (undocumented) but has no support for `xz` compression. Older support: Environment variable R\_GZIPCMD gives the command to decompress `gzip` files, and R\_BZIPCMD for `bzip2` files. (On Unix-alikes these are set at installation if found.) `xz` is used if available: if not decompression is expected to fail. Arguments `compressed`, `extras` and `verbose` are only used when an external `tar` is used. Some external `tar` commands will detect some of `lrzip`, `lzma`, `lz4`, `lzop` and `zstd` compression in addition to `gzip`, `bzip2` and `xz`. (For some external `tar` commands, compressed tarfiles can only be read if the appropriate utility program is available.) For GNU `tar`, further (de)compression programs can be specified by e.g. `extras = "-I lz4"`. For `bsdtar` this could be `extras = "--use-compress-program lz4"`. Most commands will detect (the nowadays rarely seen) ‘.tar.Z’ archives compressed by `compress`. The internal implementation restores symbolic links as links on a Unix-alike, and as file copies on Windows (which works only for existing files, not for directories), and hard links as links. If the linking operation fails (as it may on a FAT file system), a file copy is tried. Since it uses `[gzfile](../../base/html/connections)` to read a file it can handle files compressed by any of the methods that function can handle: at least `compress`, `gzip`, `bzip2` and `xz` compression, and some types of `lzma` compression. It does not guard against restoring absolute file paths, as some `tar` implementations do. It will create the parent directories for directories or files in the archive if necessary. It handles the USTAR/POSIX, GNU and `pax` ways of handling file paths of more than 100 bytes, and the GNU way of handling link targets of more than 100 bytes. You may see warnings from the internal implementation such as ``` unsupported entry type 'x' ``` This often indicates an invalid archive: entry types `"A-Z"` are allowed as extensions, but other types are reserved. The only thing you can do with such an archive is to find a `tar` program that handles it, and look carefully at the resulting files. There may also be the warning ``` using pax extended headers ``` This indicates that additional information may have been discarded, such as ACLs, encodings .... The former standards only supported ASCII filenames (indeed, only alphanumeric plus period, underscore and hyphen). `untar` makes no attempt to map filenames to those acceptable on the current system, and treats the filenames in the archive as applicable without any re-encoding in the current locale. The internal implementation does not special-case ‘resource forks’ in macOS: that system's `tar` command does. This may lead to unexpected files with names with prefix ‘.\_’. ### Value If `list = TRUE`, a character vector of (relative or absolute) paths of files contained in the tar archive. Otherwise the return code from `[system](../../base/html/system)` with an external `tar` or `0L`, invisibly. ### See Also `<tar>`, `<unzip>`. r None `bibentry` Bibliography Entries -------------------------------- ### Description Functionality for representing and manipulating bibliographic information in enhanced BibTeX style. ### Usage ``` bibentry(bibtype, textVersion = NULL, header = NULL, footer = NULL, key = NULL, ..., other = list(), mheader = NULL, mfooter = NULL) ## S3 method for class 'bibentry' print(x, style = "text", .bibstyle, ...) ## S3 method for class 'bibentry' format(x, style = "text", .bibstyle = NULL, citation.bibtex.max = getOption("citation.bibtex.max", 1), bibtex = length(x) <= citation.bibtex.max, sort = FALSE, macros = NULL, ...) ## S3 method for class 'bibentry' sort(x, decreasing = FALSE, .bibstyle = NULL, drop = FALSE, ...) ## S3 method for class 'citation' print(x, style = "citation", ...) ## S3 method for class 'citation' format(x, style = "citation", ...) ``` ### Arguments | | | | --- | --- | | `bibtype` | a character string with a BibTeX entry type. See **Entry Types** for details. | | `textVersion` | a character string with a text representation of the reference to optionally be employed for printing. It is recommended to leave this unspecified if `format(x, style = "text")` works correctly. Only if special LaTeX macros (e.g., math formatting) or special characters (e.g., with accents) are necessary, a `textVersion` should be provided. | | `header` | a character string with optional header text. | | `footer` | a character string with optional footer text. | | `key` | a character string giving the citation key for the entry. | | `...` | for `bibentry`: arguments of the form `tag=value` giving the fields of the entry, with tag and value the name and value of the field, respectively. Arguments with empty values are dropped. See **Entry Fields** for details. For the `print()` method, extra arguments to pass to the renderer which typically includes the `format()` method. For the `citation` class methods, arguments passed to the next method, i.e., the corresponding `bibentry` one. | | `other` | a list of arguments as in `...` (useful in particular for fields named the same as formals of `bibentry`). | | `mheader` | a character string with optional “outer” header text. | | `mfooter` | a character string with optional “outer” footer text. | | `x` | an object inheriting from class `"bibentry"`. | | `style` | an optional character string specifying the print style. If present, must be a unique abbreviation (with case ignored) of the available styles, see **Details**. | | `decreasing` | logical, passed to `[order](../../base/html/order)` indicating the sort direction. | | `.bibstyle` | a character string naming a bibliography style. | | `citation.bibtex.max` | (*deprecated*, use `bibtex = T|F` instead!) a number, say *m*, indicating that the bibtex code should be given in addition to the formatted tex *when* there are not more than *m* entries. The default is taken as `[getOption](../../base/html/options)("citation.bibtex.max", 1)` which is `1` typically. For example, to see no bibtex at all, you can change the default by `[options](../../base/html/options)(citation.bibtex.max = 0)`. | | `bibtex` | logical indicating if bibtex code should be given additionally; currently applies only to `style = "citation"`. The default depends on on the number of (bib) entries and `[getOption](../../base/html/options)("citation.bibtex.max")`. | | `sort` | logical indicating if bibentries should be sorted, using `[bibstyle](../../tools/html/bibstyle)(.bibstyle)$sortKeys(x)`. | | `macros` | a character string or an object with already loaded Rd macros, see **Details**. | | `drop` | logical used as `x[ ..., drop=drop]` inside the `sort()` method. | ### Details The bibentry objects created by `bibentry` can represent an arbitrary positive number of references. One can use `c()` to combine bibentry objects, and hence in particular build a multiple reference object from single reference ones. Alternatively, one can use `bibentry` to directly create a multiple reference object by “vectorizing” the given arguments, i.e., use character vectors instead of character strings. The `[print](../../base/html/print)` method for bibentry objects provides a choice between seven different styles: plain text (style `"text"`), BibTeX (`"Bibtex"`), a mixture of plain text and BibTeX as traditionally used for citations (`"citation"`), HTML (`"html"`), LaTeX (`"latex"`), R code (`"R"`), and a simple copy of the `textVersion` elements (style `"textVersion"`). The `"text"`, `"html"` and `"latex"` styles make use of the `.bibstyle` argument using the `[bibstyle](../../tools/html/bibstyle)` function. In addition, one can use the `macros` argument to provide additional (otherwise unknown, presumably LaTeX-style) Rd macros, either by giving the path to a file with Rd macros to be loaded via `[loadRdMacros](../../tools/html/loadrdmacros)`, or an object with macros already loaded. When printing bibentry objects in citation style, a `header`/`footer` for each item can be displayed as well as a `mheader`/`mfooter` for the whole vector of references. The `[print](../../base/html/print)` method is based on a `[format](../../base/html/format)` method which provides the same styles, and for formatting as R code a choice between giving a character vector with one `bibentry()` call for each bibentry (as commonly used in ‘CITATION’ files), or a character string with one collapsed call, obtained by combining the individual calls with `c()` if there is more than one bibentry. This can be controlled by setting the option `collapse` to `FALSE` (default) or `TRUE`, respectively. (Printing in R style always collapses to a single call.) Further, for the `"citation"` style, `format()`'s optional argument `citation.bibtex.max` (with default `[getOption](../../base/html/options)("citation.bibtex.max")` which defaults to 1) determines for up to how many citation bibentries text style is shown together with bibtex, automatically. It is possible to subscript bibentry objects by their keys (which are used for character subscripts if the names are `NULL`). There is also a `[toBibtex](tolatex)` method for direct conversion to BibTeX. ### Value `bibentry` produces an object of class `"bibentry"`. ### Entry Types `bibentry` creates `"bibentry"` objects, which are modeled after BibTeX entries. The entry should be a valid BibTeX entry type, e.g., Article: An article from a journal or magazine. Book: A book with an explicit publisher. InBook: A part of a book, which may be a chapter (or section or whatever) and/or a range of pages. InCollection: A part of a book having its own title. InProceedings: An article in a conference proceedings. Manual: Technical documentation like a software manual. MastersThesis: A Master's thesis. Misc: Use this type when nothing else fits. PhdThesis: A PhD thesis. Proceedings: The proceedings of a conference. TechReport: A report published by a school or other institution, usually numbered within a series. Unpublished: A document having an author and title, but not formally published. ### Entry Fields The `...` argument of `bibentry` can be any number of BibTeX fields, including address: The address of the publisher or other type of institution. author: The name(s) of the author(s), either as a `<person>` object, or as a character string which `[as.person](person)` correctly coerces to such. booktitle: Title of a book, part of which is being cited. chapter: A chapter (or section or whatever) number. doi: The DOI (<https://en.wikipedia.org/wiki/Digital_Object_Identifier>) for the reference. editor: Name(s) of editor(s), same format as `author`. institution: The publishing institution of a technical report. journal: A journal name. note: Any additional information that can help the reader. The first word should be capitalized. number: The number of a journal, magazine, technical report, or of a work in a series. pages: One or more page numbers or range of numbers. publisher: The publisher's name. school: The name of the school where a thesis was written. series: The name of a series or set of books. title: The work's title. url: A URL for the reference. (If the URL is an expanded DOI, we recommend to use the doi field with the unexpanded DOI instead.) volume: The volume of a journal or multi-volume book. year: The year of publication. ### See Also `<person>` ### Examples ``` ## R reference rref <- bibentry( bibtype = "Manual", title = "R: A Language and Environment for Statistical Computing", author = person("R Core Team"), organization = "R Foundation for Statistical Computing", address = "Vienna, Austria", year = 2014, url = "https://www.R-project.org/") ## Different printing styles print(rref) print(rref, style = "Bibtex") print(rref, style = "citation") print(rref, style = "html") print(rref, style = "latex") print(rref, style = "R") ## References for boot package and associated book bref <- c( bibentry( bibtype = "Manual", title = "boot: Bootstrap R (S-PLUS) Functions", author = c( person("Angelo", "Canty", role = "aut", comment = "S original"), person(c("Brian", "D."), "Ripley", role = c("aut", "trl", "cre"), comment = "R port, author of parallel support", email = "[email protected]") ), year = "2012", note = "R package version 1.3-4", url = "https://CRAN.R-project.org/package=boot", key = "boot-package" ), bibentry( bibtype = "Book", title = "Bootstrap Methods and Their Applications", author = as.person("Anthony C. Davison [aut], David V. Hinkley [aut]"), year = "1997", publisher = "Cambridge University Press", address = "Cambridge", isbn = "0-521-57391-2", url = "http://statwww.epfl.ch/davison/BMA/", key = "boot-book" ) ) ## Combining and subsetting c(rref, bref) bref[2] bref["boot-book"] ## Extracting fields bref$author bref[1]$author bref[1]$author[2]$email ## Convert to BibTeX toBibtex(bref) ## Format in R style ## One bibentry() call for each bibentry: writeLines(paste(format(bref, "R"), collapse = "\n\n")) ## One collapsed call: writeLines(format(bref, "R", collapse = TRUE)) ```
programming_docs
r None `txtProgressBar` Text Progress Bar ----------------------------------- ### Description Text progress bar in the **R** console. ### Usage ``` txtProgressBar(min = 0, max = 1, initial = 0, char = "=", width = NA, title, label, style = 1, file = "") getTxtProgressBar(pb) setTxtProgressBar(pb, value, title = NULL, label = NULL) ## S3 method for class 'txtProgressBar' close(con, ...) ``` ### Arguments | | | | --- | --- | | `min, max` | (finite) numeric values for the extremes of the progress bar. Must have `min < max`. | | `initial, value` | initial or new value for the progress bar. See ‘Details’ for what happens with invalid values. | | `char` | the character (or character string) to form the progress bar. | | `width` | the width of the progress bar, as a multiple of the width of `char`. If `NA`, the default, the number of characters is that which fits into `getOption("width")`. | | `style` | the ‘style’ of the bar – see ‘Details’. | | `file` | an open connection object or `""` which indicates the console: `[stderr](../../base/html/showconnections)()` might be useful here. | | `pb, con` | an object of class `"txtProgressBar"`. | | `title, label` | ignored, for compatibility with other progress bars. | | `...` | for consistency with the generic. | ### Details `txtProgressBar` will display a progress bar on the **R** console (or a connection) via a text representation. `setTxtProgessBar` will update the value. Missing (`[NA](../../base/html/na)`) and out-of-range values of `value` will be (silently) ignored. (Such values of `initial` cause the progress bar not to be displayed until a valid value is set.) The progress bar should be `close`d when finished with: this outputs the final newline character. `style = 1` and `style = 2` just shows a line of `char`. They differ in that `style = 2` redraws the line each time, which is useful if other code might be writing to the **R** console. `style = 3` marks the end of the range by `|` and gives a percentage to the right of the bar. ### Value For `txtProgressBar` an object of class `"txtProgressBar"`. For `getTxtProgressBar` and `setTxtProgressBar`, a length-one numeric vector giving the previous value (invisibly for `setTxtProgressBar`). ### Note Using `style` 2 or 3 or reducing the value with `style = 1` uses \r to return to the left margin – the interpretation of carriage return is up to the terminal or console in which **R** is running, and this is liable to produce ugly output on a connection other than a terminal, including when `stdout()` is redirected to a file. ### See Also `[winProgressBar](winprogressbar)` (Windows only), `[tkProgressBar](../../tcltk/html/tkprogressbar)` (Unix-alike platforms). ### Examples ``` # slow testit <- function(x = sort(runif(20)), ...) { pb <- txtProgressBar(...) for(i in c(0, x, 1)) {Sys.sleep(0.5); setTxtProgressBar(pb, i)} Sys.sleep(1) close(pb) } testit() testit(runif(10)) testit(style = 3) ``` r None `modifyList` Recursively Modify Elements of a List --------------------------------------------------- ### Description Modifies a possibly nested list recursively by changing a subset of elements at each level to match a second list. ### Usage ``` modifyList(x, val, keep.null = FALSE) ``` ### Arguments | | | | --- | --- | | `x` | A named `[list](../../base/html/list)`, possibly empty. | | `val` | A named list with components to replace corresponding components in `x`. | | `keep.null` | If `TRUE`, `NULL` elements in `val` become `NULL` elements in `x`. Otherwise, the corresponding element, if present, is deleted from `x`. | ### Value A modified version of `x`, with the modifications determined as follows (here, list elements are identified by their names). Elements in `val` which are missing from `x` are added to `x`. For elements that are common to both but are not both lists themselves, the component in `x` is replaced (or possibly deleted, depending on the value of `keep.null`) by the one in `val`. For common elements that are in both lists, `x[[name]]` is replaced by `modifyList(x[[name]], val[[name]])`. ### Author(s) Deepayan Sarkar [[email protected]](mailto:[email protected]) ### Examples ``` foo <- list(a = 1, b = list(c = "a", d = FALSE)) bar <- modifyList(foo, list(e = 2, b = list(d = TRUE))) str(foo) str(bar) ``` r None `SweaveSyntConv` Convert Sweave Syntax --------------------------------------- ### Description This function converts the syntax of files in `[Sweave](sweave)` format to another Sweave syntax definition. ### Usage ``` SweaveSyntConv(file, syntax, output = NULL) ``` ### Arguments | | | | --- | --- | | `file` | Name of Sweave source file. | | `syntax` | An object of class `SweaveSyntax` or a character string with its name giving the target syntax to which the file is converted. | | `output` | Name of output file, default is to remove the extension from the input file and to add the default extension of the target syntax. Any directory names in `file` are also removed such that the output is created in the current working directory. | ### Author(s) Friedrich Leisch ### See Also ‘Sweave User Manual’, a vignette in the utils package. `[RweaveLatex](rweavelatex)`, `[Rtangle](rtangle)` ### Examples ``` testfile <- system.file("Sweave", "Sweave-test-1.Rnw", package = "utils") ## convert the file to latex syntax SweaveSyntConv(testfile, SweaveSyntaxLatex) ## and run it through Sweave Sweave("Sweave-test-1.Stex") ``` r None `winProgressBar` Progress Bars under MS Windows ------------------------------------------------ ### Description Put up a Windows progress bar widget, update and access it. ### Usage ``` winProgressBar(title = "R progress bar", label = "", min = 0, max = 1, initial = 0, width = 300) getWinProgressBar(pb) setWinProgressBar(pb, value, title = NULL, label = NULL) ## S3 method for class 'winProgressBar' close(con, ...) ``` ### Arguments | | | | --- | --- | | `title, label` | character strings, giving the window title and the label on the dialog box respectively. | | `min, max` | (finite) numeric values for the extremes of the progress bar. | | `initial, value` | initial or new value for the progress bar. | | `width` | the width of the progress bar in pixels: the dialog box will be 40 pixels wider (plus frame). | | `pb, con` | an object of class `"winProgressBar"`. | | `...` | for consistency with the generic. | ### Details `winProgressBar` will display a progress bar centred on the screen. Space will be allocated for the label only if it is non-empty. `setWinProgessBar` will update the value and for non-`NULL` values, the title and label (provided there was one when the widget was created). Missing (`[NA](../../base/html/na)`) and out-of-range values of `value` will be (silently) ignored. The progress bar should be `close`d when finished with, but it will be garbage-collected once no **R** object refers to it. ### Value For `winProgressBar` an object of class `"winProgressBar"`. For `getWinProgressBar` and `setWinProgressBar`, a length-one numeric vector giving the previous value (invisibly for `setWinProgressBar`). ### Note These functions are only available on Windows. ### See Also On all platforms, `[txtProgressBar](txtprogressbar)`, `[tkProgressBar](../../tcltk/html/tkprogressbar)` ### Examples ``` pb <- winProgressBar("test progress bar", "Some information in %", 0, 100, 50) Sys.sleep(0.5) u <- c(0, sort(runif(20, 0, 100)), 100) for(i in u) { Sys.sleep(0.1) info <- sprintf("%d%% done", round(i)) setWinProgressBar(pb, i, sprintf("test (%s)", info), info) } Sys.sleep(5) close(pb) ``` r None `Rtangle` R Driver for Stangle ------------------------------- ### Description A driver for `[Stangle](sweave)` that extracts **R** code chunks. Notably all `RtangleSetup()` arguments may be used as arguments in the `[Stangle](sweave)()` call. ### Usage ``` Rtangle() RtangleSetup(file, syntax, output = NULL, annotate = TRUE, split = FALSE, quiet = FALSE, drop.evalFALSE = FALSE, ...) ``` ### Arguments | | | | --- | --- | | `file` | name of Sweave source file. See the description of the corresponding argument of `[Sweave](sweave)`. | | `syntax` | an object of class `SweaveSyntax`. | | `output` | name of output file used unless `split = TRUE`: see ‘Details’. | | `annotate` | a logical or `[function](../../base/html/function)`. When true, as by default, code chunks are separated by comment lines specifying the names and line numbers of the code chunks. If `FALSE` the decorating comments are omitted. Alternatively, `annotate` may be a function, see section ‘Chunk annotation’. | | `split` | split output into a file for each code chunk? | | `quiet` | logical to suppress all progress messages. | | `drop.evalFALSE` | logical; When false, as by default, all chunks with option `eval = FALSE` are *commented out* in the output; otherwise (`drop.evalFALSE = TRUE`) they are omitted entirely. | | `...` | additional named arguments setting defaults for further options listed in ‘Supported Options’. | ### Details Unless `split = TRUE`, the default name of the output file is `basename(file)` with an extension corresponding to the Sweave syntax (e.g., ‘Rnw’, ‘Stex’) replaced by ‘R’. File names `"stdout"` and `"stderr"` are interpreted as the output and message connection respectively. If splitting is selected (including by the options in the file), each chunk is written to a separate file with extension the name of the ‘engine’ (default ‘.R’). Note that this driver does more than simply extract the code chunks verbatim, because chunks may re-use earlier chunks. ### Chunk annotation (`annotate`) By default `annotate = TRUE`, the annotation is of one of the forms ``` ################################################### ### code chunk number 3: viewport ################################################### ################################################### ### code chunk number 18: grid.Rnw:647-648 ################################################### ################################################### ### code chunk number 19: trellisdata (eval = FALSE) ################################################### ``` using either the chunk label (if present, i.e., when specified in the source) or the file name and line numbers. `annotate` may be a function with formal arguments `(options, chunk, output)`, e.g. to produce less dominant chunk annotations; see `Rtangle()$runcode` how it is called instead of the default. ### Supported Options `Rtangle` supports the following options for code chunks (the values in parentheses show the default values): engine: character string (`"R"`). Only chunks with `engine` equal to `"R"` or `"S"` are processed. keep.source: logical (`TRUE`). If `keep.source == TRUE` the original source is copied to the file. Otherwise, deparsed source is output. eval: logical (`TRUE`). If `FALSE`, the code chunk is copied across but commented out. prefix Used if `split = TRUE`. See `prefix.string`. prefix.string: a character string, default is the name of the source file (without extension). Used if `split = TRUE` as the prefix for the filename if the chunk has no label, or if it has a label and `prefix = TRUE`. Note that this is used as part of filenames, so needs to be portable. show.line.nos logical (`FALSE`). Should the output be annotated with comments showing the line number of the first code line of the chunk? ### Author(s) Friedrich Leisch and R-core. ### See Also ‘Sweave User Manual’, a vignette in the utils package. `[Sweave](sweave)`, `[RweaveLatex](rweavelatex)` ### Examples ``` nmRnw <- "example-1.Rnw" exfile <- system.file("Sweave", nmRnw, package = "utils") ## Create R source file Stangle(exfile) nmR <- sub("Rnw$", "R", nmRnw) # the (default) R output file name if(interactive()) file.show("example-1.R") ## Smaller R source file with custom annotation: my.Ann <- function(options, chunk, output) { cat("### chunk #", options$chunknr, ": ", if(!is.null(ol <- options$label)) ol else .RtangleCodeLabel(chunk), if(!options$eval) " (eval = FALSE)", "\n", file = output, sep = "") } Stangle(exfile, annotate = my.Ann) if(interactive()) file.show("example-1.R") Stangle(exfile, annotate = my.Ann, drop.evalFALSE=TRUE) if(interactive()) file.show("example-1.R") ``` r None `head` Return the First or Last Parts of an Object --------------------------------------------------- ### Description Returns the first or last parts of a vector, matrix, table, data frame or function. Since `head()` and `tail()` are generic functions, they may also have been extended to other classes. ### Usage ``` head(x, ...) ## Default S3 method: head(x, n = 6L, ...) ## S3 method for class 'matrix' head(x, n = 6L, ...) # is exported as head.matrix() ## NB: The methods for 'data.frame' and 'array' are identical to the 'matrix' one ## S3 method for class 'ftable' head(x, n = 6L, ...) ## S3 method for class 'function' head(x, n = 6L, ...) tail(x, ...) ## Default S3 method: tail(x, n = 6L, keepnums = FALSE, addrownums, ...) ## S3 method for class 'matrix' tail(x, n = 6L, keepnums = TRUE, addrownums, ...) # exported as tail.matrix() ## NB: The methods for 'data.frame', 'array', and 'table' ## are identical to the 'matrix' one ## S3 method for class 'ftable' tail(x, n = 6L, keepnums = FALSE, addrownums, ...) ## S3 method for class 'function' tail(x, n = 6L, ...) ``` ### Arguments | | | | --- | --- | | `x` | an object | | `n` | an integer vector of length up to `dim(x)` (or 1, for non-dimensioned objects). Values specify the indices to be selected in the corresponding dimension (or along the length) of the object. A positive value of `n[i]` includes the first/last `n[i]` indices in that dimension, while a negative value excludes the last/first `abs(n[i])`, including all remaining indices. `NA` or non-specified values (when `length(n) < length(dim(x))`) select all indices in that dimension. Must contain at least one non-missing value. | | `keepnums` | in each dimension, if no names in that dimension are present, create them using the indices included in that dimension. Ignored if `dim(x)` is `NULL` or its length 1. | | `addrownums` | deprecated - `keepnums` should be used instead. Taken as the value of `keepnums` if it is explicitly set when `keepnums` is not. | | `...` | arguments to be passed to or from other methods. | ### Details For vector/array based objects, `head()` (`tail()`) returns a subset of the same dimensionality as `x`, usually of the same class. For historical reasons, by default they select the first (last) 6 indices in the first dimension ("rows") or along the length of a non-dimensioned vector, and the full extent (all indices) in any remaining dimensions. `head.matrix()` and `tail.matrix()` are exported. The default and array(/matrix) methods for `head()` and `tail()` are quite general. They will work as is for any class which has a `dim()` method, a `length()` method (only required if `dim()` returns `NULL`), and a `[` method (that accepts the `drop` argument and can subset in all dimensions in the dimensioned case). For functions, the lines of the deparsed function are returned as character strings. When `x` is an array(/matrix) of dimensionality two and more, `tail()` will add dimnames similar to how they would appear in a full printing of `x` for all dimensions `k` where `n[k]` is specified and non-missing and `dimnames(x)[[k]]` (or `dimnames(x)` itself) is `NULL`. Specifically, the form of the added dimnames will vary for different dimensions as follows: `k=1` (rows): `"[n,]"` (right justified with whitespace padding) `k=2` (columns): `"[,n]"` (with *no* whitespace padding) `k>2` (higher dims): `"n"`, i.e., the indices as *character* values Setting `keepnums = FALSE` suppresses this behaviour. As `[data.frame](../../base/html/data.frame)` subsetting (‘indexing’) keeps `[attributes](../../base/html/attributes)`, so do the `head()` and `tail()` methods for data frames. ### Value An object (usually) like `x` but generally smaller. Hence, for `[array](../../base/html/array)`s, the result corresponds to `x[.., drop=FALSE]`. For `[ftable](../../stats/html/ftable)` objects `x`, a transformed `format(x)`. ### Note For array inputs the output of `tail` when `keepnums` is `TRUE`, any dimnames vectors added for dimensions `>2` are the original numeric indices in that dimension *as character vectors*. This means that, e.g., for 3-dimensional array `arr`, `tail(arr, c(2,2,-1))[ , , 2]` and `tail(arr, c(2,2,-1))[ , , "2"]` may both be valid but have completely different meanings. ### Author(s) Patrick Burns, improved and corrected by R-Core. Negative argument added by Vincent Goulet. Multi-dimension support added by Gabriel Becker. ### Examples ``` head(letters) head(letters, n = -6L) head(freeny.x, n = 10L) head(freeny.y) head(iris3) head(iris3, c(6L, 2L)) head(iris3, c(6L, -1L, 2L)) tail(letters) tail(letters, n = -6L) tail(freeny.x) ## the bottom-right "corner" : tail(freeny.x, n = c(4, 2)) tail(freeny.y) tail(iris3) tail(iris3, c(6L, 2L)) tail(iris3, c(6L, -1L, 2L)) ## iris with dimnames stripped a3d <- iris3 ; dimnames(a3d) <- NULL tail(a3d, c(6, -1, 2)) # keepnums = TRUE is default here! tail(a3d, c(6, -1, 2), keepnums = FALSE) ## data frame w/ a (non-standard) attribute: treeS <- structure(trees, foo = "bar") (n <- nrow(treeS)) stopifnot(exprs = { # attribute is kept identical(htS <- head(treeS), treeS[1:6, ]) identical(attr(htS, "foo") , "bar") identical(tlS <- tail(treeS), treeS[(n-5):n, ]) ## BUT if I use "useAttrib(.)", this is *not* ok, when n is of length 2: ## --- because [i,j]-indexing of data frames *also* drops "other" attributes .. identical(tail(treeS, 3:2), treeS[(n-2):n, 2:3] ) }) tail(library) # last lines of function head(stats::ftable(Titanic)) ## 1d-array (with named dim) : a1 <- array(1:7, 7); names(dim(a1)) <- "O2" stopifnot(exprs = { identical( tail(a1, 10), a1) identical( head(a1, 10), a1) identical( head(a1, 1), a1 [1 , drop=FALSE] ) # was a1[1] in R <= 3.6.x identical( tail(a1, 2), a1[6:7]) identical( tail(a1, 1), a1 [7 , drop=FALSE] ) # was a1[7] in R <= 3.6.x }) ``` r None `RSiteSearch` Search for Key Words or Phrases in Documentation --------------------------------------------------------------- ### Description Search for key words or phrases in help pages, vignettes or task views, using the search engine at <http://search.r-project.org> and view them in a web browser. ### Usage ``` RSiteSearch(string, restrict = c("functions", "vignettes", "views"), format = c("normal", "short"), sortby = c("score", "date:late", "date:early", "subject", "subject:descending", "from", "from:descending", "size", "size:descending"), matchesPerPage = 20) ``` ### Arguments | | | | --- | --- | | `string` | A character string specifying word(s) or a phrase to search. If the words are to be searched as one entity, enclose all words in braces (see the first example). | | `restrict` | a character vector, typically of length greater than one. Values can be abbreviated. Possible areas to search in: `functions` for help pages, `views` for task views and `vignettes` for package vignettes. | | `format` | `normal` or `short` (no excerpts); can be abbreviated. | | `sortby` | character string (can be abbreviated) indicating how to sort the search results: (`score`, `date:late` for sorting by date with latest results first, `date:early` for earliest first, `subject` for subject in alphabetical order, `subject:descending` for reverse alphabetical order, `from` or `from:descending` for sender (when applicable), `size` or `size:descending` for size.) | | `matchesPerPage` | How many items to show per page. | ### Details This function is designed to work with the search site at <http://search.r-project.org>, and depends on that site continuing to be made available (thanks to Jonathan Baron and the School of Arts and Sciences of the University of Pennsylvania). Unique partial matches will work for all arguments. Each new browser window will stay open unless you close it. ### Value (Invisibly) the complete URL passed to the browser, including the query string. ### Author(s) Andy Liaw and Jonathan Baron ### See Also `<help.search>`, `<help.start>` for local searches. `[browseURL](browseurl)` for how the help file is displayed. ### Examples ``` # need Internet connection RSiteSearch("{logistic regression}") # matches exact phrase Sys.sleep(5) # allow browser to open, take a quick look ## Search in vignettes and store the query-string: fullquery <- RSiteSearch("lattice", restrict = "vignettes") fullquery # a string of ~ 110 characters ```
programming_docs
r None `rcompgen` A Completion Generator for R ---------------------------------------- ### Description This page documents a mechanism to generate relevant completions from a partially completed command line. It is not intended to be useful by itself, but rather in conjunction with other mechanisms that use it as a backend. The functions listed in the usage section provide a simple control and query mechanism. The actual interface consists of a few unexported functions described further down. ### Usage ``` rc.settings(ops, ns, args, dots, func, ipck, S3, data, help, argdb, fuzzy, quotes, files) rc.status() rc.getOption(name) rc.options(...) .DollarNames(x, pattern) ## Default S3 method: .DollarNames(x, pattern = "") ## S3 method for class 'list' .DollarNames(x, pattern = "") ## S3 method for class 'environment' .DollarNames(x, pattern = "") ``` ### Arguments | | | | --- | --- | | `ops, ns, args, dots, func, ipck, S3, data, help, argdb, fuzzy, quotes, files` | logical, turning some optional completion features on and off. `ops`: Activates completion after the `$` and `@` operators. `ns`: Controls namespace related completions. `args`: Enables completion of function arguments. `dots`: If disabled, drops `...` from list of function arguments. Relevant only if `args` is enabled. `func`: Enables detection of functions. If enabled, a customizable extension (`"("` by default) is appended to function names. The process of determining whether a potential completion is a function requires evaluation, including for lazy loaded symbols. This is undesirable for large objects, because of potentially wasteful use of memory in addition to the time overhead associated with loading. For this reason, this feature is disabled by default. `S3`: When `args = TRUE`, activates completion on arguments of all S3 methods (otherwise just the generic, which usually has very few arguments). `ipck`: Enables completion of installed package names inside `[library](../../base/html/library)` and `[require](../../base/html/library)`. `data`: Enables completion of data sets (including those already visible) inside `<data>`. `help`: Enables completion of help requests starting with a question mark, by looking inside help index files. `argdb`: When `args = TRUE`, completion is attempted on function arguments. Generally, the list of valid arguments is determined by dynamic calls to `[args](../../base/html/args)`. While this gives results that are technically correct, the use of the `...` argument often hides some useful arguments. To give more flexibility in this regard, an optional table of valid arguments names for specific functions is retained internally. Setting `argdb = TRUE` enables preferential lookup in this internal data base for functions with an entry in it. Of course, this is useful only when the data base contains information about the function of interest. Some functions are already included, and more can be added by the user through the unexported function `.addFunctionInfo` (see below). `fuzzy`: Enables fuzzy matching, where close but non-exact matches (e.g., with different case) are considered if no exact matches are found. This feature is experimental and the details can change. `quotes`: Enables completion in **R** code when inside quotes. This normally leads to filename completion, but can be otherwise depending on context (for example, when the open quote is preceded by `?`), help completion is invoked. Setting this to `FALSE` relegates completion to the underlying completion front-end, which may do its own processing (for example, `readline` on Unix-alikes will do filename completion). `files`: Deprecated. Use `quotes` instead. All settings are turned on by default except `ipck`, `func`, and `fuzzy`. Turn more off if your CPU cycles are valuable; you will still retain basic completion on names of objects in the search list. See below for additional details. | | `name, ...` | user-settable options. Currently valid names are `function.suffix`: default `"("` `funarg.suffix`: default `" = "` `package.suffix` default `"::"` Usage is similar to that of `[options](../../base/html/options)`. | | `x` | An R object for which valid names after `"$"` are computed and returned. | | `pattern` | A regular expression. Only matching names are returned. | ### Details There are several types of completion, some of which can be disabled using `rc.settings`. The most basic level, which can not be turned off once the completion functionality is activated, provides completion on names visible on the search path, along with a few special keywords (e.g., `TRUE`). This type of completion is not attempted if the partial ‘word’ (a.k.a. token) being completed is empty (since there would be too many completions). The more advanced types of completion are described below. **Completion after extractors `$` and `@`**: When the `ops` setting is turned on, completion after `$` and `@` is attempted. This requires the prefix to be evaluated, which is attempted unless it involves an explicit function call (implicit function calls involving the use of `[`, `$`, etc *do not* inhibit evaluation). Valid completions after the `$` extractor are determined by the generic function `.DollarNames`. Some basic methods are provided, and more can be written for custom classes. **Completion inside namespaces**: When the `ns` setting is turned on, completion inside namespaces is attempted when a token is preceded by the `::` or `:::` operators. Additionally, the basic completion mechanism is extended to include all loaded namespaces, i.e., `foopkg::` becomes a valid completion of `foo` if `"foopkg"` is a loaded namespace. The completion of package namespaces applies only to already loaded namespaces, i.e. if `MASS` is not loaded, `MAS` will not complete to `MASS::`. However, attempted completion *inside* an apparent namespace will attempt to load the namespace if it is not already loaded, e.g. trying to complete on `MASS::fr` will load `MASS` if it is not already loaded. **Completion for help items**: When the `help` setting is turned on, completion on help topics is attempted when a token is preceded by `?`. Prefixes (such as `class`, `method`) are supported, as well as quoted help topics containing special characters. **Completion of function arguments**: When the `args` setting is turned on, completion on function arguments is attempted whenever deemed appropriate. The mechanism used will currently fail if the relevant function (at the point where completion is requested) was entered on a previous prompt (which implies in particular that the current line is being typed in response to a continuation prompt, usually `+`). Note that separation by newlines is fine. The list of possible argument completions that is generated can be misleading. There is no problem for non-generic functions (except that `...` is listed as a completion; this is intentional as it signals the fact that the function can accept further arguments). However, for generic functions, it is practically impossible to give a reliable argument list without evaluating arguments (and not even then, in some cases), which is risky (in addition to being difficult to code, which is the real reason it hasn't even been tried), especially when that argument is itself an inline function call. Our compromise is to consider arguments of *all* currently available methods of that generic. This has two drawbacks. First, not all listed completions may be appropriate in the call currently being constructed. Second, for generics with many methods (like `print` and `plot`), many matches will need to be considered, which may take a noticeable amount of time. Despite these drawbacks, we believe this behaviour to be more useful than the only other practical alternative, which is to list arguments of the generic only. Only S3 methods are currently supported in this fashion, and that can be turned off using the `S3` setting. Since arguments can be unnamed in **R** function calls, other types of completion are also appropriate whenever argument completion is. Since there are usually many many more visible objects than formal arguments of any particular function, possible argument completions are often buried in a bunch of other possibilities. However, recall that basic completion is suppressed for blank tokens. This can be useful to list possible arguments of a function. For example, trying to complete `seq([TAB]` and `seq(from = 1, [TAB])` will both list only the arguments of `seq` (or any of its methods), whereas trying to complete `seq(length[TAB]` will list both the `length.out` argument and the `length(` function as possible completions. Note that no attempt is made to remove arguments already supplied, as that would incur a further speed penalty. **Special functions**: For a few special functions (`[library](../../base/html/library)`, `<data>`, etc), the first argument is treated specially, in the sense that normal completion is suppressed, and some function specific completions are enabled if so requested by the settings. The `ipck` setting, which controls whether `[library](../../base/html/library)` and `[require](../../base/html/library)` will complete on *installed packages*, is disabled by default because the first call to `<installed.packages>` is potentially time consuming (e.g., when packages are installed on a remote network file server). Note, however, that the results of a call to `<installed.packages>` is cached, so subsequent calls are usually fast, so turning this option on is not particularly onerous even in such situations. ### Value If `rc.settings` is called without any arguments, it returns the current settings as a named logical vector. Otherwise, it returns `NULL` invisibly. `rc.status` returns, as a list, the contents of an internal (unexported) environment that is used to record the results of the last completion attempt. This can be useful for debugging. For such use, one must resist the temptation to use completion when typing the call to `rc.status` itself, as that then becomes the last attempt by the time the call is executed. The items of primary interest in the returned list are: | | | | --- | --- | | `comps` | The possible completions generated by the last call to `.completeToken`, as a character vector. | | `token` | The token that was (or, is to be) completed, as set by the last call to `.assignToken` (possibly inside a call to `.guessTokenFromLine`). | | `linebuffer` | The full line, as set by the last call to `.assignLinebuffer`. | | `start` | The start position of the token in the line buffer, as set by the last call to `.assignStart`. | | `end` | The end position of the token in the line buffer, as set by the last call to `.assignEnd`. | | `fileName` | Logical, indicating whether the cursor is currently inside quotes. | | `fguess` | The name of the function the cursor is currently inside. | | `isFirstArg` | Logical. If cursor is inside a function, is it the first argument? | In addition, the components `settings` and `options` give the current values of settings and options respectively. `rc.getOption` and `rc.options` behave much like `[getOption](../../base/html/options)` and `[options](../../base/html/options)` respectively. ### Unexported API There are several unexported functions in the package. Of these, a few are special because they provide the API through which other mechanisms can make use of the facilities provided by this package (they are unexported because they are not meant to be called directly by users). The usage of these functions are: ``` .assignToken(text) .assignLinebuffer(line) .assignStart(start) .assignEnd(end) .completeToken() .retrieveCompletions() .getFileComp() .guessTokenFromLine() .win32consoleCompletion(linebuffer, cursorPosition, check.repeat = TRUE, minlength = -1) .addFunctionInfo(...) ``` The first four functions set up a completion attempt by specifying the token to be completed (`text`), and indicating where (`start` and `end`, which should be integers) the token is placed within the complete line typed so far (`line`). Potential completions of the token are generated by `.completeToken`, and the completions can be retrieved as an **R** character vector using `.retrieveCompletions`. It is possible for the user to specify a replacement for this function by setting `rc.options("custom.completer")`; if not `NULL`, this function is called to compute potential completions. This facility is meant to help in situations where completing as R code is not appropriate. See source code for more details. If the cursor is inside quotes, completion may be suppressed. The function `.getFileComp` can be used after a call to `.completeToken` to determine if this is the case (returns `TRUE`), and alternative completions generated as deemed useful. In most cases, filename completion is a reasonable fallback. The `.guessTokenFromLine` function is provided for use with backends that do not already break a line into tokens. It requires the linebuffer and endpoint (cursor position) to be already set, and itself sets the token and the start position. It returns the token as a character string. The `.win32consoleCompletion` is similar in spirit, but is more geared towards the Windows GUI (or rather, any front-end that has no completion facilities of its own). It requires the linebuffer and cursor position as arguments, and returns a list with three components, `addition`, `possible` and `comps`. If there is an unambiguous extension at the current position, `addition` contains the additional text that should be inserted at the cursor. If there is more than one possibility, these are available either as a character vector of preformatted strings in `possible`, or as a single string in `comps`. `possible` consists of lines formatted using the current `width` option, so that printing them on the console one line at a time will be a reasonable way to list them. `comps` is a space separated (collapsed) list of the same completions, in case the front-end wishes to display it in some other fashion. The `minlength` argument can be used to suppress completion when the token is too short (which can be useful if the front-end is set up to try completion on every keypress). If `check.repeat` is `TRUE`, it is detected if the same completion is being requested more than once in a row, and ambiguous completions are returned only in that case. This is an attempt to emulate GNU Readline behaviour, where a single TAB completes up to any unambiguous part, and multiple possibilities are reported only on two consecutive TABs. As the various front-end interfaces evolve, the details of these functions are likely to change as well. The function `.addFunctionInfo` can be used to add information about the permitted argument names for specific functions. Multiple named arguments are allowed in calls to it, where the tags are names of functions and values are character vectors representing valid arguments. When the `argdb` setting is `TRUE`, these are used as a source of valid argument names for the relevant functions. ### Note If you are uncomfortable with unsolicited evaluation of pieces of code, you should set `ops = FALSE`. Otherwise, trying to complete `foo@ba` will evaluate `foo`, trying to complete `foo[i, 1:10]$ba` will evaluate `foo[i, 1:10]`, etc. This should not be too bad, as explicit function calls (involving parentheses) are not evaluated in this manner. However, this *will* affect promises and lazy loaded symbols. ### Author(s) Deepayan Sarkar, [[email protected]](mailto:[email protected]) r None `citation` Citing R and R Packages in Publications --------------------------------------------------- ### Description How to cite **R** and **R** packages in publications. ### Usage ``` citation(package = "base", lib.loc = NULL, auto = NULL) readCitationFile(file, meta = NULL) ``` ### Arguments | | | | --- | --- | | `package` | a character string with the name of a single package. An error occurs if more than one package name is given. | | `lib.loc` | a character vector with path names of **R** libraries, or the directory containing the source for `package`, or `NULL`. The default value of `NULL` corresponds to all libraries currently known. If the default is used, the loaded packages are searched before the libraries. | | `auto` | a logical indicating whether the default citation auto-generated from the package ‘DESCRIPTION’ metadata should be used or not, or `NULL` (default), indicating that a ‘CITATION’ file is used if it exists, or an object of class `"[packageDescription](packagedescription)"` with package metadata (see below). | | `file` | a file name. | | `meta` | a list of package metadata as obtained by `[packageDescription](packagedescription)`, or `NULL` (the default). | ### Details The **R** core development team and the very active community of package authors have invested a lot of time and effort in creating **R** as it is today. Please give credit where credit is due and cite **R** and **R** packages when you use them for data analysis. Execute function `citation()` for information on how to cite the base R system in publications. If the name of a non-base package is given, the function either returns the information contained in the ‘CITATION’ file of the package (using `readCitationFile` with `meta` equal to `packageDescription(package, lib.loc)`) or auto-generates citation information from the ‘DESCRIPTION’ file. In **R** >= 2.14.0, one can use a Authors@R field in ‘DESCRIPTION’ to provide (**R** code giving) a `<person>` object with a refined, machine-readable description of the package “authors” (in particular specifying their precise roles). Only those with an author role will be included in the auto-generated citation. If only one reference is given, the print method for the object returned by `citation()` shows both a text version and a BibTeX entry for it, if a package has more than one reference then only the text versions are shown. The BibTeX versions can be obtained using function `toBibtex()` (see the examples below). The ‘CITATION’ file of an R package should be placed in the ‘inst’ subdirectory of the package source. The file is an R source file and may contain arbitrary R commands including conditionals and computations. Function `readCitationFile()` is used by `citation()` to extract the information in ‘CITATION’ files. The file is `source()`ed by the R parser in a temporary environment and all resulting bibliographic objects (specifically, of class `"<bibentry>"`) are collected. Traditionally, the ‘CITATION’ file contained zero or more calls to `citHeader`, then one or more calls to `[citEntry](citentry)`, and finally zero or more calls to `citFooter`, where in fact `citHeader` and `citFooter` are simply wrappers to `[paste](../../base/html/paste)`, with their `...` argument passed on to `[paste](../../base/html/paste)` as is. The `"<bibentry>"` class makes for improved representation and manipulation of bibliographic information (in fact, the old mechanism is implemented using the new one), and one can write ‘CITATION’ files using the unified `<bibentry>` interface. One can include an auto-generated package citation in the ‘CITATION’ file via `citation(auto = meta)`. `readCitationFile` makes use of the `Encoding` element (if any) of `meta` to determine the encoding of the file. ### Value An object of class `"citation"`, inheriting from class `"<bibentry>"`; see there, notably for the `[print](../../base/html/print)` and `[format](../../base/html/format)` methods. ### See Also `<bibentry>` ### Examples ``` ## the basic R reference citation() ## references for a package -- might not have these installed if(nchar(system.file(package = "lattice"))) citation("lattice") if(nchar(system.file(package = "foreign"))) citation("foreign") ## extract the bibtex entry from the return value x <- citation() toBibtex(x) ## A citation with more than one bibentry: cm <- tryCatch(citation("mgcv"), error = function(e) { warning("Recommended package 'mgcv' is not installed properly") stop(e$message) }) cm # short entries (2-3 lines each) print(cm, bibtex = TRUE) # each showing its bibtex code ```
programming_docs
r None `winextras` Get Windows Version -------------------------------- ### Description Get the self-reported Microsoft Windows version number. ### Usage ``` win.version() ``` ### Details `win.version` is an auxiliary function for `[sessionInfo](sessioninfo)` and `<bug.report>`. ### Value A character string describing the version of Windows reported to be in use. ### Note This function is only available on Microsoft Windows. The result is based on the Windows `GetVersionEx` API function, which for recent versions of Windows reports the compatibility version, and not necessarily the actual version (hence 8.1 and 10 may be reported as 8). If the API call reports 8, this function returns `>= 8`. ### Examples ``` if(.Platform$OS.type == "windows") print(win.version()) ``` r None `object.size` Report the Space Allocated for an Object ------------------------------------------------------- ### Description Provides an estimate of the memory that is being used to store an **R** object. ### Usage ``` object.size(x) ## S3 method for class 'object_size' format(x, units = "b", standard = "auto", digits = 1L, ...) ## S3 method for class 'object_size' print(x, quote = FALSE, units = "b", standard = "auto", digits = 1L, ...) ``` ### Arguments | | | | --- | --- | | `x` | an **R** object. | | `quote` | logical, indicating whether or not the result should be printed with surrounding quotes. | | `units` | the units to be used in formatting and printing the size. Allowed values for the different `standard`s are `standard = "legacy"`: `"b"`, `"Kb"`, `"Mb"`, `"Gb"`, `"Tb"`, `"Pb"`, `"B"`, `"KB"`, `"MB"`, `"GB"`, `"TB"` and `"PB"`. `standard = "IEC"`: `"B"`, `"KiB"`, `"MiB"`, `"GiB"`, `"TiB"`, `"PiB"`, `"EiB"`, `"ZiB"` and `"YiB"`. `standard = "SI"`: `"B"`, `"kB"`, `"MB"`, `"GB"`, `"TB"`, `"PB"`, `"EB"`, `"ZB"` and `"YB"`. For all standards, `unit = "auto"` is also allowed. If `standard = "auto"`, any of the "legacy" and IEC units are allowed. See ‘Formatting and printing object sizes’ for details. | | `standard` | the byte-size unit standard to be used. A character string, possibly abbreviated from `"legacy"`, `"IEC"`, `"SI"` and `"auto"`. See ‘Formatting and printing object sizes’ for details. | | `digits` | the number of digits after the decimal point, passed to `[round](../../base/html/round)`. | | `...` | arguments to be passed to or from other methods. | ### Details Exactly which parts of the memory allocation should be attributed to which object is not clear-cut. This function merely provides a rough indication: it should be reasonably accurate for atomic vectors, but does not detect if elements of a list are shared, for example. (Sharing amongst elements of a character vector is taken into account, but not that between character vectors in a single object.) The calculation is of the size of the object, and excludes the space needed to store its name in the symbol table. Associated space (e.g., the environment of a function and what the pointer in a `EXTPTRSXP` points to) is not included in the calculation. Object sizes are larger on 64-bit builds than 32-bit ones, but will very likely be the same on different platforms with the same word length and pointer size. Sizes of objects using a compact internal representation may be over-estimated. ### Value An object of class `"object_size"` with a length-one double value, an estimate of the memory allocation attributable to the object in bytes. ### Formatting and printing object sizes Object sizes can be formatted using byte-size units from **R**'s legacy standard, the IEC standard, or the SI standard. As illustrated by below tables, the legacy and IEC standards use *binary* units (multiples of 1024), whereas the SI standard uses *decimal* units (multiples of 1000). For methods `format` and `print`, argument `standard` specifies which standard to use and argument `units` specifies which byte-size unit to use. `units = "auto"` chooses the largest units in which the result is one or more (before rounding). Byte sizes are rounded to `digits` decimal places. `standard = "auto"` chooses the standard based on `units`, if possible, otherwise, the legacy standard is used. Summary of **R**'s legacy and IEC units: | | | | | --- | --- | --- | | **object size** | **legacy** | **IEC** | | 1 | 1 bytes | 1 B | | 1024 | 1 Kb | 1 KiB | | 1024^2 | 1 Mb | 1 MiB | | 1024^3 | 1 Gb | 1 GiB | | 1024^4 | 1 Tb | 1 TiB | | 1024^5 | 1 Pb | 1 PiB | | 1024^6 | | 1 EiB | | 1024^7 | | 1 ZiB | | 1024^8 | | 1 YiB | | | Summary of SI units: | | | | --- | --- | | **object size** | **SI** | | 1 | 1 B | | 1000 | 1 kB | | 1000^2 | 1 MB | | 1000^3 | 1 GB | | 1000^4 | 1 TB | | 1000^5 | 1 PB | | 1000^6 | 1 EB | | 1000^7 | 1 ZB | | 1000^8 | 1 YB | | | ### Author(s) R Core; Henrik Bengtsson for the non-legacy `standard`s. ### References The wikipedia page, <https://en.wikipedia.org/wiki/Binary_prefix>, is extensive on the different standards, usages and their history. ### See Also `[Memory-limits](../../base/html/memory-limits)` for the design limitations on object size. ### Examples ``` object.size(letters) object.size(ls) format(object.size(library), units = "auto") sl <- object.size(rep(letters, 1000)) print(sl) ## 209288 bytes print(sl, units = "auto") ## 204.4 Kb print(sl, units = "auto", standard = "IEC") ## 204.4 KiB print(sl, units = "auto", standard = "SI") ## 209.3 kB (fsl <- sapply(c("Kb", "KB", "KiB"), function(u) format(sl, units = u))) stopifnot(identical( ## assert that all three are the same : unique(substr(as.vector(fsl), 1,5)), format(round(as.vector(sl)/1024, 1)))) ## find the 10 largest objects in the base package z <- sapply(ls("package:base"), function(x) object.size(get(x, envir = baseenv()))) if(interactive()) { as.matrix(rev(sort(z))[1:10]) } else # (more constant over time): names(rev(sort(z))[1:10]) ``` r None `file.edit` Edit One or More Files ----------------------------------- ### Description Edit one or more files in a text editor. ### Usage ``` file.edit(..., title = file, editor = getOption("editor"), fileEncoding = "") ``` ### Arguments | | | | --- | --- | | `...` | one or more character vectors containing the names of the files to be displayed. These will be tilde-expanded: see `[path.expand](../../base/html/path.expand)`. | | `title` | the title to use in the editor; defaults to the filename. | | `editor` | the text editor to be used, usually as a character string naming (or giving the path to) the text editor you want to use See ‘Details’. | | `fileEncoding` | the encoding to assume for the file: the default is to assume the native encoding. See the ‘Encoding’ section of the help for `[file](../../base/html/connections)`. | ### Details The behaviour of this function is very system-dependent. Currently files can be opened only one at a time on Unix; on Windows, the internal editor allows multiple files to be opened, but has a limit of 50 simultaneous edit windows. The `title` argument is used for the window caption in Windows, and is currently ignored on other platforms. Any error in re-encoding the files to the native encoding will cause the function to fail. The default for `editor` is system-dependent. On Windows it defaults to `"internal"`, the script editor, and in the macOS GUI the document editor is used whatever the value of `editor`. On Unix the default is set from the environment variables EDITOR or VISUAL if either is set, otherwise `vi` is used. `editor` can also be an **R** function, in which case it is called with the arguments `name`, `file`, and `title`. Note that such a function will need to independently implement all desired functionality. On Windows, UTF-8-encoded paths not valid in the current locale can be used. ### See Also `[files](../../base/html/files)`, `[file.show](../../base/html/file.show)`, `<edit>`, `<fix>`, ### Examples ``` ## Not run: # open two R scripts for editing file.edit("script1.R", "script2.R") ## End(Not run) ``` r None `roman` Roman Numerals ----------------------- ### Description Simple manipulation of (a small set of) integer numbers as roman numerals. ### Usage ``` as.roman(x) .romans r1 + r2 r1 <= r2 max(r1) sum(r2) ``` ### Arguments | | | | --- | --- | | `x` | a numeric or character vector of arabic or roman numerals. | | `r1, r2` | a roman number vector, i.e., of `[class](../../base/html/class)` `"roman"`. | ### Details `as.roman` creates objects of class `"roman"` which are internally represented as integers, and have suitable methods for printing, formatting, subsetting, coercion, etc, see `<methods>(class = "roman")`. Arithmetic (`"[Arith](../../methods/html/s4groupgeneric)"`), Comparison (`"[Compare](../../methods/html/s4groupgeneric)"`) and (`"[Logic](../../methods/html/s4groupgeneric)"`), i.e., all `"[Ops](../../methods/html/s4groupgeneric)"` group operations work as for regular numbers via **R**'s integer functionality. Only numbers between 1 and 3899 have a unique representation as roman numbers, and hence others result in `as.roman(NA)`. `.romans` is the basic dictionary, a named `[character](../../base/html/character)` vector. ### References Wikipedia contributors (2006). Roman numerals. Wikipedia, The Free Encyclopedia. <https://en.wikipedia.org/w/index.php?title=Roman_numerals&oldid=78252134>. Accessed September 29, 2006. ### Examples ``` ## First five roman 'numbers'. (y <- as.roman(1 : 5)) ## Middle one. y[3] ## Current year as a roman number. (y <- as.roman(format(Sys.Date(), "%Y"))) ## Today, and 10, 20, 30, and 100 years ago ... y - 10*c(0:3,10) ## mixture of arabic and roman numbers : as.roman(c(NA, 1:3, "", strrep("I", 1:6))) # + NA with a warning for "IIIIII" cc <- c(NA, 1:3, strrep("I", 0:5)) (rc <- as.roman(cc)) # two NAs: 0 is not "roman" (ic <- as.integer(rc)) # works automatically [without an explicit method] rNA <- as.roman(NA) ## simple consistency checks -- arithmetic when result is in {1,2,..,3899} : stopifnot(identical(rc, as.roman(rc)), # as.roman(.) is "idempotent" identical(rc + rc + (3*rc), rc*5), identical(ic, c(NA, 1:3, NA, 1:5)), identical(as.integer(5*rc), 5L*ic), identical(as.numeric(rc), as.numeric(ic)), identical(rc[1], rNA), identical(as.roman(0), rNA), identical(as.roman(NA_character_), rNA), identical(as.list(rc), as.list(ic))) ## Non-Arithmetic 'Ops' : stopifnot(exprs = { # Comparisons : identical(ic < 1:5, rc < 1:5) identical(ic < 1:5, rc < as.roman(1:5)) # Logic [integers |-> logical] : identical(rc & TRUE , ic & TRUE) identical(rc & FALSE, ic & FALSE) identical(rc | FALSE, ic | FALSE) identical(rc | NA , ic | NA) }) ## 'Summary' group functions (and comparison): (rc. <- rc[!is.na(rc)]) stopifnot(exprs = { identical(min(rc), as.roman(NA)) identical(min(rc, na.rm=TRUE), as.roman(min(ic, na.rm=TRUE))) identical(range(rc.), as.roman(range(as.integer(rc.)))) identical(sum (rc, na.rm=TRUE), as.roman("XXI")) identical(format(prod(rc, na.rm=TRUE)), "DCCXX") format(prod(rc.)) == "DCCXX" }) ``` r None `relist` Allow Re-Listing an unlist()ed Object ----------------------------------------------- ### Description `relist()` is an S3 generic function with a few methods in order to allow easy inversion of `[unlist](../../base/html/unlist)(obj)` when that is used with an object `obj` of (S3) class `"relistable"`. ### Usage ``` relist(flesh, skeleton) ## Default S3 method: relist(flesh, skeleton = attr(flesh, "skeleton")) ## S3 method for class 'factor' relist(flesh, skeleton = attr(flesh, "skeleton")) ## S3 method for class 'list' relist(flesh, skeleton = attr(flesh, "skeleton")) ## S3 method for class 'matrix' relist(flesh, skeleton = attr(flesh, "skeleton")) as.relistable(x) is.relistable(x) ## S3 method for class 'relistable' unlist(x, recursive = TRUE, use.names = TRUE) ``` ### Arguments | | | | --- | --- | | `flesh` | a vector to be relisted | | `skeleton` | a list, the structure of which determines the structure of the result | | `x` | an **R** object, typically a list (or vector). | | `recursive` | logical. Should unlisting be applied to list components of `x`? | | `use.names` | logical. Should names be preserved? | ### Details Some functions need many parameters, which are most easily represented in complex structures, e.g., nested lists. Unfortunately, many mathematical functions in **R**, including `[optim](../../stats/html/optim)` and `[nlm](../../stats/html/nlm)` can only operate on functions whose domain is a vector. **R** has `[unlist](../../base/html/unlist)()` to convert nested list objects into a vector representation. `relist()`, its methods and the functionality mentioned here provide the inverse operation to convert vectors back to the convenient structural representation. This allows structured functions (such as `optim()`) to have simple mathematical interfaces. For example, a likelihood function for a multivariate normal model needs a variance-covariance matrix and a mean vector. It would be most convenient to represent it as a list containing a vector and a matrix. A typical parameter might look like ``` list(mean = c(0, 1), vcov = cbind(c(1, 1), c(1, 0))). ``` However, `[optim](../../stats/html/optim)` cannot operate on functions that take lists as input; it only likes numeric vectors. The solution is conversion. Given a function `mvdnorm(x, mean, vcov, log = FALSE)` which computes the required probability density, then ``` ipar <- list(mean = c(0, 1), vcov = c bind(c(1, 1), c(1, 0))) initial.param <- as.relistable(ipar) ll <- function(param.vector) { param <- relist(param.vector, skeleton = ipar) -sum(mvdnorm(x, mean = param$mean, vcov = param$vcov, log = TRUE)) } optim(unlist(initial.param), ll) ``` `relist` takes two parameters: skeleton and flesh. Skeleton is a sample object that has the right `shape` but the wrong content. `flesh` is a vector with the right content but the wrong shape. Invoking ``` relist(flesh, skeleton) ``` will put the content of flesh on the skeleton. You don't need to specify skeleton explicitly if the skeleton is stored as an attribute inside flesh. In particular, if flesh was created from some object obj with `unlist(as.relistable(obj))` then the skeleton attribute is automatically set. (Note that this does not apply to the example here, as `[optim](../../stats/html/optim)` is creating a new vector to pass to `ll` and not its `par` argument.) As long as `skeleton` has the right shape, it should be a precise inverse of `[unlist](../../base/html/unlist)`. These equalities hold: ``` relist(unlist(x), x) == x unlist(relist(y, skeleton)) == y x <- as.relistable(x) relist(unlist(x)) == x ``` ### Value an object of (S3) class `"relistable"` (and `"[list](../../base/html/list)"`). ### Author(s) R Core, based on a code proposal by Andrew Clausen. ### See Also `[unlist](../../base/html/unlist)` ### Examples ``` ipar <- list(mean = c(0, 1), vcov = cbind(c(1, 1), c(1, 0))) initial.param <- as.relistable(ipar) ul <- unlist(initial.param) relist(ul) stopifnot(identical(relist(ul), initial.param)) ``` r None `packageStatus` Package Management Tools ----------------------------------------- ### Description Summarize information about installed packages and packages available at various repositories, and automatically upgrade outdated packages. ### Usage ``` packageStatus(lib.loc = NULL, repositories = NULL, method, type = getOption("pkgType"), ...) ## S3 method for class 'packageStatus' summary(object, ...) ## S3 method for class 'packageStatus' update(object, lib.loc = levels(object$inst$LibPath), repositories = levels(object$avail$Repository), ...) ## S3 method for class 'packageStatus' upgrade(object, ask = TRUE, ...) ``` ### Arguments | | | | --- | --- | | `lib.loc` | a character vector describing the location of **R** library trees to search through, or `NULL`. The default value of `NULL` corresponds to all libraries currently known. | | `repositories` | a character vector of URLs describing the location of **R** package repositories on the Internet or on the local machine. If specified as `NULL`, derive appropriate URLs from [option](../../base/html/options) `"repos"`. | | `method` | Download method, see `<download.file>`. | | `type` | type of package distribution: see `<install.packages>`. | | `object` | an object of class `"packageStatus"` as returned by `packageStatus`. | | `ask` | if `TRUE`, the user is prompted which packages should be upgraded and which not. | | `...` | for `packageStatus`: arguments to be passed to `<available.packages>` and `<installed.packages>`. for the `upgrade` method, arguments to be passed to `<install.packages>` for other methods: currently not used. | ### Details The URLs in `repositories` should be full paths to the appropriate contrib sections of the repositories. The default is `contrib.url(getOption("repos"))`. There are `print` and `summary` methods for the `"packageStatus"` objects: the `print` method gives a brief tabular summary and the `summary` method prints the results. The `update` method updates the `"packageStatus"` object. The `upgrade` method is similar to `<update.packages>`: it offers to install the current versions of those packages which are not currently up-to-date. ### Value An object of class `"packageStatus"`. This is a list with two components | | | | --- | --- | | `inst` | a data frame with columns as the *matrix* returned by `<installed.packages>` plus `"Status"`, a factor with levels `c("ok", "upgrade", "unavailable")`. Only the newest version of each package is reported, in the first repository in which it appears. | | `avail` | a data frame with columns as the *matrix* returned by `<available.packages>` plus `"Status"`, a factor with levels `c("installed", "not installed")`. | For the `summary` method the result is also of class `"summary.packageStatus"` with additional components | | | | --- | --- | | `Libs` | a list with one element for each library | | `Repos` | a list with one element for each repository | with the elements being lists of character vectors of package name for each status. ### See Also `<installed.packages>`, `<available.packages>` ### Examples ``` ## Not run: x <- packageStatus() print(x) summary(x) upgrade(x) x <- update(x) print(x) ## End(Not run) ``` r None `citEntry` Bibliography Entries (Older Interface) -------------------------------------------------- ### Description Functionality for specifying bibliographic information in enhanced BibTeX style. ### Usage ``` citEntry(entry, textVersion, header = NULL, footer = NULL, ...) citHeader(...) citFooter(...) ``` ### Arguments | | | | --- | --- | | `entry` | a character string with a BibTeX entry type. See section **Entry Types** in `<bibentry>` for details. | | `textVersion` | a character string with a text representation of the reference. | | `header` | a character string with optional header text. | | `footer` | a character string with optional footer text. | | `...` | for `citEntry`, arguments of the form `tag=value` giving the fields of the entry, with tag and value the name and value of the field, respectively. See section **Entry Fields** in `<bibentry>` for details. For `citHeader` and `citFooter`, character strings. | ### Value `citEntry` produces an object of class `"bibentry"`. ### See Also `<citation>` for more information about citing R and R packages and ‘CITATION’ files; `<bibentry>` for the newer functionality for representing and manipulating bibliographic information.
programming_docs
r None `getParseData` Get Detailed Parse Information from Object ---------------------------------------------------------- ### Description If the `"keep.source"` option is `TRUE`, **R**'s parser will attach detailed information on the object it has parsed. These functions retrieve that information. ### Usage ``` getParseData(x, includeText = NA) getParseText(parseData, id) ``` ### Arguments | | | | --- | --- | | `x` | an expression returned from `[parse](../../base/html/parse)`, or a function or other object with source reference information | | `includeText` | logical; whether to include the text of parsed items in the result | | `parseData` | a data frame returned from `getParseData` | | `id` | a vector of item identifiers whose text is to be retrieved | ### Details In version 3.0.0, the **R** parser was modified to include code written by Romain Francois in his parser package. This constructs a detailed table of information about every token and higher level construct in parsed code. This table is stored in the `[srcfile](../../base/html/srcfile)` record associated with source references in the parsed code, and retrieved by the `getParseData` function. ### Value For `getParseData`: If parse data is not present, `NULL`. Otherwise a data frame is returned, containing the following columns: | | | | --- | --- | | `line1` | integer. The line number where the item starts. This is the parsed line number called `"parse"` in `[getSrcLocation](sourceutils)`, which ignores `#line` directives. | | `col1` | integer. The column number where the item starts. The first character is column 1. This corresponds to `"column"` in `[getSrcLocation](sourceutils)`. | | `line2` | integer. The line number where the item ends. | | `col2` | integer. The column number where the item ends. | | `id` | integer. An identifier associated with this item. | | `parent` | integer. The `id` of the parent of this item. | | `token` | character string. The type of the token. | | `terminal` | logical. Whether the token is “terminal”, i.e. a leaf in the parse tree. | | `text` | character string. If `includeText` is `TRUE`, the text of all tokens; if it is `NA` (the default), the text of terminal tokens. If `includeText == FALSE`, this column is not included. Very long strings (with source of 1000 characters or more) will not be stored; a message giving their length and delimiter will be included instead. | The rownames of the data frame will be equal to the `id` values, and the data frame will have a `"srcfile"` attribute containing the `[srcfile](../../base/html/srcfile)` record which was used. The rows will be ordered by starting position within the source file, with parent items occurring before their children. For `getParseText`: A character vector of the same length as `id` containing the associated text items. If they are not included in `parseData`, they will be retrieved from the original file. ### Note There are a number of differences in the results returned by `getParseData` relative to those in the original parser code: * Fewer columns are kept. * The internal token number is not returned. * `col1` starts counting at 1, not 0. * The `id` values are not attached to the elements of the parse tree, they are only retained in the table returned by `getParseData`. * `#line` directives are identified, but other comment markup (e.g., [roxygen](https://CRAN.R-project.org/package=roxygen) comments) are not. ### Author(s) Duncan Murdoch ### References Romain Francois (2012). parser: Detailed R source code parser. R package version 0.0-16. <https://github.com/halpo/parser>. ### See Also `[parse](../../base/html/parse)`, `[srcref](../../base/html/srcfile)` ### Examples ``` fn <- function(x) { x + 1 # A comment, kept as part of the source } d <- getParseData(fn) if (!is.null(d)) { plus <- which(d$token == "'+'") sum <- d$parent[plus] print(d[as.character(sum),]) print(getParseText(d, sum)) } ``` r None `contrib.url` Find Appropriate Paths in CRAN-like Repositories --------------------------------------------------------------- ### Description `contrib.url` adds the appropriate type-specific path within a repository to each URL in `repos`. ### Usage ``` contrib.url(repos, type = getOption("pkgType")) ``` ### Arguments | | | | --- | --- | | `repos` | character vector, the base URL(s) of the repositories to use. | | `type` | character string, indicating which type of packages: see `<install.packages>`. | ### Details If `type = "both"` this will use the source repository. ### Value A character vector of the same length as `repos`. ### See Also `[setRepositories](setrepositories)` to set `[options](../../base/html/options)("repos")`, the most common value used for argument `repos`. `<available.packages>`, `<download.packages>`, `<install.packages>`. The ‘R Installation and Administration’ manual for how to set up a repository. r None `demo` Demonstrations of R Functionality ----------------------------------------- ### Description `demo` is a user-friendly interface to running some demonstration **R** scripts. `demo()` gives the list of available topics. ### Usage ``` demo(topic, package = NULL, lib.loc = NULL, character.only = FALSE, verbose = getOption("verbose"), echo = TRUE, ask = getOption("demo.ask"), encoding = getOption("encoding")) ``` ### Arguments | | | | --- | --- | | `topic` | the topic which should be demonstrated, given as a [name](../../base/html/name) or literal character string, or a character string, depending on whether `character.only` is `FALSE` (default) or `TRUE`. If omitted, the list of available topics is displayed. | | `package` | a character vector giving the packages to look into for demos, or `NULL`. By default, all packages in the search path are used. | | `lib.loc` | a character vector of directory names of **R** libraries, or `NULL`. The default value of `NULL` corresponds to all libraries currently known. If the default is used, the loaded packages are searched before the libraries. | | `character.only` | logical; if `TRUE`, use `topic` as character string. | | `verbose` | a logical. If `TRUE`, additional diagnostics are printed. | | `echo` | a logical. If `TRUE`, show the **R** input when sourcing. | | `ask` | a logical (or `"default"`) indicating if `[devAskNewPage](../../grdevices/html/devasknewpage)(ask = TRUE)` should be called before graphical output happens from the demo code. The value `"default"` (the factory-fresh default) means to ask if `echo == TRUE` and the graphics device appears to be interactive. This parameter applies both to any currently opened device and to any devices opened by the demo code. If this is evaluated to `TRUE` and the session is [interactive](../../base/html/interactive), the user is asked to press RETURN to start. | | `encoding` | See `[source](../../base/html/source)`. If the package has a declared encoding, that takes preference. | ### Details If no topics are given, `demo` lists the available demos. The corresponding information is returned in an object of class `"packageIQR"`. ### See Also `[source](../../base/html/source)` and `[devAskNewPage](../../grdevices/html/devasknewpage)` which are called by `demo`. ### Examples ``` demo() # for attached packages ## All available demos: demo(package = .packages(all.available = TRUE)) ## Display a demo, pausing between pages demo(lm.glm, package = "stats", ask = TRUE) ## Display it without pausing demo(lm.glm, package = "stats", ask = FALSE) ## Not run: ch <- "scoping" demo(ch, character = TRUE) ## End(Not run) ## Find the location of a demo system.file("demo", "lm.glm.R", package = "stats") ``` r None `compareVersion` Compare Two Package Version Numbers ----------------------------------------------------- ### Description Compare two package version numbers to see which is later. ### Usage ``` compareVersion(a, b) ``` ### Arguments | | | | --- | --- | | `a, b` | Character strings representing package version numbers. | ### Details **R** package version numbers are of the form `x.y-z` for integers `x`, `y` and `z`, with components after `x` optionally missing (in which case the version number is older than those with the components present). ### Value `0` if the numbers are equal, `-1` if `b` is later and `1` if `a` is later (analogous to the C function `strcmp`). ### See Also `[package\_version](../../base/html/numeric_version)`, `[library](../../base/html/library)`, `[packageStatus](packagestatus)`. ### Examples ``` compareVersion("1.0", "1.0-1") compareVersion("7.2-0","7.1-12") ``` r None `filetest` Shell-style Tests on Files -------------------------------------- ### Description Utility for shell-style file tests. ### Usage ``` file_test(op, x, y) ``` ### Arguments | | | | --- | --- | | `op` | a character string specifying the test to be performed. Unary tests (only `x` is used) are `"-f"` (existence and not being a directory), `"-d"` (existence and directory) and `"-x"` (executable as a file or searchable as a directory). Binary tests are `"-nt"` (strictly newer than, using the modification dates) and `"-ot"` (strictly older than): in both cases the test is false unless both files exist. | | `x, y` | character vectors giving file paths. | ### Details ‘Existence’ here means being on the file system and accessible by the `stat` system call (or a 64-bit extension) – on a Unix-alike this requires execute permission on all of the directories in the path that leads to the file, but no permissions on the file itself. For the meaning of `"-x"` on Windows see `[file.access](../../base/html/file.access)`. ### See Also `[file.exists](../../base/html/files)` which only tests for existence (`test -e` on some systems) but not for not being a directory. `[file.path](../../base/html/file.path)`, `[file.info](../../base/html/file.info)` ### Examples ``` dir <- file.path(R.home(), "library", "stats") file_test("-d", dir) file_test("-nt", file.path(dir, "R"), file.path(dir, "demo")) ``` r None `Rconsole` R for Windows Configuration --------------------------------------- ### Description The file ‘Rconsole’ configures the R GUI (`Rgui`) console under MS Windows and `loadRconsole(*)` loads a new configuration. The file ‘Rdevga’ configures the graphics devices `[windows](../../grdevices/html/windows)`, `win.graph`, `win.metafile` and `win.print`, as well as the bitmap devices `[bmp](../../grdevices/html/png)`, `jpeg`, `png` and `tiff` (which use for `type = "windows"` use `windows` internally). ### Usage ``` loadRconsole(file) ``` ### Arguments | | | | --- | --- | | `file` | The file from which to load a new ‘Rconsole’ configuration. By default a file dialog is used to select a file. | ### Details There are system copies of these files in ‘[R\_HOME](../../base/html/rhome)\etc’. Users can have personal copies of the files: these are looked for in the location given by the environment variable R\_USER. The system files are read only if a corresponding personal file is not found. If the environment variable R\_USER is not set, the **R** system sets it to HOME if that is set (stripping any trailing slash), otherwise to the Windows ‘personal’ directory, otherwise to `{HOMEDRIVE}{HOMEPATH}` if `HOMEDRIVE` and `HOMEDRIVE` are both set otherwise to the working directory. This is as described in the file ‘rw-FAQ’. ### Value Each of the files contains details in its comments of how to set the values. At the time of writing ‘Rdevga’ configured the mapping of font numbers to fonts, and ‘Rconsole’ configured the appearance (single or multiple document interface, toolbar, statusbar on MDI), size, font and colours of the GUI console, and whether resizing the console sets `[options](../../base/html/options)("width")`. The file ‘Rconsole’ also configures the internal pager. This shares the font and colours of the console, but can be sized separately. ‘Rconsole’ can also set the initial positions of the console and the graphics device, as well as the size and position of the MDI workspace in MDI mode. `loadRconsole` is called for its side effect of loading new defaults. It returns no useful value. ### Chinese/Japanese/Korean Users of these languages will need to select a suitable font for the console (perhaps `MS Mincho`) and for the graphics device (although the default `Arial` has many East Asian characters). It is essential that the font selected for the console has double-width East Asian characters – many monospaced fonts do not. ### Note The `GUI preferences` item on the `Edit` menu brings up an dialog box which can be used to edit the console settings, and to save them to a file. This is only available on Windows. ### Author(s) Guido Masarotto and R-core members ### See Also `[windows](../../grdevices/html/windows)` ### Examples ``` if(.Platform$OS.type == "windows") withAutoprint({ ruser <- Sys.getenv("R_USER") cat("\n\nLocation for personal configuration files is\n R_USER = ", ruser, "\n\n", sep = "") ## see if there are personal configuration files file.exists(file.path(ruser, c("Rconsole", "Rdevga"))) ## show the configuration files used showConfig <- function(file) { ruser <- Sys.getenv("R_USER") path <- file.path(ruser, file) if(!file.exists(path)) path <- file.path(R.home(), "etc", file) file.show(path, header = path) } showConfig("Rconsole") }) ``` r None `count.fields` Count the Number of Fields per Line --------------------------------------------------- ### Description `count.fields` counts the number of fields, as separated by `sep`, in each of the lines of `file` read. ### Usage ``` count.fields(file, sep = "", quote = "\"'", skip = 0, blank.lines.skip = TRUE, comment.char = "#") ``` ### Arguments | | | | --- | --- | | `file` | a character string naming an ASCII data file, or a `[connection](../../base/html/connections)`, which will be opened if necessary, and if so closed at the end of the function call. | | `sep` | the field separator character. Values on each line of the file are separated by this character. By default, arbitrary amounts of whitespace can separate fields. | | `quote` | the set of quoting characters | | `skip` | the number of lines of the data file to skip before beginning to read data. | | `blank.lines.skip` | logical: if `TRUE` blank lines in the input are ignored. | | `comment.char` | character: a character vector of length one containing a single character or an empty string. | ### Details This used to be used by `<read.table>` and can still be useful in discovering problems in reading a file by that function. For the handling of comments, see `[scan](../../base/html/scan)`. Consistent with `[scan](../../base/html/scan)`, `count.fields` allows quoted strings to contain newline characters. In such a case the starting line will have the field count recorded as `NA`, and the ending line will include the count of all fields from the beginning of the record. ### Value A vector with the numbers of fields found. ### See Also `<read.table>` ### Examples ``` fil <- tempfile() cat("NAME", "1:John", "2:Paul", file = fil, sep = "\n") count.fields(fil, sep = ":") unlink(fil) ``` r None `packageDescription` Package Description ----------------------------------------- ### Description Parses and returns the ‘DESCRIPTION’ file of a package as a `"packageDescription"`. Utility functions return (transformed) parts of that. ### Usage ``` packageDescription(pkg, lib.loc = NULL, fields = NULL, drop = TRUE, encoding = "") packageVersion(pkg, lib.loc = NULL) packageDate(pkg, lib.loc = NULL, date.fields = c("Date", "Packaged", "Date/Publication", "Built"), tryFormats = c("%Y-%m-%d", "%Y/%m/%d", "%D", "%m/%d/%y"), desc = packageDescription(pkg, lib.loc=lib.loc, fields=date.fields)) asDateBuilt(built) ``` ### Arguments | | | | --- | --- | | `pkg` | a character string with the package name. | | `lib.loc` | a character vector of directory names of **R** libraries, or `NULL`. The default value of `NULL` corresponds to all libraries currently known. If the default is used, the loaded packages and namespaces are searched before the libraries. | | `fields` | a character vector giving the tags of fields to return (if other fields occur in the file they are ignored). | | `drop` | If `TRUE` and the length of `fields` is 1, then a single character string with the value of the respective field is returned instead of an object of class `"packageDescription"`. | | `encoding` | If there is an `Encoding` field, to what encoding should re-encoding be attempted? If `NA`, no re-encoding. The other values are as used by `[iconv](../../base/html/iconv)`, so the default `""` indicates the encoding of the current locale. | | `date.fields` | character vector of field tags to be tried. The first for which `[as.Date](../../base/html/as.date)(.)` is not `[NA](../../base/html/na)` will be returned. (Partly experimental, see *Note*.) | | `tryFormats` | date formats to try, see `[as.Date.character](../../base/html/as.date)()`. | | `desc` | optionally, a named `[list](../../base/html/list)` with components named from `date.fields`; where the default is fine, a complete `packageDescription()` maybe specified as well. | | `built` | for `asDateBuilt()`, a `[character](../../base/html/character)` string as from `packageDescription(*, fields="Built")`. | ### Details A package will not be ‘found’ unless it has a ‘DESCRIPTION’ file which contains a valid `Version` field. Different warnings are given when no package directory is found and when there is a suitable directory but no valid ‘DESCRIPTION’ file. An [attach](../../base/html/attach)ed environment named to look like a package (e.g., `package:utils2`) will be ignored. `packageVersion()` is a convenience shortcut, allowing things like `if (packageVersion("MASS") < "7.3") { do.things }` . For `packageDate()`, if `desc` is valid, both `pkg` and `lib.loc` are not made use of. ### Value If a ‘DESCRIPTION’ file for the given package is found and can successfully be read, `packageDescription` returns an object of class `"packageDescription"`, which is a named list with the values of the (given) fields as elements and the tags as names, unless `drop = TRUE`. If parsing the ‘DESCRIPTION’ file was not successful, it returns a named list of `NA`s with the field tags as names if `fields` is not null, and `NA` otherwise. `packageVersion()` returns a (length-one) object of class `"[package\_version](../../base/html/numeric_version)"`. `packageDate()` will return a `"Date"` object from `[as.Date](../../base/html/as.date)()` or `NA`. `asDateBuilt(built)` returns a `"Date"` object or signals an error if `built` is invalid. ### Note The default behavior of `packageDate()`, notably for `date.fields`, is somewhat experimental and may change. Using `date.fields = <string>` single ### See Also `[read.dcf](../../base/html/dcf)` ### Examples ``` packageDescription("stats") packageDescription("stats", fields = c("Package", "Version")) packageDescription("stats", fields = "Version") packageDescription("stats", fields = "Version", drop = FALSE) if(packageVersion("MASS") < "7.3.29") message("you need to update 'MASS'") pu <- packageDate("utils") str(pu) stopifnot(identical(pu, packageDate(desc = packageDescription("utils"))), identical(pu, packageDate("stats"))) # as "utils" and "stats" are # both 'base R' and "Built" at same time ``` r None `installed.packages` Find Installed Packages --------------------------------------------- ### Description Find (or retrieve) details of all packages installed in the specified libraries. ### Usage ``` installed.packages(lib.loc = NULL, priority = NULL, noCache = FALSE, fields = NULL, subarch = .Platform$r_arch, ...) ``` ### Arguments | | | | --- | --- | | `lib.loc` | character vector describing the location of **R** library trees to search through, or `NULL` for all known trees (see `[.libPaths](../../base/html/libpaths)`). | | `priority` | character vector or `NULL` (default). If non-null, used to select packages; `"high"` is equivalent to `c("base", "recommended")`. To select all packages without an assigned priority use `priority = "NA"`. | | `noCache` | Do not use cached information, nor cache it. | | `fields` | a character vector giving the fields to extract from each package's `DESCRIPTION` file in addition to the default ones, or `NULL` (default). Unavailable fields result in `NA` values. | | `subarch` | character string or `NULL`. If non-null and non-empty, used to select packages which are installed for that sub-architecture. | | `...` | allows unused arguments to be passed down from other functions. | ### Details `installed.packages` scans the ‘DESCRIPTION’ files of each package found along `lib.loc` and returns a matrix of package names, library paths and version numbers. The information found is cached (by library) for the **R** session and specified `fields` argument, and updated only if the top-level library directory has been altered, for example by installing or removing a package. If the cached information becomes confused, it can be avoided by specifying `noCache = TRUE`. ### Value A matrix with one row per package, row names the package names and column names (currently) `"Package"`, `"LibPath"`, `"Version"`, `"Priority"`, `"Depends"`, `"Imports"`, `"LinkingTo"`, `"Suggests"`, `"Enhances"`, `"OS_type"`, `"License"` and `"Built"` (the **R** version the package was built under). Additional columns can be specified using the `fields` argument. ### Note This needs to read several files per installed package, which will be slow on Windows and on some network-mounted file systems. It will be slow when thousands of packages are installed, so do not use it to find out if a named package is installed (use `[find.package](../../base/html/find.package)` or `[system.file](../../base/html/system.file)`) nor to find out if a package is usable (call `[requireNamespace](../../base/html/ns-load)` or `[require](../../base/html/library)` and check the return value) nor to find details of a small number of packages (use `[packageDescription](packagedescription)`). ### See Also `<update.packages>`, `<install.packages>`, `[INSTALL](install)`, `[REMOVE](remove)`. ### Examples ``` ## confine search to .Library for speed str(ip <- installed.packages(.Library, priority = "high")) ip[, c(1,3:5)] plic <- installed.packages(.Library, priority = "high", fields = "License") ## what licenses are there: table( plic[, "License"] ) ```
programming_docs
r None `read.socket` Read from or Write to a Socket --------------------------------------------- ### Description `read.socket` reads a string from the specified socket, `write.socket` writes to the specified socket. There is very little error checking done by either. ### Usage ``` read.socket(socket, maxlen = 256L, loop = FALSE) write.socket(socket, string) ``` ### Arguments | | | | --- | --- | | `socket` | a socket object. | | `maxlen` | maximum length (in bytes) of string to read. | | `loop` | wait for ever if there is nothing to read? | | `string` | string to write to socket. | ### Value `read.socket` returns the string read as a length-one character vector. `write.socket` returns the number of bytes written. ### Author(s) Thomas Lumley ### See Also `<close.socket>`, `<make.socket>` ### Examples ``` finger <- function(user, host = "localhost", port = 79, print = TRUE) { if (!is.character(user)) stop("user name must be a string") user <- paste(user,"\r\n") socket <- make.socket(host, port) on.exit(close.socket(socket)) write.socket(socket, user) output <- character(0) repeat{ ss <- read.socket(socket) if (ss == "") break output <- paste(output, ss) } close.socket(socket) if (print) cat(output) invisible(output) } ## Not run: finger("root") ## only works if your site provides a finger daemon ## End(Not run) ``` r None `RHOME` R Home Directory ------------------------- ### Description Returns the location of the **R** home directory, which is the root of the installed **R** tree. ### Usage ``` R RHOME ``` r None `alarm` Alert the User ----------------------- ### Description Gives an audible or visual signal to the user. ### Usage ``` alarm() ``` ### Details `alarm()` works by sending a `"\a"` character to the console. On most platforms this will ring a bell, beep, or give some other signal to the user (unless standard output has been redirected). It attempts to flush the console (see `<flush.console>`). ### Value No useful value is returned. ### Examples ``` alarm() ``` r None `chooseCRANmirror` Select a CRAN Mirror ---------------------------------------- ### Description Interact with the user to choose a CRAN mirror. ### Usage ``` chooseCRANmirror(graphics = getOption("menu.graphics"), ind = NULL, local.only = FALSE) getCRANmirrors(all = FALSE, local.only = FALSE) ``` ### Arguments | | | | --- | --- | | `graphics` | Logical. If true, use a graphical list: on Windows or the macOS GUI use a list box, and on a Unix-alike use a Tk widget if package tcltk and an X server are available. Otherwise use a text `<menu>`. | | `ind` | Optional numeric value giving which entry to select. | | `all` | Logical, get all known mirrors or only the ones flagged as OK. | | `local.only` | Logical, try to get most recent list from the CRAN master or use file on local disk only. | ### Details A list of mirrors is stored in file ‘[R\_HOME](../../base/html/rhome)/doc/CRAN\_mirrors.csv’, but first an on-line list of current mirrors is consulted, and the file copy used only if the on-line list is inaccessible. This function is called by a Windows GUI menu item and by `<contrib.url>` if it finds the initial dummy value of `[options](../../base/html/options)("repos")`. HTTPS mirrors with mirroring over `ssh` will be offered in preference to other mirrors (which are listed in a sub-menu). `ind` chooses a row in the list of current mirrors, by number. It is best used with `local.only = TRUE` and row numbers in ‘[R\_HOME](../../base/html/rhome)/doc/CRAN\_mirrors.csv’. ### Value None for `chooseCRANmirror()`, this function is invoked for its side effect of updating `options("repos")`. `getCRANmirrors()` returns a data frame with mirror information. ### See Also `[setRepositories](setrepositories)`, `[chooseBioCmirror](choosebiocmirror)`, `<contrib.url>`. r None `rtags` An Etags-like Tagging Utility for R -------------------------------------------- ### Description `rtags` provides etags-like indexing capabilities for R code, using R's own parser. ### Usage ``` rtags(path = ".", pattern = "\\.[RrSs]$", recursive = FALSE, src = list.files(path = path, pattern = pattern, full.names = TRUE, recursive = recursive), keep.re = NULL, ofile = "", append = FALSE, verbose = getOption("verbose"), type = c("etags", "ctags")) ``` ### Arguments | | | | --- | --- | | `path, pattern, recursive` | Arguments passed on to `[list.files](../../base/html/list.files)` to determine the files to be tagged. By default, these are all files with extension `.R`, `.r`, `.S`, and `.s` in the current directory. These arguments are ignored if `src` is specified. | | `src` | A vector of file names to be indexed. | | `keep.re` | A regular expression further restricting `src` (the files to be indexed). For example, specifying `keep.re = "/R/[^/]*\\.R$"` will only retain files with extension `.R` inside a directory named `R`. | | `ofile` | Passed on to `[cat](../../base/html/cat)` as the `file` argument; typically the output file where the tags will be written (`"TAGS"` or `"tags"` by convention). By default, the output is written to the R console (unless redirected). | | `append` | Logical, indicating whether the output should overwrite an existing file, or append to it. | | `verbose` | Logical. If `TRUE`, file names are echoed to the R console as they are processed. | | `type` | Character string specifying whether emacs style (`"etags"`) or vi style (`"ctags"`) tags are to be generated. | ### Details Many text editors allow definitions of functions and other language objects to be quickly and easily located in source files through a tagging utility. This functionality requires the relevant source files to be preprocessed, producing an index (or tag) file containing the names and their corresponding locations. There are multiple tag file formats, the most popular being the vi-style ctags format and the and emacs-style etags format. Tag files in these formats are usually generated by the `ctags` and `etags` utilities respectively. Unfortunately, these programs do not recognize R code syntax. They do allow tagging of arbitrary language files through regular expressions, but this too is insufficient. The `rtags` function is intended to be a tagging utility for R code. It parses R code files (using R's parser) and produces tags in both etags and ctags formats. The support for vi-style ctags is rudimentary, and was adapted from a patch by Neal Fultz; see [PR#17214](https://bugs.R-project.org/bugzilla3/show_bug.cgi?id=17214). It may be more convenient to use the command-line wrapper script `R CMD rtags`. ### Author(s) Deepayan Sarkar ### References <https://en.wikipedia.org/wiki/Ctags>, <https://www.gnu.org/software/emacs/manual/html_node/emacs/Tags-Tables.html> ### See Also `[list.files](../../base/html/list.files)`, `[cat](../../base/html/cat)` ### Examples ``` ## Not run: rtags("/path/to/src/repository", pattern = "[.]*\\.[RrSs]$", keep.re = "/R/", verbose = TRUE, ofile = "TAGS", append = FALSE, recursive = TRUE) ## End(Not run) ``` r None `adist` Approximate String Distances ------------------------------------- ### Description Compute the approximate string distance between character vectors. The distance is a generalized Levenshtein (edit) distance, giving the minimal possibly weighted number of insertions, deletions and substitutions needed to transform one string into another. ### Usage ``` adist(x, y = NULL, costs = NULL, counts = FALSE, fixed = TRUE, partial = !fixed, ignore.case = FALSE, useBytes = FALSE) ``` ### Arguments | | | | --- | --- | | `x` | a character vector. [Long vectors](../../base/html/longvectors) are not supported. | | `y` | a character vector, or `NULL` (default) indicating taking `x` as `y`. | | `costs` | a numeric vector or list with names partially matching insertions, deletions and substitutions giving the respective costs for computing the Levenshtein distance, or `NULL` (default) indicating using unit cost for all three possible transformations. | | `counts` | a logical indicating whether to optionally return the transformation counts (numbers of insertions, deletions and substitutions) as the `"counts"` attribute of the return value. | | `fixed` | a logical. If `TRUE` (default), the `x` elements are used as string literals. Otherwise, they are taken as regular expressions and `partial = TRUE` is implied (corresponding to the approximate string distance used by `[agrep](../../base/html/agrep)` with `fixed = FALSE`). | | `partial` | a logical indicating whether the transformed `x` elements must exactly match the complete `y` elements, or only substrings of these. The latter corresponds to the approximate string distance used by `[agrep](../../base/html/agrep)` (by default). | | `ignore.case` | a logical. If `TRUE`, case is ignored for computing the distances. | | `useBytes` | a logical. If `TRUE` distance computations are done byte-by-byte rather than character-by-character. | ### Details The (generalized) Levenshtein (or edit) distance between two strings s and t is the minimal possibly weighted number of insertions, deletions and substitutions needed to transform s into t (so that the transformation exactly matches t). This distance is computed for `partial = FALSE`, currently using a dynamic programming algorithm (see, e.g., <https://en.wikipedia.org/wiki/Levenshtein_distance>) with space and time complexity *O(mn)*, where *m* and *n* are the lengths of s and t, respectively. Additionally computing the transformation sequence and counts is *O(\max(m, n))*. The generalized Levenshtein distance can also be used for approximate (fuzzy) string matching, in which case one finds the substring of t with minimal distance to the pattern s (which could be taken as a regular expression, in which case the principle of using the leftmost and longest match applies), see, e.g., <https://en.wikipedia.org/wiki/Approximate_string_matching>. This distance is computed for `partial = TRUE` using tre by Ville Laurikari (<https://github.com/laurikari/tre>) and corresponds to the distance used by `[agrep](../../base/html/agrep)`. In this case, the given cost values are coerced to integer. Note that the costs for insertions and deletions can be different, in which case the distance between s and t can be different from the distance between t and s. ### Value A matrix with the approximate string distances of the elements of `x` and `y`, with rows and columns corresponding to `x` and `y`, respectively. If `counts` is `TRUE`, the transformation counts are returned as the `"counts"` attribute of this matrix, as a 3-dimensional array with dimensions corresponding to the elements of `x`, the elements of `y`, and the type of transformation (insertions, deletions and substitutions), respectively. Additionally, if `partial = FALSE`, the transformation sequences are returned as the `"trafos"` attribute of the return value, as character strings with elements M, I, D and S indicating a match, insertion, deletion and substitution, respectively. If `partial = TRUE`, the offsets (positions of the first and last element) of the matched substrings are returned as the `"offsets"` attribute of the return value (with both offsets *-1* in case of no match). ### See Also `[agrep](../../base/html/agrep)` for approximate string matching (fuzzy matching) using the generalized Levenshtein distance. ### Examples ``` ## Cf. https://en.wikipedia.org/wiki/Levenshtein_distance adist("kitten", "sitting") ## To see the transformation counts for the Levenshtein distance: drop(attr(adist("kitten", "sitting", counts = TRUE), "counts")) ## To see the transformation sequences: attr(adist(c("kitten", "sitting"), counts = TRUE), "trafos") ## Cf. the examples for agrep: adist("lasy", "1 lazy 2") ## For a "partial approximate match" (as used for agrep): adist("lasy", "1 lazy 2", partial = TRUE) ``` r None `debugger` Post-Mortem Debugging --------------------------------- ### Description Functions to dump the evaluation environments (frames) and to examine dumped frames. ### Usage ``` dump.frames(dumpto = "last.dump", to.file = FALSE, include.GlobalEnv = FALSE) debugger(dump = last.dump) ``` ### Arguments | | | | --- | --- | | `dumpto` | a character string. The name of the object or file to dump to. | | `to.file` | logical. Should the dump be to an **R** object or to a file? | | `include.GlobalEnv` | logical indicating if a *copy* of the `[.GlobalEnv](../../base/html/environment)` environment should be included in addition to the `[sys.frames](../../base/html/sys.parent)()`. Will be particularly useful when used in a batch job. | | `dump` | an **R** dump object created by `dump.frames`. | ### Details To use post-mortem debugging, set the option `error` to be a call to `dump.frames`. By default this dumps to an **R** object `last.dump` in the workspace, but it can be set to dump to a file (a dump of the object produced by a call to `[save](../../base/html/save)`). The dumped object contain the call stack, the active environments and the last error message as returned by `[geterrmessage](../../base/html/stop)`. When dumping to file, `dumpto` gives the name of the dumped object and the file name has ‘.rda’ appended. A dump object of class `"dump.frames"` can be examined by calling `debugger`. This will give the error message and a list of environments from which to select repeatedly. When an environment is selected, it is copied and the `[browser](../../base/html/browser)` called from within the copy. Note that not all the information in the original frame will be available, e.g. promises which have not yet been evaluated and the contents of any `...` argument. If `dump.frames` is installed as the error handler, execution will continue even in non-interactive sessions. See the examples for how to dump and then quit. ### Value Invisible `NULL`. ### Note Functions such as `[sys.parent](../../base/html/sys.parent)` and `[environment](../../base/html/environment)` applied to closures will not work correctly inside `debugger`. If the error occurred when computing the default value of a formal argument the debugger will report “recursive default argument reference” when trying to examine that environment. Of course post-mortem debugging will not work if **R** is too damaged to produce and save the dump, for example if it has run out of workspace. ### References Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) *The New S Language*. Wadsworth & Brooks/Cole. ### See Also `[browser](../../base/html/browser)` for the actions available at the `Browse` prompt. `[options](../../base/html/options)` for setting `error` options; `<recover>` is an interactive debugger working similarly to `debugger` but directly after the error occurs. ### Examples ``` ## Not run: options(error = quote(dump.frames("testdump", TRUE))) f <- function() { g <- function() stop("test dump.frames") g() } f() # will generate a dump on file "testdump.rda" options(error = NULL) ## possibly in another R session load("testdump.rda") debugger(testdump) Available environments had calls: 1: f() 2: g() 3: stop("test dump.frames") Enter an environment number, or 0 to exit Selection: 1 Browsing in the environment with call: f() Called from: debugger.look(ind) Browse[1]> ls() [1] "g" Browse[1]> g function() stop("test dump.frames") <environment: 759818> Browse[1]> Available environments had calls: 1: f() 2: g() 3: stop("test dump.frames") Enter an environment number, or 0 to exit Selection: 0 ## A possible setting for non-interactive sessions options(error = quote({dump.frames(to.file = TRUE); q(status = 1)})) ## End(Not run) ``` r None `hsearch-utils` Help Search Utilities -------------------------------------- ### Description Utilities for searching the help system. ### Usage ``` hsearch_db(package = NULL, lib.loc = NULL, types = getOption("help.search.types"), verbose = getOption("verbose"), rebuild = FALSE, use_UTF8 = FALSE) hsearch_db_concepts(db = hsearch_db()) hsearch_db_keywords(db = hsearch_db()) ``` ### Arguments | | | | --- | --- | | `package` | a character vector with the names of packages to search through, or `NULL` in which case *all* available packages in the library trees specified by `lib.loc` are searched. | | `lib.loc` | a character vector describing the location of **R** library trees to search through, or `NULL`. The default value of `NULL` corresponds to all libraries currently known. | | `types` | a character vector listing the types of documentation to search. See `<help.search>` for details. | | `verbose` | a logical controlling the verbosity of building the help search database. See `<help.search>` for details. | | `rebuild` | a logical indicating whether the help search database should be rebuilt. See `<help.search>` for details. | | `use_UTF8` | logical: should results be given in UTF-8 encoding? | | `db` | a help search database as obtained by calls to `hsearch_db()`. | ### Details `hsearch_db()` builds and caches the help search database for subsequent use by `<help.search>`. (In fact, re-builds only when forced (`rebuild = TRUE`) or “necessary”.) The format of the help search database is still experimental, and may change in future versions. Currently, it consists of four tables: one with base information about all documentation objects found, including their names and titles and unique ids; three more tables contain the individual aliases, concepts and keywords together with the ids of the documentation objects they belong to. Separating out the latter three tables accounts for the fact that a single documentation object may provide several of these entries, and allows for efficient searching. See the details in `<help.search>` for how searchable entries are interpreted according to help type. `hsearch_db_concepts()` and `hsearch_db_keywords()` extract all concepts or keywords, respectively, from a help search database, and return these in a data frame together with their total frequencies and the numbers of packages they are used in, with entries sorted in decreasing total frequency. ### Examples ``` db <- hsearch_db() ## Total numbers of documentation objects, aliases, keywords and ## concepts (using the current format): sapply(db, NROW) ## Can also be obtained from print method: db ## 10 most frequent concepts: head(hsearch_db_concepts(), 10) ## 10 most frequent keywords: head(hsearch_db_keywords(), 10) ``` r None `help.search` Search the Help System ------------------------------------- ### Description Allows for searching the help system for documentation matching a given character string in the (file) name, alias, title, concept or keyword entries (or any combination thereof), using either [fuzzy matching](../../base/html/agrep) or [regular expression](../../base/html/regex) matching. Names and titles of the matched help entries are displayed nicely formatted. Vignette names, titles and keywords and demo names and titles may also be searched. ### Usage ``` help.search(pattern, fields = c("alias", "concept", "title"), apropos, keyword, whatis, ignore.case = TRUE, package = NULL, lib.loc = NULL, help.db = getOption("help.db"), verbose = getOption("verbose"), rebuild = FALSE, agrep = NULL, use_UTF8 = FALSE, types = getOption("help.search.types")) ??pattern field??pattern ``` ### Arguments | | | | --- | --- | | `pattern` | a character string to be matched in the specified fields. If this is given, the arguments `apropos`, `keyword`, and `whatis` are ignored. | | `fields` | a character vector specifying the fields of the help database to be searched. The entries must be abbreviations of `"name"`, `"title"`, `"alias"`, `"concept"`, and `"keyword"`, corresponding to the help page's (file) name, its title, the topics and concepts it provides documentation for, and the keywords it can be classified to. See below for details and how vignettes and demos are searched. | | `apropos` | a character string to be matched in the help page topics and title. | | `keyword` | a character string to be matched in the help page ‘keywords’. ‘Keywords’ are really categories: the standard categories are listed in file ‘R.home("doc")/KEYWORDS’ (see also the example) and some package writers have defined their own. If `keyword` is specified, `agrep` defaults to `FALSE`. | | `whatis` | a character string to be matched in the help page topics. | | `ignore.case` | a logical. If `TRUE`, case is ignored during matching; if `FALSE`, pattern matching is case sensitive. | | `package` | a character vector with the names of packages to search through, or `NULL` in which case *all* available packages in the library trees specified by `lib.loc` are searched. | | `lib.loc` | a character vector describing the location of **R** library trees to search through, or `NULL`. The default value of `NULL` corresponds to all libraries currently known. | | `help.db` | a character string giving the file path to a previously built and saved help database, or `NULL`. | | `verbose` | logical; if `TRUE`, the search process is traced. Integer values are also accepted, with `TRUE` being equivalent to `2`, and `1` being less verbose. On Windows a progress bar is shown during rebuilding, and on Unix a heartbeat is shown for `verbose = 1` and a package-by-package list for `verbose >= 2`. | | `rebuild` | a logical indicating whether the help database should be rebuilt. This will be done automatically if `lib.loc` or the search path is changed, or if `package` is used and a value is not found. | | `agrep` | if `NULL` (the default unless `keyword` is used) and the character string to be matched consists of alphanumeric characters, whitespace or a dash only, approximate (fuzzy) matching via `[agrep](../../base/html/agrep)` is used unless the string has fewer than 5 characters; otherwise, it is taken to contain a [regular expression](../../base/html/regex) to be matched via `[grep](../../base/html/grep)`. If `FALSE`, approximate matching is not used. Otherwise, one can give a numeric or a list specifying the maximal distance for the approximate match, see argument `max.distance` in the documentation for `[agrep](../../base/html/agrep)`. | | `use_UTF8` | logical: should results be given in UTF-8 encoding? Also changes the meaning of regexps in `agrep` to be Perl regexps. | | `types` | a character vector listing the types of documentation to search. The entries must be abbreviations of `"vignette"` `"help"` or `"demo"`. Results will be presented in the order specified. | | `field` | a single value of `fields` to search. | ### Details Upon installation of a package, a pre-built help.search index is serialized as ‘hsearch.rds’ in the ‘Meta’ directory (provided the package has any help pages). Vignettes are also indexed in the ‘Meta/vignette.rds’ file. These files are used to create the help search database via `[hsearch\_db](hsearch-utils)`. The arguments `apropos` and `whatis` play a role similar to the Unix commands with the same names. Searching with `agrep = FALSE` will be several times faster than the default (once the database is built). However, approximate searches should be fast enough (around a second with 5000 packages installed). If possible, the help database is saved in memory for use by subsequent calls in the session. Note that currently the aliases in the matching help files are not displayed. As with `[?](question)`, in `??` the pattern may be prefixed with a package name followed by `::` or `:::` to limit the search to that package. For help files, \keyword entries which are not among the standard keywords as listed in file ‘KEYWORDS’ in the **R** documentation directory are taken as concepts. For standard keyword entries different from internal, the corresponding descriptions from file ‘KEYWORDS’ are additionally taken as concepts. All \concept entries used as concepts. Vignettes are searched as follows. The `"name"` and `"alias"` are both the base of the vignette filename, and the `"concept"` entries are taken from the `\VignetteKeyword` entries. Vignettes are not classified using the help system `"keyword"` classifications. Demos are handled similarly to vignettes, without the `"concept"` search. ### Value The results are returned in a list object of class `"hsearch"`, which has a print method for nicely formatting the results of the query. This mechanism is experimental, and may change in future versions of **R**. In `R.app` on macOS, this will show up a browser with selectable items. On exiting this browser, the help pages for the selected items will be shown in separate help windows. The internal format of the class is undocumented and subject to change. ### See Also `[hsearch\_db](hsearch-utils)` for more information on the help search database employed, and for utilities to inspect available concepts and keywords. `<help>`; `<help.start>` for starting the hypertext (currently HTML) version of **R**'s online documentation, which offers a similar search mechanism. `[RSiteSearch](rsitesearch)` to access an on-line search of **R** resources. `<apropos>` uses regexps and has nice examples. ### Examples ``` help.search("linear models") # In case you forgot how to fit linear # models help.search("non-existent topic") ??utils::help # All the topics matching "help" in the utils package help.search("print") # All help pages with topics or title # matching 'print' help.search(apropos = "print") # The same help.search(keyword = "hplot") # All help pages documenting high-level # plots. file.show(file.path(R.home("doc"), "KEYWORDS")) # show all keywords ## Help pages with documented topics starting with 'try'. help.search("\\btry", fields = "alias") ```
programming_docs
r None `make.packages.html` Update HTML Package List ---------------------------------------------- ### Description Re-create the HTML list of packages. ### Usage ``` make.packages.html(lib.loc = .libPaths(), temp = FALSE, verbose = TRUE, docdir = R.home("doc")) ``` ### Arguments | | | | --- | --- | | `lib.loc` | character vector. List of libraries to be included. | | `temp` | logical: should the package indices be created in a temporary location for use by the HTTP server? | | `verbose` | logical. If true, print out a message. | | `docdir` | If `temp` is false, directory in whose ‘html’ directory the ‘packages.html’ file is to be created/updated. | ### Details This creates the ‘packages.html’ file, either a temporary copy for use by `<help.start>`, or the copy in ‘R.home("doc")/html’ (for which you will need write permission). It can be very slow, as all the package ‘DESCRIPTION’ files in all the library trees are read. For `temp = TRUE` there is some caching of information, so the file will only be re-created if `lib.loc` or any of the directories it lists have been changed. ### Value Invisible logical, with `FALSE` indicating a failure to create the file, probably due to lack of suitable permissions. ### See Also `<help.start>` ### Examples ``` ## Not run: make.packages.html() # this can be slow for large numbers of installed packages. ## End(Not run) ``` r None `savehistory` Load or Save or Display the Commands History ----------------------------------------------------------- ### Description Load or save or display the commands history. ### Usage ``` loadhistory(file = ".Rhistory") savehistory(file = ".Rhistory") history(max.show = 25, reverse = FALSE, pattern, ...) timestamp(stamp = date(), prefix = "##------ ", suffix = " ------##", quiet = FALSE) ``` ### Arguments | | | | --- | --- | | `file` | The name of the file in which to save the history, or from which to load it. The path is relative to the current working directory. | | `max.show` | The maximum number of lines to show. `Inf` will give all of the currently available history. | | `reverse` | logical. If true, the lines are shown in reverse order. Note: this is not useful when there are continuation lines. | | `pattern` | A character string to be matched against the lines of the history. When supplied, only *unique* matching lines are shown. | | `...` | Arguments to be passed to `[grep](../../base/html/grep)` when doing the matching. | | `stamp` | A value or vector of values to be written into the history. | | `prefix` | A prefix to apply to each line. | | `suffix` | A suffix to apply to each line. | | `quiet` | If `TRUE`, suppress printing timestamp to the console. | ### Details There are several history mechanisms available for the different **R** consoles, which work in similar but not identical ways. Notably, there are different implementations for Unix and Windows. Windows: The functions described here work in `Rgui` and interactive `Rterm` but not in batch use of `Rterm` nor in embedded/DCOM versions. Unix-alikes: The functions described here work under the `readline` command-line interface but may not otherwise (for example, in batch use or in an embedded application). Note that **R** can be built without `readline`. `R.app`, the console on macOS, has a separate and largely incompatible history mechanism, which by default uses a file ‘.Rapp.history’ and saves up to 250 entries. These functions are not currently implemented there. The (`readline` on Unix-alikes) history mechanism is controlled by two environment variables: R\_HISTSIZE controls the number of lines that are saved (default 512), and R\_HISTFILE (default ‘.Rhistory’) sets the filename used for the loading/saving of history if requested at the beginning/end of a session (but not the default for `loadhistory`/`savehistory`). There is no limit on the number of lines of history retained during a session, so setting R\_HISTSIZE to a large value has no penalty unless a large file is actually generated. These environment variables are read at the time of saving, so can be altered within a session by the use of `[Sys.setenv](../../base/html/sys.setenv)`. On Unix-alikes: Note that `readline` history library saves files with permission `0600`, that is with read/write permission for the user and not even read permission for any other account. The `timestamp` function writes a timestamp (or other message) into the history and echos it to the console. On platforms that do not support a history mechanism only the console message is printed. ### Note If you want to save the history at the end of (almost) every interactive session (even those in which you do not save the workspace), you can put a call to `savehistory()` in `[.Last](../../base/html/quit)`. See the examples. ### Examples ``` ## Not run: ## Save the history in the home directory: note that it is not ## (by default) read from there but from the current directory .Last <- function() if(interactive()) try(savehistory("~/.Rhistory")) ## End(Not run) ``` r None `readRegistry` Read a Windows Registry Hive -------------------------------------------- ### Description On Windows, read values of keys in the Windows Registry, and optionally whole hives. ### Usage ``` readRegistry(key, hive = c("HLM", "HCR", "HCU", "HU", "HCC", "HPD"), maxdepth = 1, view = c("default", "32-bit", "64-bit")) ``` ### Arguments | | | | --- | --- | | `key` | character string, the path to the key in the Windows Registry. | | `hive` | The ‘hive’ containing the key. The abbreviations are for `HKEY_LOCAL_MACHINE`, `HKEY_CLASSES_ROOT`. `HKEY_CURRENT_USER`, `HKEY_USERS`, `HKEY_CURRENT_CONFIG` and `HKEY_PERFORMANCE_DATA` | | `maxdepth` | How far to recurse into the subkeys of the key. By default only the values of the key and the names of subkeys are returned. | | `view` | On 64-bit Windows, the view of the Registry to be used: see ‘Details’. | ### Details Registry access is done using the security settings of the current **R** session: this means that some Registry keys may not be accessible even if they exist. This may result in `NULL` values in the object returned, and, possibly, empty element names. On 64-bit Windows, this will by default read the 32-bit view of the Registry when run from 32-bit **R**, and the 64-bit view when run from 64-bit **R**: see <https://docs.microsoft.com/en-us/windows/win32/winprog64/registry-redirector>. ### Value A named list of values and subkeys (which may themselves be named lists). The default value (if any) precedes named values which precede subkeys, and both the latter sets are sorted alphabetically. ### Note This is only available on Windows. ### Examples ``` if(.Platform$OS.type == "windows") withAutoprint({ ## only in HLM if set in an admin-mode install. try(readRegistry("SOFTWARE\\R-core", maxdepth = 3)) gmt <- file.path("SOFTWARE", "Microsoft", "Windows NT", "CurrentVersion", "Time Zones", "GMT Standard Time", fsep = "\\") readRegistry(gmt, "HLM") }) ## Not run: ## on a 64-bit R need this to find 32-bit JAGS readRegistry("SOFTWARE\\JAGS", maxdepth = 3, view = "32") ## See if there is a 64-bit user install readRegistry("SOFTWARE\\R-core\\R64", "HCU", maxdepth = 2) ## End(Not run) ``` r None `sessionInfo` Collect Information About the Current R Session -------------------------------------------------------------- ### Description Print version information about **R**, the OS and attached or loaded packages. ### Usage ``` sessionInfo(package = NULL) ## S3 method for class 'sessionInfo' print(x, locale = TRUE, RNG = !identical(x$RNGkind, .RNGdefaults), ...) ## S3 method for class 'sessionInfo' toLatex(object, locale = TRUE, RNG = !identical(object$RNGkind, .RNGdefaults), ...) osVersion ``` ### Arguments | | | | --- | --- | | `package` | a character vector naming installed packages, or `NULL` (the default) meaning all attached packages. | | `x` | an object of class `"sessionInfo"`. | | `object` | an object of class `"sessionInfo"`. | | `locale` | show locale and code page information? | | `RNG` | show information on `[RNGkind](../../base/html/random)()`? Defaults to true iff it differs from the **R** version's default, i.e., `[RNGversion](../../base/html/random)(*)`. | | `...` | currently not used. | ### Value `sessionInfo()` returns an object of class `"sessionInfo"` which has `print` and `[toLatex](tolatex)` methods. This is a list with components | | | | --- | --- | | `R.version` | a list, the result of calling `[R.Version](../../base/html/version)()`. | | `platform` | a character string describing the platform **R** was built under. Where sub-architectures are in use this is of the form platform/sub-arch (nn-bit). | | `running` | a character string (or possibly `NULL`), the same as `osVersion`, see below. | | `RNGkind` | a character vector, the result of calling `[RNGkind](../../base/html/random)()`. | | `matprod` | a character string, the result of calling `[getOption](../../base/html/options)("matprod")`. | | `BLAS` | a character string, the result of calling `[extSoftVersion](../../base/html/extsoftversion)()["BLAS"]`. | | `LAPACK` | a character string, the result of calling `[La\_library](../../base/html/la_library)()`. | | `locale` | a character string, the result of calling `[Sys.getlocale](../../base/html/locales)()`. | | | | | --- | --- | | `basePkgs` | a character vector of base packages which are attached. | | `otherPkgs` | (not always present): a character vector of other attached packages. | | `loadedOnly` | (not always present): a named list of the results of calling `[packageDescription](packagedescription)` on packages whose namespaces are loaded but are not attached. | ### `osVersion` `osVersion` is a character string (or possibly `NULL` on bizarre platforms) describing the OS and version which it is running under (as distinct from built under). This attempts to name a Linux distribution and give the OS name on an Apple Mac. It is the same as `sessionInfo()$running` and created when loading the utils package. Windows may report unexpected versions: see the help for `[win.version](winextras)`. How OSes identify themselves and their versions can be arcane: where possible `osVersion` (and hence `sessionInfo()$running`) uses a human-readable form. Where **R** is compiled under an earlier version of macOS (as the CRAN distribution has been) but running under ‘Big Sur’, macOS reports itself as 10.16 (which **R** recognizes as ‘Big Sur’) and not 11.x. ### Note The information on ‘loaded’ packages and namespaces is the *current* version installed at the location the package was loaded from: it can be wrong if another process has been changing packages during the session. ### See Also `[R.version](../../base/html/version)` ### Examples ``` sI <- sessionInfo() sI # The same, showing the RNGkind, but not the locale : print(sI, RNG = TRUE, locale = FALSE) toLatex(sI, locale = FALSE) # shortest; possibly desirable at end of report ``` r None `winDialog` Dialog Boxes under Windows --------------------------------------- ### Description On MS Windows only, put up a dialog box to communicate with the user. There are various types, either for the user to select from a set of buttons or to edit a string. ### Usage ``` winDialog(type = c("ok", "okcancel", "yesno", "yesnocancel"), message) winDialogString(message, default) ``` ### Arguments | | | | --- | --- | | `type` | character. The type of dialog box. It will have the buttons implied by its name. | | `message` | character. The information field of the dialog box. Limited to 255 chars (by Windows, checked by R). | | `default` | character. The default string. | ### Value For `winDialog` a character string giving the name of the button pressed (in capitals) or `NULL` (invisibly) if the user had no choice. For `winDialogString` a string giving the contents of the text box when `Ok` was pressed, or `NULL` if `Cancel` was pressed. ### Note The standard keyboard accelerators work with these dialog boxes: where appropriate `Return` accepts the default action, `Esc` cancels and the underlined initial letter (`Y` or `N`) can be used. These functions are only available on Windows. ### See Also `[winMenuAdd](winmenus)` `[file.choose](../../base/html/file.choose)` to select a file package `windlgs` in the package source distribution for ways to program dialogs in C in the `GraphApp` toolkit. ### Examples ``` ## Not run: winDialog("yesno", "Is it OK to delete file blah") ``` r None `packageName` Find Package Associated with an Environment ---------------------------------------------------------- ### Description Many environments are associated with a package; this function attempts to determine that package. ### Usage ``` packageName(env = parent.frame()) ``` ### Arguments | | | | --- | --- | | `env` | The environment whose name we seek. | ### Details Environment `env` would be associated with a package if `[topenv](../../base/html/ns-topenv)(env)` is the namespace environment for that package. Thus when `env` is the environment associated with functions inside a package, or local functions defined within them, `packageName` will normally return the package name. Not all environments are associated with a package: for example, the global environment, or the evaluation frames of functions defined there. `packageName` will return `NULL` in these cases. ### Value A length one character vector containing the name of the package, or `NULL` if there is no name. ### See Also `[getPackageName](../../methods/html/getpackagename)` is a more elaborate function that can construct a name if none is found. ### Examples ``` packageName() packageName(environment(mean)) ``` r None `dataentry` Spreadsheet Interface for Entering Data ---------------------------------------------------- ### Description A spreadsheet-like editor for entering or editing data. ### Usage ``` data.entry(..., Modes = NULL, Names = NULL) dataentry(data, modes) de(..., Modes = list(), Names = NULL) ``` ### Arguments | | | | --- | --- | | `...` | A list of variables: currently these should be numeric or character vectors or list containing such vectors. | | `Modes` | The modes to be used for the variables. | | `Names` | The names to be used for the variables. | | `data` | A list of numeric and/or character vectors. | | `modes` | A list of length up to that of `data` giving the modes of (some of) the variables. `list()` is allowed. | ### Details The data entry editor is only available on some platforms and GUIs. Where available it provides a means to visually edit a matrix or a collection of variables (including a data frame) as described in the Notes section. `data.entry` has side effects, any changes made in the spreadsheet are reflected in the variables. The functions `de`, `de.ncols`, `de.setup` and `de.restore` are designed to help achieve these side effects. If the user passes in a matrix, `X` say, then the matrix is broken into columns before `dataentry` is called. Then on return the columns are collected and glued back together and the result assigned to the variable `X`. If you don't want this behaviour use dataentry directly. The primitive function is `dataentry`. It takes a list of vectors of possibly different lengths and modes (the second argument) and opens a spreadsheet with these variables being the columns. The columns of the dataentry window are returned as vectors in a list when the spreadsheet is closed. `de.ncols` counts the number of columns which are supplied as arguments to `data.entry`. It attempts to count columns in lists, matrices and vectors. `de.setup` sets things up so that on return the columns can be regrouped and reassigned to the correct name. This is handled by `de.restore`. ### Value `de` and `dataentry` return the edited value of their arguments. `data.entry` invisibly returns a vector of variable names but its main value is its side effect of assigning new version of those variables in the user's workspace. ### Resources The data entry window responds to X resources of class `R_dataentry`. Resources `foreground`, `background` and `geometry` are utilized. ### Note The details of interface to the data grid may differ by platform and GUI. The following description applies to the X11-based implementation under Unix. You can navigate around the grid using the cursor keys or by clicking with the (left) mouse button on any cell. The active cell is highlighted by thickening the surrounding rectangle. Moving to the right or down will scroll the grid as needed: there is no constraint to the rows or columns currently in use. There are alternative ways to navigate using the keys. Return and (keypad) Enter and LineFeed all move down. Tab moves right and Shift-Tab move left. Home moves to the top left. PageDown or Control-F moves down a page, and PageUp or Control-B up by a page. End will show the last used column and the last few rows used (in any column). Using any other key starts an editing process on the currently selected cell: moving away from that cell enters the edited value whereas Esc cancels the edit and restores the previous value. When the editing process starts the cell is cleared. In numerical columns (the default) only letters making up a valid number (including `-.eE`) are accepted, and entering an invalid edited value (such as blank) enters `NA` in that cell. The last entered value can be deleted using the BackSpace or Del(ete) key. Only a limited number of characters (currently 29) can be entered in a cell, and if necessary only the start or end of the string will be displayed, with the omissions indicated by `>` or `<`. (The start is shown except when editing.) Entering a value in a cell further down a column than the last used cell extends the variable and fills the gap (if any) by `NA`s (not shown on screen). The column names can only be selected by clicking in them. This gives a popup menu to select the column type (currently Real (numeric) or Character) or to change the name. Changing the type converts the current contents of the column (and converting from Character to Real may generate `NA`s.) If changing the name is selected the header cell becomes editable (and is cleared). As with all cells, the value is entered by moving away from the cell by clicking elsewhere or by any of the keys for moving down (only). New columns are created by entering values in them (and not by just assigning a new name). The mode of the column is auto-detected from the first value entered: if this is a valid number it gives a numeric column. Unused columns are ignored, so adding data in `var5` to a three-column grid adds one extra variable, not two. The `Copy` button copies the currently selected cell: `paste` copies the last copied value to the current cell, and right-clicking selects a cell *and* copies in the value. Initially the value is blank, and attempts to paste a blank value will have no effect. Control-L will refresh the display, recalculating field widths to fit the current entries. In the default mode the column widths are chosen to fit the contents of each column, with a default of 10 characters for empty columns. you can specify fixed column widths by setting option `de.cellwidth` to the required fixed width (in characters). (set it to zero to return to variable widths). The displayed width of any field is limited to 600 pixels (and by the window width). ### See Also `[vi](edit)`, `<edit>`: `edit` uses `dataentry` to edit data frames. ### Examples ``` # call data entry with variables x and y ## Not run: data.entry(x, y) ```
programming_docs
r None `stack` Stack or Unstack Vectors from a Data Frame or List ----------------------------------------------------------- ### Description Stacking vectors concatenates multiple vectors into a single vector along with a factor indicating where each observation originated. Unstacking reverses this operation. ### Usage ``` stack(x, ...) ## Default S3 method: stack(x, drop=FALSE, ...) ## S3 method for class 'data.frame' stack(x, select, drop=FALSE, ...) unstack(x, ...) ## Default S3 method: unstack(x, form, ...) ## S3 method for class 'data.frame' unstack(x, form, ...) ``` ### Arguments | | | | --- | --- | | `x` | a list or data frame to be stacked or unstacked. | | `select` | an expression, indicating which variable(s) to select from a data frame. | | `form` | a two-sided formula whose left side evaluates to the vector to be unstacked and whose right side evaluates to the indicator of the groups to create. Defaults to `[formula](../../stats/html/formula)(x)` in the data frame method for `unstack`. | | `drop` | Whether to drop the unused levels from the “ind” column of the return value. | | `...` | further arguments passed to or from other methods. | ### Details The `stack` function is used to transform data available as separate columns in a data frame or list into a single column that can be used in an analysis of variance model or other linear model. The `unstack` function reverses this operation. Note that `stack` applies to *vectors* (as determined by `[is.vector](../../base/html/vector)`): non-vector columns (e.g., factors) will be ignored with a warning. Where vectors of different types are selected they are concatenated by `[unlist](../../base/html/unlist)` whose help page explains how the type of the result is chosen. These functions are generic: the supplied methods handle data frames and objects coercible to lists by `[as.list](../../base/html/list)`. ### Value `unstack` produces a list of columns according to the formula `form`. If all the columns have the same length, the resulting list is coerced to a data frame. `stack` produces a data frame with two columns: | | | | --- | --- | | `values` | the result of concatenating the selected vectors in `x`. | | `ind` | a factor indicating from which vector in `x` the observation originated. | ### Author(s) Douglas Bates ### See Also `[lm](../../stats/html/lm)`, `[reshape](../../stats/html/reshape)` ### Examples ``` require(stats) formula(PlantGrowth) # check the default formula pg <- unstack(PlantGrowth) # unstack according to this formula pg stack(pg) # now put it back together stack(pg, select = -ctrl) # omitting one vector ``` r None `update.packages` Compare Installed Packages with CRAN-like Repositories ------------------------------------------------------------------------- ### Description `old.packages` indicates packages which have a (suitable) later version on the repositories whereas `update.packages` offers to download and install such packages. `new.packages` looks for (suitable) packages on the repositories that are not already installed, and optionally offers them for installation. ### Usage ``` update.packages(lib.loc = NULL, repos = getOption("repos"), contriburl = contrib.url(repos, type), method, instlib = NULL, ask = TRUE, available = NULL, oldPkgs = NULL, ..., checkBuilt = FALSE, type = getOption("pkgType")) old.packages(lib.loc = NULL, repos = getOption("repos"), contriburl = contrib.url(repos, type), instPkgs = installed.packages(lib.loc = lib.loc, ...), method, available = NULL, checkBuilt = FALSE, ..., type = getOption("pkgType")) new.packages(lib.loc = NULL, repos = getOption("repos"), contriburl = contrib.url(repos, type), instPkgs = installed.packages(lib.loc = lib.loc, ...), method, available = NULL, ask = FALSE, ..., type = getOption("pkgType")) ``` ### Arguments | | | | --- | --- | | `lib.loc` | character vector describing the location of R library trees to search through (and update packages therein), or `NULL` for all known trees (see `[.libPaths](../../base/html/libpaths)`). | | `repos` | character vector, the base URL(s) of the repositories to use, e.g., the URL of a CRAN mirror such as `"https://cloud.r-project.org"`. | | `contriburl` | URL(s) of the contrib sections of the repositories. Use this argument if your repository is incomplete. Overrides argument `repos`. Incompatible with `type = "both"`. | | `method` | Download method, see `<download.file>`. Unused if a non-`NULL` `available` is supplied. | | `instlib` | character string giving the library directory where to install the packages. | | `ask` | logical indicating whether to ask the user to select packages before they are downloaded and installed, or the character string `"graphics"`, which brings up a widget to allow the user to (de-)select from the list of packages which could be updated. The latter value only works on systems with a GUI version of `<select.list>`, and is otherwise equivalent to `ask = TRUE`. `ask` does not control questions asked before installing packages from source via `type = "both"` (see option `"install.packages.compile.from.source"`). | | `available` | an object as returned by `<available.packages>` listing packages available at the repositories, or `NULL` which makes an internal call to `available.packages`. Incompatible with `type = "both"`. | | `checkBuilt` | If `TRUE`, a package built under an earlier major.minor version of **R** (e.g., `3.4`) is considered to be ‘old’. | | `oldPkgs` | if specified as non-NULL, `update.packages()` only considers these packages for updating. This may be a character vector of package names or a matrix as returned by `old.packages`. | | `instPkgs` | by default all installed packages, `<installed.packages>(lib.loc = lib.loc)`. A subset can be specified; currently this must be in the same (character matrix) format as returned by `installed.packages()`. | | `...` | Arguments such as `destdir` and `dependencies` to be passed to `<install.packages>` and `ignore_repo_cache`, `max_repo_cache_age` and `noCache` to `<available.packages>` or `<installed.packages>`. | | `type` | character, indicating the type of package to download and install. See `<install.packages>`. | ### Details `old.packages` compares the information from `<available.packages>` with that from `instPkgs` (computed by `<installed.packages>` by default) and reports installed packages that have newer versions on the repositories or, if `checkBuilt = TRUE`, that were built under an earlier minor version of **R** (for example built under 3.3.x when running **R** 3.4.0). (For binary package types there is no check that the version on the repository was built under the current minor version of **R**, but it is advertised as being suitable for this version.) `new.packages` does the same comparison but reports uninstalled packages that are available at the repositories. If `ask != FALSE` it asks which packages should be installed in the first element of `lib.loc`. The main function of the set is `update.packages`. First a list of all packages found in `lib.loc` is created and compared with those available at the repositories. If `ask = TRUE` (the default) packages with a newer version are reported and for each one the user can specify if it should be updated. If so the packages are downloaded from the repositories and installed in the respective library path (or `instlib` if specified). For how the list of suitable available packages is determined see `<available.packages>`. `available = NULL` make a call to `available.packages(contriburl = contriburl, method = method)` and hence by default filters on **R** version, OS type and removes duplicates. ### Value `update.packages` returns `NULL` invisibly. For `old.packages`, `NULL` or a matrix with one row per package, row names the package names and column names `"Package"`, `"LibPath"`, `"Installed"` (the version), `"Built"` (the version built under), `"ReposVer"` and `"Repository"`. For `new.packages` a character vector of package names, *after* any selected *via* `ask` have been installed. ### Warning Take care when using `dependencies` (passed to `<install.packages>`) with `update.packages`, for it is unclear where new dependencies should be installed. The current implementation will only allow it if all the packages to be updated are in a single library, when that library will be used. ### See Also `<install.packages>`, `<available.packages>`, `<download.packages>`, `<installed.packages>`, `<contrib.url>`. The options listed for `install.packages` under `[options](../../base/html/options)`. See `<download.file>` for how to handle proxies and other options to monitor file transfers. `[INSTALL](install)`, `[REMOVE](remove)`, `<remove.packages>`, `[library](../../base/html/library)`, `[.packages](../../base/html/zpackages)`, `[read.dcf](../../base/html/dcf)` The ‘R Installation and Administration’ manual for how to set up a repository. r None `logLik-methods` Methods for Function logLik in Package stats4 --------------------------------------------------------------- ### Description Extract the maximized log-likelihood from `"mle"` objects. ### Methods `signature(object = "ANY")` Generic function: see `[logLik](../../stats/html/loglik)`. `signature(object = "mle")` Extract log-likelihood from the fit. ### Note The `mle` method does not know about the number of observations unless `nobs` was specified on the call and so may not be suitable for use with `[BIC](../../stats/html/aic)`. r None `profile-methods` Methods for Function profile in Package stats4 ----------------------------------------------------------------- ### Description Profile likelihood for `"mle"` objects. ### Usage ``` ## S4 method for signature 'mle' profile(fitted, which = 1:p, maxsteps = 100, alpha = 0.01, zmax = sqrt(qchisq(1 - alpha, 1L)), del = zmax/5, trace = FALSE, ...) ``` ### Arguments | | | | --- | --- | | `fitted` | Object to be profiled | | `which` | Optionally select subset of parameters to profile. | | `maxsteps` | Maximum number of steps to bracket `zmax`. | | `alpha` | Significance level corresponding to `zmax`, based on a Scheffe-style multiple testing interval. Ignored if `zmax` is specified. | | `zmax` | Cutoff for the profiled value of the signed root-likelihood. | | `del` | Initial stepsize on root-likelihood scale. | | `trace` | Logical. Print intermediate results. | | `...` | Currently unused. | ### Details The profiling algorithm tries to find an approximately evenly spaced set of at least five parameter values (in each direction from the optimum) to cover the root-likelihood function. Some care is taken to try and get sensible results in cases of high parameter curvature. Notice that it may not always be possible to obtain the cutoff value, since the likelihood might level off. ### Value An object of class `"profile.mle"`, see `"profile.mle-class"`. ### Methods `signature(fitted = "ANY")` Generic function: see `[profile](../../stats/html/profile)`. `signature(fitted = "mle")` Profile the likelihood in the vicinity of the optimum of an `"mle"` object. r None `vcov-methods` Methods for Function vcov in Package stats4 ----------------------------------------------------------- ### Description Extract the approximate variance-covariance matrix from `"mle"` objects. ### Methods `signature(object = "ANY")` Generic function: see `[vcov](../../stats/html/vcov)`. `signature(object = "mle")` Extract the estimated variance-covariance matrix for the estimated parameters (if any). r None `summary-methods` Methods for Function summary in Package stats4 ----------------------------------------------------------------- ### Description Summarize objects ### Methods `signature(object = "ANY")` Generic function `signature(object = "mle")` Generate a summary as an object of class `"summary.mle"`, containing estimates, asymptotic SE, and value of *-2 log L*. r None `update-methods` Methods for Function update in Package stats4 --------------------------------------------------------------- ### Description Update `"mle"` objects. ### Usage ``` ## S4 method for signature 'mle' update(object, ..., evaluate = TRUE) ``` ### Arguments | | | | --- | --- | | `object` | An existing fit. | | `...` | Additional arguments to the call, or arguments with changed values. Use `name = NULL` to remove the argument `name`. | | `evaluate` | If true evaluate the new call else return the call. | ### Methods `signature(object = "ANY")` Generic function: see `[update](../../stats/html/update)`. `signature(object = "mle")` Update a fit. ### Examples ``` x <- 0:10 y <- c(26, 17, 13, 12, 20, 5, 9, 8, 5, 4, 8) ll <- function(ymax = 15, xhalf = 6) -sum(stats::dpois(y, lambda = ymax/(1+x/xhalf), log = TRUE)) fit <- mle(ll) ## note the recorded call contains ..1, a problem with S4 dispatch update(fit, fixed = list(xhalf = 3)) ``` r None `stats4-package` Statistical Functions using S4 Classes -------------------------------------------------------- ### Description Statistical Functions using S4 classes. ### Details This package contains functions and classes for statistics using the [S version 4](../../methods/html/methods-package) class system. The methods currently support maximum likelihood (function `<mle>()` returning class `"[mle](mle-class)"`), including methods for `[logLik](loglik-methods)` for use with `[AIC](../../stats/html/aic)`. ### Author(s) R Core Team and contributors worldwide Maintainer: R Core Team [[email protected]](mailto:[email protected]) r None `mle` Maximum Likelihood Estimation ------------------------------------ ### Description Estimate parameters by the method of maximum likelihood. ### Usage ``` mle(minuslogl, start, optim = stats::optim, method = if(!useLim) "BFGS" else "L-BFGS-B", fixed = list(), nobs, lower, upper, ...) ``` ### Arguments | | | | --- | --- | | `minuslogl` | Function to calculate negative log-likelihood. | | `start` | Named list of vectors or single vector. Initial values for optimizer. By default taken from the default arguments of `minuslogl` | | `optim` | Optimizer function. (Experimental) | | `method` | Optimization method to use. See `[optim](../../stats/html/optim)`. | | `fixed` | Named list of vectors or single vector. Parameter values to keep fixed during optimization. | | `nobs` | optional integer: the number of observations, to be used for e.g. computing `[BIC](../../stats/html/aic)`. | | `lower, upper` | Named lists of vectors or single vectors. Bounds for `[optim](../../stats/html/optim)`, if relevant. | | `...` | Further arguments to pass to `[optim](../../stats/html/optim)`. | ### Details The `optim` optimizer is used to find the minimum of the negative log-likelihood. An approximate covariance matrix for the parameters is obtained by inverting the Hessian matrix at the optimum. By default, `[optim](../../stats/html/optim)` from the `stats` package is used; other optimizers need to be plug-compatible, both with respect to arguments and return values. The function `minuslogl` should take one or several arguments, each of which can be a vector. The optimizer optimizes a function which takes a single vector argument, containing the concatenation of the arguments to `minuslogl`, removing any values that should be held fixed. This function internally unpacks the argument vector, inserts the fixed values and calls `minuslogl`. The vector arguments `start`, `fixed`, `upper`, and `lower`, can be given in both packed and unpacked form, either as a single vector or as a list of vectors. In the latter case, you only need to specify those list elements that are actually affected. For vector arguments, including those inside lists, use a default marker for those values that you don't want to set: `NA` for `fixed` and `start`, and `+Inf, -Inf` for `upper`, and `lower`. ### Value An object of class `<mle-class>`. ### Note Notice that the `mll` argument should calculate -log L (not -2 log L). It is for the user to ensure that the likelihood is correct, and that asymptotic likelihood inference is valid. ### See Also `<mle-class>` ### Examples ``` ## Avoid printing to unwarranted accuracy od <- options(digits = 5) ## Simulated EC50 experiment with count data x <- 0:10 y <- c(26, 17, 13, 12, 20, 5, 9, 8, 5, 4, 8) ## Easy one-dimensional MLE: nLL <- function(lambda) -sum(stats::dpois(y, lambda, log = TRUE)) fit0 <- mle(nLL, start = list(lambda = 5), nobs = NROW(y)) ## sanity check --- notice that "nobs" must be input ## (not guaranteed to be meaningful for any likelihood) stopifnot(nobs(fit0) == length(y)) # For 1D, this is preferable: fit1 <- mle(nLL, start = list(lambda = 5), nobs = NROW(y), method = "Brent", lower = 1, upper = 20) ## This needs a constrained parameter space: most methods will accept NA ll <- function(ymax = 15, xhalf = 6) { if(ymax > 0 && xhalf > 0) -sum(stats::dpois(y, lambda = ymax/(1+x/xhalf), log = TRUE)) else NA } (fit <- mle(ll, nobs = length(y))) mle(ll, fixed = list(xhalf = 6)) ## Alternative using bounds on optimization ll2 <- function(ymax = 15, xhalf = 6) -sum(stats::dpois(y, lambda = ymax/(1+x/xhalf), log = TRUE)) mle(ll2, lower = rep(0, 2)) AIC(fit) BIC(fit) summary(fit) logLik(fit) vcov(fit) plot(profile(fit), absVal = FALSE) confint(fit) ## Use bounded optimization ## The lower bounds are really > 0, ## but we use >=0 to stress-test profiling (fit2 <- mle(ll2, lower = c(0, 0))) plot(profile(fit2), absVal = FALSE) ## A better parametrization: ll3 <- function(lymax = log(15), lxhalf = log(6)) -sum(stats::dpois(y, lambda = exp(lymax)/(1+x/exp(lxhalf)), log = TRUE)) (fit3 <- mle(ll3)) plot(profile(fit3), absVal = FALSE) exp(confint(fit3)) # Regression tests for bounded cases (this was broken in R 3.x) fit4 <- mle(ll, lower = c(0, 4)) # has max on boundary confint(fit4) ## direct check that fixed= and constraints work together mle(ll, lower = c(0, 4), fixed=list(ymax=23)) # has max on boundary ## Linear regression using MLE x <- 1:10 y <- c(0.48, 2.24, 2.22, 5.15, 4.64, 5.53, 7, 8.8, 7.67, 9.23) LM_mll <- function(formula, data = environment(formula)) { y <- model.response(model.frame(formula, data)) X <- model.matrix(formula, data) b0 <- numeric(NCOL(X)) names(b0) <- colnames(X) function(b=b0, sigma=1) -sum(dnorm(y, X %*% b, sigma, log=TRUE)) } mll <- LM_mll(y ~ x) summary(lm(y~x)) # for comparison -- notice variance bias in MLE summary(mle(mll, lower=c(-Inf,-Inf, 0.01))) summary(mle(mll, lower=list(sigma = 0.01))) # alternative specification confint(mle(mll, lower=list(sigma = 0.01))) plot(profile(mle(mll, lower=list(sigma = 0.01)))) Binom_mll <- function(x, n) { force(x); force(n) ## beware lazy evaluation function(p=.5) -dbinom(x, n, p, log=TRUE) } ## Likelihood functions for different x. ## This code goes wrong, if force(x) is not used in Binom_mll: curve(Binom_mll(0, 10)(p), xname="p", ylim=c(0, 10)) mll_list <- list(10) for (x in 1:10) mll_list[[x]] <- Binom_mll(x, 10) for (mll in mll_list) curve(mll(p), xname="p", add=TRUE) mll <- Binom_mll(4,10) mle(mll, lower = 1e-16, upper = 1-1e-16) # limits must be inside (0,1) ## Boundary case: This works, but fails if limits are set closer to 0 and 1 mll <- Binom_mll(0, 10) mle(mll, lower=.005, upper=.995) ## Not run: ## We can use limits closer to the boundaries if we use the ## drop-in replacement optimr() from the optimx package. mle(mll, lower = 1e-16, upper = 1-1e-16, optim=optimx::optimr) ## End(Not run) options(od) ```
programming_docs
r None `confint-methods` Methods for Function confint in Package stats4 ----------------------------------------------------------------- ### Description Generate confidence intervals ### Methods `signature(object = "ANY")` Generic function: see `[confint](../../stats/html/confint)`. `signature(object = "mle")` First generate profile and then confidence intervals from the profile. `signature(object = "profile.mle")` Generate confidence intervals based on likelihood profile. r None `profile.mle-class` Class "profile.mle"; Profiling information for "mle" object -------------------------------------------------------------------------------- ### Description Likelihood profiles along each parameter of likelihood function ### Objects from the Class Objects can be created by calls of the form `new("profile.mle", ...)`, but most often by invoking `profile` on an "mle" object. ### Slots `profile`: Object of class `"list"`. List of profiles, one for each requested parameter. Each profile is a data frame with the first column called `z` being the signed square root of the -2 log likelihood ratio, and the others being the parameters with names prefixed by `par.vals.` `summary`: Object of class `"summary.mle"`. Summary of object being profiled. ### Methods confint `signature(object = "profile.mle")`: Use profile to generate approximate confidence intervals for parameters. plot `signature(x = "profile.mle", y = "missing")`: Plot profiles for each parameter. ### See Also `<mle>`, `<mle-class>`, `<summary.mle-class>` r None `summary.mle-class` Class "summary.mle", Summary of "mle" Objects ------------------------------------------------------------------ ### Description Extract of "mle" object ### Objects from the Class Objects can be created by calls of the form `new("summary.mle", ...)`, but most often by invoking `summary` on an "mle" object. They contain values meant for printing by `show`. ### Slots `call`: Object of class `"language"` The call that generated the "mle" object. `coef`: Object of class `"matrix"`. Estimated coefficients and standard errors `m2logL`: Object of class `"numeric"`. Minus twice the log likelihood. ### Methods show `signature(object = "summary.mle")`: Pretty-prints `object` coef `signature(object = "summary.mle")`: Extracts the contents of the `coef` slot ### See Also `[summary](../../base/html/summary)`, `<mle>`, `<mle-class>` r None `show-methods` Methods for Function show in Package stats4 ----------------------------------------------------------- ### Description Show objects of classes `mle` and `summary.mle` ### Methods `signature(object = "mle")` Print simple summary of `mle` object. Just the coefficients and the call. `signature(object = "summary.mle")` Shows call, table of coefficients and standard errors, and *-2 log L*. r None `coef-methods` Methods for Function coef in Package stats4 ----------------------------------------------------------- ### Description Extract the coefficient vector from `"mle"` objects. ### Methods `signature(object = "ANY")` Generic function: see `[coef](../../stats/html/coef)`. `signature(object = "mle")` Extract the full coefficient vector (including any fixed coefficients) from the fit. `signature(object = "summary.mle")` Extract the coefficient vector and standard errors from the summary of the fit. r None `mle-class` Class "mle" for Results of Maximum Likelihood Estimation --------------------------------------------------------------------- ### Description This class encapsulates results of a generic maximum likelihood procedure. ### Objects from the Class Objects can be created by calls of the form `new("mle", ...)`, but most often as the result of a call to `<mle>`. ### Slots `call`: Object of class `"language"`. The call to `<mle>`. `coef`: Object of class `"numeric"`. Estimated parameters. `fullcoef`: Object of class `"numeric"`. Full parameter set of fixed and estimated parameters. `fixed`: Object of class `"numeric"`. Fixed parameter values (`NA` for non-fixed parameters). `vcov`: Object of class `"matrix"`. Approximate variance-covariance matrix. `min`: Object of class `"numeric"`. Minimum value of objective function. `details`: a `"[list](../../base/html/list)"`, as returned from `[optim](../../stats/html/optim)`. `minuslogl`: Object of class `"function"`. The negative loglikelihood function. `nobs`: `"[integer](../../base/html/integer)"` of length one. The number of observations (often `NA`, when not set in call explicitly). `method`: Object of class `"character"`. The optimization method used. ### Methods confint `signature(object = "mle")`: Confidence intervals from likelihood profiles. logLik `signature(object = "mle")`: Extract maximized log-likelihood. profile `signature(fitted = "mle")`: Likelihood profile generation. nobs `signature(object = "mle")`: Number of observations, here simply accessing the `nobs` slot mentioned above. show `signature(object = "mle")`: Display object briefly. summary `signature(object = "mle")`: Generate object summary. update `signature(object = "mle")`: Update fit. vcov `signature(object = "mle")`: Extract variance-covariance matrix. r None `plot-methods` Methods for Function plot in Package stats4 ----------------------------------------------------------- ### Description Plot profile likelihoods for `"mle"` objects. ### Usage ``` ## S4 method for signature 'profile.mle,missing' plot(x, levels, conf = c(99, 95, 90, 80, 50)/100, nseg = 50, absVal = TRUE, ...) ``` ### Arguments | | | | --- | --- | | `x` | an object of class `"profile.mle"` | | `levels` | levels, on the scale of the absolute value of a t statistic, at which to interpolate intervals. Usually `conf` is used instead of giving `levels` explicitly. | | `conf` | a numeric vector of confidence levels for profile-based confidence intervals on the parameters. | | `nseg` | an integer value giving the number of segments to use in the spline interpolation of the profile t curves. | | `absVal` | a logical value indicating whether or not the plots should be on the scale of the absolute value of the profile t. Defaults to `TRUE`. | | `...` | other arguments to the `plot` function can be passed here. | ### Methods `signature(x = "ANY", y = "ANY")` Generic function: see `[plot](../../graphics/html/plot.default)`. `signature(x = "profile.mle", y = "missing")` Plot likelihood profiles for `x`. r None `na.rpart` Handles Missing Values in an Rpart Object ----------------------------------------------------- ### Description Handles missing values in an `"rpart"` object. ### Usage ``` na.rpart(x) ``` ### Arguments | | | | --- | --- | | `x` | a model frame. | ### Details Default function that handles missing values when calling the function `rpart`. It omits cases where part of the response is missing or all the explanatory variables are missing. r None `predict.rpart` Predictions from a Fitted Rpart Object ------------------------------------------------------- ### Description Returns a vector of predicted responses from a fitted `rpart` object. ### Usage ``` ## S3 method for class 'rpart' predict(object, newdata, type = c("vector", "prob", "class", "matrix"), na.action = na.pass, ...) ``` ### Arguments | | | | --- | --- | | `object` | fitted model object of class `"rpart"`. This is assumed to be the result of some function that produces an object with the same named components as that returned by the `rpart` function. | | `newdata` | data frame containing the values at which predictions are required. The predictors referred to in the right side of `formula(object)` must be present by name in `newdata`. If missing, the fitted values are returned. | | `type` | character string denoting the type of predicted value returned. If the `rpart` object is a classification tree, then the default is to return `prob` predictions, a matrix whose columns are the probability of the first, second, etc. class. (This agrees with the default behavior of `[tree](../../tree/html/tree)`). Otherwise, a vector result is returned. | | `na.action` | a function to determine what should be done with missing values in `newdata`. The default is to pass them down the tree using surrogates in the way selected when the model was built. Other possibilities are `[na.omit](../../stats/html/na.fail)` and `[na.fail](../../stats/html/na.fail)`. | | `...` | further arguments passed to or from other methods. | ### Details This function is a method for the generic function predict for class `"rpart"`. It can be invoked by calling `predict` for an object of the appropriate class, or directly by calling `predict.rpart` regardless of the class of the object. ### Value A new object is obtained by dropping `newdata` down the object. For factor predictors, if an observation contains a level not used to grow the tree, it is left at the deepest possible node and `frame$yval` at the node is the prediction. If `type = "vector"`: vector of predicted responses. For regression trees this is the mean response at the node, for Poisson trees it is the estimated response rate, and for classification trees it is the predicted class (as a number). If `type = "prob"`: (for a classification tree) a matrix of class probabilities. If `type = "matrix"`: a matrix of the full responses (`frame$yval2` if this exists, otherwise `frame$yval`). For regression trees, this is the mean response, for Poisson trees it is the response rate and the number of events at that node in the fitted tree, and for classification trees it is the concatenation of at least the predicted class, the class counts at that node in the fitted tree, and the class probabilities (some versions of rpart may contain further columns). If `type = "class"`: (for a classification tree) a factor of classifications based on the responses. ### See Also `[predict](../../stats/html/predict)`, `<rpart.object>` ### Examples ``` z.auto <- rpart(Mileage ~ Weight, car.test.frame) predict(z.auto) fit <- rpart(Kyphosis ~ Age + Number + Start, data = kyphosis) predict(fit, type = "prob") # class probabilities (default) predict(fit, type = "vector") # level numbers predict(fit, type = "class") # factor predict(fit, type = "matrix") # level number, class frequencies, probabilities sub <- c(sample(1:50, 25), sample(51:100, 25), sample(101:150, 25)) fit <- rpart(Species ~ ., data = iris, subset = sub) fit table(predict(fit, iris[-sub,], type = "class"), iris[-sub, "Species"]) ``` r None `printcp` Displays CP table for Fitted Rpart Object ---------------------------------------------------- ### Description Displays the `cp` table for fitted `rpart` object. ### Usage ``` printcp(x, digits = getOption("digits") - 2) ``` ### Arguments | | | | --- | --- | | `x` | fitted model object of class `"rpart"`. This is assumed to be the result of some function that produces an object with the same named components as that returned by the `rpart` function. | | `digits` | the number of digits of numbers to print. | ### Details Prints a table of optimal prunings based on a complexity parameter. ### See Also `<summary.rpart>`, `<rpart.object>` ### Examples ``` z.auto <- rpart(Mileage ~ Weight, car.test.frame) printcp(z.auto) ## Not run: Regression tree: rpart(formula = Mileage ~ Weight, data = car.test.frame) Variables actually used in tree construction: [1] Weight Root node error: 1354.6/60 = 22.576 CP nsplit rel error xerror xstd 1 0.595349 0 1.00000 1.03436 0.178526 2 0.134528 1 0.40465 0.60508 0.105217 3 0.012828 2 0.27012 0.45153 0.083330 4 0.010000 3 0.25729 0.44826 0.076998 ## End(Not run) ``` r None `rpart.object` Recursive Partitioning and Regression Trees Object ------------------------------------------------------------------ ### Description These are objects representing fitted `rpart` trees. ### Value | | | | --- | --- | | `frame` | data frame with one row for each node in the tree. The `row.names` of `frame` contain the (unique) node numbers that follow a binary ordering indexed by node depth. Columns of `frame` include `var`, a factor giving the names of the variables used in the split at each node (leaf nodes are denoted by the level `"<leaf>"`), `n`, the number of observations reaching the node, `wt`, the sum of case weights for observations reaching the node, `dev`, the deviance of the node, `yval`, the fitted value of the response at the node, and `splits`, a two column matrix of left and right split labels for each node. Also included in the frame are `complexity`, the complexity parameter at which this split will collapse, `ncompete`, the number of competitor splits recorded, and `nsurrogate`, the number of surrogate splits recorded. Extra response information which may be present is in `yval2`, which contains the number of events at the node (poisson tree), or a matrix containing the fitted class, the class counts for each node, the class probabilities and the ‘node probability’ (classification trees). | | `where` | an integer vector of the same length as the number of observations in the root node, containing the row number of `frame` corresponding to the leaf node that each observation falls into. | | `call` | an image of the call that produced the object, but with the arguments all named and with the actual formula included as the formula argument. To re-evaluate the call, say `update(tree)`. | | `terms` | an object of class `c("terms", "formula")` (see `[terms.object](../../stats/html/terms.object)`) summarizing the formula. Used by various methods, but typically not of direct relevance to users. | | `splits` | a numeric matrix describing the splits: only present if there are any. The row label is the name of the split variable, and columns are `count`, the number of observations (which are not missing and are of positive weight) sent left or right by the split (for competitor splits this is the number that would have been sent left or right had this split been used, for surrogate splits it is the number missing the primary split variable which were decided using this surrogate), `ncat`, the number of categories or levels for the variable (`+/-1` for a continuous variable), `improve`, which is the improvement in deviance given by this split, or, for surrogates, the concordance of the surrogate with the primary, and `index`, the numeric split point. The last column `adj` gives the adjusted concordance for surrogate splits. For a factor, the `index` column contains the row number of the csplit matrix. For a continuous variable, the sign of `ncat` determines whether the subset `x < cutpoint` or `x > cutpoint` is sent to the left. | | `csplit` | an integer matrix. (Only present only if at least one of the split variables is a factor or ordered factor.) There is a row for each such split, and the number of columns is the largest number of levels in the factors. Which row is given by the `index` column of the `splits` matrix. The columns record `1` if that level of the factor goes to the left, `3` if it goes to the right, and `2` if that level is not present at this node of the tree (or not defined for the factor). | | `method` | character string: the method used to grow the tree. One of `"class"`, `"exp"`, `"poisson"`, `"anova"` or `"user"` (if splitting functions were supplied). | | `cptable` | a matrix of information on the optimal prunings based on a complexity parameter. | | `variable.importance` | a named numeric vector giving the importance of each variable. (Only present if there are any splits.) When printed by `<summary.rpart>` these are rescaled to add to 100. | | `numresp` | integer number of responses; the number of levels for a factor response. | | `parms, control` | a record of the arguments supplied, which defaults filled in. | | `functions` | the `summary`, `print` and `text` functions for method used. | | `ordered` | a named logical vector recording for each variable if it was an ordered factor. | | `na.action` | (where relevant) information returned by `[model.frame](../../stats/html/model.frame)` on the special handling of `NA`s derived from the `na.action` argument. | There may be [attributes](../../base/html/attributes) `"xlevels"` and `"levels"` recording the levels of any factor splitting variables and of a factor response respectively. Optional components include the model frame (`model`), the matrix of predictors (`x`) and the response variable (`y`) used to construct the `rpart` object. ### Structure The following components must be included in a legitimate `rpart` object. ### See Also `<rpart>`. r None `cu.summary` Automobile Data from 'Consumer Reports' 1990 ---------------------------------------------------------- ### Description The `cu.summary` data frame has 117 rows and 5 columns, giving data on makes of cars taken from the April, 1990 issue of *Consumer Reports*. ### Usage ``` cu.summary ``` ### Format This data frame contains the following columns: `Price` a numeric vector giving the list price in US dollars of a standard model `Country` of origin, a factor with levels Brazil, England, France, Germany, Japan, Japan/USA, Korea, Mexico, Sweden and USA `Reliability` an ordered factor with levels Much worse < worse < average < better < Much better `Mileage` fuel consumption miles per US gallon, as tested. `Type` a factor with levels `Compact` `Large` `Medium` `Small` `Sporty` `Van` ### Source *Consumer Reports*, April, 1990, pp. 235–288 quoted in John M. Chambers and Trevor J. Hastie eds. (1992) *Statistical Models in S*, Wadsworth and Brooks/Cole, Pacific Grove, CA, pp. 46–47. ### See Also `<car.test.frame>`, `<car90>` ### Examples ``` fit <- rpart(Price ~ Mileage + Type + Country, cu.summary) par(xpd = TRUE) plot(fit, compress = TRUE) text(fit, use.n = TRUE) ``` r None `residuals.rpart` Residuals From a Fitted Rpart Object ------------------------------------------------------- ### Description Method for `residuals` for an `rpart` object. ### Usage ``` ## S3 method for class 'rpart' residuals(object, type = c("usual", "pearson", "deviance"), ...) ``` ### Arguments | | | | --- | --- | | `object` | fitted model object of class `"rpart"`. | | `type` | Indicates the type of residual desired. For regression or `anova` trees all three residual definitions reduce to `y - fitted`. This is the residual returned for `user` method trees as well. For classification trees the `usual` residuals are the misclassification losses L(actual, predicted) where L is the loss matrix. With default losses this residual is 0/1 for correct/incorrect classification. The `pearson` residual is (1-fitted)/sqrt(fitted(1-fitted)) and the `deviance` residual is sqrt(minus twice logarithm of fitted). For `poisson` and `exp` (or survival) trees, the `usual` residual is the observed - expected number of events. The `pearson` and `deviance` residuals are as defined in McCullagh and Nelder. | | `...` | further arguments passed to or from other methods. | ### Value Vector of residuals of type `type` from a fitted `rpart` object. ### References McCullagh P. and Nelder, J. A. (1989) *Generalized Linear Models*. London: Chapman and Hall. ### Examples ``` fit <- rpart(skips ~ Opening + Solder + Mask + PadType + Panel, data = solder.balance, method = "anova") summary(residuals(fit)) plot(predict(fit),residuals(fit)) ``` r None `post.rpart` PostScript Presentation Plot of an Rpart Object ------------------------------------------------------------- ### Description Generates a PostScript presentation plot of an `rpart` object. ### Usage ``` post(tree, ...) ## S3 method for class 'rpart' post(tree, title., filename = paste(deparse(substitute(tree)), ".ps", sep = ""), digits = getOption("digits") - 2, pretty = TRUE, use.n = TRUE, horizontal = TRUE, ...) ``` ### Arguments | | | | --- | --- | | `tree` | fitted model object of class `"rpart"`. This is assumed to be the result of some function that produces an object with the same named components as that returned by the `rpart` function. | | `title.` | a title which appears at the top of the plot. By default, the name of the `rpart` endpoint is printed out. | | `filename` | ASCII file to contain the output. By default, the name of the file is the name of the object given by `rpart` (with the suffix `.ps` added). If `filename = ""`, the plot appears on the current graphical device. | | `digits` | number of significant digits to include in numerical data. | | `pretty` | an integer denoting the extent to which factor levels will be abbreviated in the character strings defining the splits; (0) signifies no abbreviation of levels. A `NULL` signifies using elements of letters to represent the different factor levels. The default (`TRUE`) indicates the maximum possible abbreviation. | | `use.n` | Logical. If `TRUE` (default), adds to label (\#events level1/ \#events level2/etc. for method `class`, `n` for method `anova`, and \#events/n for methods `poisson` and `exp`). | | `horizontal` | Logical. If `TRUE` (default), plot is horizontal. If `FALSE`, plot appears as landscape. | | `...` | other arguments to the `postscript` function. | ### Details The plot created uses the functions `plot.rpart` and `text.rpart` (with the `fancy` option). The settings were chosen because they looked good to us, but other options may be better, depending on the `rpart` object. Users are encouraged to write their own function containing favorite options. ### Side Effects a plot of `rpart` is created using the `postscript` driver, or the current device if `filename = ""`. ### See Also `<plot.rpart>`, `<rpart>`, `<text.rpart>`, `[abbreviate](../../base/html/abbreviate)` ### Examples ``` ## Not run: z.auto <- rpart(Mileage ~ Weight, car.test.frame) post(z.auto, file = "") # display tree on active device # now construct postscript version on file "pretty.ps" # with no title post(z.auto, file = "pretty.ps", title = " ") z.hp <- rpart(Mileage ~ Weight + HP, car.test.frame) post(z.hp) ## End(Not run) ```
programming_docs
r None `path.rpart` Follow Paths to Selected Nodes of an Rpart Object --------------------------------------------------------------- ### Description Returns a names list where each element contains the splits on the path from the root to the selected nodes. ### Usage ``` path.rpart(tree, nodes, pretty = 0, print.it = TRUE) ``` ### Arguments | | | | --- | --- | | `tree` | fitted model object of class `"rpart"`. This is assumed to be the result of some function that produces an object with the same named components as that returned by the `rpart` function. | | `nodes` | an integer vector containing indices (node numbers) of all nodes for which paths are desired. If missing, user selects nodes as described below. | | `pretty` | an integer denoting the extent to which factor levels in split labels will be abbreviated. A value of (0) signifies no abbreviation. A `NULL`, the default, signifies using elements of letters to represent the different factor levels. | | `print.it` | Logical. Denotes whether paths will be printed out as nodes are interactively selected. Irrelevant if `nodes` argument is supplied. | ### Details The function has a required argument as an `rpart` object and a list of nodes as optional arguments. Omitting a list of nodes will cause the function to wait for the user to select nodes from the dendrogram. It will return a list, with one component for each node specified or selected. The component contains the sequence of splits leading to that node. In the graphical interaction, the individual paths are printed out as nodes are selected. ### Value A named (by node) list, each element of which contains all the splits on the path from the root to the specified or selected nodes. ### Graphical Interaction A dendrogram of the `rpart` object is expected to be visible on the graphics device, and a graphics input device (e.g. a mouse) is required. Clicking (the selection button) on a node selects that node. This process may be repeated any number of times. Clicking the exit button will stop the selection process and return the list of paths. ### References This function was modified from `path.tree` in S. ### See Also `<rpart>` ### Examples ``` fit <- rpart(Kyphosis ~ Age + Number + Start, data = kyphosis) print(fit) path.rpart(fit, node = c(11, 22)) ``` r None `rpart.control` Control for Rpart Fits --------------------------------------- ### Description Various parameters that control aspects of the `rpart` fit. ### Usage ``` rpart.control(minsplit = 20, minbucket = round(minsplit/3), cp = 0.01, maxcompete = 4, maxsurrogate = 5, usesurrogate = 2, xval = 10, surrogatestyle = 0, maxdepth = 30, ...) ``` ### Arguments | | | | --- | --- | | `minsplit` | the minimum number of observations that must exist in a node in order for a split to be attempted. | | `minbucket` | the minimum number of observations in any terminal `<leaf>` node. If only one of `minbucket` or `minsplit` is specified, the code either sets `minsplit` to `minbucket*3` or `minbucket` to `minsplit/3`, as appropriate. | | `cp` | complexity parameter. Any split that does not decrease the overall lack of fit by a factor of `cp` is not attempted. For instance, with `anova` splitting, this means that the overall R-squared must increase by `cp` at each step. The main role of this parameter is to save computing time by pruning off splits that are obviously not worthwhile. Essentially,the user informs the program that any split which does not improve the fit by `cp` will likely be pruned off by cross-validation, and that hence the program need not pursue it. | | `maxcompete` | the number of competitor splits retained in the output. It is useful to know not just which split was chosen, but which variable came in second, third, etc. | | `maxsurrogate` | the number of surrogate splits retained in the output. If this is set to zero the compute time will be reduced, since approximately half of the computational time (other than setup) is used in the search for surrogate splits. | | `usesurrogate` | how to use surrogates in the splitting process. `0` means display only; an observation with a missing value for the primary split rule is not sent further down the tree. `1` means use surrogates, in order, to split subjects missing the primary variable; if all surrogates are missing the observation is not split. For value `2` ,if all surrogates are missing, then send the observation in the majority direction. A value of `0` corresponds to the action of `tree`, and `2` to the recommendations of Breiman *et.al* (1984). | | `xval` | number of cross-validations. | | `surrogatestyle` | controls the selection of a best surrogate. If set to `0` (default) the program uses the total number of correct classification for a potential surrogate variable, if set to `1` it uses the percent correct, calculated over the non-missing values of the surrogate. The first option more severely penalizes covariates with a large number of missing values. | | `maxdepth` | Set the maximum depth of any node of the final tree, with the root node counted as depth 0. Values greater than 30 `rpart` will give nonsense results on 32-bit machines. | | `...` | mop up other arguments. | ### Value A list containing the options. ### See Also `<rpart>` r None `plotcp` Plot a Complexity Parameter Table for an Rpart Fit ------------------------------------------------------------ ### Description Gives a visual representation of the cross-validation results in an `rpart` object. ### Usage ``` plotcp(x, minline = TRUE, lty = 3, col = 1, upper = c("size", "splits", "none"), ...) ``` ### Arguments | | | | --- | --- | | `x` | an object of class `"rpart"` | | `minline` | whether a horizontal line is drawn 1SE above the minimum of the curve. | | `lty` | line type for this line | | `col` | colour for this line | | `upper` | what is plotted on the top axis: the size of the tree (the number of leaves), the number of splits or nothing. | | `...` | additional plotting parameters | ### Details The set of possible cost-complexity prunings of a tree from a nested set. For the geometric means of the intervals of values of `cp` for which a pruning is optimal, a cross-validation has (usually) been done in the initial construction by `<rpart>`. The `cptable` in the fit contains the mean and standard deviation of the errors in the cross-validated prediction against each of the geometric means, and these are plotted by this function. A good choice of `cp` for pruning is often the leftmost value for which the mean lies below the horizontal line. ### Value None. ### Side Effects A plot is produced on the current graphical device. ### See Also `<rpart>`, `<printcp>`, `<rpart.object>` r None `meanvar.rpart` Mean-Variance Plot for an Rpart Object ------------------------------------------------------- ### Description Creates a plot on the current graphics device of the deviance of the node divided by the number of observations at the node. Also returns the node number. ### Usage ``` meanvar(tree, ...) ## S3 method for class 'rpart' meanvar(tree, xlab = "ave(y)", ylab = "ave(deviance)", ...) ``` ### Arguments | | | | --- | --- | | `tree` | fitted model object of class `"rpart"`. This is assumed to be the result of some function that produces an object with the same named components as that returned by the `rpart` function. | | `xlab` | x-axis label for the plot. | | `ylab` | y-axis label for the plot. | | `...` | additional graphical parameters may be supplied as arguments to this function. | ### Value an invisible list containing the following vectors is returned. | | | | --- | --- | | `x` | fitted value at terminal nodes (`yval`). | | `y` | deviance of node divided by number of observations at node. | | `label` | node number. | ### Side Effects a plot is put on the current graphics device. ### See Also `<plot.rpart>`. ### Examples ``` z.auto <- rpart(Mileage ~ Weight, car.test.frame) meanvar(z.auto, log = 'xy') ``` r None `prune.rpart` Cost-complexity Pruning of an Rpart Object --------------------------------------------------------- ### Description Determines a nested sequence of subtrees of the supplied `rpart` object by recursively `snipping` off the least important splits, based on the complexity parameter (`cp`). ### Usage ``` prune(tree, ...) ## S3 method for class 'rpart' prune(tree, cp, ...) ``` ### Arguments | | | | --- | --- | | `tree` | fitted model object of class `"rpart"`. This is assumed to be the result of some function that produces an object with the same named components as that returned by the `rpart` function. | | `cp` | Complexity parameter to which the `rpart` object will be trimmed. | | `...` | further arguments passed to or from other methods. | ### Value A new `rpart` object that is trimmed to the value `cp`. ### See Also `<rpart>` ### Examples ``` z.auto <- rpart(Mileage ~ Weight, car.test.frame) zp <- prune(z.auto, cp = 0.1) plot(zp) #plot smaller rpart object ``` r None `rsq.rpart` Plots the Approximate R-Square for the Different Splits -------------------------------------------------------------------- ### Description Produces 2 plots. The first plots the r-square (apparent and apparent - from cross-validation) versus the number of splits. The second plots the Relative Error(cross-validation) +/- 1-SE from cross-validation versus the number of splits. ### Usage ``` rsq.rpart(x) ``` ### Arguments | | | | --- | --- | | `x` | fitted model object of class `"rpart"`. This is assumed to be the result of some function that produces an object with the same named components as that returned by the `rpart` function. | ### Side Effects Two plots are produced. ### Note The labels are only appropriate for the `"anova"` method. ### Examples ``` z.auto <- rpart(Mileage ~ Weight, car.test.frame) rsq.rpart(z.auto) ``` r None `snip.rpart` Snip Subtrees of an Rpart Object ---------------------------------------------- ### Description Creates a "snipped" rpart object, containing the nodes that remain after selected subtrees have been snipped off. The user can snip nodes using the toss argument, or interactively by clicking the mouse button on specified nodes within the graphics window. ### Usage ``` snip.rpart(x, toss) ``` ### Arguments | | | | --- | --- | | `x` | fitted model object of class `"rpart"`. This is assumed to be the result of some function that produces an object with the same named components as that returned by the `rpart` function. | | `toss` | an integer vector containing indices (node numbers) of all subtrees to be snipped off. If missing, user selects branches to snip off as described below. | ### Details A dendrogram of `rpart` is expected to be visible on the graphics device, and a graphics input device (e.g., a mouse) is required. Clicking (the selection button) on a node displays the node number, sample size, response y-value, and Error (dev). Clicking a second time on the same node snips that subtree off and visually erases the subtree. This process may be repeated an number of times. Warnings result from selecting the root or leaf nodes. Clicking the exit button will stop the snipping process and return the resulting `rpart` object. See the documentation for the specific graphics device for details on graphical input techniques. ### Value A `rpart` object containing the nodes that remain after specified or selected subtrees have been snipped off. ### Warning Visually erasing the plot is done by over-plotting with the background colour. This will do nothing if the background is transparent (often true for screen devices). ### See Also `<plot.rpart>` ### Examples ``` ## dataset not in R ## Not run: z.survey <- rpart(market.survey) # grow the rpart object plot(z.survey) # plot the tree z.survey2 <- snip.rpart(z.survey, toss = 2) # trim subtree at node 2 plot(z.survey2) # plot new tree # can also interactively select the node using the mouse in the # graphics window ## End(Not run) ``` r None `plot.rpart` Plot an Rpart Object ---------------------------------- ### Description Plots an rpart object on the current graphics device. ### Usage ``` ## S3 method for class 'rpart' plot(x, uniform = FALSE, branch = 1, compress = FALSE, nspace, margin = 0, minbranch = 0.3, ...) ``` ### Arguments | | | | --- | --- | | `x` | a fitted object of class `"rpart"`, containing a classification, regression, or rate tree. | | `uniform` | if `TRUE`, uniform vertical spacing of the nodes is used; this may be less cluttered when fitting a large plot onto a page. The default is to use a non-uniform spacing proportional to the error in the fit. | | `branch` | controls the shape of the branches from parent to child node. Any number from 0 to 1 is allowed. A value of 1 gives square shouldered branches, a value of 0 give V shaped branches, with other values being intermediate. | | `compress` | if `FALSE`, the leaf nodes will be at the horizontal plot coordinates of `1:nleaves`. If `TRUE`, the routine attempts a more compact arrangement of the tree. The compaction algorithm assumes `uniform=TRUE`; surprisingly, the result is usually an improvement even when that is not the case. | | `nspace` | the amount of extra space between a node with children and a leaf, as compared to the minimal space between leaves. Applies to compressed trees only. The default is the value of `branch`. | | `margin` | an extra fraction of white space to leave around the borders of the tree. (Long labels sometimes get cut off by the default computation). | | `minbranch` | set the minimum length for a branch to `minbranch` times the average branch length. This parameter is ignored if `uniform=TRUE`. Sometimes a split will give very little improvement, or even (in the classification case) no improvement at all. A tree with branch lengths strictly proportional to improvement leaves no room to squeeze in node labels. | | `...` | arguments to be passed to or from other methods. | ### Details This function is a method for the generic function `plot`, for objects of class `rpart`. The y-coordinate of the top node of the tree will always be 1. ### Value The coordinates of the nodes are returned as a list, with components `x` and `y`. ### Side Effects An unlabeled plot is produced on the current graphics device: one being opened if needed. In order to build up a plot in the usual S style, e.g., a separate `text` command for adding labels, some extra information about the plot needs be retained. This is kept in an environment in the package. ### See Also `<rpart>`, `<text.rpart>` ### Examples ``` fit <- rpart(Price ~ Mileage + Type + Country, cu.summary) par(xpd = TRUE) plot(fit, compress = TRUE) text(fit, use.n = TRUE) ``` r None `car.test.frame` Automobile Data from 'Consumer Reports' 1990 -------------------------------------------------------------- ### Description The `car.test.frame` data frame has 60 rows and 8 columns, giving data on makes of cars taken from the April, 1990 issue of *Consumer Reports*. This is part of a larger dataset, some columns of which are given in `<cu.summary>`. ### Usage ``` car.test.frame ``` ### Format This data frame contains the following columns: `Price` a numeric vector giving the list price in US dollars of a standard model `Country` of origin, a factor with levels France, Germany, Japan , Japan/USA, Korea, Mexico, Sweden and USA `Reliability` a numeric vector coded `1` to `5`. `Mileage` fuel consumption miles per US gallon, as tested. `Type` a factor with levels `Compact` `Large` `Medium` `Small` `Sporty` `Van` `Weight` kerb weight in pounds. `Disp.` the engine capacity (displacement) in litres. `HP` the net horsepower of the vehicle. ### Source *Consumer Reports*, April, 1990, pp. 235–288 quoted in John M. Chambers and Trevor J. Hastie eds. (1992) *Statistical Models in S*, Wadsworth and Brooks/Cole, Pacific Grove, CA, pp. 46–47. ### See Also `<car90>`, `<cu.summary>` ### Examples ``` z.auto <- rpart(Mileage ~ Weight, car.test.frame) summary(z.auto) ``` r None `text.rpart` Place Text on a Dendrogram Plot --------------------------------------------- ### Description Labels the current plot of the tree dendrogram with text. ### Usage ``` ## S3 method for class 'rpart' text(x, splits = TRUE, label, FUN = text, all = FALSE, pretty = NULL, digits = getOption("digits") - 3, use.n = FALSE, fancy = FALSE, fwidth = 0.8, fheight = 0.8, bg = par("bg"), minlength = 1L, ...) ``` ### Arguments | | | | --- | --- | | `x` | fitted model object of class `"rpart"`. This is assumed to be the result of some function that produces an object with the same named components as that returned by the `rpart` function. | | `splits` | logical flag. If `TRUE` (default), then the splits in the tree are labeled with the criterion for the split. | | `label` | For compatibility with `rpart2`, ignored in this version (with a warning). | | `FUN` | the name of a labeling function, e.g. `text`. | | `all` | Logical. If `TRUE`, all nodes are labeled, otherwise just terminal nodes. | | `minlength` | the length to use for factor labels. A value of 1 causes them to be printed as ‘a’, ‘b’, ..... Larger values use abbreviations of the label names. See the `labels.rpart` function for details. | | `pretty` | an alternative to the `minlength` argument, see `<labels.rpart>`. | | `digits` | number of significant digits to include in numerical labels. | | `use.n` | Logical. If `TRUE`, adds to label (\#events level1/ \#events level2/etc. for `class`, `n` for `anova`, and \#events/n for `poisson` and `exp`). | | `fancy` | Logical. If `TRUE`, nodes are represented by ellipses (interior nodes) and rectangles (leaves) and labeled by `yval`. The edges connecting the nodes are labeled by left and right splits. | | `fwidth` | Relates to option `fancy` and the width of the ellipses and rectangles. If `fwidth < 1` then it is a scaling factor (default = 0.8). If `fwidth > 1` then it represents the number of character widths (for current graphical device) to use. | | `fheight` | Relates to option `fancy` and the height of the ellipses and rectangles. If `fheight <1` then it is a scaling factor (default = 0.8). If `fheight > 1` then it represents the number of character heights (for current graphical device) to use. | | `bg` | The color used to paint the background to annotations if `fancy = TRUE`. | | `...` | Graphical parameters may also be supplied as arguments to this function (see `par`). As labels often extend outside the plot region it can be helpful to specify `xpd = TRUE`. | ### Side Effects the current plot of a tree dendrogram is labeled. ### See Also `[text](../../graphics/html/text)`, `<plot.rpart>`, `<rpart>`, `<labels.rpart>`, `[abbreviate](../../base/html/abbreviate)` ### Examples ``` freen.tr <- rpart(y ~ ., freeny) par(xpd = TRUE) plot(freen.tr) text(freen.tr, use.n = TRUE, all = TRUE) ``` r None `rpart` Recursive Partitioning and Regression Trees ---------------------------------------------------- ### Description Fit a `rpart` model ### Usage ``` rpart(formula, data, weights, subset, na.action = na.rpart, method, model = FALSE, x = FALSE, y = TRUE, parms, control, cost, ...) ``` ### Arguments | | | | --- | --- | | `formula` | a [formula](../../stats/html/formula), with a response but no interaction terms. If this a a data frame, that is taken as the model frame (see `[model.frame](../../stats/html/model.frame)).` | | `data` | an optional data frame in which to interpret the variables named in the formula. | | `weights` | optional case weights. | | `subset` | optional expression saying that only a subset of the rows of the data should be used in the fit. | | `na.action` | the default action deletes all observations for which `y` is missing, but keeps those in which one or more predictors are missing. | | `method` | one of `"anova"`, `"poisson"`, `"class"` or `"exp"`. If `method` is missing then the routine tries to make an intelligent guess. If `y` is a survival object, then `method = "exp"` is assumed, if `y` has 2 columns then `method = "poisson"` is assumed, if `y` is a factor then `method = "class"` is assumed, otherwise `method = "anova"` is assumed. It is wisest to specify the method directly, especially as more criteria may added to the function in future. Alternatively, `method` can be a list of functions named `init`, `split` and `eval`. Examples are given in the file ‘tests/usersplits.R’ in the sources, and in the vignettes ‘User Written Split Functions’. | | `model` | if logical: keep a copy of the model frame in the result? If the input value for `model` is a model frame (likely from an earlier call to the `rpart` function), then this frame is used rather than constructing new data. | | `x` | keep a copy of the `x` matrix in the result. | | `y` | keep a copy of the dependent variable in the result. If missing and `model` is supplied this defaults to `FALSE`. | | `parms` | optional parameters for the splitting function. Anova splitting has no parameters. Poisson splitting has a single parameter, the coefficient of variation of the prior distribution on the rates. The default value is 1. Exponential splitting has the same parameter as Poisson. For classification splitting, the list can contain any of: the vector of prior probabilities (component `prior`), the loss matrix (component `loss`) or the splitting index (component `split`). The priors must be positive and sum to 1. The loss matrix must have zeros on the diagonal and positive off-diagonal elements. The splitting index can be `gini` or `information`. The default priors are proportional to the data counts, the losses default to 1, and the split defaults to `gini`. | | `control` | a list of options that control details of the `rpart` algorithm. See `<rpart.control>`. | | `cost` | a vector of non-negative costs, one for each variable in the model. Defaults to one for all variables. These are scalings to be applied when considering splits, so the improvement on splitting on a variable is divided by its cost in deciding which split to choose. | | `...` | arguments to `<rpart.control>` may also be specified in the call to `rpart`. They are checked against the list of valid arguments. | ### Details This differs from the `tree` function in S mainly in its handling of surrogate variables. In most details it follows Breiman *et. al* (1984) quite closely. **R** package tree provides a re-implementation of `tree`. ### Value An object of class `rpart`. See `<rpart.object>`. ### References Breiman L., Friedman J. H., Olshen R. A., and Stone, C. J. (1984) *Classification and Regression Trees.* Wadsworth. ### See Also `<rpart.control>`, `<rpart.object>`, `<summary.rpart>`, `<print.rpart>` ### Examples ``` fit <- rpart(Kyphosis ~ Age + Number + Start, data = kyphosis) fit2 <- rpart(Kyphosis ~ Age + Number + Start, data = kyphosis, parms = list(prior = c(.65,.35), split = "information")) fit3 <- rpart(Kyphosis ~ Age + Number + Start, data = kyphosis, control = rpart.control(cp = 0.05)) par(mfrow = c(1,2), xpd = NA) # otherwise on some devices the text is clipped plot(fit) text(fit, use.n = TRUE) plot(fit2) text(fit2, use.n = TRUE) ```
programming_docs
r None `car90` Automobile Data from 'Consumer Reports' 1990 ----------------------------------------------------- ### Description Data on 111 cars, taken from pages 235–255, 281–285 and 287–288 of the April 1990 *Consumer Reports* Magazine. ### Usage ``` data(car90) ``` ### Format The data frame contains the following columns Country a factor giving the country in which the car was manufactured Disp engine displacement in cubic inches Disp2 engine displacement in liters Eng.Rev engine revolutions per mile, or engine speed at 60 mph Front.Hd distance between the car's head-liner and the head of a 5 ft. 9 in. front seat passenger, in inches, as measured by CU Frt.Leg.Room maximum front leg room, in inches, as measured by CU Frt.Shld front shoulder room, in inches, as measured by CU Gear.Ratio the overall gear ratio, high gear, for manual transmission Gear2 the overall gear ratio, high gear, for automatic transmission HP net horsepower HP.revs the red line—the maximum safe engine speed in rpm Height height of car, in inches, as supplied by manufacturer Length overall length, in inches, as supplied by manufacturer Luggage luggage space Mileage a numeric vector of gas mileage in miles/gallon as tested by CU; contains NAs. Model2 alternate name, if the car was sold under two labels Price list price with standard equipment, in dollars Rear.Hd distance between the car's head-liner and the head of a 5 ft 9 in. rear seat passenger, in inches, as measured by CU Rear.Seating rear fore-and-aft seating room, in inches, as measured by CU RearShld rear shoulder room, in inches, as measured by CU Reliability an ordered factor with levels Much worse < worse < average < better < Much better: contains `NA`s. Rim factor giving the rim size Sratio.m Number of turns of the steering wheel required for a turn of 30 foot radius, manual steering Sratio.p Number of turns of the steering wheel required for a turn of 30 foot radius, power steering Steering steering type offered: manual, power, or both Tank fuel refill capacity in gallons Tires factor giving tire size Trans1 manual transmission, a factor with levels , man.4, man.5 and man.6 Trans2 automatic transmission, a factor with levels , auto.3, auto.4, and auto.CVT. No car is missing both the manual and automatic transmission variables, but several had both as options Turning the radius of the turning circle in feet Type a factor giving the general type of car. The levels are: Small, Sporty, Compact, Medium, Large, Van Weight an order statistic giving the relative weights of the cars; 1 is the lightest and 111 is the heaviest Wheel.base length of wheelbase, in inches, as supplied by manufacturer Width width of car, in inches, as supplied by manufacturer ### Source This is derived (with permission) from the data set `car.all` in S-PLUS, but with some further clean up of variable names and definitions. ### See Also `<car.test.frame>`, `<cu.summary>` for extracts from other versions of the dataset. ### Examples ``` data(car90) plot(car90$Price/1000, car90$Weight, xlab = "Price (thousands)", ylab = "Weight (lbs)") mlowess <- function(x, y, ...) { keep <- !(is.na(x) | is.na(y)) lowess(x[keep], y[keep], ...) } with(car90, lines(mlowess(Price/1000, Weight, f = 0.5))) ``` r None `labels.rpart` Create Split Labels For an Rpart Object ------------------------------------------------------- ### Description This function provides labels for the branches of an `rpart` tree. ### Usage ``` ## S3 method for class 'rpart' labels(object, digits = 4, minlength = 1L, pretty, collapse = TRUE, ...) ``` ### Arguments | | | | --- | --- | | `object` | fitted model object of class `"rpart"`. This is assumed to be the result of some function that produces an object with the same named components as that returned by the `rpart` function. | | `digits` | the number of digits to be used for numeric values. All of the `rpart` functions that call labels explicitly set this value, with `options("digits")` as the default. | | `minlength` | the minimum length for abbreviation of character or factor variables. If `0` no abbreviation is done; if `1` single English letters are used, first lower case than upper case (with a maximum of 52 levels). If the value is greater than , the `[abbreviate](../../base/html/abbreviate)` function is used, passed the `minlength` argument. | | `pretty` | an argument included for compatibility with the tree package: `pretty = 0` implies `minlength = 0L`, `pretty = NULL` implies `minlength = 1L`, and `pretty = TRUE` implies `minlength = 4L`. | | `collapse` | logical. The returned set of labels is always of the same length as the number of nodes in the tree. If `collapse = TRUE` (default), the returned value is a vector of labels for the branch leading into each node, with `"root"` as the label for the top node. If `FALSE`, the returned value is a two column matrix of labels for the left and right branches leading out from each node, with `"leaf"` as the branch labels for terminal nodes. | | `...` | optional arguments to `abbreviate`. | ### Value Vector of split labels (`collapse = TRUE`) or matrix of left and right splits (`collapse = FALSE`) for the supplied `rpart` object. This function is called by printing methods for `rpart` and is not intended to be called directly by the users. ### See Also `[abbreviate](../../base/html/abbreviate)` r None `summary.rpart` Summarize a Fitted Rpart Object ------------------------------------------------ ### Description Returns a detailed listing of a fitted `rpart` object. ### Usage ``` ## S3 method for class 'rpart' summary(object, cp = 0, digits = getOption("digits"), file, ...) ``` ### Arguments | | | | --- | --- | | `object` | fitted model object of class `"rpart"`. This is assumed to be the result of some function that produces an object with the same named components as that returned by the `rpart` function. | | `digits` | Number of significant digits to be used in the result. | | `cp` | trim nodes with a complexity of less than `cp` from the listing. | | `file` | write the output to a given file name. (Full listings of a tree are often quite long). | | `...` | arguments to be passed to or from other methods. | ### Details This function is a method for the generic function summary for class `"rpart"`. It can be invoked by calling `summary` for an object of the appropriate class, or directly by calling `summary.rpart` regardless of the class of the object. It prints the call, the table shown by `<printcp>`, the variable importance (summing to 100) and details for each node (the details depending on the type of tree). ### See Also `[summary](../../base/html/summary)`, `<rpart.object>`, `<printcp>`. ### Examples ``` ## a regression tree z.auto <- rpart(Mileage ~ Weight, car.test.frame) summary(z.auto) ## a classification tree with multiple variables and surrogate splits. summary(rpart(Kyphosis ~ Age + Number + Start, data = kyphosis)) ``` r None `rpart.exp` Initialization function for exponential fitting ------------------------------------------------------------ ### Description This function does the initialization step for rpart, when the response is a survival object. It rescales the data so as to have an exponential baseline hazard and then uses Poisson methods. This function would rarely if ever be called directly by a user. ### Usage ``` rpart.exp(y, offset, parms, wt) ``` ### Arguments | | | | --- | --- | | `y` | the response, which will be of class `Surv` | | `offset` | optional offset | | `parms` | parameters controlling the fit. This is a list with components `shrink` and `method`. The first is the prior for the coefficient of variation of the predictions. The second is either `"deviance"` or `"sqrt"` and is the measure used for cross-validation. If values are missing the defaults are used, which are `"deviance"` for the method, and a shrinkage of 1.0 for the deviance method and 0 for the square root. | | `wt` | case weights, if present | ### Value a list with the necessary initialization components ### Author(s) Terry Therneau ### See Also `<rpart>` r None `xpred.rpart` Return Cross-Validated Predictions ------------------------------------------------- ### Description Gives the predicted values for an `rpart` fit, under cross validation, for a set of complexity parameter values. ### Usage ``` xpred.rpart(fit, xval = 10, cp, return.all = FALSE) ``` ### Arguments | | | | --- | --- | | `fit` | a object of class `"rpart"`. | | `xval` | number of cross-validation groups. This may also be an explicit list of integers that define the cross-validation groups. | | `cp` | the desired list of complexity values. By default it is taken from the `cptable` component of the fit. | | `return.all` | if FALSE return only the first element of the prediction | ### Details Complexity penalties are actually ranges, not values. If the `cp` values found in the table were *.36*, *.28*, and *.13*, for instance, this means that the first row of the table holds for all complexity penalties in the range *[.36, 1]*, the second row for `cp` in the range *[.28, .36)* and the third row for *[.13,.28)*. By default, the geometric mean of each interval is used for cross validation. ### Value A matrix with one row for each observation and one column for each complexity value. If `return.all` is TRUE and the prediction for each node is a vector, then the result will be an array containing all of the predictions. When the response is categorical, for instance, the result contains the predicted class followed by the class probabilities of the selected terminal node; `result[1,,]` will be the matrix of predicted classes, `result[2,,]` the matrix of class 1 probabilities, etc. ### See Also `<rpart>` ### Examples ``` fit <- rpart(Mileage ~ Weight, car.test.frame) xmat <- xpred.rpart(fit) xerr <- (xmat - car.test.frame$Mileage)^2 apply(xerr, 2, sum) # cross-validated error estimate # approx same result as rel. error from printcp(fit) apply(xerr, 2, sum)/var(car.test.frame$Mileage) printcp(fit) ``` r None `solder.balance` Soldering of Components on Printed-Circuit Boards ------------------------------------------------------------------- ### Description The `solder.balance` data frame has 720 rows and 6 columns, representing a balanced subset of a designed experiment varying 5 factors on the soldering of components on printed-circuit boards. The `solder` data frame is the full version of the data with 900 rows. It is located in both the rpart and the survival packages. ### Usage ``` solder ``` ### Format This data frame contains the following columns: `Opening` a factor with levels L, M and S indicating the amount of clearance around the mounting pad. `Solder` a factor with levels Thick and Thin giving the thickness of the solder used. `Mask` a factor with levels A1.5, A3, B3 and B6 indicating the type and thickness of mask used. `PadType` a factor with levels D4, D6, D7, L4, L6, L7, L8, L9, W4 and W9 giving the size and geometry of the mounting pad. `Panel` `1:3` indicating the panel on a board being tested. `skips` a numeric vector giving the number of visible solder skips. ### Source John M. Chambers and Trevor J. Hastie eds. (1992) *Statistical Models in S*, Wadsworth and Brooks/Cole, Pacific Grove, CA. ### Examples ``` fit <- rpart(skips ~ Opening + Solder + Mask + PadType + Panel, data = solder.balance, method = "anova") summary(residuals(fit)) plot(predict(fit), residuals(fit)) ``` r None `stagec` Stage C Prostate Cancer --------------------------------- ### Description A set of 146 patients with stage C prostate cancer, from a study exploring the prognostic value of flow cytometry. ### Usage ``` data(stagec) ``` ### Format A data frame with 146 observations on the following 8 variables. `pgtime` Time to progression or last follow-up (years) `pgstat` 1 = progression observed, 0 = censored `age` age in years `eet` early endocrine therapy, 1 = no, 2 = yes `g2` percent of cells in G2 phase, as found by flow cytometry `grade` grade of the tumor, Farrow system `gleason` grade of the tumor, Gleason system `ploidy` the ploidy status of the tumor, from flow cytometry. Values are diploid, tetraploid, and aneuploid ### Details A tumor is called diploid (normal complement of dividing cells) if the fraction of cells in G2 phase was determined to be 13% or less. Aneuploid cells have a measurable fraction with a chromosome count that is neither 24 nor 48, for these the G2 percent is difficult or impossible to measure. ### Examples ``` require(survival) rpart(Surv(pgtime, pgstat) ~ ., stagec) ``` r None `kyphosis` Data on Children who have had Corrective Spinal Surgery ------------------------------------------------------------------- ### Description The `kyphosis` data frame has 81 rows and 4 columns. representing data on children who have had corrective spinal surgery ### Usage ``` kyphosis ``` ### Format This data frame contains the following columns: `Kyphosis` a factor with levels `absent` `present` indicating if a kyphosis (a type of deformation) was present after the operation. `Age` in months `Number` the number of vertebrae involved `Start` the number of the first (topmost) vertebra operated on. ### Source John M. Chambers and Trevor J. Hastie eds. (1992) *Statistical Models in S*, Wadsworth and Brooks/Cole, Pacific Grove, CA. ### Examples ``` fit <- rpart(Kyphosis ~ Age + Number + Start, data = kyphosis) fit2 <- rpart(Kyphosis ~ Age + Number + Start, data = kyphosis, parms = list(prior = c(0.65, 0.35), split = "information")) fit3 <- rpart(Kyphosis ~ Age + Number + Start, data=kyphosis, control = rpart.control(cp = 0.05)) par(mfrow = c(1,2), xpd = TRUE) plot(fit) text(fit, use.n = TRUE) plot(fit2) text(fit2, use.n = TRUE) ``` r None `print.rpart` Print an Rpart Object ------------------------------------ ### Description This function prints an `rpart` object. It is a method for the generic function `print` of class `"rpart"`. ### Usage ``` ## S3 method for class 'rpart' print(x, minlength = 0, spaces = 2, cp, digits = getOption("digits"), ...) ``` ### Arguments | | | | --- | --- | | `x` | fitted model object of class `"rpart"`. This is assumed to be the result of some function that produces an object with the same named components as that returned by the `rpart` function. | | `minlength` | Controls the abbreviation of labels: see `<labels.rpart>`. | | `spaces` | the number of spaces to indent nodes of increasing depth. | | `digits` | the number of digits of numbers to print. | | `cp` | prune all nodes with a complexity less than `cp` from the printout. Ignored if unspecified. | | `...` | arguments to be passed to or from other methods. | ### Details This function is a method for the generic function `print` for class `"rpart"`. It can be invoked by calling print for an object of the appropriate class, or directly by calling `print.rpart` regardless of the class of the object. ### Side Effects A semi-graphical layout of the contents of `x$frame` is printed. Indentation is used to convey the tree topology. Information for each node includes the node number, split, size, deviance, and fitted value. For the `"class"` method, the class probabilities are also printed. ### See Also `[print](../../base/html/print)`, `<rpart.object>`, `<summary.rpart>`, `<printcp>` ### Examples ``` z.auto <- rpart(Mileage ~ Weight, car.test.frame) z.auto ## Not run: node), split, n, deviance, yval * denotes terminal node 1) root 60 1354.58300 24.58333 2) Weight>=2567.5 45 361.20000 22.46667 4) Weight>=3087.5 22 61.31818 20.40909 * 5) Weight<3087.5 23 117.65220 24.43478 10) Weight>=2747.5 15 60.40000 23.80000 * 11) Weight<2747.5 8 39.87500 25.62500 * 3) Weight<2567.5 15 186.93330 30.93333 * ## End(Not run) ``` r None `draw.colorkey` Produce a colorkey typically for levelplot ----------------------------------------------------------- ### Description Creates (and optionally draws) a grid frame grob representing a color key that can be placed in other grid-based plots. Primarily used by `levelplot` when a color key is requested. ### Usage ``` draw.colorkey(key, draw = FALSE, vp = NULL) ``` ### Arguments | | | | --- | --- | | `key` | A list determining the key. See documentation for `<levelplot>`, in particular the section describing the `colorkey` argument, for details. | | `draw` | A scalar logical, indicating whether the grob is to be drawn. | | `vp` | The viewport in which to draw the grob, if applicable. | ### Value A grid frame object (that inherits from `"grob"`) ### Author(s) Deepayan Sarkar [[email protected]](mailto:[email protected]) ### See Also `<xyplot>`, `<levelplot>` r None `panel.qqmathline` Useful panel function with qqmath ----------------------------------------------------- ### Description Useful panel function with qqmath. Draws a line passing through the points (usually) determined by the .25 and .75 quantiles of the sample and the theoretical distribution. ### Usage ``` panel.qqmathline(x, y = x, distribution = qnorm, probs = c(0.25, 0.75), qtype = 7, groups = NULL, ..., identifier = "qqmathline") ``` ### Arguments | | | | --- | --- | | `x` | The original sample, possibly reduced to a fewer number of quantiles, as determined by the `f.value` argument to `qqmath` | | `y` | an alias for `x` for backwards compatibility | | `distribution` | quantile function for reference theoretical distribution. | | `probs` | numeric vector of length two, representing probabilities. Corresponding quantile pairs define the line drawn. | | `qtype` | the `type` of quantile computation used in `[quantile](../../stats/html/quantile)` | | `groups` | optional grouping variable. If non-null, a line will be drawn for each group. | | `...` | other arguments. | | `identifier` | A character string that is prepended to the names of grobs that are created by this panel function. | ### Author(s) Deepayan Sarkar [[email protected]](mailto:[email protected]) ### See Also `[prepanel.qqmathline](prepanel.functions)`, `<qqmath>`, `[quantile](../../stats/html/quantile)` r None `splom` Scatter Plot Matrices ------------------------------ ### Description Draw Conditional Scatter Plot Matrices and Parallel Coordinate Plots ### Usage ``` splom(x, data, ...) parallelplot(x, data, ...) ## S3 method for class 'formula' splom(x, data, auto.key = FALSE, aspect = 1, between = list(x = 0.5, y = 0.5), panel = lattice.getOption("panel.splom"), prepanel, scales, strip, groups, xlab, xlim, ylab = NULL, ylim, superpanel = lattice.getOption("panel.pairs"), pscales = 5, varnames = NULL, drop.unused.levels, ..., lattice.options = NULL, default.scales, default.prepanel = lattice.getOption("prepanel.default.splom"), subset = TRUE) ## S3 method for class 'formula' parallelplot(x, data, auto.key = FALSE, aspect = "fill", between = list(x = 0.5, y = 0.5), panel = lattice.getOption("panel.parallel"), prepanel, scales, strip, groups, xlab = NULL, xlim, ylab = NULL, ylim, varnames = NULL, horizontal.axis = TRUE, drop.unused.levels, ..., lattice.options = NULL, default.scales, default.prepanel = lattice.getOption("prepanel.default.parallel"), subset = TRUE) ## S3 method for class 'data.frame' splom(x, data = NULL, ..., groups = NULL, subset = TRUE) ## S3 method for class 'matrix' splom(x, data = NULL, ..., groups = NULL, subset = TRUE) ## S3 method for class 'matrix' parallelplot(x, data = NULL, ..., groups = NULL, subset = TRUE) ## S3 method for class 'data.frame' parallelplot(x, data = NULL, ..., groups = NULL, subset = TRUE) ``` ### Arguments | | | | --- | --- | | `x` | The object on which method dispatch is carried out. For the `"formula"` method, a formula describing the structure of the plot, which should be of the form `~ x | g1 * g2 * ...`, where `x` is a data frame or matrix. Each of `g1,g2,...` must be either factors or shingles. The conditioning variables `g1, g2, ...` may be omitted. For the `data.frame` methods, a data frame. | | `data` | For the `formula` methods, an optional data frame in which variables in the formula (as well as `groups` and `subset`, if any) are to be evaluated. | | `aspect` | aspect ratio of each panel (and subpanel), square by default for `splom`. | | `between` | to avoid confusion between panels and subpanels, the default is to show the panels of a splom plot with space between them. | | `panel` | For `parallelplot`, this has the usual interpretation, i.e., a function that creates the display within each panel. For `splom`, the terminology is slightly complicated. The role played by the panel function in most other high-level functions is played here by the `superpanel` function, which is responsible for the display for each conditional data subset. `panel` is simply an argument to the default `superpanel` function `panel.pairs`, and is passed on to it unchanged. It is used there to create each pairwise display. See `<panel.pairs>` for more useful options. | | `superpanel` | function that sets up the splom display, by default as a scatterplot matrix. | | `pscales` | a numeric value or a list, meant to be a less functional substitute for the `scales` argument in `xyplot` etc. This argument is passed to the `superpanel` function, and is handled by the default superpanel function `panel.pairs`. The help page for the latter documents this argument in more detail. | | `varnames` | A character or expression vector or giving names to be used for the variables in `x`. By default, the column names of `x`. | | `horizontal.axis` | logical indicating whether the parallel axes should be laid out horizontally (`TRUE`) or vertically (`FALSE`). | | `auto.key, prepanel, scales, strip, groups, xlab, xlim, ylab, ylim, drop.unused.levels, lattice.options, default.scales, subset` | See `<xyplot>` | | `default.prepanel` | Fallback prepanel function. See `<xyplot>`. | | `...` | Further arguments. See corresponding entry in `<xyplot>` for non-trivial details. | ### Details `splom` produces Scatter Plot Matrices. The role usually played by `panel` is taken over by `superpanel`, which takes a data frame subset and is responsible for plotting it. It is called with the coordinate system set up to have both x- and y-limits from `0.5` to `ncol(z) + 0.5`. The only built-in option currently available is `<panel.pairs>`, which calls a further panel function for each pair `(i, j)` of variables in `z` inside a rectangle of unit width and height centered at `c(i, j)` (see `<panel.pairs>` for details). Many of the finer customizations usually done via arguments to high level function like `xyplot` are instead done by `panel.pairs` for `splom`. These include control of axis limits, tick locations and prepanel calcultions. If you are trying to fine-tune your `splom` plot, definitely look at the `<panel.pairs>` help page. The `scales` argument is usually not very useful in `splom`, and trying to change it may have undesired effects. `[parallelplot](splom)` draws Parallel Coordinate Plots. (Difficult to describe, see example.) These and all other high level Trellis functions have several arguments in common. These are extensively documented only in the help page for `xyplot`, which should be consulted to learn more detailed usage. ### Value An object of class `"trellis"`. The `[update](update.trellis)` method can be used to update components of the object and the `[print](print.trellis)` method (usually called by default) will plot it on an appropriate plotting device. ### Author(s) Deepayan Sarkar [[email protected]](mailto:[email protected]) ### See Also `<xyplot>`, `[Lattice](lattice)`, `<panel.pairs>`, `<panel.parallel>`. ### Examples ``` super.sym <- trellis.par.get("superpose.symbol") splom(~iris[1:4], groups = Species, data = iris, panel = panel.superpose, key = list(title = "Three Varieties of Iris", columns = 3, points = list(pch = super.sym$pch[1:3], col = super.sym$col[1:3]), text = list(c("Setosa", "Versicolor", "Virginica")))) splom(~iris[1:3]|Species, data = iris, layout=c(2,2), pscales = 0, varnames = c("Sepal\nLength", "Sepal\nWidth", "Petal\nLength"), page = function(...) { ltext(x = seq(.6, .8, length.out = 4), y = seq(.9, .6, length.out = 4), labels = c("Three", "Varieties", "of", "Iris"), cex = 2) }) parallelplot(~iris[1:4] | Species, iris) parallelplot(~iris[1:4], iris, groups = Species, horizontal.axis = FALSE, scales = list(x = list(rot = 90))) ```
programming_docs
r None `panel.loess` Panel Function to Add a LOESS Smooth --------------------------------------------------- ### Description A predefined panel function that can be used to add a LOESS smooth based on the provided data. ### Usage ``` panel.loess(x, y, span = 2/3, degree = 1, family = c("symmetric", "gaussian"), evaluation = 50, lwd, lty, col, col.line, type, horizontal = FALSE, ..., identifier = "loess") ``` ### Arguments | | | | --- | --- | | `x, y` | Variables defining the data to be used. | | `lwd, lty, col, col.line` | Graphical parameters for the added line. `col.line` overrides `col`. | | `type` | Ignored. The argument is present only to make sure that an explicitly specified `type` argument (perhaps meant for another function) does not affect the display. | | `span, degree, family, evaluation` | Arguments to `[loess.smooth](../../stats/html/scatter.smooth)`, for which `panel.loess` is essentially a wrapper. | | `horizontal` | A logical flag controlling which variable is to be treated as the predictor (by default `x`) and which as the response (by default `y`). If `TRUE`, the plot is ‘transposed’ in the sense that `y` becomes the predictor and `x` the response. (The name ‘horizontal’ may seem an odd choice for this argument, and originates from similar usage in `[bwplot](xyplot)`). | | `...` | Extra arguments, passed on to `[panel.lines](llines)`. | | `identifier` | A character string that is prepended to the names of grobs that are created by this panel function. | ### Value The object returned by `[loess.smooth](../../stats/html/scatter.smooth)`. ### Author(s) Deepayan Sarkar [[email protected]](mailto:[email protected]) ### See Also [Lattice](lattice), `[loess.smooth](../../stats/html/scatter.smooth)`, `[prepanel.loess](prepanel.functions)` r None `environmental` Atmospheric environmental conditions in New York City ---------------------------------------------------------------------- ### Description Daily measurements of ozone concentration, wind speed, temperature and solar radiation in New York City from May to September of 1973. ### Usage ``` environmental ``` ### Format A data frame with 111 observations on the following 4 variables. ozone Average ozone concentration (of hourly measurements) of in parts per billion. radiation Solar radiation (from 08:00 to 12:00) in langleys. temperature Maximum daily emperature in degrees Fahrenheit. wind Average wind speed (at 07:00 and 10:00) in miles per hour. ### Author(s) Documentation contributed by Kevin Wright. ### Source Bruntz, S. M., W. S. Cleveland, B. Kleiner, and J. L. Warner. (1974). The Dependence of Ambient Ozone on Solar Radiation, Wind, Temperature, and Mixing Height. In *Symposium on Atmospheric Diffusion and Air Pollution*, pages 125–128. American Meterological Society, Boston. ### References Cleveland, William S. (1993) *Visualizing Data*. Hobart Press, Summit, New Jersey. ### Examples ``` # Scatter plot matrix with loess lines splom(~environmental, panel=function(x,y){ panel.xyplot(x,y) panel.loess(x,y) } ) # Conditioned plot similar to figure 5.3 from Cleveland attach(environmental) Temperature <- equal.count(temperature, 4, 1/2) Wind <- equal.count(wind, 4, 1/2) xyplot((ozone^(1/3)) ~ radiation | Temperature * Wind, aspect=1, prepanel = function(x, y) prepanel.loess(x, y, span = 1), panel = function(x, y){ panel.grid(h = 2, v = 2) panel.xyplot(x, y, cex = .5) panel.loess(x, y, span = 1) }, xlab = "Solar radiation (langleys)", ylab = "Ozone (cube root ppb)") detach() # Similar display using the coplot function with(environmental,{ coplot((ozone^.33) ~ radiation | temperature * wind, number=c(4,4), panel = function(x, y, ...) panel.smooth(x, y, span = .8, ...), xlab="Solar radiation (langleys)", ylab="Ozone (cube root ppb)") }) ``` r None `trellis.par.get` Graphical Parameters for Trellis Displays ------------------------------------------------------------ ### Description Functions used to query, display and modify graphical parameters for fine control of Trellis displays. Modifications are made to the settings for the currently active device only. ### Usage ``` trellis.par.set(name, value, ..., theme, warn = TRUE, strict = FALSE) trellis.par.get(name = NULL) show.settings(x = NULL) ``` ### Arguments | | | | --- | --- | | `name` | A character string giving the name of a component. If unspecified in `trellis.par.get()`, the return value is a named list containing all the current settings (this can be used to get the valid values for `name`). | | `value` | a list giving the desired value of the component. Components that are already defined as part of the current settings but are not mentioned in `value` will remain unchanged. | | `theme` | a list decribing how to change the settings, similar to what is returned by `trellis.par.get()`. This is purely for convenience, allowing multiple calls to `trellis.par.set` to be condensed into one. The name of each component must be a valid `name` as described above, with the corresponding value a valid `value` as described above. As in `<trellis.device>`, `theme` can also be a function that produces such a list when called. The function name can be supplied as a quoted string. | | `...` | Multiple settings can be specified in `name = value` form. Equivalent to calling with `theme = list(...)` | | `warn` | A logical flag, indicating whether a warning should be issued when `trellis.par.get` is called when no graphics device is open. | | `strict` | Usually a logical flag, indicating whether the `value` should be interpreted strictly. Usually, assignment of value to the corresponding named component is fuzzy in the sense that sub-components that are absent from `value` but not currently `NULL` are retained. By specifying `strict = TRUE`, such values will be removed. An even stricter interpretation is allowed by specifying `strict` as a numeric value larger than `1`. In that case, top-level components not specified in the call will also be removed. This is primarily for internal use. | | `x` | optional list of components that change the settings (any valid value of `theme`). These are used to modify the current settings (obtained by `trellis.par.get`) before they are displayed. | ### Details The various graphical parameters (color, line type, background etc) that control the look and feel of Trellis displays are highly customizable. Also, R can produce graphics on a number of devices, and it is expected that a different set of parameters would be more suited to different devices. These parameters are stored internally in a variable named `lattice.theme`, which is a list whose components define settings for particular devices. The components are idenified by the name of the device they represent (as obtained by `.Device`), and are created as and when new devices are opened for the first time using `trellis.device` (or Lattice plots are drawn on a device for the first time in that session). The initial settings for each device defaults to values appropriate for that device. In practice, this boils down to three distinct settings, one for screen devices like `x11` and `windows`, one for black and white plots (mostly useful for `postscript`) and one for color printers (color `postcript`, `pdf`). Once a device is open, its settings can be modified. When another instance of the same device is opened later using `trellis.device`, the settings for that device are reset to its defaults, unless otherwise specified in the call to `trellis.device`. But settings for different devices are treated separately, i.e., opening a postscript device will not alter the x11 settings, which will remain in effect whenever an x11 device is active. The functions `trellis.par.*` are meant to be interfaces to the global settings. They always apply on the settings for the currently ACTIVE device. `trellis.par.get`, called without any arguments, returns the full list of settings for the active device. With the `name` argument present, it returns that component only. `trellis.par.get` sets the value of the `name` component of the current active device settings to `value`. `trellis.par.get` is usually used inside trellis functions to get graphical parameters before plotting. Modifications by users via `trellis.par.set` is traditionally done as follows: `add.line <- trellis.par.get("add.line")` `add.line$col <- "red"` `trellis.par.set("add.line", add.line)` More convenient (but not S compatible) ways to do this are `trellis.par.set(list(add.line = list(col = "red")))` and `trellis.par.set(add.line = list(col = "red"))` The actual list of the components in `trellis.settings` has not been finalized, so I'm not attempting to list them here. The current value can be obtained by `print(trellis.par.get())`. Most names should be self-explanatory. `show.settings` provides a graphical display summarizing some of the values in the current settings. ### Value `trellis.par.get` returns a list giving parameters for that component. If `name` is missing, it returns the full list. Most of the settings are graphical parameters that control various elements of a lattice plot. For details, see the examples below. The more unusual settings are described here. grid.pars Grid graphical parameters that are in effect globally unless overridden by specific settings. fontsize A list of two components (each a numeric scalar), `text` and `points`, for text and symbols respectively. clip A list of two components (each a character string, either `"on"` or `"off"`), `panel` and `strip`. axis.components layout.heights layout.widths ### Note In some ways, `trellis.par.get` and `trellis.par.set` together are a replacement for the `[par](../../graphics/html/par)` function used in traditional R graphics. In particular, changing `par` settings has little (if any) effect on lattice output. Since lattice plots are implemented using Grid graphics, its parameter system *does* have an effect unless overridden by a suitable lattice parameter setting. Such parameters can be specified as part of a lattice theme by including them in the `grid.pars` component (see `[gpar](../../grid/html/gpar)` for a list of valid parameter names). ### Author(s) Deepayan Sarkar [[email protected]](mailto:[email protected]) ### See Also `<trellis.device>`, `[Lattice](lattice)`, `[gpar](../../grid/html/gpar)` ### Examples ``` show.settings() tp <- trellis.par.get() unusual <- c("grid.pars", "fontsize", "clip", "axis.components", "layout.heights", "layout.widths") for (u in unusual) tp[[u]] <- NULL names.tp <- lapply(tp, names) unames <- sort(unique(unlist(names.tp))) ans <- matrix(0, nrow = length(names.tp), ncol = length(unames)) rownames(ans) <- names(names.tp) colnames(ans) <- unames for (i in seq(along = names.tp)) ans[i, ] <- as.numeric(unames %in% names.tp[[i]]) ans <- ans[, order(-colSums(ans))] ans <- ans[order(rowSums(ans)), ] ans[ans == 0] <- NA levelplot(t(ans), colorkey = FALSE, scales = list(x = list(rot = 90)), panel = function(x, y, z, ...) { panel.abline(v = unique(as.numeric(x)), h = unique(as.numeric(y)), col = "darkgrey") panel.xyplot(x, y, pch = 16 * z, ...) }, xlab = "Graphical parameters", ylab = "Setting names") ``` r None `ethanol` Engine exhaust fumes from burning ethanol ---------------------------------------------------- ### Description Ethanol fuel was burned in a single-cylinder engine. For various settings of the engine compression and equivalence ratio, the emissions of nitrogen oxides were recorded. ### Usage ``` ethanol ``` ### Format A data frame with 88 observations on the following 3 variables. NOx Concentration of nitrogen oxides (NO and NO2) in micrograms/J. C Compression ratio of the engine. E Equivalence ratio–a measure of the richness of the air and ethanol fuel mixture. ### Author(s) Documentation contributed by Kevin Wright. ### Source Brinkman, N.D. (1981) Ethanol Fuel—A Single-Cylinder Engine Study of Efficiency and Exhaust Emissions. *SAE transactions*, **90**, 1410–1424. ### References Cleveland, William S. (1993) *Visualizing Data*. Hobart Press, Summit, New Jersey. ### Examples ``` ## Constructing panel functions on the fly EE <- equal.count(ethanol$E, number=9, overlap=1/4) xyplot(NOx ~ C | EE, data = ethanol, prepanel = function(x, y) prepanel.loess(x, y, span = 1), xlab = "Compression ratio", ylab = "NOx (micrograms/J)", panel = function(x, y) { panel.grid(h=-1, v= 2) panel.xyplot(x, y) panel.loess(x,y, span=1) }, aspect = "xy") # Wireframe loess surface fit. See Figure 4.61 from Cleveland. require(stats) with(ethanol, { eth.lo <- loess(NOx ~ C * E, span = 1/3, parametric = "C", drop.square = "C", family="symmetric") eth.marginal <- list(C = seq(min(C), max(C), length.out = 25), E = seq(min(E), max(E), length.out = 25)) eth.grid <- expand.grid(eth.marginal) eth.fit <- predict(eth.lo, eth.grid) wireframe(eth.fit ~ eth.grid$C * eth.grid$E, shade=TRUE, screen = list(z = 40, x = -60, y=0), distance = .1, xlab = "C", ylab = "E", zlab = "NOx") }) ``` r None `panel.bwplot` Default Panel Function for bwplot ------------------------------------------------- ### Description This is the default panel function for `bwplot`. ### Usage ``` panel.bwplot(x, y, box.ratio = 1, box.width = box.ratio / (1 + box.ratio), horizontal = TRUE, pch, col, alpha, cex, font, fontfamily, fontface, fill, varwidth = FALSE, notch = FALSE, notch.frac = 0.5, ..., levels.fos, stats = boxplot.stats, coef = 1.5, do.out = TRUE, identifier = "bwplot") ``` ### Arguments | | | | --- | --- | | `x, y` | numeric vector or factor. Boxplots drawn for each unique value of `y` (`x`) if `horizontal` is `TRUE` (`FALSE`) | | `box.ratio` | ratio of box thickness to inter box space | | `box.width` | thickness of box in absolute units; overrides `box.ratio`. Useful for specifying thickness when the categorical variable is not a factor, as use of `box.ratio` alone cannot achieve a thickness greater than 1. | | `horizontal` | logical. If FALSE, the plot is ‘transposed’ in the sense that the behaviours of x and y are switched. x is now the ‘factor’. Interpretation of other arguments change accordingly. See documentation of `[bwplot](xyplot)` for a fuller explanation. | | `pch, col, alpha, cex, font, fontfamily, fontface` | graphical parameters controlling the dot. `pch="|"` is treated specially, by replacing the dot with a line (similar to `[boxplot](../../graphics/html/boxplot)`) | | `fill` | color to fill the boxplot | | `varwidth` | logical. If TRUE, widths of boxplots are proportional to the number of points used in creating it. | | `notch` | if `notch` is `TRUE`, a notch is drawn in each side of the boxes. If the notches of two plots do not overlap this is ‘strong evidence’ that the two medians differ (Chambers et al., 1983, p. 62). See `[boxplot.stats](../../grdevices/html/boxplot.stats)` for the calculations used. | | `notch.frac` | numeric in (0,1). When `notch=TRUE`, the fraction of the box width that the notches should use. | | `stats` | a function, defaulting to `[boxplot.stats](../../grdevices/html/boxplot.stats)`, that accepts a numeric vector and returns a list similar to the return value of `boxplot.stats`. The function must accept arguments `coef` and `do.out` even if they do not use them (a `...` argument is good enough). This function is used to determine the box and whisker plot. | | `coef, do.out` | passed to `stats` | | `levels.fos` | numeric values corresponding to positions of the factor or shingle variable. For internal use. | | `...` | further arguments, ignored. | | `identifier` | A character string that is prepended to the names of grobs that are created by this panel function. | ### Details Creates Box and Whisker plot of `x` for every level of `y` (or the other way round if `horizontal=FALSE`). By default, the actual boxplot statistics are calculated using `boxplot.stats`. Note that most arguments controlling the display can be supplied to the high-level `bwplot` call directly. Although the graphical parameters for the dot representing the median can be controlled by optional arguments, many others can not. These parameters are obtained from the relevant settings parameters (`"box.rectangle"` for the box, `"box.umbrella"` for the whiskers and `"plot.symbol"` for the outliers). ### Author(s) Deepayan Sarkar [[email protected]](mailto:[email protected]) ### See Also `[bwplot](xyplot)`, `[boxplot.stats](../../grdevices/html/boxplot.stats)` ### Examples ``` bwplot(voice.part ~ height, data = singer, xlab = "Height (inches)", panel = function(...) { panel.grid(v = -1, h = 0) panel.bwplot(...) }, par.settings = list(plot.symbol = list(pch = 4))) bwplot(voice.part ~ height, data = singer, xlab = "Height (inches)", notch = TRUE, pch = "|") ``` r None `panel.cloud` Default Panel Function for cloud ----------------------------------------------- ### Description These are default panel functions controlling `cloud` and `wireframe` displays. ### Usage ``` panel.cloud(x, y, subscripts, z, groups = NULL, perspective = TRUE, distance = if (perspective) 0.2 else 0, xlim, ylim, zlim, panel.3d.cloud = "panel.3dscatter", panel.3d.wireframe = "panel.3dwire", screen = list(z = 40, x = -60), R.mat = diag(4), aspect = c(1, 1), par.box = NULL, xlab, ylab, zlab, xlab.default, ylab.default, zlab.default, scales.3d, proportion = 0.6, wireframe = FALSE, scpos, ..., at, identifier = "cloud") panel.wireframe(...) panel.3dscatter(x, y, z, rot.mat, distance, groups, type = "p", xlim, ylim, zlim, xlim.scaled, ylim.scaled, zlim.scaled, zero.scaled, col, col.point, col.line, lty, lwd, cex, pch, fill, cross, ..., .scale = FALSE, subscripts, identifier = "3dscatter") panel.3dwire(x, y, z, rot.mat = diag(4), distance, shade = FALSE, shade.colors.palette = trellis.par.get("shade.colors")$palette, light.source = c(0, 0, 1000), xlim, ylim, zlim, xlim.scaled, ylim.scaled, zlim.scaled, col = if (shade) "transparent" else "black", lty = 1, lwd = 1, alpha, col.groups = superpose.polygon$col, polynum = 100, ..., .scale = FALSE, drape = FALSE, at, col.regions = regions$col, alpha.regions = regions$alpha, identifier = "3dwire") ``` ### Arguments | | | | --- | --- | | `x, y, z` | numeric (or possibly factors) vectors representing the data to be displayed. The interpretation depends on the context. For `panel.cloud` these are essentially the same as the data passed to the high level plot (except if `formula` was a matrix, the appropriate `x` and `y` vectors are generated). By the time they are passed to `panel.3dscatter` and `panel.3dwire`, they have been appropriately subsetted (using `subscripts`) and scaled (to lie inside a bounding box, usually the [-0.5, 0.5] cube). Further, for `panel.3dwire`, `x` and `y` are shorter than `z` and represent the sorted locations defining a rectangular grid. Also in this case, `z` may be a matrix if the display is grouped, with each column representing one surface. In `panel.cloud` (called from `wireframe`) and `panel.3dwire`, `x`, `y` and `z` could also be matrices (of the same dimension) when they represent a 3-D surface parametrized on a 2-D grid. | | `subscripts` | index specifying which points to draw. The same `x`, `y` and `z` values (representing the whole data) are passed to `panel.cloud` for each panel. `subscripts` specifies the subset of rows to be used for the particular panel. | | `groups` | specification of a grouping variable, passed down from the high level functions. | | `perspective` | logical, whether to plot a perspective view. Setting this to `FALSE` is equivalent to setting `distance` to 0 | | `distance` | numeric, between 0 and 1, controls amount of perspective. The distance of the viewing point from the origin (in the transformed coordinate system) is `1 / distance`. This is described in a little more detail in the documentation for `<cloud>` | | `screen` | A list determining the sequence of rotations to be applied to the data before being plotted. The initial position starts with the viewing point along the positive z-axis, and the x and y axes in the usual position. Each component of the list should be named one of `"x"`, `"y"` or `"z"` (repetitions are allowed), with their values indicating the amount of rotation about that axis in degrees. | | `R.mat` | initial rotation matrix in homogeneous coordinates, to be applied to the data before `screen` rotates the view further. | | `par.box` | graphical parameters for box, namely, col, lty and lwd. By default obtained from the parameter `box.3d`. | | `xlim, ylim, zlim` | limits for the respective axes. As with other lattice functions, these could each be a numeric 2-vector or a character vector indicating levels of a factor. | | `panel.3d.cloud, panel.3d.wireframe` | functions that draw the data-driven part of the plot (as opposed to the bounding box and scales) in `cloud` and `wireframe`. This function is called after the ‘back’ of the bounding box is drawn, but before the ‘front’ is drawn. Any user-defined custom display would probably want to change these functions. The intention is to pass as much information to this function as might be useful (not all of which are used by the defaults). In particular, these functions can expect arguments called `xlim`, `ylim`, `zlim` which give the bounding box ranges in the original data scale and `xlim.scaled`, `ylim.scaled`, `zlim.scaled` which give the bounding box ranges in the transformed scale. More arguments can be considered on request. | | `aspect` | aspect as in `cloud` | | `xlab, ylab, zlab` | Labels, have to be lists. Typically the user will not manipulate these, but instead control this via arguments to `cloud` directly. | | `xlab.default` | for internal use | | `ylab.default` | for internal use | | `zlab.default` | for internal use | | `scales.3d` | list defining the scales | | `proportion` | numeric scalar, gives the length of arrows as a proportion of the sides | | `scpos` | A list with three components x, y and z (each a scalar integer), describing which of the 12 sides of the cube the scales should be drawn. The defaults should be OK. Valid values are x: 1, 3, 9, 11; y: 8, 5, 7, 6 and z: 4, 2, 10, 12. (See comments in the source code of `panel.cloud` to see the details of this enumeration.) | | `wireframe` | logical, indicating whether this is a wireframe plot | | `drape` | logical, whether the facets will be colored by height, in a manner similar to `levelplot`. This is ignored if `shade=TRUE`. | | `at, col.regions, alpha.regions` | deals with specification of colors when `drape = TRUE` in `[wireframe](cloud)`. `at` can be a numeric vector, `col.regions` a vector of colors, and `alpha.regions` a numeric scalar controlling transparency. The resulting behaviour is similar to `<levelplot>`, `at` giving the breakpoints along the z-axis where colors change, and the other two determining the colors of the facets that fall in between. | | `rot.mat` | 4x4 transformation matrix in homogeneous coordinates. This gives the rotation matrix combining the `screen` and `R.mat` arguments to `<panel.cloud>` | | `type` | Character vector, specifying type of cloud plot. Can include one or more of `"p"`, `"l"`, `"h"` or `"b"`. `"p"` and `"l"` mean ‘points’ and ‘lines’ respectively, and `"b"` means ‘both’. `"h"` stands for ‘histogram’, and causes a line to be drawn from each point to the X-Y plane (i.e., the plane representing `z = 0`), or the lower (or upper) bounding box face, whichever is closer. | | `xlim.scaled, ylim.scaled, zlim.scaled` | axis limits (after being scaled to the bounding box) | | `zero.scaled` | z-axis location (after being scaled to the bounding box) of the X-Y plane in the original data scale, to which lines will be dropped (if within range) from each point when `type = "h"` | | `cross` | logical, defaults to `TRUE` if `pch = "+"`. `panel.3dscatter` can represent each point by a 3d ‘cross’ of sorts (it's much easier to understand looking at an example than from a description). This is different from the usual `pch` argument, and reflects the depth of the points and the orientation of the axes. This argument indicates whether this feature will be used. This is useful for two reasons. It can be set to `FALSE` to use `"+"` as the plotting character in the regular sense. It can also be used to force this feature in grouped displays. | | `shade` | logical, indicating whether the surface is to be colored using an illumination model with a single light source | | `shade.colors.palette` | a function (or the name of one) that is supposed to calculate the color of a facet when shading is being used. Three pieces of information are available to the function: first, the cosine of the angle between the incident light ray and the normal to the surface (representing foreshortening); second, the cosine of half the angle between the reflected ray and the viewing direction (useful for non-Lambertian surfaces); and third, the scaled (average) height of that particular facet with respect to the total plot z-axis limits. All three numbers should be between 0 and 1. The `shade.colors.palette` function should return a valid color. The default function is obtained from the trellis settings. | | `light.source` | a 3-vector representing (in cartesian coordinates) the light source. This is relative to the viewing point being (0, 0, 1/distance) (along the positive z-axis), keeping in mind that all observations are bounded within the [-0.5, 0.5] cube | | `polynum` | quadrilateral faces are drawn in batches of `polynum` at a time. Drawing too few at a time increases the total number of calls to the underlying `grid.polygon` function, which affects speed. Trying to draw too many at once may be unnecessarily memory intensive. This argument controls the trade-off. | | `col.groups` | colors for different groups | | `col, col.point, col.line, lty, lwd, cex, pch, fill, alpha` | Graphical parameters. Some other arguments (such as `lex` for line width) may also be passed through the `...` argument. | | `...` | other parameters, passed down when appropriate | | `.scale` | Logical flag, indicating whether `x`, `y`, and `z` should be assumed to be in the original data scale and hence scaled before being plotted. `x`, `y`, and `z` are usually already scaled. However, setting `.scale=TRUE` may be helpful for calls to `panel.3dscatter` and `panel.3dwire` in user-supplied panel functions. | | `identifier` | A character string that is prepended to the names of grobs that are created by this panel function. | ### Details These functions together are responsible for the content drawn inside each panel in `cloud` and `wireframe`. `panel.wireframe` is a wrapper to `panel.cloud`, which does the actual work. `panel.cloud` is responsible for drawing the content that does not depend on the data, namely, the bounding box, the arrows/scales, etc. At some point, depending on whether `wireframe` is TRUE, it calls either `panel.3d.wireframe` or `panel.3d.cloud`, which draws the data-driven part of the plot. The arguments accepted by these two functions are different, since they have essentially different purposes. For cloud, the data is unstructured, and `x`, `y` and `z` are all passed to the `panel.3d.cloud` function. For wireframe, on the other hand, `x` and `y` are increasing vectors with unique values, defining a rectangular grid. `z` must be a matrix with `length(x) * length(y)` rows, and as many columns as the number of groups. `panel.3dscatter` is the default `panel.3d.cloud` function. It has a `type` argument similar to `<panel.xyplot>`, and supports grouped displays. It tries to honour depth ordering, i.e., points and lines closer to the camera are drawn later, overplotting more distant ones. (Of course there is no absolute ordering for line segments, so an ad hoc ordering is used. There is no hidden point removal.) `panel.3dwire` is the default `panel.3d.wireframe` function. It calculates polygons corresponding to the facets one by one, but waits till it has collected information about `polynum` facets, and draws them all at once. This avoids the overhead of drawing `grid.polygon` repeatedly, speeding up the rendering considerably. If `shade = TRUE`, these attempt to color the surface as being illuminated from a light source at `light.source`. `palette.shade` is a simple function that provides the deafult shading colors Multiple surfaces are drawn if `groups` is non-null in the call to `wireframe`, however, the algorithm is not sophisticated enough to render intersecting surfaces correctly. ### Author(s) Deepayan Sarkar [[email protected]](mailto:[email protected]) ### See Also `<cloud>`, `<utilities.3d>`
programming_docs
r None `Rows` Extract rows from a list -------------------------------- ### Description Convenience function to extract subset of a list. Usually used in creating keys. ### Usage ``` Rows(x, which) ``` ### Arguments | | | | --- | --- | | `x` | list with each member a vector of the same length | | `which` | index for members of `x` | ### Value A list similar to `x`, with each `x[[i]]` replaced by `x[[i]][which]` ### Author(s) Deepayan Sarkar [[email protected]](mailto:[email protected]) ### See Also `<xyplot>`, `[Lattice](lattice)` r None `panel.stripplot` Default Panel Function for stripplot ------------------------------------------------------- ### Description This is the default panel function for `stripplot`. Also see `panel.superpose` ### Usage ``` panel.stripplot(x, y, jitter.data = FALSE, factor = 0.5, amount = NULL, horizontal = TRUE, groups = NULL, ..., identifier = "stripplot") ``` ### Arguments | | | | --- | --- | | `x,y` | coordinates of points to be plotted | | `jitter.data` | whether points should be jittered to avoid overplotting. The actual jittering is performed inside `<panel.xyplot>`, using its `jitter.x` or `jitter.y` argument (depending on the value of `horizontal`). | | `factor, amount` | amount of jittering, see `[jitter](../../base/html/jitter)` | | `horizontal` | logical. If FALSE, the plot is ‘transposed’ in the sense that the behaviours of x and y are switched. x is now the ‘factor’. Interpretation of other arguments change accordingly. See documentation of `[bwplot](xyplot)` for a fuller explanation. | | `groups` | optional grouping variable | | `...` | additional arguments, passed on to `<panel.xyplot>` | | `identifier` | A character string that is prepended to the names of grobs that are created by this panel function. | ### Details Creates stripplot (one dimensional scatterplot) of `x` for each level of `y` (or vice versa, depending on the value of `horizontal`) ### Author(s) Deepayan Sarkar [[email protected]](mailto:[email protected]) ### See Also `[stripplot](xyplot)`, `[jitter](../../base/html/jitter)` r None `update.trellis` Retrieve and Update Trellis Object ---------------------------------------------------- ### Description Update method for objects of class `"trellis"`, and a way to retrieve the last printed trellis object (that was saved). ### Usage ``` ## S3 method for class 'trellis' update(object, panel, aspect, as.table, between, key, auto.key, legend, layout, main, page, par.strip.text, prepanel, scales, skip, strip, strip.left, sub, xlab, ylab, xlab.top, ylab.right, xlim, ylim, xscale.components, yscale.components, axis, par.settings, plot.args, lattice.options, index.cond, perm.cond, ...) ## S3 method for class 'trellis' t(x) ## S3 method for class 'trellis' x[i, j, ..., drop = FALSE] trellis.last.object(..., prefix) ``` ### Arguments | | | | --- | --- | | `object, x` | The object to be updated, of class `"trellis"`. | | `i, j` | indices to be used. Names are not currently allowed. | | `drop` | logical, whether dimensions with only one level are to be dropped. Currently ignored, behaves as if it were `FALSE`. | | | | | --- | --- | | `panel, aspect, as.table, between, key, auto.key, legend, layout, main, page, par.strip.text, prepanel, scales, skip, strip, strip.left, sub, xlab, ylab, xlab.top, ylab.right, xlim, ylim, xscale.components, yscale.components, axis, par.settings, plot.args, lattice.options, index.cond, perm.cond, ...` | arguments that will be used to update `object`. See details below. | | `prefix` | A character string acting as a prefix identifying the plot of a `"trellis"` object. Only relevant when a particular page is occupied by more than one plot. Defaults to the value appropriate for the last `"trellis"` object printed. See `[trellis.focus](interaction)`. | ### Details All high level lattice functions such as `xyplot` produce an object of (S3) class `"trellis"`, which is usually displayed by its `print` method. However, the object itself can be manipulated and modified to a large extent using the `update` method, and then re-displayed as needed. Most arguments to high level functions can also be supplied to the `update` method as well, with some exceptions. Generally speaking, anything that would needs to change the data within each panel is a no-no (this includes the `formula, data, groups, subscripts` and `subset`). Everything else is technically game, though might not be implemented yet. If you find something missing that you wish to have, feel free to make a request. Not all arguments accepted by a Lattice function are processed by `update`, but the ones listed above should work. The purpose of these arguments are described in the help page for `<xyplot>`. Any other argument is added to the list of arguments to be passed to the `panel` function. Because of their somewhat special nature, updates to objects produced by `cloud` and `wireframe` do not work very well yet. The `"["` method is a convenient shortcut for updating `index.cond`. The `t` method is a convenient shortcut for updating `perm.cond` in the special (but frequent) case where there are exactly two conditioning variables, when it has the effect of switching (‘transposing’) their order. The print method for `"trellis"` objects optionally saves the object after printing it. If this feature is enabled, `trellis.last.object` can retrieve it. By default, the last object plotted is retrieved, but if multiple objects are plotted on the current page, then others can be retrieved using the appropriate `prefix` argument. If `[trellis.last.object](update.trellis)` is called with arguments, these are used to update the retrieved object before returning it. ### Value An object of class `trellis`, by default plotted by `print.trellis`. `trellis.last.object` returns `NULL` is no saved object is available. ### Author(s) Deepayan Sarkar [[email protected]](mailto:[email protected]) ### See Also `<trellis.object>`, `[Lattice](lattice)`, `<xyplot>` ### Examples ``` spots <- by(sunspots, gl(235, 12, labels = 1749:1983), mean) old.options <- lattice.options(save.object = TRUE) xyplot(spots ~ 1749:1983, xlab = "", type = "l", scales = list(x = list(alternating = 2)), main = "Average Yearly Sunspots") update(trellis.last.object(), aspect = "xy") trellis.last.object(xlab = "Year") lattice.options(old.options) ``` r None `panel.pairs` Default Superpanel Function for splom ---------------------------------------------------- ### Description This is the default superpanel function for `splom`. ### Usage ``` panel.pairs(z, panel = lattice.getOption("panel.splom"), lower.panel = panel, upper.panel = panel, diag.panel = "diag.panel.splom", as.matrix = FALSE, groups = NULL, panel.subscripts, subscripts, pscales = 5, prepanel.limits = scale.limits, varnames = colnames(z), varname.col, varname.cex, varname.font, varname.fontfamily, varname.fontface, axis.text.col, axis.text.cex, axis.text.font, axis.text.fontfamily, axis.text.fontface, axis.text.lineheight, axis.line.col, axis.line.lty, axis.line.lwd, axis.line.alpha, axis.line.tck, ...) diag.panel.splom(x = NULL, varname = NULL, limits, at = NULL, labels = NULL, draw = TRUE, tick.number = 5, varname.col, varname.cex, varname.lineheight, varname.font, varname.fontfamily, varname.fontface, axis.text.col, axis.text.alpha, axis.text.cex, axis.text.font, axis.text.fontfamily, axis.text.fontface, axis.text.lineheight, axis.line.col, axis.line.alpha, axis.line.lty, axis.line.lwd, axis.line.tck, ...) ``` ### Arguments | | | | --- | --- | | `z` | The data frame used for the plot. | | `panel, lower.panel, upper.panel` | The panel function used to display each pair of variables. If specified, `lower.panel` and `upper.panel` are used for panels below and above the diagonal respectively. In addition to extra arguments not recognized by `panel.pairs`, the list of arguments passed to the panel function also includes arguments named `i` and `j`, with values indicating the row and column of the scatterplot matrix being plotted. | | `diag.panel` | The panel function used for the diagonals. See arguments to `diag.panel.splom` to know what arguments this function is passed when called. Use `diag.panel=NULL` to suppress plotting on the diagonal panels. | | `as.matrix` | logical. If `TRUE`, the layout of the panels will have origin on the top left instead of bottom left (similar to `pairs`). This is in essence the same functionality as provided by `as.table` for the panel layout | | `groups` | Grouping variable, if any | | `panel.subscripts` | logical specifying whether the panel function accepts an argument named `subscripts`. | | `subscripts` | The indices of the rows of `z` that are to be displayed in this (super)panel. | | `pscales` | Controls axis labels, passed down from `splom`. If `pscales` is a single number, it indicates the approximate number of equally-spaced ticks that should appear on each axis. If `pscales` is a list, it should have one component for each column in `z`, each of which itself a list with the following valid components: `at`: a numeric vector specifying tick locations `labels`: character vector labels to go with at `limits`: numeric 2-vector specifying axis limits (should be made more flexible at some point to handle factors) These are specifications on a per-variable basis, and used on all four sides in the diagonal cells used for labelling. Factor variables are labelled with the factor names. Use `pscales=0` to supress the axes entirely. | | `prepanel.limits` | A function to calculate suitable axis limits given a single argument `x` containing a data vector. The return value of the function should be similar to the `xlim` or `ylim` argument documented in `<xyplot>`; that is, it should be a numeric or DateTime vector of length 2 defining a range, or a character vector representing levels of a factor. Most high-level lattice plots (such as `xyplot`) use the `prepanel` function for deciding on axis limits from data. This function serves a similar function by calculating the per-variable limits. These limits can be overridden by the corresponding `limits` component in the `pscales` list. | | `x` | data vector corresponding to that row / column (which will be the same for diagonal ‘panels’). | | `varname` | (scalar) character string or expression that is to be written centred within the panel | | `limits` | numeric of length 2, or, vector of characters, specifying the scale for that panel (used to calculate tick locations when missing) | | `at` | locations of tick marks | | `labels` | optional labels for tick marks | | `draw` | A logical flag specifying whether to draw the tick marks and labels. If `FALSE`, variable names are shown but axis annotation is omitted. | | `tick.number` | A Numeric scalar giving the suggested number of tick marks. | | `varnames` | A character or expression vector or giving names to be used for the variables in `x`. By default, the column names of `x`. | | `varname.col` | Color for the variable name in each diagonal panel. See `[gpar](../../grid/html/gpar)` for details on this and the other graphical parameters listed below. | | `varname.cex` | Size multiplier for the variable name in each diagonal panel. | | `varname.lineheight` | Line height for the variable name in each diagonal panel. | | `varname.font, varname.fontfamily, varname.fontface` | Font specification for the variable name in each diagonal panel. | | `axis.text.col` | Color for axis label text. | | `axis.text.cex` | Size multiplier for axis label text. | | `axis.text.font, axis.text.fontfamily, axis.text.fontface` | Font specification for axis label text. | | `axis.text.lineheight` | Line height for axis label text. | | `axis.text.alpha` | Alpha-transparency for axis label text. | | `axis.line.col` | Color for the axes. | | `axis.line.lty` | Line type for the axes. | | `axis.line.lwd` | Line width for the axes. | | `axis.line.alpha` | Alpha-transparency for the axes. | | `axis.line.tck` | A numeric multiplier for the length of tick marks in diagonal panels. | | `...` | Further arguments, passed on to `panel`, `lower.panel`, `upper.panel`, and `diag.panel` from `panel.pairs`. Currently ignored by `diag.panel.splom`. | ### Details `panel.pairs` is the function that is actually used as the panel function in a `"trellis"` object produced by `splom`. ### Author(s) Deepayan Sarkar [[email protected]](mailto:[email protected]) ### See Also `<splom>` ### Examples ``` Cmat <- outer(1:6,1:6, function(i,j) rainbow(11, start=.12, end=.5)[i+j-1]) splom(~diag(6), as.matrix = TRUE, panel = function(x, y, i, j, ...) { panel.fill(Cmat[i,j]) panel.text(.5,.5, paste("(",i,",",j,")",sep="")) }) ``` r None `tmd` Tukey Mean-Difference Plot --------------------------------- ### Description `tmd` Creates Tukey Mean-Difference Plots from a trellis object returned by `xyplot`, `qq` or `qqmath`. The prepanel and panel functions are used as appropriate. The `formula` method for `tmd` is provided for convenience, and simply calls `tmd` on the object created by calling `xyplot` on that formula. ### Usage ``` tmd(object, ...) ## S3 method for class 'trellis' tmd(object, xlab = "mean", ylab = "difference", panel, prepanel, ...) prepanel.tmd.qqmath(x, f.value = NULL, distribution = qnorm, qtype = 7, groups = NULL, subscripts, ...) panel.tmd.qqmath(x, f.value = NULL, distribution = qnorm, qtype = 7, groups = NULL, subscripts, ..., identifier = "tmd") panel.tmd.default(x, y, groups = NULL, ..., identifier = "tmd") prepanel.tmd.default(x, y, ...) ``` ### Arguments | | | | --- | --- | | `object` | An object of class `"trellis"` returned by `xyplot`, `qq` or `qqmath`. | | `xlab` | x label | | `ylab` | y label | | `panel` | panel function to be used. See details below. | | `prepanel` | prepanel function. See details below. | | `f.value, distribution, qtype` | see `<panel.qqmath>`. | | `groups, subscripts` | see `<xyplot>`. | | `x, y` | data as passed to panel functions in original call. | | `...` | other arguments | | `identifier` | A character string that is prepended to the names of grobs that are created by this panel function. | ### Details The Tukey Mean-difference plot is produced by modifying the (x,y) values of each panel as follows: the new coordinates are given by `x=(x+y)/2` and `y=y-x`, which are then plotted. The default panel function(s) add a reference line at `y=0` as well. `tmd` acts on the a `"trellis"` object, not on the actual plot this object would have produced. As such, it only uses the arguments supplied to the panel function in the original call, and completely ignores what the original panel function might have done with this data. `tmd` uses these panel arguments to set up its own scales (using its `prepanel` argument) and display (using `panel`). It is thus important to provide suitable prepanel and panel functions to `tmd` depending on the original call. Such functions currently exist for `xyplot`, `qq` (the ones with `default` in their name) and `qqmath`, as listed in the usage section above. These assume the default displays for the corresponding high-level call. If unspecified, the `prepanel` and `panel` arguments default to suitable choices. `tmd` uses the `update` method for `"trellis"` objects, which processes all extra arguments supplied to `tmd`. ### Value An object of class `"trellis"`. The `[update](update.trellis)` method can be used to update components of the object and the `[print](print.trellis)` method (usually called by default) will plot it on an appropriate plotting device. ### Author(s) Deepayan Sarkar [[email protected]](mailto:[email protected]) ### See Also `<qq>`, `<qqmath>`, `<xyplot>`, `[Lattice](lattice)` ### Examples ``` tmd(qqmath(~height | voice.part, data = singer)) ``` r None `panel.number` Accessing Auxiliary Information During Plotting --------------------------------------------------------------- ### Description Control over lattice plots are provided through a collection of user specifiable functions that perform various tasks during the plotting. Not all information is available to all functions. The functions documented here attempt to provide a consistent interface to access relevant information from within these user specified functions, namely those specified as the `panel`, `strip` and `axis` functions. Note that this information is not available to the `prepanel` function, which is executed prior to the actual plotting. ### Usage ``` current.row(prefix) current.column(prefix) panel.number(prefix) packet.number(prefix) which.packet(prefix) trellis.currentLayout(which = c("packet", "panel"), prefix) ``` ### Arguments | | | | --- | --- | | `which` | whether return value (a matrix) should contain panel numbers or packet numbers, which are usually, but not necessarily, the same (see below for details). | | `prefix` | A character string acting as a prefix identifying the plot of a `"trellis"` object. Only relevant when a particular page is occupied by more than one plot. Defaults to the value appropriate for the last `"trellis"` object printed. See `[trellis.focus](interaction)`. | ### Value `trellis.currentLayout` returns a matrix with as many rows and columns as in the layout of panels in the current plot. Entries in the matrix are integer indices indicating which packet (or panel; see below) occupies that position, with 0 indicating the absence of a panel. `current.row` and `current.column` return integer indices specifying which row and column in the layout are currently active. `panel.number` returns an integer counting which panel is being drawn (starting from 1 for the first panel, a.k.a. the panel order). `packet.number` gives the packet number according to the packet order, which is determined by varying the first conditioning variable the fastest, then the second, and so on. `which.packet` returns the combination of levels of the conditioning variables in the form of a numeric vector as long as the number of conditioning variables, with each element an integer indexing the levels of the corresponding variable. ### Note The availability of these functions make redundant some features available in earlier versions of lattice, namely optional arguments called `panel.number` and `packet.number` that were made available to `panel` and `strip`. If you have written such functions, it should be enough to replace instances of `panel.number` and `packet.number` by the corresponding function calls. You should also remove `panel.number` and `packet.number` from the argument list of your function to avoid a warning. If these accessor functions are not enough for your needs, feel free to contact the maintainer and ask for more. ### Author(s) Deepayan Sarkar [[email protected]](mailto:[email protected]) ### See Also `[Lattice](lattice)`, `<xyplot>`
programming_docs
r None `singer` Heights of New York Choral Society singers ---------------------------------------------------- ### Description Heights in inches of the singers in the New York Choral Society in 1979. The data are grouped according to voice part. The vocal range for each voice part increases in pitch according to the following order: Bass 2, Bass 1, Tenor 2, Tenor 1, Alto 2, Alto 1, Soprano 2, Soprano 1. ### Usage ``` singer ``` ### Format A data frame with 235 observations on the following 2 variables. height Height in inches of the singers. voice.part (Unordered) factor with levels "`Bass 2`", "`Bass 1`", "`Tenor 2`", "`Tenor 1`", "`Alto 2`", "`Alto 1`", "`Soprano 2`", "`Soprano 1`". ### Author(s) Documentation contributed by Kevin Wright. ### Source Chambers, J.M., W. S. Cleveland, B. Kleiner, and P. A. Tukey. (1983). *Graphical Methods for Data Analysis*. Chapman and Hall, New York. ### References Cleveland, William S. (1993) *Visualizing Data*. Hobart Press, Summit, New Jersey. ### Examples ``` # Separate histogram for each voice part (Figure 1.2 from Cleveland) histogram(~ height | voice.part, data = singer, aspect=1, layout = c(2, 4), nint=15, xlab = "Height (inches)") # Quantile-Quantile plot (Figure 2.11 from Cleveland) qqmath(~ height | voice.part, data=singer, aspect=1, layout=c(2,4), prepanel = prepanel.qqmathline, panel = function(x, ...) { panel.grid() panel.qqmathline(x, ...) panel.qqmath(x, ...) }, xlab = "Unit Normal Quantile", ylab="Height (inches)") ``` r None `trellis.object` A Trellis Plot Object --------------------------------------- ### Description This class of objects is returned by high level lattice functions, and is usually plotted by default by its `[print](print.trellis)` method. ### Details A trellis object, as returned by high level lattice functions like `<xyplot>`, is a list with the `"class"` attribute set to `"trellis"`. Many of the components of this list are simply the arguments to the high level function that produced the object. Among them are: `as.table`, `layout`, `page`, `panel`, `prepanel`, `main`, `sub`, `par.strip.text`, `strip`, `skip`, `xlab` `ylab`, `par.settings`, `lattice.options` and `plot.args`. Some other typical components are: `formula` the Trellis formula used in the call `index.cond` list with index for each of the conditioning variables `perm.cond` permutation of the order of the conditioning variables `aspect.fill` logical, whether `aspect` is `"fill"` `aspect.ratio` numeric, aspect ratio to be used if `aspect.fill` is `FALSE` `call` call that generated the object. `condlevels` list with levels of the conditioning variables `legend` list describing the legend(s) to be drawn `panel.args` a list as long as the number of panels, each element being a list itself, containing the arguments in named form to be passed to the panel function in that panel. `panel.args.common` a list containing the arguments common to all the panel functions in `name=value` form `x.scales` list describing x-scale, can consist of several other lists, paralleling panel.args, if x-relation is not `"same"` `y.scales` list describing y-scale, similar to `x.scales` `x.between` numeric vector of interpanel x-space `y.between` numeric vector of interpanel y-space `x.limits` numeric vector of length 2 or list, giving x-axis limits `y.limits` similar to `x.limits` `packet.sizes` array recording the number of observations in each packet ### Author(s) Deepayan Sarkar [[email protected]](mailto:[email protected]) ### See Also `[Lattice](lattice)`, `<xyplot>`, `<print.trellis>` r None `panel.barchart` Default Panel Function for barchart ----------------------------------------------------- ### Description Default panel function for `barchart`. ### Usage ``` panel.barchart(x, y, box.ratio = 1, box.width, horizontal = TRUE, origin = NULL, reference = TRUE, stack = FALSE, groups = NULL, col = if (is.null(groups)) plot.polygon$col else superpose.polygon$col, border = if (is.null(groups)) plot.polygon$border else superpose.polygon$border, lty = if (is.null(groups)) plot.polygon$lty else superpose.polygon$lty, lwd = if (is.null(groups)) plot.polygon$lwd else superpose.polygon$lwd, ..., identifier = "barchart") ``` ### Arguments | | | | --- | --- | | `x` | Extent of Bars. By default, bars start at left of panel, unless `origin` is specified, in which case they start there. | | `y` | Horizontal location of bars. Possibly a factor. | | `box.ratio` | Ratio of bar width to inter-bar space. | | `box.width` | Thickness of bars in absolute units; overrides `box.ratio`. Useful for specifying thickness when the categorical variable is not a factor, as use of `box.ratio` alone cannot achieve a thickness greater than 1. | | `horizontal` | Logical flag. If FALSE, the plot is ‘transposed’ in the sense that the behaviours of x and y are switched. x is now the ‘factor’. Interpretation of other arguments change accordingly. See documentation of `[bwplot](xyplot)` for a fuller explanation. | | `origin` | The origin for the bars. For grouped displays with `stack = TRUE`, this argument is ignored and the origin set to 0. Otherwise, defaults to `NULL`, in which case bars start at the left (or bottom) end of a panel. This choice is somewhat unfortuntate, as it can be misleading, but is the default for historical reasons. For tabular (or similar) data, `origin = 0` is usually more appropriate; if not, one should reconsider the use of a bar chart in the first place (dot plots are often a good alternative). | | `reference` | Logical, whether a reference line is to be drawn at the origin. | | `stack` | logical, relevant when groups is non-null. If `FALSE` (the default), bars for different values of the grouping variable are drawn side by side, otherwise they are stacked. | | `groups` | Optional grouping variable. | | `col, border, lty, lwd` | Graphical parameters for the bars. By default, the trellis parameter `plot.polygon` is used if there is no grouping variable, otherwise `superpose.polygon` is used. `col` gives the fill color, `border` the border color, and `lty` and `lwd` the line type and width of the borders. | | `...` | Extra arguments will be accepted but ignored. | | `identifier` | A character string that is prepended to the names of grobs that are created by this panel function. | ### Details A barchart is drawn in the panel. Note that most arguments controlling the display can be supplied to the high-level `barchart` call directly. ### Author(s) Deepayan Sarkar [[email protected]](mailto:[email protected]) ### See Also `[barchart](xyplot)` ### Examples ``` barchart(yield ~ variety | site, data = barley, groups = year, layout = c(1,6), origin = 0, ylab = "Barley Yield (bushels/acre)", scales = list(x = list(abbreviate = TRUE, minlength = 5))) ``` r None `rfs` Residual and Fit Spread Plots ------------------------------------ ### Description Plots fitted values and residuals (via qqmath) on a common scale for any object that has methods for fitted values and residuals. ### Usage ``` rfs(model, layout=c(2, 1), xlab="f-value", ylab=NULL, distribution = qunif, panel, prepanel, strip, ...) ``` ### Arguments | | | | --- | --- | | `model` | a fitted model object with methods `fitted.values` and `residuals`. Can be the value returned by `oneway` | | `layout` | default layout is c(2,1) | | `xlab` | defaults to `"f.value"` | | `distribution` | the distribution function to be used for `qqmath` | | `ylab, panel, prepanel, strip` | See `<xyplot>` | | `...` | other arguments, passed on to `<qqmath>`. | ### Value An object of class `"trellis"`. The `[update](update.trellis)` method can be used to update components of the object and the `[print](print.trellis)` method (usually called by default) will plot it on an appropriate plotting device. ### Author(s) Deepayan Sarkar [[email protected]](mailto:[email protected]) ### See Also `<oneway>`, `<qqmath>`, `<xyplot>`, `[Lattice](lattice)` ### Examples ``` rfs(oneway(height ~ voice.part, data = singer, spread = 1), aspect = 1) ``` r None `latticeParseFormula` Parse Trellis formula -------------------------------------------- ### Description this function is used by high level Lattice functions like `xyplot` to parse the formula argument and evaluate various components of the data. ### Usage ``` latticeParseFormula(model, data, dimension = 2, subset = TRUE, groups = NULL, multiple, outer, subscripts, drop) ``` ### Arguments | | | | --- | --- | | `model` | the model/formula to be parsed. This can be in either of two possible forms, one for 2d and one for 3d formulas, determined by the `dimension` argument. The 2d formulas are of the form `y ~ x| g1 * ... *gn`, and the 3d formulas are of the form `z ~ x * y | g1 * ...* gn`. In the first form, `y` may be omitted. The conditioning variables `g1, ...,gn` can be omitted in either case. | | `data` | the environment/dataset where the variables in the formula are evaluated. | | `dimension` | dimension of the model, see above | | `subset` | index for choosing a subset of the data frame | | `groups` | the grouping variable, if present | | `multiple, outer` | logicals, determining how a ‘+’ in the y and x components of the formula are processed. See `<xyplot>` for details | | `subscripts` | logical, whether subscripts are to be calculated | | `drop` | logical or list, similar to the `drop.unused.levels` argument in `<xyplot>`, indicating whether unused levels of conditioning factors and data variables that are factors are to be dropped. | ### Value returns a list with several components, including `left, right, left.name, right.name, condition` for 2-D, and `left, right.x, right.y, left.name, right.x.name, right.y.name, condition` for 3-D. Other possible components are groups, subscr ### Author(s) Saikat DebRoy, Deepayan Sarkar [[email protected]](mailto:[email protected]) ### See Also `<xyplot>`, `[Lattice](lattice)` r None `panel.superpose` Panel Function for Display Marked by groups -------------------------------------------------------------- ### Description These are panel functions for Trellis displays useful when a grouping variable is specified for use within panels. The `x` (and `y` where appropriate) variables are plotted with different graphical parameters for each distinct value of the grouping variable. ### Usage ``` panel.superpose(x, y = NULL, subscripts, groups, panel.groups = "panel.xyplot", ..., col, col.line, col.symbol, pch, cex, fill, font, fontface, fontfamily, lty, lwd, alpha, type = "p", grid = FALSE, distribute.type = FALSE) panel.superpose.2(..., distribute.type = TRUE) panel.superpose.plain(..., col, col.line, col.symbol, pch, cex, fill, font, fontface, fontfamily, lty, lwd, alpha) ``` ### Arguments | | | | --- | --- | | `x,y` | Coordinates of the points to be displayed. Usually numeric. | | `panel.groups` | The panel function to be used for each subgroup of points. Defaults to `panel.xyplot`. To be able to distinguish between different levels of the originating group inside `panel.groups`, it will be supplied two special arguments called `group.number` and `group.value` which will hold the numeric code and factor level corresponding to the current level of `groups`. No special care needs to be taken when writing a `panel.groups` function if this feature is not used. | | `subscripts` | An integer vector of subscripts giving indices of the `x` and `y` values in the original data source. See the corresponding entry in `<xyplot>` for details. | | `groups` | A grouping variable. Different graphical parameters will be used to plot the subsets of observations given by each distinct value of `groups`. The default graphical parameters are obtained from the `"superpose.symbol"` and `"superpose.line"` settings using `<trellis.par.get>` wherever appropriate. | | `type` | Usually a character vector specifying how each group should be drawn. Formally, it is passed on to the `panel.groups` function, which must know what to do with it. By default, `panel.groups` is `<panel.xyplot>`, whose help page describes the admissible values. The functions `panel.superpose` and `panel.superpose.2` differ only in the default value of `distribute.type`, which controls the way the `type` argument is interpreted. If `distribute.type = FALSE`, then the interpretation is the same as for `panel.xyplot` for each of the unique groups. In other words, if `type` is a vector, all the individual components are honoured concurrently. If `distribute.type = TRUE`, `type` is replicated to be as long as the number of unique values in `groups`, and one component used for the points corresponding to the each different group. Even in this case, it is possible to request multiple types per group, specifying `type` as a list, each component being the desired `type` vector for the corresponding group. If `distribute.type = FALSE`, any occurrence of `"g"` in `type` causes a grid to be drawn, and all such occurrences are removed before `type` is passed on to `panel.groups`. | | `grid` | Logical flag specifying whether a background reference grid should be drawn. See `<panel.xyplot>` for details. | | `col` | A vector color specification. See Details. | | `col.line` | A vector color specification. See Details. | | `col.symbol` | A vector color specification. See Details. | | `pch` | A vector plotting character specification. See Details. | | `cex` | A vector size factor specification. See Details. | | `fill` | A vector fill color specification. See Details. | | `font, fontface, fontfamily` | A vector color specification. See Details. | | `lty` | A vector color specification. See Details. | | `lwd` | A vector color specification. See Details. | | `alpha` | A vector alpha-transparency specification. See Details. | | `...` | Extra arguments. Passed down to `panel.superpose` from `panel.superpose.2`, and to `panel.groups` from `panel.superpose`. | | `distribute.type` | logical controlling interpretation of the `type` argument. | ### Details `panel.superpose` divides up the `x` (and optionally `y`) variable(s) by the unique values of `groups[subscripts]`, and plots each subset with different graphical parameters. The graphical parameters (`col.symbol`, `pch`, etc.) are usually supplied as suitable atomic vectors, but can also be lists. When `panel.groups` is called for the `i`-th level of `groups`, the corresponding element of each graphical parameter is passed to it. In the list form, the individual components can themselves be vectors. The actual plot for each subgroup is created by the `panel.groups` function. With the default `panel.groups`, the `col` argument is overridden by `col.line` and `col.symbol` for lines and points respectively, which default to the `"superpose.line"` and `"superpose.symbol"` settings. However, `col` will still be supplied as an argument to `panel.groups` functions that make use of it, with a default of `"black"`. The defaults of other graphical parameters are also taken from the `"superpose.line"` and `"superpose.symbol"` settings as appropriate. The `alpha` parameter takes it default from the `"superpose.line"` setting. `panel.superpose` and `panel.superpose.2` differ essentially in how `type` is interpreted by default. The default behaviour in `panel.superpose` is the opposite of that in S, which is the same as that of `panel.superpose.2`. `panel.superpose.plain` is the same as `panel.superpose`, except that the default settings for the style arguments are the same for all groups and are taken from the default plot style. It is used in `<xyplot.ts>`. ### Author(s) Deepayan Sarkar [[email protected]](mailto:[email protected]) (`panel.superpose.2` originally contributed by Neil Klepeis) ### See Also Different functions when used as `panel.groups` gives different types of plots, for example `<panel.xyplot>`, `<panel.dotplot>` and `[panel.average](panel.functions)` (This can be used to produce interaction plots). See `[Lattice](lattice)` for an overview of the package, and `<xyplot>` for common arguments (in particular, the discussion of the extended formula interface and the `groups` argument). r None `axis.default` Default axis annotation utilities ------------------------------------------------- ### Description Lattice funtions provide control over how the plot axes are annotated through a common interface. There are two levels of control. The `xscale.components` and `yscale.components` arguments can be functions that determine tick mark locations and labels given a packet. For more direct control, the `axis` argument can be a function that actually draws the axes. The functions documented here are the defaults for these arguments. They can additonally be used as components of user written replacements. ### Usage ``` xscale.components.default(lim, packet.number = 0, packet.list = NULL, top = TRUE, ...) yscale.components.default(lim, packet.number = 0, packet.list = NULL, right = TRUE, ...) axis.default(side = c("top", "bottom", "left", "right"), scales, components, as.table, labels = c("default", "yes", "no"), ticks = c("default", "yes", "no"), ..., prefix) ``` ### Arguments | | | | --- | --- | | `lim` | the range of the data in that packet (data subset corresponding to a combination of levels of the conditioning variable). The range is not necessarily numeric; e.g. for factors, they could be character vectors representing levels, and for the various date-time representations, they could be vectors of length 2 with the corresponding class. | | `packet.number` | which packet (counted according to the packet order, described in `<print.trellis>`) is being processed. In cases where all panels have the same limits, this function is called only once (rather than once for each packet), in which case this argument will have the value `0`. | | `packet.list` | list, as long as the number of packets, giving all the actual packets. Specifically, each component is the list of arguments given to the panel function when and if that packet is drawn in a panel. (This has not yet been implemented.) | | `top, right` | the value of the `top` and `right` components of the result, as appropriate. See below for interpretation. | | `side` | on which side the axis is to be drawn. The usual partial matching rules apply. | | `scales` | the appropriate component of the `scales` argument supplied to the high level function, suitably standardized. | | `components` | list, similar to those produced by `xscale.components.default` and `yscale.components.default`. | | `as.table` | the `as.table` argument in the high level function. | | `labels` | whether labels are to be drawn. By default, the rules determined by `scales` are used. | | `ticks` | whether labels are to be drawn. By default, the rules determined by `scales` are used. | | `...` | many other arguments may be supplied, and are passed on to other internal functions. | | `prefix` | A character string identifying the plot being drawn (see `<print.trellis>`). Used to retrieve location of current panel in the overall layout, so that axes can be drawn appropriately. | ### Details These functions are part of a new API introduced in lattice 0.14 to provide the user more control over how axis annotation is done. While the API has been designed in anticipation of use that was previously unsupported, the implementation has initially focused on reproducing existing capabilities, rather than test new features. At the time of writing, several features are unimplemented. If you require them, please contact the maintainer. ### Value `xscale.components.default` and `yscale.components.default` return a list of the form suitable as the `components` argument of `axis.default`. Valid components in the return value of `xscale.components.default` are: | | | | --- | --- | | ``num.limit`` | A numeric limit for the box. | | ``bottom`` | A list with two elements, `ticks` and `labels`. `ticks` must be a list with components `at` and `tck` which give the location and lengths of tick marks. `tck` can be a vector, and will be recycled to be as long as `at`. `labels` must be a list with components `at`, `labels`, and `check.overlap`. `at` and `labels` give the location and labels of the tick labels; this is usually the same as the location of the ticks, but is not required to be so. `check.overlap` is a logical flag indicating whether overlapping of labels should be avoided by omitting some of the labels while rendering. | | ``top`` | This can be a logical flag; if `TRUE`, `top` is treated as being the same as `bottom`; if `FALSE`, axis annotation for the top axis is omitted. Alternatively, `top` can be a list like `bottom`. | Valid components in the return value of `yscale.components.default` are `left` and `right`. Their interpretations are analogous to (respectively) the `bottom` and `top` components described above. ### Author(s) Deepayan Sarkar [[email protected]](mailto:[email protected]) ### See Also `[Lattice](lattice)`, `<xyplot>`, `<print.trellis>` ### Examples ``` str(xscale.components.default(c(0, 1))) set.seed(36872) rln <- rlnorm(100) densityplot(rln, scales = list(x = list(log = 2), alternating = 3), xlab = "Simulated lognormal variates", xscale.components = function(...) { ans <- xscale.components.default(...) ans$top <- ans$bottom ans$bottom$labels$labels <- parse(text = ans$bottom$labels$labels) ans$top$labels$labels <- if (require(MASS)) fractions(2^(ans$top$labels$at)) else 2^(ans$top$labels$at) ans }) ## Direct use of axis to show two temperature scales (Celcius and ## Fahrenheit). This does not work for multi-row plots, and doesn't ## do automatic allocation of space F2C <- function(f) 5 * (f - 32) / 9 C2F <- function(c) 32 + 9 * c / 5 axis.CF <- function(side, ...) { ylim <- current.panel.limits()$ylim switch(side, left = { prettyF <- pretty(ylim) labF <- parse(text = sprintf("%s ~ degree * F", prettyF)) panel.axis(side = side, outside = TRUE, at = prettyF, labels = labF) }, right = { prettyC <- pretty(F2C(ylim)) labC <- parse(text = sprintf("%s ~ degree * C", prettyC)) panel.axis(side = side, outside = TRUE, at = C2F(prettyC), labels = labC) }, axis.default(side = side, ...)) } xyplot(nhtemp ~ time(nhtemp), aspect = "xy", type = "o", scales = list(y = list(alternating = 3)), axis = axis.CF, xlab = "Year", ylab = "Temperature", main = "Yearly temperature in New Haven, CT") ## version using yscale.components yscale.components.CF <- function(...) { ans <- yscale.components.default(...) ans$right <- ans$left ans$left$labels$labels <- parse(text = sprintf("%s ~ degree * F", ans$left$labels$at)) prettyC <- pretty(F2C(ans$num.limit)) ans$right$ticks$at <- C2F(prettyC) ans$right$labels$at <- C2F(prettyC) ans$right$labels$labels <- parse(text = sprintf("%s ~ degree * C", prettyC)) ans } xyplot(nhtemp ~ time(nhtemp), aspect = "xy", type = "o", scales = list(y = list(alternating = 3)), yscale.components = yscale.components.CF, xlab = "Year", ylab = "Temperature", main = "Yearly temperature in New Haven, CT") ```
programming_docs
r None `prepanel.default` Default Prepanel Functions ---------------------------------------------- ### Description These prepanel functions are used as fallback defaults in various high level plot functions in Lattice. These are rarely useful to normal users but may be helpful in developing new displays. ### Usage ``` prepanel.default.bwplot(x, y, horizontal, nlevels, origin, stack, ...) prepanel.default.histogram(x, breaks, equal.widths, type, nint, ...) prepanel.default.qq(x, y, ...) prepanel.default.xyplot(x, y, type, subscripts, groups, ...) prepanel.default.cloud(perspective, distance, xlim, ylim, zlim, screen = list(z = 40, x = -60), R.mat = diag(4), aspect = c(1, 1), panel.aspect = 1, ..., zoom = 0.8) prepanel.default.levelplot(x, y, subscripts, ...) prepanel.default.qqmath(x, f.value, distribution, qtype, groups, subscripts, ..., tails.n = 0) prepanel.default.densityplot(x, darg, groups, weights, subscripts, ...) prepanel.default.parallel(x, y, z, ..., horizontal.axis) prepanel.default.splom(z, ...) ``` ### Arguments | | | | --- | --- | | `x, y` | x and y values, numeric or factor | | `horizontal` | logical, applicable when one of the variables is to be treated as categorical (factor or shingle). | | `horizontal.axis` | logical indicating whether the parallel axes should be laid out horizontally (`TRUE`) or vertically (`FALSE`). | | `nlevels` | number of levels of such a categorical variable. | | `origin, stack` | for barcharts or the `type="h"` plot type | | `breaks, equal.widths, type, nint` | details of histogram calculations. `type` has a different meaning in `prepanel.default.xyplot` (see `<panel.xyplot>`) | | `groups, subscripts` | See `<xyplot>`. Whenever appropriate, calculations are done separately for each group and then combined. | | `weights` | numeric vector of weights for the density calculations. If this is specified, it is subsetted by `subscripts` to match it to `x`. | | `perspective, distance, xlim, ylim, zlim, screen, R.mat, aspect, panel.aspect, zoom` | see `<panel.cloud>` | | `f.value, distribution, tails.n` | see `panel.qqmath` | | `darg` | list of arguments passed to `[density](../../stats/html/density)` | | `z` | see `<panel.parallel>` and `<panel.pairs>` | | `qtype` | type of `[quantile](../../stats/html/quantile)` | | `...` | other arguments, usually ignored | ### Value A list with components `xlim`, `ylim`, `dx` and `dy`, and possibly `xat` and `yat`, the first two being used to calculate panel axes limits, the last two for banking computations. The form of these components are described in the help page for `<xyplot>`. ### Author(s) Deepayan Sarkar [[email protected]](mailto:[email protected]) ### See Also `<xyplot>`, `<banking>`, `[Lattice](lattice)`. See documentation of corresponding panel functions for more details about the arguments. r None `qq` Quantile-Quantile Plots of Two Samples -------------------------------------------- ### Description Quantile-Quantile plots for comparing two Distributions ### Usage ``` qq(x, data, ...) ## S3 method for class 'formula' qq(x, data, aspect = "fill", panel = lattice.getOption("panel.qq"), prepanel, scales, strip, groups, xlab, xlim, ylab, ylim, f.value = NULL, drop.unused.levels = lattice.getOption("drop.unused.levels"), ..., lattice.options = NULL, qtype = 7, default.scales = list(), default.prepanel = lattice.getOption("prepanel.default.qq"), subscripts, subset) ``` ### Arguments | | | | --- | --- | | `x` | The object on which method dispatch is carried out. For the `"formula"` method, `x` should be a formula of the form `y ~ x | g1 * g2 * ...`, where `x` should be a numeric variable, and `y` a factor, shingle, character, or numeric variable, with the restriction that there must be exactly two levels of `y`, which divide the values of `x` into two groups. Quantiles for these groups will be plotted against each other along the two axes. | | `data` | For the `formula` method, an optional data source (usually a data frame) in which variables are to be evaluated (see `<xyplot>` for details). | | `f.value` | An optional numeric vector of probabilities, quantiles corresponding to which should be plotted. This can also be a function of a single integer (representing sample size) that returns such a numeric vector. A typical value for this argument is the function `ppoints`, which is also the S-PLUS default. If specified, the probabilities generated by this function is used for the plotted quantiles, through the `quantile` function. `f.value` defaults to `NULL`, which is equivalent to ``` f.value = function(n) ppoints(n, a = 1) ``` This has the effect of including the minimum and maximum data values in the computed quantiles. This is similar to what happens for `qqplot` but different from the default behaviour of `qq` in S-PLUS. For large `x`, this argument can be used to restrict the number of quantiles plotted. | | `panel` | A function, called once for each panel, that uses the packet (subset of panel variables) corresponding to the panel to create a display. The default panel function `[panel.qq](panel.xyplot)` is documented separately, and has arguments that can be used to customize its output in various ways. Such arguments can usually be directly supplied to the high-level function. | | `qtype` | The `type` argument for `[quantile](../../stats/html/quantile)`. | | `aspect` | See `<xyplot>`. | | `prepanel` | See `<xyplot>`. | | `scales` | See `<xyplot>`. | | `strip` | See `<xyplot>`. | | `groups` | See `<xyplot>`. | | `xlab, ylab` | See `<xyplot>`. | | `xlim, ylim` | See `<xyplot>`. | | `drop.unused.levels` | See `<xyplot>`. | | `lattice.options` | See `<xyplot>`. | | `default.scales` | See `<xyplot>`. | | `subscripts` | See `<xyplot>`. | | `subset` | See `<xyplot>`. | | `default.prepanel` | Fallback prepanel function. See `<xyplot>`. | | `...` | Further arguments. See corresponding entry in `<xyplot>` for non-trivial details. | ### Details `qq` produces Q-Q plots of two samples. The default behaviour of `qq` is different from the corresponding S-PLUS function. See the entry for `f.value` for specifics. This and all other high level Trellis functions have several arguments in common. These are extensively documented only in the help page for `xyplot`, which should be consulted to learn more detailed usage. ### Value An object of class `"trellis"`. The `[update](update.trellis)` method can be used to update components of the object and the `[print](print.trellis)` method (usually called by default) will plot it on an appropriate plotting device. ### Author(s) Deepayan Sarkar [[email protected]](mailto:[email protected]) ### See Also `<xyplot>`, `[panel.qq](panel.xyplot)`, `<qqmath>`, `[Lattice](lattice)` ### Examples ``` qq(voice.part ~ height, aspect = 1, data = singer, subset = (voice.part == "Bass 2" | voice.part == "Tenor 1")) ``` r None `make.groups` Grouped data from multiple vectors ------------------------------------------------- ### Description Combines two or more vectors, possibly of different lengths, producing a data frame with a second column indicating which of these vectors that row came from. This is mostly useful for getting data into a form suitable for use in high level Lattice functions. ### Usage ``` make.groups(...) ``` ### Arguments | | | | --- | --- | | `...` | one or more vectors of the same type (coercion is attempted if not), or one or more data frames with similar columns, with possibly differing number of rows. | ### Value When all the input arguments are vectors, a data frame with two columns | | | | --- | --- | | ``data`` | all the vectors supplied, concatenated | | ``which`` | factor indicating which vector the corresponding `data` value came from | When all the input arguments are data frames, the result of `[rbind](../../base/html/cbind)` applied to them, along with an additional `which` column as described above. ### Author(s) Deepayan Sarkar [[email protected]](mailto:[email protected]) ### See Also `[Lattice](lattice)` ### Examples ``` sim.dat <- make.groups(uniform = runif(200), exponential = rexp(175), lognormal = rlnorm(150), normal = rnorm(125)) qqmath( ~ data | which, sim.dat, scales = list(y = "free")) ``` r None `panel.qqmath` Default Panel Function for qqmath ------------------------------------------------- ### Description This is the default panel function for `qqmath`. ### Usage ``` panel.qqmath(x, f.value = NULL, distribution = qnorm, qtype = 7, groups = NULL, ..., tails.n = 0, identifier = "qqmath") ``` ### Arguments | | | | --- | --- | | `x` | vector (typically numeric, coerced if not) of data values to be used in the panel. | | `f.value, distribution` | Defines how quantiles are calculated. See `<qqmath>` for details. | | `qtype` | The `type` argument to be used in `[quantile](../../stats/html/quantile)` | | `groups` | An optional grouping variable. Within each panel, one Q-Q plot is produced for every level of this grouping variable, differentiated by different graphical parameters. | | `...` | Further arguments, often graphical parameters, eventually passed on to `<panel.xyplot>`. Arguments `grid` and `abline` of `panel.xyplot` may be particularly useful. | | `tails.n` | number of data points to represent exactly on each tail of the distribution. This reproduces the effect of `f.value = NULL` for the extreme data values, while approximating the remaining data. It has no effect if `f.value = NULL`. If `tails.n` is given, `qtype` is forced to be 1. | | `identifier` | A character string that is prepended to the names of grobs that are created by this panel function. | ### Details Creates a Q-Q plot of the data and the theoretical distribution given by `distribution`. Note that most of the arguments controlling the display can be supplied directly to the high-level `qqmath` call. ### Author(s) Deepayan Sarkar [[email protected]](mailto:[email protected]) ### See Also `<qqmath>` ### Examples ``` set.seed(0) xx <- rt(10000, df = 10) qqmath(~ xx, pch = "+", distribution = qnorm, grid = TRUE, abline = c(0, 1), xlab.top = c("raw", "ppoints(100)", "tails.n = 50"), panel = function(..., f.value) { switch(panel.number(), panel.qqmath(..., f.value = NULL), panel.qqmath(..., f.value = ppoints(100)), panel.qqmath(..., f.value = ppoints(100), tails.n = 50)) }, layout = c(3, 1))[c(1,1,1)] ``` r None `interaction` Functions to Interact with Lattice Plots ------------------------------------------------------- ### Description The classic Trellis paradigm is to plot the whole object at once, without the possibility of interacting with it afterwards. However, by keeping track of the grid viewports where the panels and strips are drawn, it is possible to go back to them afterwards and enhance them one panel at a time. These functions provide convenient interfaces to help in this. Note that these are still experimental and the exact details may change in future. ### Usage ``` panel.identify(x, y = NULL, subscripts = seq_along(x), labels = subscripts, n = length(x), offset = 0.5, threshold = 18, ## in points, roughly 0.25 inches panel.args = trellis.panelArgs(), ...) panel.identify.qqmath(x, distribution, groups, subscripts, labels, panel.args = trellis.panelArgs(), ...) panel.identify.cloud(x, y, z, subscripts, perspective, distance, xlim, ylim, zlim, screen, R.mat, aspect, scales.3d, ..., panel.3d.identify, n = length(subscripts), offset = 0.5, threshold = 18, labels = subscripts, panel.args = trellis.panelArgs()) panel.link.splom(threshold = 18, verbose = getOption("verbose"), ...) panel.brush.splom(threshold = 18, verbose = getOption("verbose"), ...) trellis.vpname(name = c("position", "split", "split.location", "toplevel", "figure", "panel", "strip", "strip.left", "legend", "legend.region", "main", "sub", "xlab", "ylab", "xlab.top", "ylab.right", "page"), column, row, side = c("left", "top", "right", "bottom", "inside"), clip.off = FALSE, prefix) trellis.grobname(name, type = c("", "panel", "strip", "strip.left", "key", "colorkey"), group = 0, which.given = lattice.getStatus("current.which.given", prefix = prefix), which.panel = lattice.getStatus("current.which.panel", prefix = prefix), column = lattice.getStatus("current.focus.column", prefix = prefix), row = lattice.getStatus("current.focus.row", prefix = prefix), prefix = lattice.getStatus("current.prefix")) trellis.focus(name, column, row, side, clip.off, highlight = interactive(), ..., prefix, guess = TRUE, verbose = getOption("verbose")) trellis.switchFocus(name, side, clip.off, highlight, ..., prefix) trellis.unfocus() trellis.panelArgs(x, packet.number) ``` ### Arguments | | | | --- | --- | | `x, y, z` | variables defining the contents of the panel. In the case of `trellis.panelArgs`, a `"trellis"` object. | | `n` | the number of points to identify by default (overridden by a right click) | | `subscripts` | an optional vector of integer indices associated with each point. See details below. | | `labels` | an optional vector of labels associated with each point. Defaults to `subscripts` | | `distribution, groups` | typical panel arguments of `<panel.qqmath>`. These will usually be obtained from `panel.args` | | `offset` | the labels are printed either below, above, to the left or to the right of the identified point, depending on the relative location of the mouse click. The `offset` specifies (in "char" units) how far from the identified point the labels should be printed. | | `threshold` | threshold in grid's `"points"` units. Points further than these from the mouse click position are not considered | | `panel.args` | list that contains components names `x` (and usually `y`), to be used if `x` is missing. Typically, when called after `trellis.focus`, this would appropriately be the arguments passed to that panel. | | `perspective, distance, xlim, ylim, zlim, screen, R.mat, aspect, scales.3d` | arguments as passed to `<panel.cloud>`. These are required to recompute the relevant three-dimensional projections in `panel.identify.cloud`. | | `panel.3d.identify` | the function that is responsible for the actual interaction once the data rescaling and rotation computations have been done. By default, an internal function similar to `panel.identify` is used. | | `name` | A character string indicating which viewport or grob we are looking for. Although these do not necessarily provide access to all viewports and grobs created by a lattice plot, they cover most of the ones that end-users may find interesting. `trellis.vpname` and `trellis.focus` deal with viewport names only, and only accept the values explicitly listed above. `trellis.grobname` is meant to create names for grobs, and can currently accept any value. If `name`, as well as `column` and `row` is missing in a call to `trellis.focus`, the user can click inside a panel (or an associated strip) to focus on that panel. Note however that this assumes equal width and height for each panel, and may not work when this is not true. When `name` is `"panel"`, `"strip"`, or `"strip.left"`, `column` and `row` must also be specified. When `name` is `"legend"`, `side` must also be specified. | | `column, row` | integers, indicating position of the panel or strip that should be assigned focus in the Trellis layout. Rows are usually calculated from the bottom up, unless the plot was created with `as.table=TRUE` | | `guess` | logical. If `TRUE`, and the display has only one panel, that panel will be automatically selected by a call to `trellis.focus`. | | `side` | character string, relevant only for legends (i.e., when `name="legend"`), indicating their position. Partial specification is allowed, as long as it is unambiguous. | | `clip.off` | logical, whether clipping should be off, relevant when `name` is `"panel"` or `"strip"`. This is necessary if axes are to be drawn outside the panel or strip. Note that setting `clip.off=FALSE` does not necessarily mean that clipping is on; that is determined by conditions in effect during printing. | | `type` | A character string specifying whether the grob is specific to a particular panel or strip. When `type` is `"panel"`, `"strip"`, or `"strip.left"`, information about the panel is added to the grob name. | | `group` | An integer specifying whether the grob is specific to a particular group within the plot. When `group` is greater than zero, information about the group is added to the grob name. | | `which.given, which.panel` | integers, indicating which conditional variable is being represented (within a strip) and the current levels of the conditional variables. When `which.panel` has length greater than 1, and the `type` is `"strip"` or `"strip.left"`, information about the conditional variable is added to the grob name. | | `prefix` | A character string acting as a prefix identifying the plot of a `"trellis"` object, primarily used to distinguish otherwise equivalent viewports in different plots. This only becomes relevant when a particular page is occupied by more than one plot. Defaults to the value appropriate for the last `"trellis"` object printed, as determined by the `prefix` argument in `<print.trellis>`. Users should not usually need to supply a value for this argument except to interact with an existing plot other than the one plotted last. For `switchFocus`, ignored except when it does not match the prefix of the currently active plot, in which case an error occurs. | | `highlight` | logical, whether the viewport being assigned focus should be highlighted. For `trellis.focus`, the default is `TRUE` in interactive mode, and `trellis.switchFocus` by default preserves the setting currently active. | | `packet.number` | integer, which panel to get data from. See `[packet.number](panel.number)` for details on how this is calculated | | `verbose` | whether details will be printed | | `...` | For `panel.identify.qqmath`, extra parameters are passed on to `panel.identify`. For `panel.identify`, extra arguments are treated as graphical parameters and are used for labelling. For `trellis.focus` and `trellis.switchFocus`, these are used (in combination with `<lattice.options>`) for highlighting the chosen viewport if so requested. Graphical parameters can be supplied for `panel.link.splom`. | ### Details `panel.identify` is similar to `[identify](../../graphics/html/identify)`. When called, it waits for the user to identify points (in the panel being drawn) via mouse clicks. Clicks other than left-clicks terminate the procedure. Although it is possible to call it as part of the panel function, it is more typical to use it to identify points after plotting the whole object, in which case a call to `trellis.focus` first is necessary. `panel.link.splom` is meant for use with `<splom>`, and requires a panel to be chosen using `trellis.focus` before it is called. Clicking on a point causes that and the corresponding proections in other pairwise scatter plots to be highlighted. `panel.brush.splom` is a (misnamed) alias for `panel.link.splom`, retained for back-compatibility. `panel.identify.qqmath` is a specialized wrapper meant for use with the display produced by `<qqmath>`. `panel.identify.qqmath` is a specialized wrapper meant for use with the display produced by `<cloud>`. It would be unusual to call them except in a context where default panel function arguments are available through `trellis.panelArgs` (see below). One way in which `panel.identify` etc. are different from `[identify](../../graphics/html/identify)` is in how it uses the `subscripts` argument. In general, when one identifies points in a panel, one wants to identify the origin in the data frame used to produce the plot, and not within that particular panel. This information is available to the panel function, but only in certain situations. One way to ensure that `subscripts` is available is to specify `subscripts = TRUE` in the high level call such as `xyplot`. If `subscripts` is not explicitly specified in the call to `panel.identify`, but is available in `panel.args`, then those values will be used. Otherwise, they default to `seq_along(x)`. In either case, the final return value will be the subscripts that were marked. The process of printing (plotting) a Trellis object builds up a grid layout with named viewports which can then be accessed to modify the plot further. While full flexibility can only be obtained by using grid functions directly, a few lattice functions are available for the more common tasks. `trellis.focus` can be used to move to a particular panel or strip, identified by its position in the array of panels. It can also be used to focus on the viewport corresponding to one of the labels or a legend, though such usage would be less useful. The exact viewport is determined by the `name` along with the other arguments, not all of which are relevant for all names. Note that when more than one object is plotted on a page, `trellis.focus` will always go to the plot that was created last. For more flexibility, use grid functions directly (see note below). After a successful call to `trellis.focus`, the desired viewport (typically panel or strip area) will be made the ‘current’ viewport (plotting area), which can then be enhanced by calls to standard lattice panel functions as well as grid functions. It is quite common to have the layout of panels chosen when a `"trellis"` object is drawn, and not before then. Information on the layout (specifically, how many rows and columns, and which packet belongs in which position in this layout) is retained for the last `"trellis"` object plotted, and is available through `trellis.currentLayout`. `trellis.unfocus` unsets the focus, and makes the top level viewport the current viewport. `trellis.switchFocus` is a convenience function to switch from one viewport to another, while preserving the current `row` and `column`. Although the rows and columns only make sense for panels and strips, they would be preserved even when the user switches to some other viewport (where row/column is irrelevant) and then switches back. Once a panel or strip is in focus, `trellis.panelArgs` can be used to retrieve the arguments that were available to the panel function at that position. In this case, it can be called without arguments as ``` trellis.panelArgs() ``` This usage is also allowed when a `"trellis"` object is being printed, e.g. inside the panel functions or the axis function (but not inside the prepanel function). `trellis.panelArgs` can also retrieve the panel arguments from any `"trellis"` object. Note that for this usage, one needs to specify the `packet.number` (as described under the `panel` entry in `<xyplot>`) and not the position in the layout, because a layout determines the panel only **after** the object has been printed. It is usually not necessary to call `trellis.vpname` and `trellis.grobname` directly. However, they can be useful in generating appropriate names in a portable way when using grid functions to interact with the plots directly, as described in the note below. ### Value `panel.identify` returns an integer vector containing the subscripts of the identified points (see details above). The equivalent of `identify` with `pos=TRUE` is not yet implemented, but can be considered for addition if requested. `trellis.panelArgs` returns a named list of arguments that were available to the panel function for the chosen panel. `trellis.vpname` and `trellis.grobname` return character strings. `trellis.focus` has a meaningful return value only if it has been used to focus on a panel interactively, in which case the return value is a list with components `col` and `row` giving the column and row positions respectively of the chosen panel, unless the choice was cancelled (by a right click), in which case the return value is `NULL`. If click was outside a panel, both `col` and `row` are set to 0. ### Note The viewports created by lattice are accessible to the user through `trellis.focus` as described above. Functions from the grid package can also be used directly. For example, `[current.vpTree](../../grid/html/current.viewport)` can be used to inspect the current viewport tree and `[seekViewport](../../grid/html/viewports)` or `[downViewport](../../grid/html/viewports)` can be used to navigate to these viewports. For such usage, `trellis.vpname` and `trellis.grobname` provides a portable way to access the appropriate viewports and grobs by name. ### Author(s) Deepayan Sarkar [[email protected]](mailto:[email protected]). Felix Andrews provided initial implementations of `panel.identify.qqmath` and support for focusing on panels interctively. ### See Also `[identify](../../graphics/html/identify)`, `[Lattice](lattice)`, `<print.trellis>`, `[trellis.currentLayout](panel.number)`, `[current.vpTree](../../grid/html/current.viewport)`, `[viewports](../../grid/html/viewports)` ### Examples ``` ## Not run: xyplot(1:10 ~ 1:10) trellis.focus("panel", 1, 1) panel.identify() ## End(Not run) xyplot(Petal.Length ~ Sepal.Length | Species, iris, layout = c(2, 2)) Sys.sleep(1) trellis.focus("panel", 1, 1) do.call("panel.lmline", trellis.panelArgs()) Sys.sleep(0.5) trellis.unfocus() trellis.focus("panel", 2, 1) do.call("panel.lmline", trellis.panelArgs()) Sys.sleep(0.5) trellis.unfocus() trellis.focus("panel", 1, 2) do.call("panel.lmline", trellis.panelArgs()) Sys.sleep(0.5) trellis.unfocus() ## choosing loess smoothing parameter p <- xyplot(dist ~ speed, cars) panel.loessresid <- function(x = panel.args$x, y = panel.args$y, span, panel.args = trellis.panelArgs()) { fm <- loess(y ~ x, span = span) xgrid <- do.breaks(current.panel.limits()$xlim, 50) ygrid <- predict(fm, newdata = data.frame(x = xgrid)) panel.lines(xgrid, ygrid) pred <- predict(fm) ## center residuals so that they fall inside panel resids <- y - pred + mean(y) fm.resid <- loess.smooth(x, resids, span = span) ##panel.points(x, resids, col = 1, pch = 4) panel.lines(fm.resid, col = 1) } spans <- c(0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8) update(p, index.cond = list(rep(1, length(spans)))) panel.locs <- trellis.currentLayout() i <- 1 for (row in 1:nrow(panel.locs)) for (column in 1:ncol(panel.locs)) if (panel.locs[row, column] > 0) { trellis.focus("panel", row = row, column = column, highlight = FALSE) panel.loessresid(span = spans[i]) grid::grid.text(paste("span = ", spans[i]), x = 0.25, y = 0.75, default.units = "npc") trellis.unfocus() i <- i + 1 } ```
programming_docs
r None `shingles` shingles -------------------- ### Description Functions to handle shingles ### Usage ``` shingle(x, intervals=sort(unique(x))) equal.count(x, ...) as.shingle(x) is.shingle(x) ## S3 method for class 'shingle' plot(x, panel, xlab, ylab, ...) ## S3 method for class 'shingle' print(x, showValues = TRUE, ...) ## S3 method for class 'shingleLevel' as.character(x, ...) ## S3 method for class 'shingleLevel' print(x, ...) ## S3 method for class 'shingle' summary(object, showValues = FALSE, ...) ## S3 method for class 'shingle' x[subset, drop = FALSE] as.factorOrShingle(x, subset, drop) ``` ### Arguments | | | | --- | --- | | `x` | numeric variable or R object, shingle in `plot.shingle` and `x[]`. An object (list of intervals) of class "shingleLevel" in `print.shingleLevel` | | `object` | shingle object to be summarized | | `showValues` | logical, whether to print the numeric part. If FALSE, only the intervals are printed | | | | | --- | --- | | `intervals` | numeric vector or matrix with 2 columns | | `subset` | logical vector | | `drop` | whether redundant shingle levels are to be dropped | | `panel, xlab, ylab` | standard Trellis arguments (see `<xyplot>` ) | | `...` | other arguments, passed down as appropriate. For example, extra arguments to `equal.count` are passed on to `co.intervals`. graphical parameters can be passed as arguments to the `plot` method. | ### Details A shingle is a data structure used in Trellis, and is a generalization of factors to ‘continuous’ variables. It consists of a numeric vector along with some possibly overlapping intervals. These intervals are the ‘levels’ of the shingle. The `levels` and `nlevels` functions, usually applicable to factors, also work on shingles. The implementation of shingles is slightly different from S. There are print methods for shingles, as well as for printing the result of `levels()` applied to a shingle. For use in labelling, the `as.character` method can be used to convert levels of a shingle to character strings. `equal.count` converts `x` to a shingle using the equal count algorithm. This is essentially a wrapper around `co.intervals`. All arguments are passed to `co.intervals`. `shingle` creates a shingle using the given `intervals`. If `intervals` is a vector, these are used to form 0 length intervals. `as.shingle` returns `shingle(x)` if `x` is not a shingle. `is.shingle` tests whether `x` is a shingle. `plot.shingle` displays the ranges of shingles via rectangles. `print.shingle` and `summary.shingle` describe the shingle object. ### Value `x$intervals` for `levels.shingle(x)`, logical for `is.shingle`, an object of class `"trellis"` for `plot` (printed by default by `print.trellis`), and an object of class `"shingle"` for the others. ### Author(s) Deepayan Sarkar [[email protected]](mailto:[email protected]) ### See Also `<xyplot>`, `[co.intervals](../../graphics/html/coplot)`, `[Lattice](lattice)` ### Examples ``` z <- equal.count(rnorm(50)) plot(z) print(z) print(levels(z)) ``` r None `panel.xyplot` Default Panel Function for xyplot ------------------------------------------------- ### Description This is the default panel function for `xyplot`. Also see `panel.superpose`. The default panel functions for `splom` and `qq` are essentially the same function. ### Usage ``` panel.xyplot(x, y, type = "p", groups = NULL, pch, col, col.line, col.symbol, font, fontfamily, fontface, lty, cex, fill, lwd, horizontal = FALSE, ..., grid = FALSE, abline = NULL, jitter.x = FALSE, jitter.y = FALSE, factor = 0.5, amount = NULL, identifier = "xyplot") panel.splom(..., identifier = "splom") panel.qq(..., identifier = "qq") ``` ### Arguments | | | | --- | --- | | `x,y` | variables to be plotted in the scatterplot | | `type` | character vector consisting of one or more of the following: `"p"`, `"l"`, `"h"`, `"b"`, `"o"`, `"s"`, `"S"`, `"r"`, `"a"`, `"g"`, `"smooth"`, and `"spline"`. If `type` has more than one element, an attempt is made to combine the effect of each of the components. The behaviour if any of the first six are included in `type` is similar to the effect of `type` in `[plot](../../graphics/html/plot.default)` (type `"b"` is actually the same as `"o"`). `"r"` adds a linear regression line (same as `[panel.lmline](panel.functions)`, except for default graphical parameters). `"smooth"` adds a loess fit (same as `<panel.loess>`). `"spline"` adds a cubic smoothing spline fit (same as `<panel.spline>`). `"g"` adds a reference grid using `[panel.grid](panel.functions)` in the background (but using the `grid` argument is now the preferred way to do so). `"a"` has the effect of calling `[panel.average](panel.functions)`, which can be useful for creating interaction plots. The effect of several of these specifications depend on the value of `horizontal`. Type `"s"` (and `"S"`) sorts the values along one of the axes (depending on `horizontal`); this is unlike the behavior in `plot`. For the latter behavior, use `type = "s"` with `panel = panel.points`. See `example(xyplot)` and `demo(lattice)` for examples. | | `groups` | an optional grouping variable. If present, `<panel.superpose>` will be used instead to display each subgroup | | `col, col.line, col.symbol` | default colours are obtained from `plot.symbol` and `plot.line` using `<trellis.par.get>`. | | `font, fontface, fontfamily` | font used when `pch` is a character | | `pch, lty, cex, lwd, fill` | other graphical parameters. `fill` serves the purpose of `bg` in `[points](../../graphics/html/points)` for certain values of `pch` | | `horizontal` | A logical flag controlling the orientation for certain `type`'s, e.g., `"h"`, `"s"`, ans `"S"`. | | `...` | Extra arguments, if any, for `panel.xyplot`. In most cases `panel.xyplot` ignores these. For types "r" and "smooth", these are passed on to `panel.lmline` and `panel.loess` respectively. | | `grid` | A logical flag, character string, or list specifying whether and how a background grid should be drawn. This provides the same functionality as `type="g"`, but is the preferred alternative as the effect `type="g"` is conceptually different from that of other `type` values (which are all data-dependent). Using the `grid` argument also allows more flexibility. Most generally, `grid` can be a list of arguments to be supplied to `[panel.grid](panel.functions)`, which is called with those arguments. Three shortcuts are available: `TRUE`: roughly equivalent to `list(h = -1, v = -1)` `"h"`: roughly equivalent to `list(h = -1, v = 0)` `"v"`: roughly equivalent to `list(h = 0, v = -1)` No grid is drawn if `grid = FALSE`. | | `abline` | A numeric vector or list, specifying arguments arguments for `[panel.abline](panel.functions)`, which is called with those arguments. If specified as a (possibly named) numeric vector, `abline` is coerced to a list. This allows arguments of the form `abline = c(0, 1)`, which adds the diagonal line, or `abline = c(h = 0, v = 0)`, which adds the x- and y-axes to the plot. Use the list form for finer control; e.g., `abline = list(h = 0, v = 0, col = "grey")`. For more flexibility, use `[panel.abline](panel.functions)` directly. | | `jitter.x, jitter.y` | logical, whether the data should be jittered before being plotted. | | `factor, amount` | controls amount of jittering. | | `identifier` | A character string that is prepended to the names of grobs that are created by this panel function. | ### Details Creates scatterplot of `x` and `y`, with various modifications possible via the type argument. `panel.qq` draws a 45 degree line before calling `panel.xyplot`. Note that most of the arguments controlling the display can be supplied directly to the high-level (e.g. `<xyplot>`) call. ### Author(s) Deepayan Sarkar [[email protected]](mailto:[email protected]) ### See Also `<panel.superpose>`, `<xyplot>`, `<splom>` ### Examples ``` types.plain <- c("p", "l", "o", "r", "g", "s", "S", "h", "a", "smooth") types.horiz <- c("s", "S", "h", "a", "smooth") horiz <- rep(c(FALSE, TRUE), c(length(types.plain), length(types.horiz))) types <- c(types.plain, types.horiz) x <- sample(seq(-10, 10, length.out = 15), 30, TRUE) y <- x + 0.25 * (x + 1)^2 + rnorm(length(x), sd = 5) xyplot(y ~ x | gl(1, length(types)), xlab = "type", ylab = list(c("horizontal=TRUE", "horizontal=FALSE"), y = c(1/6, 4/6)), as.table = TRUE, layout = c(5, 3), between = list(y = c(0, 1)), strip = function(...) { panel.fill(trellis.par.get("strip.background")$col[1]) type <- types[panel.number()] grid::grid.text(label = sprintf('"%s"', type), x = 0.5, y = 0.5) grid::grid.rect() }, scales = list(alternating = c(0, 2), tck = c(0, 0.7), draw = FALSE), par.settings = list(layout.widths = list(strip.left = c(1, 0, 0, 0, 0))), panel = function(...) { type <- types[panel.number()] horizontal <- horiz[panel.number()] panel.xyplot(..., type = type, horizontal = horizontal) })[rep(1, length(types))] ``` r None `panel.functions` Useful Panel Function Components --------------------------------------------------- ### Description These are predefined panel functions available in lattice for use in constructing new panel functions (often on-the-fly). ### Usage ``` panel.abline(a = NULL, b = 0, h = NULL, v = NULL, reg = NULL, coef = NULL, col, col.line, lty, lwd, alpha, type, ..., reference = FALSE, identifier = "abline") panel.refline(...) panel.curve(expr, from, to, n = 101, curve.type = "l", col, lty, lwd, type, ..., identifier = "curve") panel.rug(x = NULL, y = NULL, regular = TRUE, start = if (regular) 0 else 0.97, end = if (regular) 0.03 else 1, x.units = rep("npc", 2), y.units = rep("npc", 2), col, col.line, lty, lwd, alpha, ..., identifier = "rug") panel.average(x, y, fun = mean, horizontal = TRUE, lwd, lty, col, col.line, type, ..., identifier = "linejoin") panel.linejoin(x, y, fun = mean, horizontal = TRUE, lwd, lty, col, col.line, type, ..., identifier = "linejoin") panel.fill(col, border, ..., identifier = "fill") panel.grid(h=3, v=3, col, col.line, lty, lwd, x, y, ..., identifier = "grid") panel.lmline(x, y, ..., identifier = "lmline") panel.mathdensity(dmath = dnorm, args = list(mean=0, sd=1), n = 50, col, col.line, lwd, lty, type, ..., identifier = "mathdensity") ``` ### Arguments | | | | --- | --- | | `x, y` | Variables defining the contents of the panel. In `panel.grid` these are optional and are used only to choose an appropriate method of `[pretty](../../base/html/pretty)`. | | `a, b` | Coefficients of the line to be added by `panel.abline`. `a` can be a vector of length 2, representing the coefficients of the line to be added, in which case `b` should be missing. `a` can also be an appropriate ‘regression’ object, i.e., an object which has a `[coef](../../stats/html/coef)` method that returns a length 2 numeric vector. The corresponding line will be plotted. The `reg` argument overrides `a` if specified. | | `coef` | Coefficients of the line to be added as a vector of length 2. | | `reg` | A (linear) regression object, with a `[coef](../../stats/html/coef)` method that gives the coefficints of the corresponding regression line. | | `h, v` | For `panel.abline`, these are numeric vectors giving locations respectively of horizontal and vertical lines to be added to the plot, in native coordinates. For `panel.grid`, these usually specify the number of horizontal and vertical reference lines to be added to the plot. Alternatively, they can be negative numbers. `h=-1` and `v=-1` are intended to make the grids aligned with the axis labels. This doesn't always work; all that actually happens is that the locations are chosen using `pretty`, which is also how the label positions are chosen in the most common cases (but not for factor variables, for instance). `h` and `v` can be negative numbers other than `-1`, in which case `-h` and `-v` (as appropriate) is supplied as the `n` argument to `[pretty](../../base/html/pretty)`. If `x` and/or `y` are specified in `panel.grid`, they will be used to select an appropriate method for `[pretty](../../base/html/pretty)`. This is particularly useful while plotting date-time objects. | | `reference` | A logical flag determining whether the default graphical parameters for `panel.abline` should be taken from the “reference.line” parameter settings. The default is to take them from the “add.line” settings. The `panel.refline` function is a wrapper around `panel.abline` that calls it with `reference = TRUE`. | | `expr` | An expression considered as a function of `x`, or a function, to be plotted as a curve. | | `n` | The number of points to use for drawing the curve. | | `from, to` | optional lower and upper x-limits of curve. If missing, limits of current panel are used | | `curve.type` | Type of curve (`"p"` for points, etc), passed to `<llines>` | | `regular` | A logical flag indicating whether the ‘rug’ is to be drawn on the ‘regular’ side (left / bottom) or not (right / top). | | `start, end` | endpoints of rug segments, in normalized parent coordinates (between 0 and 1). Defaults depend on value of `regular`, and cover 3% of the panel width and height. | | `x.units, y.units` | Character vectors, replicated to be of length two. Specifies the (grid) units associated with `start` and `end` above. `x.units` and `y.units` are for the rug on the x-axis and y-axis respectively (and thus are associated with `start` and `end` values on the y and x scales respectively). | | `col, col.line, lty, lwd, alpha, border` | Graphical parameters. | | `type` | Usually ignored by the panel functions documented here; the argument is present only to make sure an explicitly specified `type` argument (perhaps meant for another function) does not affect the display. | | `fun` | The function that will be applied to the subset of `x` values (or `y` if `horizontal` is `FALSE`) determined by the unique values of `y` (`x`). | | `horizontal` | A logical flag. If `FALSE`, the plot is ‘transposed’ in the sense that the roles of `x` and `y` are switched; `x` is now the ‘factor’. Interpretation of other arguments change accordingly. See documentation of `[bwplot](xyplot)` for a fuller explanation. | | `dmath` | A vectorized function that produces density values given a numeric vector named `x`, e.g., `[dnorm](../../stats/html/normal)`. | | `args` | A list giving additional arguments to be passed to `dmath`. | | `...` | Further arguments, typically graphical parameters, passed on to other low-level functions as appropriate. Color can usually be specified by `col`, `col.line`, and `col.symbol`, the last two overriding the first for lines and points respectively. | | `identifier` | A character string that is prepended to the names of grobs that are created by this panel function. | ### Details `panel.abline` adds a line of the form `y = a + b * x`, or vertical and/or horizontal lines. Graphical parameters are obtained from the “add.line” settings by default. `panel.refline` is similar, but uses the “reference.line” settings for the defaults. `panel.grid` draws a reference grid. `panel.curve` adds a curve, similar to what `[curve](../../graphics/html/curve)` does with `add = TRUE`. Graphical parameters for the curve are obtained from the “add.line” setting. `panel.average` treats one of `x` and `y` as a factor (according to the value of `horizontal`), calculates `fun` applied to the subsets of the other variable determined by each unique value of the factor, and joins them by a line. Can be used in conjunction with `panel.xyplot`, and more commonly with `<panel.superpose>` to produce interaction plots. `panel.linejoin` is an alias for `panel.average`. It is retained for back-compatibility, and may go away in future. `panel.mathdensity` plots a (usually theoretical) probability density function. This can be useful in conjunction with `histogram` and `densityplot` to visually assess goodness of fit (note, however, that `qqmath` is more suitable for this). `panel.rug` adds a *rug* representation of the (marginal) data to the panel, much like `[rug](../../graphics/html/rug)`. `panel.lmline(x, y)` is equivalent to `panel.abline(lm(y ~ x))`. ### Author(s) Deepayan Sarkar [[email protected]](mailto:[email protected]) ### See Also [Lattice](lattice), `<panel.axis>`, `[panel.identify](interaction)` `[identify](../../graphics/html/identify)`, `[trellis.par.set](trellis.par.get)`. ### Examples ``` ## Interaction Plot bwplot(yield ~ site, barley, groups = year, panel = function(x, y, groups, subscripts, ...) { panel.grid(h = -1, v = 0) panel.stripplot(x, y, ..., jitter.data = TRUE, groups = groups, subscripts = subscripts) panel.superpose(x, y, ..., panel.groups = panel.average, groups = groups, subscripts = subscripts) }, auto.key = list(points = FALSE, lines = TRUE, columns = 2)) ## Superposing a fitted normal density on a Histogram histogram( ~ height | voice.part, data = singer, layout = c(2, 4), type = "density", border = "transparent", col.line = "grey60", xlab = "Height (inches)", ylab = "Density Histogram\n with Normal Fit", panel = function(x, ...) { panel.histogram(x, ...) panel.mathdensity(dmath = dnorm, args = list(mean=mean(x),sd=sd(x)), ...) } ) ``` r None `draw.key` Produce a Legend or Key ----------------------------------- ### Description Produces (and possibly draws) a Grid frame grob which is a legend (aka key) that can be placed in other Grid plots. ### Usage ``` draw.key(key, draw=FALSE, vp=NULL, ...) ``` ### Arguments | | | | --- | --- | | `key` | A list determining the key. See documentation for `xyplot`, in particular the section describing the `key` argument, for details. | | `draw` | logical, whether the grob is to be drawn. | | `vp` | viewport | | `...` | ignored | ### Value A Grid frame object (that inherits from ‘grob’). ### Author(s) Deepayan Sarkar [[email protected]](mailto:[email protected]) ### See Also `<xyplot>` r None `simpleTheme` Function to generate a simple theme -------------------------------------------------- ### Description Simple interface to generate a list appropriate as a theme, typically used as the `par.settings` argument in a high level call ### Usage ``` simpleTheme(col, alpha, cex, pch, lty, lwd, font, fill, border, col.points, col.line, alpha.points, alpha.line) ``` ### Arguments | | | | --- | --- | | `col, col.points, col.line` | A color specification. `col` is used for components `"plot.symbol"`, `"plot.line"`, `"plot.polygon"`, `"superpose.symbol"`, `"superpose.line"`, and `"superpose.polygon"`. `col.points` overrides `col`, but is used only for `"plot.symbol"` and `"superpose.symbol"`. Similarly, `col.line` overrides `col` for `"plot.line"` and `"superpose.line"`. The arguments can be vectors, but only the first component is used for scalar targets (i.e., the ones without `"superpose"` in their name). | | `alpha, alpha.points, alpha.line` | A numeric alpha transparency specification. The same rules as `col`, etc., apply. | | `cex, pch, font` | Parameters for points. Applicable for components `plot.symbol` (for which only the first component is used) and `superpose.symbol` (for which the arguments can be vectors). | | `lty, lwd` | Parameters for lines. Applicable for components `plot.line` (for which only the first component is used) and `superpose.line` (for which the arguments can be vectors). | | `fill` | fill color, applicable for components `plot.symbol`, `plot.polygon`, `superpose.symbol`, and `superpose.polygon`. | | `border` | border color, applicable for components `plot.polygon` and `superpose.polygon`. | ### Details The appearance of a lattice display depends partly on the “theme” active when the display is plotted (see `<trellis.device>` for details). This theme is used to obtain defaults for various graphical parameters, and in particular, the `auto.key` argument works on the premise that the same source is used for both the actual graphical encoding and the legend. The easiest way to specify custom settings for a particular display is to use the `par.settings` argument, which is usually tedious to construct as it is a nested list. The `simpleTheme` function can be used in such situations as a wrapper that generates a suitable list given parameters in simple `name=value` form, with the nesting made implicit. This is less flexible, but straightforward and sufficient in most situations. ### Value A list that would work as the `theme` argument to `<trellis.device>` and `[trellis.par.set](trellis.par.get)`, or as the `par.settings` argument to any high level lattice function such as `<xyplot>`. ### Author(s) Deepayan Sarkar [[email protected]](mailto:[email protected]), based on a suggestion from John Maindonald. ### See Also `<trellis.device>`, `<xyplot>`, `[Lattice](lattice)` ### Examples ``` str(simpleTheme(pch = 16)) dotplot(variety ~ yield | site, data = barley, groups = year, auto.key = list(space = "right"), par.settings = simpleTheme(pch = 16), xlab = "Barley Yield (bushels/acre) ", aspect=0.5, layout = c(1,6)) ```
programming_docs
r None `utilities.3d` Utility functions for 3-D plots ----------------------------------------------- ### Description These are (related to) the default panel functions for `cloud` and `wireframe`. ### Usage ``` ltransform3dMatrix(screen, R.mat) ltransform3dto3d(x, R.mat, dist) ``` ### Arguments | | | | --- | --- | | `x` | `x` can be a numeric matrix with 3 rows for `ltransform3dto3d` | | `screen` | list, as described in `<panel.cloud>` | | `R.mat` | 4x4 transformation matrix in homogeneous coordinates | | `dist` | controls transformation to account for perspective viewing | ### Details `ltransform3dMatrix` and `ltransform3dto3d` are utility functions to help in computation of projections. These functions are used inside the panel functions for `cloud` and `wireframe`. They may be useful in user-defined panel functions as well. The first function takes a list of the form of the `screen` argument in `cloud` and `wireframe` and a `R.mat`, a 4x4 transformation matrix in homogeneous coordinates, to return a new 4x4 transformation matrix that is the result of applying `R.mat` followed by the rotations in `screen`. The second function applies a 4x4 transformation matrix in homogeneous coordinates to a 3xn matrix representing points in 3-D space, and optionally does some perspective computations. (There has been no testing with non-trivial transformation matrices, and my knowledge of the homogeneous coordinate system is very limited, so there may be bugs here.) ### Author(s) Deepayan Sarkar [[email protected]](mailto:[email protected]) ### See Also `<cloud>`, `<panel.cloud>` r None `trellis.device` Initializing Trellis Displays ----------------------------------------------- ### Description Initialization of a display device with appropriate graphical parameters. ### Usage ``` trellis.device(device = getOption("device"), color = !(dev.name == "postscript"), theme = lattice.getOption("default.theme"), new = TRUE, retain = FALSE, ...) standard.theme(name, color) canonical.theme(name, color) col.whitebg() ``` ### Arguments | | | | --- | --- | | `device` | function (or the name of one as a character string) that starts a device. Admissible values depend on the platform and how **R** was compiled (see `[Devices](../../grdevices/html/devices)`), but usually `"pdf"`, `"postscript"`, `"png"`, `"jpeg"` and at least one of `"X11"`, `"windows"` and `"quartz"` will be available. | | `color` | logical, whether the initial settings should be color or black and white. Defaults to `FALSE` for postscript devices, `TRUE` otherwise. Note that this only applies to the initial choice of colors, which can be overridden using `theme` or subsequent calls to `[trellis.par.set](trellis.par.get)` (and by arguments supplied directly in high level calls for some settings). | | `theme` | list of components that changes the settings of the device opened, or, a function that when called produces such a list. The function name can be supplied as a quoted string. These settings are only used to modify the default settings (determined by other arguments), and need not contain all possible parameters. A possible use of this argument is to change the default settings by specifying `lattice.options(default.theme = "col.whitebg")`. For back-compatibility, this is initially (when lattice is loaded) set to `getOption(lattice.theme)`. If `theme` is a function, it will not be supplied any arguments, however, it is guaranteed that a device will already be open when it is called, so one may use `.Device` inside the function to ascertain what device has been opened. | | `new` | logical flag indicating whether a new device should be started. If `FALSE`, the options for the current device are changed to the defaults determined by the other arguments. | | `retain` | logical. If `TRUE` and a setting for this device already exists, then that is used instead of the defaults for this device. By default, pre-existing settings are overwritten (and lost). | | `name` | name of the device for which the setting is required, as returned by `.Device` | | `...` | additional parameters to be passed to the `device` function, most commonly `file` for non-screen devices, as well as `height`, `width`, etc. See the help file for individual devices for admissible arguments. | ### Details Trellis Graphics functions obtain the default values of various graphical parameters (colors, line types, fonts, etc.) from a customizable “settings” list. This functionality is analogous to `[par](../../graphics/html/par)` for standard **R** graphics and, together with `<lattice.options>`, mostly supplants it (`[par](../../graphics/html/par)` settings are mostly ignored by Lattice). Unlike `[par](../../graphics/html/par)`, Trellis settings can be controlled separately for each different device type (but not concurrently for different instances of the same device). `standard.theme` and `col.whitebg` produce predefined settings (a.k.a. themes), while `trellis.device` provides a high level interface to control which “theme” will be in effect when a new device is opened. `trellis.device` is called automatically when a `"trellis"` object is plotted, and the defaults can be used to provide sufficient control, so in a properly configured system it is rarely necessary for the user to call `trellis.device` explicitly. The `standard.theme` function is intended to provide device specific settings (e.g. light colors on a grey background for screen devices, dark colors or black and white for print devices) which were used as defaults prior to **R** 2.3.0. However, these defaults are not always appropriate, due to the variety of platforms and hardware settings on which **R** is used, as well as the fact that a plot created on a particular device may be subsequently used in many different ways. For this reason, a “safe” default is used for all devices from **R** 2.3.0 onwards. The old behaviour can be reinstated by setting `standard.theme` as the default `theme` argument, e.g. by putting `lattice.options(default.theme = "standard.theme")` in a startup script (see the entry for `theme` above for details). ### Value `standard.theme` returns a list of components defining graphical parameter settings for Lattice displays. It is used internally in `trellis.device`, and can also be used as the `theme` argument to `trellis.par.set`, or even as `theme` in `trellis.device` to use the defaults for another device. `canonical.theme` is an alias for `standard.theme`. `col.whitebg` returns a similar (but smaller) list that is suitable as the `theme` argument to `trellis.device` and `[trellis.par.set](trellis.par.get)`. It contains settings values which provide colors suitable for plotting on a white background. Note that the name `col.whitebg` is somewhat of a misnomer, since it actually sets the background to transparent rather than white. ### Note Earlier versions of `trellis.device` had a `bg` argument to set the background color, but this is no longer supported. If supplied, the `bg` argument will be passed on to the device function; however, this will have no effect on the Trellis settings. It is rarely meaningful to change the background alone; if you feel the need to change the background, consider using the `theme` argument instead. ### Author(s) Deepayan Sarkar [[email protected]](mailto:[email protected]) ### References Sarkar, Deepayan (2008) *Lattice: Multivariate Data Visualization with R*, Springer. <http://lmdvr.r-forge.r-project.org/> ### See Also `[Lattice](lattice)` for an overview of the `lattice` package. `[Devices](../../grdevices/html/devices)` for valid choices of `device` on your platform. `<trellis.par.get>` and `[trellis.par.set](trellis.par.get)` can be used to query and modify the settings *after* a device has been initialized. The `par.settings` argument to high level functions, described in `<xyplot>`, can be used to attach transient settings to a `"trellis"` object. r None `panel.histogram` Default Panel Function for histogram ------------------------------------------------------- ### Description This is the default panel function for `histogram`. ### Usage ``` panel.histogram(x, breaks, equal.widths = TRUE, type = "density", nint = round(log2(length(x)) + 1), alpha, col, border, lty, lwd, ..., identifier = "histogram") ``` ### Arguments | | | | --- | --- | | `x` | The data points for which the histogram is to be drawn | | `breaks` | The breakpoints for the histogram | | `equal.widths` | logical used when `breaks==NULL` | | `type` | Type of histogram, possible values being `"percent"`, `"density"` and `"count"` | | `nint` | Number of bins for the histogram | | `alpha, col, border, lty, lwd` | graphical parameters for bars; defaults are obtained from the `plot.polygon` settings. | | `...` | other arguments, passed to `[hist](../../graphics/html/hist)` when deemed appropriate | | `identifier` | A character string that is prepended to the names of grobs that are created by this panel function. | ### Author(s) Deepayan Sarkar [[email protected]](mailto:[email protected]) ### See Also `<histogram>` r None `panel.levelplot` Panel Functions for levelplot and contourplot ---------------------------------------------------------------- ### Description These are the default panel functions for `<levelplot>` and `contourplot`. Also documented is an alternative raster-based panel function for use with `levelplot`. ### Usage ``` panel.levelplot(x, y, z, subscripts, at = pretty(z), shrink, labels, label.style = c("mixed", "flat", "align"), contour = FALSE, region = TRUE, col = add.line$col, lty = add.line$lty, lwd = add.line$lwd, border = "transparent", border.lty = 1, border.lwd = 0.1, ..., col.regions = regions$col, alpha.regions = regions$alpha, identifier = "levelplot") panel.contourplot(...) panel.levelplot.raster(x, y, z, subscripts, at = pretty(z), ..., col.regions = regions$col, alpha.regions = regions$alpha, interpolate = FALSE, identifier = "levelplot") ``` ### Arguments | | | | --- | --- | | `x, y, z` | Variables defining the plot. | | `subscripts` | Integer vector indicating what subset of `x`, `y` and `z` to draw. | | `at` | Numeric vector giving breakpoints along the range of `z`. See `<levelplot>` for details. | | `shrink` | Either a numeric vector of length 2 (meant to work as both x and y components), or a list with components x and y which are numeric vectors of length 2. This allows the rectangles to be scaled proportional to the z-value. The specification can be made separately for widths (x) and heights (y). The elements of the length 2 numeric vector gives the minimum and maximum proportion of shrinkage (corresponding to min and max of z). | | `labels` | Either a logical scalar indicating whether the labels are to be drawn, or a character or expression vector giving the labels associated with the `at` values. Alternatively, `labels` can be a list with the following components: `labels`: a character or expression vector giving the labels. This can be omitted, in which case the defaults will be used. `col, cex, alpha`: graphical parameters for label texts `fontfamily, fontface, font`: font used for the labels | | `label.style` | Controls how label positions and rotation are determined. A value of `"flat"` causes the label to be positioned where the contour is flattest, and the label is not rotated. A value of `"align"` causes the label to be drawn as far from the boundaries as possible, and the label is rotated to align with the contour at that point. The default is to mix these approaches, preferring the flattest location unless it is too close to the boundaries. | | `contour` | A logical flag, specifying whether contour lines should be drawn. | | `region` | A logical flag, specifying whether inter-contour regions should be filled with appropriately colored rectangles. | | `col, lty, lwd` | Graphical parameters for contour lines. | | `border` | Border color for rectangles used when `region=TRUE`. | | `border.lty, border.lwd` | Graphical parameters for the border | | | | | --- | --- | | `...` | Extra parameters. | | `col.regions` | A vector of colors, or a function to produce a vecor of colors, to be used if `region=TRUE`. Each interval defined by `at` is assigned a color, so the number of colors actually used is one less than the length of `at`. See `<level.colors>` for details on how the color assignment is done. | | `alpha.regions` | numeric scalar controlling transparency of facets | | `interpolate` | logical, passed to `[grid.raster](../../grid/html/grid.raster)`. | | `identifier` | A character string that is prepended to the names of grobs that are created by this panel function. | ### Details The same panel function is used for both `levelplot` and `contourplot` (which differ only in default values of some arguments). `panel.contourplot` is a simple wrapper to `panel.levelplot`. When `contour=TRUE`, the `contourLines` function is used to calculate the contour lines. `panel.levelplot.raster` is an alternative panel function that uses the raster drawing abilities in R 2.11.0 and higher (through `[grid.raster](../../grid/html/grid.raster)`). It has fewer options (e.g., can only render data on an equispaced grid), but can be more efficient. When using `panel.levelplot.raster`, it may be desirable to render the color key in the same way. This is possible, but must be done separately; see `<levelplot>` for details. ### Author(s) Deepayan Sarkar [[email protected]](mailto:[email protected]) ### See Also `<levelplot>`, `<level.colors>`, `[contourLines](../../grdevices/html/contourlines)` ### Examples ``` require(grid) levelplot(rnorm(10) ~ 1:10 + sort(runif(10)), panel = panel.levelplot) suppressWarnings(plot(levelplot(rnorm(10) ~ 1:10 + sort(runif(10)), panel = panel.levelplot.raster, interpolate = TRUE))) levelplot(volcano, panel = panel.levelplot.raster) levelplot(volcano, panel = panel.levelplot.raster, col.regions = topo.colors, cuts = 30, interpolate = TRUE) ``` r None `level.colors` A function to compute false colors representing a numeric or categorical variable ------------------------------------------------------------------------------------------------- ### Description Calculates false colors from a numeric variable (including factors, using their numeric codes) given a color scheme and breakpoints. ### Usage ``` level.colors(x, at, col.regions, colors = TRUE, ...) ``` ### Arguments | | | | --- | --- | | `x` | A numeric or `[factor](../../base/html/factor)` variable. | | `at` | A numeric variable of breakpoints defining intervals along the range of `x`. | | `col.regions` | A specification of the colors to be assigned to each interval defined by `at`. This could be either a vector of colors, or a function that produces a vector of colors when called with a single argument giving the number of colors. See details below. | | `colors` | logical indicating whether colors should be computed and returned. If `FALSE`, only the indices representing which interval (among those defined by `at`) each value in `x` falls into is returned. | | `...` | Extra arguments, ignored. | ### Details If `at` has length n, then it defines n-1 intervals. Values of `x` outside the range of `at` are not assigned to an interval, and the return value is `NA` for such values. Colors are chosen by assigning a color to each of the n-1 intervals. If `col.regions` is a palette function (such as `[topo.colors](../../grdevices/html/palettes)`, or the result of calling `[colorRampPalette](../../grdevices/html/colorramp)`), it is called with n-1 as an argument to obtain the colors. Otherwise, if there are exactly n-1 colors in `col.regions`, these get assigned to the intervals. If there are fewer than n-1 colors, `col.regions` gets recycled. If there are more, a more or less equally spaced (along the length of `col.regions`) subset is chosen. ### Value A vector of the same length as `x`. Depending on the `colors` argument, this could be either a vector of colors (in a form usable by **R**), or a vector of integer indices representing which interval the values of `x` fall in. ### Author(s) Deepayan Sarkar [[email protected]](mailto:[email protected]) ### See Also `<levelplot>`, `[colorRampPalette](../../grdevices/html/colorramp)`. ### Examples ``` depth.col <- with(quakes, level.colors(depth, at = do.breaks(range(depth), 30), col.regions = terrain.colors)) xyplot(lat ~ long | equal.count(stations), quakes, strip = strip.custom(var.name = "Stations"), colours = depth.col, panel = function(x, y, colours, subscripts, ...) { panel.xyplot(x, y, pch = 21, col = "transparent", fill = colours[subscripts], ...) }) ``` r None `banking` Banking ------------------ ### Description Calculates banking slope ### Usage ``` banking(dx, dy) ``` ### Arguments | | | | --- | --- | | `dx, dy` | vector of consecutive x, y differences. | ### Details `banking` is the banking function used when `aspect = "xy"` in high level Trellis functions. It is usually not very meaningful except with `xyplot`. It considers the absolute slopes (based on `dx` and `dy`) and returns a value which when adjusted by the panel scale limits will make the median of the above absolute slopes correspond to a 45 degree line. This function was inspired by the discussion of banking in the documentation for Trellis Graphics available at Bell Labs' website (see `[Lattice](lattice)`), but is most likely identical to an algorithm described by Cleveland et al (see below). It is not clear (to the author) whether this is the algorithm used in S-PLUS. Alternative banking rules, implemented as a similar function, can be used as a drop-in replacement by suitably modifying `lattice.options("banking")`. ### Author(s) Deepayan Sarkar [[email protected]](mailto:[email protected]) ### References Cleveland, William S. and McGill, Marylyn E. and McGill, Robert (1988) “The Shape Parameter of a Two-variable Graph”, *Journal of the American Statistical Association*, **83**, 289–300. ### See Also `[Lattice](lattice)`, `<xyplot>` ### Examples ``` ## with and without banking plot <- xyplot(sunspot.year ~ 1700:1988, xlab = "", type = "l", scales = list(x = list(alternating = 2)), main = "Yearly Sunspots") print(plot, position = c(0, .3, 1, .9), more = TRUE) print(update(plot, aspect = "xy", main = "", xlab = "Year"), position = c(0, 0, 1, .3)) ## cut-and-stack plot (see also xyplot.ts) xyplot(sunspot.year ~ time(sunspot.year) | equal.count(time(sunspot.year)), xlab = "", type = "l", aspect = "xy", strip = FALSE, scales = list(x = list(alternating = 2, relation = "sliced")), as.table = TRUE, main = "Yearly Sunspots") ``` r None `llines` Replacements of traditional graphics functions -------------------------------------------------------- ### Description These functions are intended to replace common low level traditional graphics functions, primarily for use in panel functions. The originals can not be used (at least not easily) because lattice panel functions need to use grid graphics. Low level drawing functions in grid can be used directly as well, and is often more flexible. These functions are provided for convenience and portability. ### Usage ``` lplot.xy(xy, type, pch, lty, col, cex, lwd, font, fontfamily, fontface, col.line, col.symbol, alpha, fill, origin = 0, ..., identifier, name.type) llines(x, ...) lpoints(x, ...) ltext(x, ...) ## Default S3 method: llines(x, y = NULL, type = "l", col, alpha, lty, lwd, ..., identifier, name.type) ## Default S3 method: lpoints(x, y = NULL, type = "p", col, pch, alpha, fill, font, fontfamily, fontface, cex, ..., identifier, name.type) ## Default S3 method: ltext(x, y = NULL, labels = seq_along(x), col, alpha, cex, srt = 0, lineheight, font, fontfamily, fontface, adj = c(0.5, 0.5), pos = NULL, offset = 0.5, ..., identifier, name.type) lsegments(x0, y0, x1, y1, x2, y2, col, alpha, lty, lwd, font, fontface, ..., identifier, name.type) lrect(xleft, ybottom, xright, ytop, x = (xleft + xright) / 2, y = (ybottom + ytop) / 2, width = xright - xleft, height = ytop - ybottom, col = "transparent", border = "black", lty = 1, lwd = 1, alpha = 1, just = "center", hjust = NULL, vjust = NULL, font, fontface, ..., identifier, name.type) larrows(x0 = NULL, y0 = NULL, x1, y1, x2 = NULL, y2 = NULL, angle = 30, code = 2, length = 0.25, unit = "inches", ends = switch(code, "first", "last", "both"), type = "open", col = add.line$col, alpha = add.line$alpha, lty = add.line$lty, lwd = add.line$lwd, fill = NULL, font, fontface, ..., identifier, name.type) lpolygon(x, y = NULL, border = "black", col = "transparent", fill = NULL, font, fontface, ..., identifier, name.type) panel.lines(...) panel.points(...) panel.segments(...) panel.text(...) panel.rect(...) panel.arrows(...) panel.polygon(...) ``` ### Arguments | | | | --- | --- | | `x, y, x0, y0, x1, y1, x2, y2, xy` | locations. `x2` and `y2` are available for for S compatibility. | | `length, unit` | determines extent of arrow head. `length` specifies the length in terms of `unit`, which can be any valid grid unit as long as it doesn't need a `data` argument. `unit` defaults to inches, which is the only option in the base version of the function, `[arrows](../../graphics/html/arrows)`. | | `angle, code, type, labels, srt, adj, pos, offset` | arguments controlling behaviour. See respective base functions for details. For `larrows` and `panel.larrows`, `type` is either `"open"` or `"closed"`, indicating the type of arrowhead. | | `ends` | serves the same function as `code`, using descriptive names rather than integer codes. If specified, this overrides `code` | | `col, alpha, lty, lwd, fill, pch, cex, lineheight, font, fontfamily, fontface, col.line, col.symbol, border` | graphical parameters. `fill` applies to points when `pch` is in `21:25` and specifies the fill color, similar to the `bg` argument in the base graphics function `[points](../../graphics/html/points)`. For devices that support alpha-transparency, a numeric argument `alpha` between 0 and 1 can controls transparency. Be careful with this, since for devices that do not support alpha-transparency, nothing will be drawn at all if this is set to anything other than 0. `fill`, `font` and `fontface` are included in `lrect`, `larrows`, `lpolygon`, and `lsegments` only to ensure that they are not passed down (as `[gpar](../../grid/html/gpar)` does not like them). | | `origin` | for `type="h"` or `type="H"`, the value to which lines drop down. | | `xleft, ybottom, xright, ytop` | see `[rect](../../graphics/html/rect)` | | `width, height, just, hjust, vjust` | finer control over rectangles, see `[grid.rect](../../grid/html/grid.rect)` | | `...` | extra arguments, passed on to lower level functions as appropriate. | | `identifier` | A character string that is prepended to the name of the grob that is created. | | `name.type` | A character value indicating whether the name of the grob should have panel or strip information added to it. Typically either `"panel"`, `"strip"`, `"strip.left"`, or `""` (for no extra information). | ### Details These functions are meant to be grid replacements of the corresponding base R graphics functions, to allow existing Trellis code to be used with minimal modification. The functions `panel.*` are essentally identical to the `l*` versions, are recommended for use in new code (as opposed to ported code) as they have more readable names. See the documentation of the base functions for usage. Not all arguments are always supported. All these correspond to the default methods only. ### Note There is a new `type="H"` option wherever appropriate, which is similar to `type="h"`, but with horizontal lines. ### Author(s) Deepayan Sarkar [[email protected]](mailto:[email protected]) ### See Also `[points](../../graphics/html/points)`, `[lines](../../graphics/html/lines)`, `[rect](../../graphics/html/rect)`, `[text](../../graphics/html/text)`, `[segments](../../graphics/html/segments)`, `[arrows](../../graphics/html/arrows)`, `[Lattice](lattice)`
programming_docs
r None `packet.panel.default` Associating Packets with Panels ------------------------------------------------------- ### Description When a `"trellis"` object is plotted, panels are always drawn in an order such that columns vary the fastest, then rows and then pages. An optional function can be specified that determines, given the column, row and page and other relevant information, the packet (if any) which should be used in that panel. The function documented here implements the default behaviour, which is to match panel order with packet order, determined by varying the first conditioning variable the fastest, then the second, and so on. This matching is performed after any reordering and/or permutation of the conditioning variables. ### Usage ``` packet.panel.default(layout, condlevels, page, row, column, skip, all.pages.skip = TRUE) ``` ### Arguments | | | | --- | --- | | `layout` | the `layout` argument in high level functions, suitably standardized. | | `condlevels` | a list of levels of conditioning variables, after relevant permutations and/or reordering of levels | | `page, row, column` | the location of the panel in the coordinate system of pages, rows and columns. | | `skip` | the `skip` argument in high level functions | | `all.pages.skip` | whether `skip` should be replicated over all pages. If `FALSE`, `skip` will be replicated to be only as long as the number of positions on a page, and that template will be used for all pages. | ### Value A suitable combination of levels of the conditioning variables in the form of a numeric vector as long as the number of conditioning variables, with each element an integer indexing the levels of the corresponding variable. Specifically, if the return value is `p`, then the `i`-th conditioning variable will have level `condlevels[[i]][p[i]]`. ### Author(s) Deepayan Sarkar [[email protected]](mailto:[email protected]) ### See Also `[Lattice](lattice)`, `<xyplot>` ### Examples ``` packet.panel.page <- function(n) { ## returns a function that when used as the 'packet.panel' ## argument in print.trellis plots page number 'n' only function(layout, page, ...) { stopifnot(layout[3] == 1) packet.panel.default(layout = layout, page = n, ...) } } data(mtcars) HP <- equal.count(mtcars$hp, 6) p <- xyplot(mpg ~ disp | HP * factor(cyl), mtcars, layout = c(0, 6, 1)) print(p, packet.panel = packet.panel.page(1)) print(p, packet.panel = packet.panel.page(2)) ``` r None `cloud` 3d Scatter Plot and Wireframe Surface Plot --------------------------------------------------- ### Description Generic functions to draw 3d scatter plots and surfaces. The `"formula"` methods do most of the actual work. ### Usage ``` cloud(x, data, ...) wireframe(x, data, ...) ## S3 method for class 'formula' cloud(x, data, allow.multiple = is.null(groups) || outer, outer = FALSE, auto.key = FALSE, aspect = c(1,1), panel.aspect = 1, panel = lattice.getOption("panel.cloud"), prepanel = NULL, scales = list(), strip = TRUE, groups = NULL, xlab, ylab, zlab, xlim = if (is.factor(x)) levels(x) else range(x, finite = TRUE), ylim = if (is.factor(y)) levels(y) else range(y, finite = TRUE), zlim = if (is.factor(z)) levels(z) else range(z, finite = TRUE), at, drape = FALSE, pretty = FALSE, drop.unused.levels, ..., lattice.options = NULL, default.scales = list(distance = c(1, 1, 1), arrows = TRUE, axs = axs.default), default.prepanel = lattice.getOption("prepanel.default.cloud"), colorkey, col.regions, alpha.regions, cuts = 70, subset = TRUE, axs.default = "r") ## S3 method for class 'formula' wireframe(x, data, panel = lattice.getOption("panel.wireframe"), default.prepanel = lattice.getOption("prepanel.default.wireframe"), ...) ## S3 method for class 'matrix' cloud(x, data = NULL, type = "h", zlab = deparse(substitute(x)), aspect, ..., xlim, ylim, row.values, column.values) ## S3 method for class 'table' cloud(x, data = NULL, groups = FALSE, zlab = deparse(substitute(x)), type = "h", ...) ## S3 method for class 'matrix' wireframe(x, data = NULL, zlab = deparse(substitute(x)), aspect, ..., xlim, ylim, row.values, column.values) ``` ### Arguments | | | | --- | --- | | `x` | The object on which method dispatch is carried out. For the `"formula"` methods, a formula of the form `z ~ x * y | g1 * g2 * ...`, where `z` is a numeric response, and `x`, `y` are numeric values. `g1, g2, ...`, if present, are conditioning variables used for conditioning, and must be either factors or shingles. In the case of `wireframe`, calculations are based on the assumption that the `x` and `y` values are evaluated on a rectangular grid defined by their unique values. The grid points need not be equally spaced. For `wireframe`, `x`, `y` and `z` may also be matrices (of the same dimension), in which case they are taken to represent a 3-D surface parametrized on a 2-D grid (e.g., a sphere). Conditioning is not possible with this feature. See details below. Missing values are allowed, either as `NA` values in the `z` vector, or missing rows in the data frame (note however that in that case the X and Y grids will be determined only by the available values). For a grouped display (producing multiple surfaces), missing rows are not allowed, but `NA`-s in `z` are. Both `wireframe` and `cloud` have methods for `matrix` objects, in which case `x` provides the `z` vector described above, while its rows and columns are interpreted as the `x` and `y` vectors respectively. This is similar to the form used in `persp`. | | `data` | for the `"formula"` methods, an optional data frame in which variables in the formula (as well as `groups` and `subset`, if any) are to be evaluated. `data` should not be specified except when using the `"formula"` method. | | `row.values, column.values` | Optional vectors of values that define the grid when `x` is a matrix. `row.values` and `column.values` must have the same lengths as `nrow(x)` and `ncol(x)` respectively. By default, row and column numbers. | | `allow.multiple, outer, auto.key, prepanel, strip, groups, xlab, xlim, ylab, ylim, drop.unused.levels, lattice.options, default.scales, subset` | These arguments are documented in the help page for `<xyplot>`. For the `cloud.table` method, `groups` must be a logical indicating whether the last dimension should be used as a grouping variable as opposed to a conditioning variable. This is only relevant if the table has more than 2 dimensions. | | `type` | type of display in `cloud` (see `[panel.3dscatter](panel.cloud)` for details). Defaults to `"h"` for the `matrix` method. | | `aspect, panel.aspect` | Unlike other high level functions, `aspect` is taken to be a numeric vector of length 2, giving the relative aspects of the y-size/x-size and z-size/x-size of the enclosing cube. The usual role of the `aspect` argument in determining the aspect ratio of the panel (see `<xyplot>` for details) is played by `panel.aspect`, except that it can only be a numeric value. For the `matrix` methods, the default y/x aspect is `ncol(x) / nrow(x)` and the z/x aspect is the smaller of the y/x aspect and 1. | | `panel` | panel function used to create the display. See `<panel.cloud>` for (non-trivial) details. | | `default.prepanel` | Fallback prepanel function. See `<xyplot>`. | | `scales` | a list describing the scales. As with other high level functions (see `<xyplot>` for details), this list can contain parameters in name=value form. It can also contain components with the special names `x`, `y` and `z`, which can be similar lists with axis-specific values overriding the ones specified in `scales`. The most common use for this argument is to set `arrows=FALSE`, which causes tick marks and labels to be used instead of arrows being drawn (the default). Both can be suppressed by `draw=FALSE`. Another special component is `distance`, which specifies the relative distance of the axis label from the bounding box. If specified as a component of `scales` (as opposed to one of `scales$z` etc), this can be (and is recycled if not) a vector of length 3, specifying distances for the x, y and z labels respectively. Other components that work in the `scales` argument of `xyplot` etc. should also work here (as long as they make sense), including explicit specification of tick mark locations and labels. (Not everything is implemented yet, but if you find something that should work but does not, feel free to bug the maintainer.) Note, however, that for these functions `scales` cannot contain information that is specific to particular panels. If you really need that, consider using the `scales.3d` argument of `panel.cloud`. | | `axs.default` | Unlike 2-D display functions, `cloud` does not expand the bounding box to slightly beyound the range of the data, even though it should. This is primarily because this is the natural behaviour in `wireframe`, which uses the same code. `axs.default` is intended to provide a different default for `cloud`. However, this feature has not yet been implemented. | | `zlab` | Specifies a label describing the z variable in ways similar to `xlab` and `ylab` (i.e. “grob”, character string, expression or list) in other high level functions. Additionally, if `zlab` (and `xlab` and `ylab`) is a list, it can contain a component called `rot`, controlling the rotation for the label | | `zlim` | limits for the z-axis. Similar to `xlim` and `ylim` in other high level functions | | `drape` | logical, whether the wireframe is to be draped in color. If `TRUE`, the height of a facet is used to determine its color in a manner similar to the coloring scheme used in `<levelplot>`. Otherwise, the background color is used to color the facets. This argument is ignored if `shade = TRUE` (see `[panel.3dwire](panel.cloud)`). | | `at, col.regions, alpha.regions` | these arguments are analogous to those in `<levelplot>`. if `drape=TRUE`, `at` gives the vector of cutpoints where the colors change, and `col.regions` the vector of colors to be used in that case. `alpha.regions` determines the alpha-transparency on supporting devices. These are passed down to the panel function, and also used in the colorkey if appropriate. The default for `col.regions` and `alpha.regions` is derived from the Trellis setting `"regions"` | | `cuts` | if `at` is unspecified, the approximate number of cutpoints if `drape=TRUE` | | `pretty` | whether automatic choice of cutpoints should be prettfied | | `colorkey` | logical indicating whether a color key should be drawn alongside, or a list describing such a key. See `<levelplot>` for details. | | `...` | Any number of other arguments can be specified, and are passed to the panel function. In particular, the arguments `distance`, `perspective`, `screen` and `R.mat` are very important in determining the 3-D display. The argument `shade` can be useful for `wireframe` calls, and controls shading of the rendered surface. These arguments are described in detail in the help page for `<panel.cloud>`. Additionally, an argument called `zoom` may be specified, which should be a numeric scalar to be interpreted as a scale factor by which the projection is magnified. This can be useful to get the variable names into the plot. This argument is actually only used by the default prepanel function. | ### Details These functions produce three dimensional plots in each panel (as long as the default panel functions are used). The orientation is obtained as follows: the data are scaled to fall within a bounding box that is contained in the [-0.5, 0.5] cube (even smaller for non-default values of `aspect`). The viewing direction is given by a sequence of rotations specified by the `screen` argument, starting from the positive Z-axis. The viewing point (camera) is located at a distance of `1/distance` from the origin. If `perspective=FALSE`, `distance` is set to 0 (i.e., the viewing point is at an infinite distance). `cloud` draws a 3-D Scatter Plot, while `wireframe` draws a 3-D surface (usually evaluated on a grid). Multiple surfaces can be drawn by `wireframe` using the `groups` argument (although this is of limited use because the display is incorrect when the surfaces intersect). Specifying `groups` with `cloud` results in a `panel.superpose`-like effect (via `[panel.3dscatter](panel.cloud)`). `wireframe` can optionally render the surface as being illuminated by a light source (no shadows though). Details can be found in the help page for `[panel.3dwire](panel.cloud)`. Note that although arguments controlling these are actually arguments for the panel function, they can be supplied to `cloud` and `wireframe` directly. For single panel plots, `wireframe` can also plot parametrized 3-D surfaces (i.e., functions of the form f(u,v) = (x(u,v), y(u,v), z(u,v)), where values of (u,v) lie on a rectangle. The simplest example of this sort of surface is a sphere parametrized by latitude and longitude. This can be achieved by calling `wireframe` with a formula `x` of the form `z~x*y`, where `x`, `y` and `z` are all matrices of the same dimension, representing the values of x(u,v), y(u,v) and z(u,v) evaluated on a discrete rectangular grid (the actual values of (u,v) are irrelevant). When this feature is used, the heights used to calculate `drape` colors or shading colors are no longer the `z` values, but the distances of `(x,y,z)` from the origin. Note that this feature does not work with `groups`, `subscripts`, `subset`, etc. Conditioning variables are also not supported in this case. The algorithm for identifying which edges of the bounding box are ‘behind’ the points doesn't work in some extreme situations. Also, `<panel.cloud>` tries to figure out the optimal location of the arrows and axis labels automatically, but can fail on occasion (especially when the view is from ‘below’ the data). This can be manually controlled by the `scpos` argument in `<panel.cloud>`. These and all other high level Trellis functions have several other arguments in common. These are extensively documented only in the help page for `<xyplot>`, which should be consulted to learn more detailed usage. ### Value An object of class `"trellis"`. The `[update](update.trellis)` method can be used to update components of the object and the `[print](print.trellis)` method (usually called by default) will plot it on an appropriate plotting device. ### Note There is a known problem with grouped `wireframe` displays when the (x, y) coordinates represented in the data do not represent the full evaluation grid. The problem occurs whether the grouping is specified through the `groups` argument or through the formula interface, and currently causes memory access violations. Depending on the circumstances, this is manifested either as a meaningless plot or a crash. To work around the problem, it should be enough to have a row in the data frame for each grid point, with an `NA` response (`z`) in rows that were previously missing. ### Author(s) Deepayan Sarkar [[email protected]](mailto:[email protected]) ### References Sarkar, Deepayan (2008) *Lattice: Multivariate Data Visualization with R*, Springer. <http://lmdvr.r-forge.r-project.org/> ### See Also `[Lattice](lattice)` for an overview of the package, as well as `<xyplot>`, `<levelplot>`, `<panel.cloud>`. For interaction, see `[panel.identify.cloud](interaction)`. ### Examples ``` ## volcano ## 87 x 61 matrix wireframe(volcano, shade = TRUE, aspect = c(61/87, 0.4), light.source = c(10,0,10)) g <- expand.grid(x = 1:10, y = 5:15, gr = 1:2) g$z <- log((g$x^g$gr + g$y^2) * g$gr) wireframe(z ~ x * y, data = g, groups = gr, scales = list(arrows = FALSE), drape = TRUE, colorkey = TRUE, screen = list(z = 30, x = -60)) cloud(Sepal.Length ~ Petal.Length * Petal.Width | Species, data = iris, screen = list(x = -90, y = 70), distance = .4, zoom = .6) ## cloud.table cloud(prop.table(Titanic, margin = 1:3), type = c("p", "h"), strip = strip.custom(strip.names = TRUE), scales = list(arrows = FALSE, distance = 2), panel.aspect = 0.7, zlab = "Proportion")[, 1] ## transparent axes par.set <- list(axis.line = list(col = "transparent"), clip = list(panel = "off")) print(cloud(Sepal.Length ~ Petal.Length * Petal.Width, data = iris, cex = .8, groups = Species, main = "Stereo", screen = list(z = 20, x = -70, y = 3), par.settings = par.set, scales = list(col = "black")), split = c(1,1,2,1), more = TRUE) print(cloud(Sepal.Length ~ Petal.Length * Petal.Width, data = iris, cex = .8, groups = Species, main = "Stereo", screen = list(z = 20, x = -70, y = 0), par.settings = par.set, scales = list(col = "black")), split = c(2,1,2,1)) ``` r None `xyplot` Common Bivariate Trellis Plots ---------------------------------------- ### Description This help page documents several commonly used high-level Lattice functions. `xyplot` produces bivariate scatterplots or time-series plots, `bwplot` produces box-and-whisker plots, `dotplot` produces Cleveland dot plots, `barchart` produces bar plots, and `stripplot` produces one-dimensional scatterplots. All these functions, along with other high-level Lattice functions, respond to a common set of arguments that control conditioning, layout, aspect ratio, legends, axis annotation, and many other details in a consistent manner. These arguments are described extensively in this help page, and should be used as the reference for other high-level functions as well. For control and customization of the actual display in each panel, the help page of the respective default panel function will often be more informative. In particular, these help pages describe many arguments commonly used when calling the corresponding high-level function but are specific to them. ### Usage ``` xyplot(x, data, ...) dotplot(x, data, ...) barchart(x, data, ...) stripplot(x, data, ...) bwplot(x, data, ...) ## S3 method for class 'formula' xyplot(x, data, allow.multiple = is.null(groups) || outer, outer = !is.null(groups), auto.key = FALSE, aspect = "fill", panel = lattice.getOption("panel.xyplot"), prepanel = NULL, scales = list(), strip = TRUE, groups = NULL, xlab, xlim, ylab, ylim, drop.unused.levels = lattice.getOption("drop.unused.levels"), ..., lattice.options = NULL, default.scales, default.prepanel = lattice.getOption("prepanel.default.xyplot"), subscripts = !is.null(groups), subset = TRUE) ## S3 method for class 'formula' dotplot(x, data, panel = lattice.getOption("panel.dotplot"), default.prepanel = lattice.getOption("prepanel.default.dotplot"), ...) ## S3 method for class 'formula' barchart(x, data, panel = lattice.getOption("panel.barchart"), default.prepanel = lattice.getOption("prepanel.default.barchart"), box.ratio = 2, ...) ## S3 method for class 'formula' stripplot(x, data, panel = lattice.getOption("panel.stripplot"), default.prepanel = lattice.getOption("prepanel.default.stripplot"), ...) ## S3 method for class 'formula' bwplot(x, data, allow.multiple = is.null(groups) || outer, outer = FALSE, auto.key = FALSE, aspect = "fill", panel = lattice.getOption("panel.bwplot"), prepanel = NULL, scales = list(), strip = TRUE, groups = NULL, xlab, xlim, ylab, ylim, box.ratio = 1, horizontal = NULL, drop.unused.levels = lattice.getOption("drop.unused.levels"), ..., lattice.options = NULL, default.scales, default.prepanel = lattice.getOption("prepanel.default.bwplot"), subscripts = !is.null(groups), subset = TRUE) ``` ### Arguments | | | | --- | --- | | `x` | All high-level function in lattice are generic. `x` is the object on which method dispatch is carried out. For the `"formula"` methods, `x` must be a formula describing the primary variables (used for the per-panel display) and the optional conditioning variables (which define the subsets plotted in different panels) to be used in the plot. Conditioning is described in the “Details” section below. For the functions documented here, the formula is generally of the form `y ~ x | g1 * g2 * ...` (or equivalently, `y ~ x | g1 + g2 + ...`), indicating that plots of `y` (on the y-axis) versus `x` (on the x-axis) should be produced conditional on the variables `g1, g2, ...`. Here `x` and `y` are the primary variables, and `g1, g2, ...` are the conditioning variables. The conditioning variables may be omitted to give a formula of the form `y ~ x`, in which case the plot will consist of a single panel with the full dataset. The formula can also involve expressions, e.g., `sqrt()`, `log()`, etc. See the `data` argument below for rules regarding evaluation of the terms in the formula. With the exception of `xyplot`, the functions documented here may also be supplied a formula of the form `~ x | g1 * g2 * ...`. In that case, `y` defaults to `names(x)` if `x` is named, and a factor with a single level otherwise. Cases where `x` is not a formula is handled by appropriate methods. The `numeric` methods are equivalent to a call with no left hand side and no conditioning variables in the formula. For `barchart` and `dotplot`, non-trivial methods exist for tables and arrays, documented at `<barchart.table>`. The conditioning variables `g1, g2, ...` must be either factors or shingles. Shingles provide a way of using numeric variables for conditioning; see the help page of `[shingle](shingles)` for details. Like factors, they have a `"levels"` attribute, which is used in producing the conditional plots. If necessary, numeric conditioning variables are converted to shingles using the `shingle` function; however, using `[equal.count](shingles)` may be more appropriate in many cases. Character variables are coerced to factors. **Extended formula interface:** As a useful extension of the interface described above, the primary variable terms (both the LHS `y` and RHS `x`) may consist of multiple terms separated by a ‘+’ sign, e.g., `y1 + y2 ~ x | a * b`. This formula would be taken to mean that the user wants to plot both `y1 ~ x | a * b` and `y2 ~ x | a * b`, but with the `y1 ~ x` and `y2 ~ x` superposed in each panel. The two groups will be distinguished by different graphical parameters. This is essentially what the `groups` argument (see below) would produce, if `y1` and `y2` were concatenated to produce a longer vector, with the `groups` argument being an indicator of which rows come from which variable. In fact, this is exactly what is done internally using the `[reshape](../../stats/html/reshape)` function. This feature cannot be used in conjunction with the `groups` argument. To interpret `y1 + y2` as a sum, one can either set `allow.multiple=FALSE` or use `I(y1+y2)`. A variation on this feature is when the `outer` argument is set to `TRUE`. In that case, the plots are not superposed in each panel, but instead separated into different panels (as if a new conditioning variable had been added). **Primary variables:** The `x` and `y` variables should both be numeric in `xyplot`, and an attempt is made to coerce them if not. However, if either is a factor, the levels of that factor are used as axis labels. In the other four functions documented here, exactly one of `x` and `y` should be numeric, and the other a factor or shingle. Which of these will happen is determined by the `horizontal` argument — if `horizontal=TRUE`, then `y` will be coerced to be a factor or shingle, otherwise `x`. The default value of `horizontal` is `FALSE` if `x` is a factor or shingle, `TRUE` otherwise. (The functionality provided by `horizontal=FALSE` is not S-compatible.) Note that the `x` argument used to be called `formula` in earlier versions (when the high-level functions were not generic and the formula method was essentially the only method). This is no longer allowed. It is recommended that this argument not be named in any case, but instead be the first (unnamed) argument. | | `data` | For the `formula` methods, a data frame (or more precisely, anything that is a valid `envir` argument in `[eval](../../base/html/eval)`, e.g., a list or an environment) containing values for any variables in the formula, as well as `groups` and `subset` if applicable. If not found in `data`, or if `data` is unspecified, the variables are looked for in the environment of the formula. For other methods (where `x` is not a formula), `data` is usually ignored, often with a warning if it is explicitly specified. | | `allow.multiple` | Logical flag specifying whether the extended formula interface described above should be in effect. Defaults to `TRUE` whenever sensible. | | `outer` | Logical flag controlling what happens with formulas using the extended interface described above (see the entry for `x` for details). Defaults to `FALSE`, except when `groups` is explicitly specified or grouping does not make sense for the default panel function. | | `box.ratio` | Applicable to `barchart` and `bwplot`. Specifies the ratio of the width of the rectangles to the inter-rectangle space. See also the `box.width` argument in the respective default panel functions. | | `horizontal` | Logical flag applicable to `bwplot`, `dotplot`, `barchart`, and `stripplot`. Determines which of `x` and `y` is to be a factor or shingle (`y` if TRUE, `x` otherwise). Defaults to `FALSE` if `x` is a factor or shingle, `TRUE` otherwise. This argument is used to process the arguments to these high-level functions, but more importantly, it is passed as an argument to the panel function, which is expected to use it as appropriate. A potentially useful component of `scales` in this case may be `abbreviate = TRUE`, in which case long labels which would usually overlap will be abbreviated. `scales` could also contain a `minlength` argument in this case, which would be passed to the `abbreviate` function. | **Common arguments:** The following arguments are common to all the functions documented here, as well as most other high-level Trellis functions. These are not documented elsewhere, except to override the usage given here. | | | | --- | --- | | `panel` | Once the subset of rows defined by each unique combination of the levels of the grouping variables are obtained (see “Details”), the corresponding `x` and `y` variables (or other variables, as appropriate, in the case of other high-level functions) are passed on to be plotted in each panel. The actual plotting is done by the function specified by the `panel` argument. The argument may be a function object or a character string giving the name of a predefined function. Each high-level function has its own default panel function, named as “`panel.`” followed by the name of the corresponding high-level function (e.g., `<panel.xyplot>`, `<panel.barchart>`, etc). Much of the power of Trellis Graphics comes from the ability to define customized panel functions. A panel function appropriate for the functions described here would usually expect arguments named `x` and `y`, which would be provided by the conditioning process. It can also have other arguments. It is useful to know in this context that all arguments passed to a high-level Lattice function (such as `xyplot`) that are not recognized by it are passed through to the panel function. It is thus generally good practice when defining panel functions to allow a `...` argument. Such extra arguments typically control graphical parameters, but other uses are also common. See documentation for individual panel functions for specifics. Note that unlike in S-PLUS, it is not guaranteed that panel functions will be supplied only numeric vectors for the `x` and `y` arguments; they can be factors as well (but not shingles). Panel functions need to handle this case, which in most cases can be done by simply coercing them to numeric. Technically speaking, panel functions must be written using Grid graphics functions. However, knowledge of Grid is usually not necessary to construct new custom panel functions, as there are several predefined panel functions which can help; for example, `panel.grid`, `panel.loess`, etc. There are also some grid-compatible replacements of commonly used traditional graphics functions useful for this purpose. For example, `lines` can be replaced by `llines` (or equivalently, `panel.lines`). Note that traditional graphics functions like `lines` will not work in a lattice panel function. One case where a bit more is required of the panel function is when the `groups` argument is not `NULL`. In that case, the panel function should also accept arguments named `groups` and `subscripts` (see below for details). A useful panel function predefined for use in such cases is `<panel.superpose>`, which can be combined with different `panel.groups` functions to determine what is plotted for each group. See the “Examples” section for an interaction plot constructed in this way. Several other panel functions can also handle the `groups` argument, including the default ones for `xyplot`, `barchart`, `dotplot`, and `stripplot`. Even when `groups` is not present, the panel function can have `subscripts` as a formal argument. In either case, the `subscripts` argument passed to the panel function are the indices of the `x` and `y` data for that panel in the original `data`, BEFORE taking into account the effect of the `subset` argument. Note that `groups` remains unaffected by any subsetting operations, so `groups[subscripts]` gives the values of `groups` that correspond to the data in that panel. This interpretation of `subscripts` does not hold when the extended formula interface is in use (i.e., when `allow.multiple` is in effect). A comprehensive description would be too complicated (details can be found in the source code of the function `latticeParseFormula`), but in short, the extended interface works by creating an artificial grouping variable that is longer than the original data frame, and consequently, `subscripts` needs to refer to rows beyond those in the original data. To further complicate matters, the artificial grouping variable is created after any effect of `subset`, in which case `subscripts` may have no relationship with corresponding rows in the original data frame. One can also use functions called `<panel.number>` and `[packet.number](panel.number)`, representing panel order and packet order respectively, inside the panel function (as well as the strip function or while interacting with a lattice display using `[trellis.focus](interaction)` etc). Both provide a simple integer index indicating which panel is currently being drawn, but differ in how the count is calculated. The panel number is a simple incremental counter that starts with 1 and is incremented each time a panel is drawn. The packet number on the other hand indexes the combination of levels of the conditioning variables that is represented by that panel. The two indices coincide unless the order of conditioning variables is permuted and/or the plotting order of levels within one or more conditioning variables is altered (using `perm.cond` and `index.cond` respectively), in which case `packet.number` gives the index corresponding to the ‘natural’ ordering of that combination of levels of the conditioning variables. `<panel.xyplot>` has an argument called `type` which is worth mentioning here because it is quite frequently used (and as mentioned above, can be passed to `xyplot` directly). In the event that a `groups` variable is used, `<panel.xyplot>` calls `<panel.superpose>`, arguments of which can also be passed directly to `xyplot`. Panel functions for `bwplot` and friends should have an argument called `horizontal` to account for the cases when `x` is the factor or shingle. | | | | | --- | --- | | `aspect` | This argument controls the physical aspect ratio of the panels, which is usually the same for all the panels. It can be specified as a ratio (vertical size/horizontal size) or as a character string. In the latter case, legitimate values are `"fill"` (the default) which tries to make the panels as big as possible to fill the available space; `"xy"`, which computes the aspect ratio based on the 45 degree banking rule (see `<banking>`); and `"iso"` for isometric scales, where the relation between physical distance on the device and distance in the data scale are forced to be the same for both axes. If a `prepanel` function is specified and it returns components `dx` and `dy`, these are used for banking calculations. Otherwise, values from the default prepanel function are used. Not all default prepanel functions produce sensible banking calculations. | | `groups` | A variable or expression to be evaluated in `data`, expected to act as a grouping variable within each panel, typically used to distinguish different groups by varying graphical parameters like color and line type. Formally, if `groups` is specified, then `groups` along with `subscripts` is passed to the panel function, which is expected to handle these arguments. For high level functions where grouping is appropriate, the default panel functions can handle grouping. It is very common to use a key (legend) when a grouping variable is specified. See entries for `key`, `auto.key` and `[simpleKey](simplekey)` for how to draw a key. | | `auto.key` | A logical, or a list containing components to be used as arguments to `[simpleKey](simplekey)`. `auto.key=TRUE` is equivalent to `auto.key=list()`, in which case `[simpleKey](simplekey)` is called with a set of default arguments (which may depend on the relevant high-level function). Most valid components to the `key` argument can be specified in this manner, as `[simpleKey](simplekey)` will simply add unrecognized arguments to the list it produces. `auto.key` is typically used to automatically produce a suitable legend in conjunction with a grouping variable. If `auto.key=TRUE`, a suitable legend will be drawn if a `groups` argument is also provided, and not otherwise. In list form, `auto.key` will modify the default legend thus produced. For example, `auto.key=list(columns = 2)` will create a legend split into two columns (`columns` is documented in the entry for `key`). More precisely, if `auto.key` is not `FALSE`, `groups` is non-null, and there is no `key` or `legend` argument specified in the call, a key is created with `simpleKey` with `levels(groups)` as the first (`text`) argument. (Note: this may not work in all high-level functions, but it does work for the ones where grouping makes sense with the default panel function). If `auto.key` is provided as a list and includes a `text` component, then that is used instead as the text labels in the key, and the key is drawn even if `groups` is not specified. Note that `simpleKey` uses the default settings (see `<trellis.par.get>`) to determine the graphical parameters in the key, so the resulting legend will be meaningful only if the same settings are used in the plot as well. The `par.settings` argument, possibly in conjunction with `[simpleTheme](simpletheme)`, may be useful to temporarily modify the default settings for this purpose. One disadvantage to using `key` (or even `simpleKey`) directly is that the graphical parameters used in the key are absolutely determined at the time when the `"trellis"` object is created. Consequently, if a plot once created is re-`plot`-ted with different settings, the original parameter settings will be used for the key even though the new settings are used for the actual display. However, with `auto.key`, the key is actually created at plotting time, so the settings will match. | | `prepanel` | A function that takes the same arguments as the `panel` function and returns a list, possibly containing components named `xlim`, `ylim`, `dx`, and `dy` (and less frequently, `xat` and `yat`). The return value of a user-supplied prepanel function need not contain all these components; in case some are missing, they are replaced by the component-wise defaults. The `xlim` and `ylim` components are similar to the high level `xlim` and `ylim` arguments (i.e., they are usually a numeric vector of length 2 defining a range, or a character vector representing levels of a factor). If the `xlim` and `ylim` arguments are not explicitly specified (possibly as components in `scales`) in the high-level call, then the actual limits of the panels are guaranteed to include the limits returned by the prepanel function. This happens globally if the `relation` component of `scales` is `"same"`, and on a per-panel basis otherwise. The `dx` and `dy` components are used for banking computations in case `aspect` is specified as `"xy"`. See documentation of `<banking>` for details. If `xlim` or `ylim` is a character vector (which is appropriate when the corresponding variable is a factor), this implicitly indicates that the scale should include the first `n` integers, where `n` is the length of `xlim` or `ylim`, as the case may be. The elements of the character vector are used as the default labels for these `n` integers. Thus, to make this information consistent between panels, the `xlim` or `ylim` values should represent all the levels of the corresponding factor, even if some are not used within that particular panel. In such cases, an additional component `xat` or `yat` may be returned by the `prepanel` function, which should be a subset of `1:n`, indicating which of the `n` values (levels) are actually represented in the panel. This is useful when calculating the limits with `relation="free"` or `relation="sliced"` in `scales`. The prepanel function is responsible for providing a meaningful return value when the `x`, `y` (etc.) variables are zero-length vectors. When nothing else is appropriate, values of NA should be returned for the `xlim` and `ylim` components. | | `strip` | A logical flag or function. If `FALSE`, strips are not drawn. Otherwise, strips are drawn using the `strip` function, which defaults to `strip.default`. See documentation of `<strip.default>` to see the arguments that are available to the strip function. This description also applies to the `strip.left` argument (see `...` below), which can be used to draw strips on the left of each panel (useful for wide short panels, e.g., in time-series plots). | | `xlab` | Character or expression (or a `"grob"`) giving label(s) for the x-axis. Generally defaults to the expression for `x` in the formula defining the plot. Can be specified as `NULL` to omit the label altogether. Finer control is possible, as described in the entry for `main`, with the modification that if the `label` component is omitted from the list, it is replaced by the default `xlab`. | | `ylab` | Character or expression (or `"grob"`) giving label for the y-axis. Generally defaults to the expression for `y` in the formula defining the plot. Finer control is possible, see entries for `main` and `xlab`. | | `scales` | Generally a list determining how the x- and y-axes (tick marks and labels) are drawn. The list contains parameters in `name=value` form, and may also contain two other lists called `x` and `y` of the same form (described below). Components of `x` and `y` affect the respective axes only, while those in `scales` affect both. When parameters are specified in both lists, the values in `x` or `y` are used. Note that certain high-level functions have defaults that are specific to a particular axis (e.g., `bwplot` has `alternating=FALSE` for the categorical axis only); these can only be overridden by an entry in the corresponding component of `scales`. As a special exception, `scales` (or its `x` and `y` components) can also be a character string, in which case it is interpreted as the `relation` component. The possible components are : `relation` A character string that determines how axis limits are calculated for each panel. Possible values are `"same"` (default), `"free"` and `"sliced"`. For `relation="same"`, the same limits, usually large enough to encompass all the data, are used for all the panels. For `relation="free"`, limits for each panel is determined by just the points in that panel. Behavior for `relation="sliced"` is similar, except that the length (max - min) of the scales are constrained to remain the same across panels. The determination of what axis limits are suitable for each panel can be controlled by the `prepanel` function, which can be overridden by `xlim`, `ylim` or `scales$limits` (except when `relation="sliced"`, in which case explicitly specified limits are ignored with a warning). When `relation` is `"free"`, `xlim` or `ylim` can be a list, in which case it is treated as if its components were the limit values obtained from the prepanel calculations for each panel (after being replicated if necessary). `tick.number` An integer, giving the suggested number of intervals between ticks. This is ignored for a factor, shingle, or character vector, for in these cases there is no natural rule for leaving out some of the labels. But see `xlim`. `draw` A logical flag, defaulting to `TRUE`, that determines whether to draw the axis (i.e., tick marks and labels) at all. `alternating` Usually a logical flag specifying whether axis labels should alternate from one side of the group of panels to the other. For finer control, `alternating` can also be a vector (replicated to be as long as the number of rows or columns per page) consisting of the following numbers * 0: do not draw tick labels * 1: bottom/left * 2: top/right * 3: both. `alternating` applies only when `relation="same"`. The default is `TRUE`, or equivalently, `c(1, 2)` `limits` Same as `xlim` and `ylim`. `at` The location of tick marks along the axis (in native coordinates), or a list as long as the number of panels describing tick locations for each panel. `labels` Vector of labels (characters or expressions) to go along with `at`. Can also be a list like `at`. `cex` A numeric multiplier to control character sizes for axis labels. Can be a vector of length 2, to control left/bottom and right/top labels separately. `font`, `fontface`, `fontfamily` Specifies the font to be used for axis labels. `lineheight` Specifies the line height parameter (height of line as a multiple of the size of text); relevant for multi-line labels. (This is currently ignored for `<cloud>`.) `tck` Usually a numeric scalar controlling the length of tick marks. Can also be a vector of length 2, to control the length of left/bottom and right/top tick marks separately. `col` Color of tick marks and labels. `rot` Angle (in degrees) by which the axis labels are to be rotated. Can be a vector of length 2, to control left/bottom and right/top axes separately. `abbreviate` A logical flag, indicating whether to abbreviate the labels using the `[abbreviate](../../base/html/abbreviate)` function. Can be useful for long labels (e.g., in factors), especially on the x-axis. `minlength` Argument passed to `[abbreviate](../../base/html/abbreviate)` if `abbreviate=TRUE`. `log` Controls whether the corresponding variable (`x` or `y`) will be log transformed before being passed to the panel function. Defaults to `FALSE`, in which case the data are not transformed. Other possible values are any number that works as a base for taking logarithm, `TRUE` (which is equivalent to 10), and `"e"` (for the natural logarithm). As a side effect, the corresponding axis is labeled differently. Note that this is in reality a transformation of the data, not the axes. Other than the axis labeling, using this feature is no different than transforming the data in the formula; e.g., `scales=list(x = list(log = 2))` is equivalent to `y ~ log2(x)`. See entry for `equispaced.log` below for details on how to control axis labeling. `equispaced.log` A logical flag indicating whether tick mark locations should be equispaced when ‘log scales’ are in use. Defaults to `TRUE`. Tick marks are always labeled in the original (untransformed) scale, but this makes the choice of tick mark locations nontrivial. If `equispaced.log` is `FALSE`, the choice made is similar to how log scales are annotated in traditional graphics. If `TRUE`, tick mark locations are chosen as ‘pretty’ equispaced values in the transformed scale, and labeled in the form `"base^loc"`, where `base` is the base of the logarithm transformation, and `loc` are the locations in the transformed scale. See also `xscale.components.logpower` in the latticeExtra package. `format` The `format` to use for POSIXct variables. See `[strptime](../../base/html/strptime)` for description of valid values. `axs` A character string, `"r"` (default) or `"i"`. In the latter case, the axis limits are calculated as the exact data range, instead of being padded on either side. (May not always work as expected.) Note that much of the function of `scales` is accomplished by `pscales` in `<splom>`. | | `subscripts` | A logical flag specifying whether or not a vector named `subscripts` should be passed to the panel function. Defaults to `FALSE`, unless `groups` is specified, or if the panel function accepts an argument named `subscripts`. This argument is useful if one wants the subscripts to be passed on even if these conditions do not hold; a typical example is when one wishes to augment a Lattice plot after it has been drawn, e.g., using `[panel.identify](interaction)`. | | `subset` | An expression that evaluates to a logical or integer indexing vector. Like `groups`, it is evaluated in `data`. Only the resulting rows of `data` are used for the plot. If `subscripts` is `TRUE`, the subscripts provided to the panel function will be indices referring to the rows of `data` prior to the subsetting. Whether levels of factors in the data frame that are unused after the subsetting will be dropped depends on the `drop.unused.levels` argument. | | `xlim` | Normally a numeric vector (or a DateTime object) of length 2 giving left and right limits for the x-axis, or a character vector, expected to denote the levels of `x`. The latter form is interpreted as a range containing c(1, length(xlim)), with the character vector determining labels at tick positions `1:length(xlim)`. `xlim` could also be a list, with as many components as the number of panels (recycled if necessary), with each component as described above. This is meaningful only when `scales$x$relation` is `"free"`, in which case these are treated as if they were the corresponding limit components returned by prepanel calculations. | | `ylim` | Similar to `xlim`, applied to the y-axis. | | `drop.unused.levels` | A logical flag indicating whether the unused levels of factors will be dropped, usually relevant when a subsetting operation is performed or an `[interaction](../../base/html/interaction)` is created. Unused levels are usually dropped, but it is sometimes appropriate to suppress dropping to preserve a useful layout. For finer control, this argument could also be list containing components `cond` and `data`, both logical, indicating desired behavior for conditioning variables and primary variables respectively. The default is given by `lattice.getOption("drop.unused.levels")`, which is initially set to `TRUE` for both components. Note that this argument does not control dropping of levels of the `groups` argument. | | `default.scales` | A list giving the default values of `scales` for a particular high-level function. This is rarely of interest to the end-user, but may be helpful when defining other functions that act as a wrapper to one of the high-level Lattice functions. | | `default.prepanel` | A function or character string giving the name of a function that serves as the (component-wise) fallback prepanel function when the `prepanel` argument is not specified, or does not return all necessary components. The main purpose of this argument is to enable the defaults to be overridden through the use of `<lattice.options>`. | | `lattice.options` | A list that could be supplied to `<lattice.options>`. These options are applied temporarily for the duration of the call, after which the settings revert back to what they were before. The options are retained along with the object and reused during plotting. This enables the user to attach options settings to the trellis object itself rather than change the settings globally. See also the `par.settings` argument described below for a similar treatment of graphical settings. | | `...` | Further arguments, usually not directly processed by the high-level functions documented here, but instead passed on to other functions. Such arguments can be broadly categorized into two types: those that affect all high-level Lattice functions in a similar manner, and those that are meant for the specific panel function being used. The first group of arguments are processed by a common, unexported function called `trellis.skeleton`. These arguments affect all high-level functions, but are only documented here (except to override the behaviour described here). All other arguments specified in a high-level call, specifically those neither described here nor in the help page of the relevant high-level function, are passed unchanged to the panel function used. By convention, the default panel function used for any high-level function is named as “`panel.`” followed by the name of the high-level function; for example, the default panel function for `bwplot` is `panel.bwplot`. In practical terms, this means that in addition to the help page of the high-level function being used, the user should also consult the help page of the corresponding panel function for arguments that may be specified in the high-level call. The effect of the first group of common arguments are as follows: `as.table`: A logical flag that controls the order in which panels should be displayed: if `FALSE` (the default), panels are drawn left to right, bottom to top (as in a graph); if `TRUE`, left to right, top to bottom (as in a table). `between`: A list with components `x` and `y` (both usually 0 by default), numeric vectors specifying the space between the panels (units are character heights). `x` and `y` are repeated to account for all panels in a page and any extra components are ignored. The result is used for all pages in a multi page display. In other words, it is not possible to use different `between` values for different pages. `key`: A list that defines a legend to be drawn on the plot. This list is used as an argument to the `<draw.key>` function, which produces a `"grob"` (grid object) eventually plotted by the print method for `"trellis"` objects. The structure of the legend is constrained in the ways described below. Although such a list can be and often is created explicitly, it is also possible to generate such a list using the `[simpleKey](simplekey)` function; the latter is more convenient but less flexible. The `auto.key` argument can be even more convenient for the most common situation where legends are used, namely, in conjunction with a grouping variable. To use more than one legend, or to have arbitrary legends not constrained by the structure imposed by `key`, use the `legend` argument. The position of the key can be controlled in either of two possible ways. If a component called `space` is present, the key is positioned outside the plot region, in one of the four sides, determined by the value of `space`, which can be one of `"top"`, `"bottom"`, `"left"` and `"right"`. Alternatively, the key can be positioned inside the plot region by specifying components `x`, `y` and `corner`. `x` and `y` determine the location of the corner of the key given by `corner`, which is usually one of `c(0,0)`, `c(1,0)`, `c(1,1)` and `c(0,1)`, which denote the corners of the unit square. Fractional values are also allowed, in which case `x` and `y` determine the position of an arbitrary point inside (or outside for values outside the unit interval) the key. `x` and `y` should be numbers between 0 and 1, giving coordinates with respect to the “display area”. Depending on the value of the `"legend.bbox"` option (see `[lattice.getOption](lattice.options)`), this can be either the full figure region (`"full"`), or just the region that bounds the panels and strips (`"panel"`). The key essentially consists of a number of columns, possibly divided into blocks, each containing some rows. The contents of the key are determined by (possibly repeated) components named `"rectangles"`, `"lines"`, `"points"` or `"text"`. Each of these must be lists with relevant graphical parameters (see later) controlling their appearance. The `key` list itself can contain graphical parameters, these would be used if relevant graphical components are omitted from the other components. The length (number of rows) of each such column (except `"text"`s) is taken to be the largest of the lengths of the graphical components, including the ones specified outside (see the entry for `rep` below for details on this). The `"text"` component must have a character or expression vector as its first component, to be used as labels. The length of this vector determines the number of rows. The graphical components that can be included in `key` and also in the components named `"text"`, `"lines"`, `"points"` and `"rectangles"` (as appropriate) are: * `cex=1` (text, lines, points) * `col="black"` (text, rectangles, lines, points) * `alpha=1` (text, rectangles, lines, points) * `fill="transparent"` (lines, points) * `lty=1` (lines) * `lwd=1` (lines, points) * `font=1` (text, points) * `fontface` (text, points) * `fontfamily` (text, points) * `pch=8` (lines, points) * `adj=0` (text) * `type="l"` (lines) * `size=5` (rectangles, lines) * `height=1` (rectangles) * `lineheight=1` (text) * `angle=0` (rectangles, but ignored) * `density=-1` (rectangles, but ignored) In addition, the component `border` can be included inside the `"rect"` component to control the border color of the rectangles; when specified at the top level, `border` controls the border of the entire key (see below). `angle` and `density` are unimplemented. `size` determines the width of columns of rectangles and lines in character widths. `type` is relevant for lines; `"l"` denotes a line, `"p"` denotes a point, and `"b"` and `"o"` both denote both together. `height` gives heights of rectangles as a fraction of the default. Other possible components of `key` are: `reverse.rows` Logical flag, defaulting to `FALSE`. If `TRUE`, all components are reversed *after* being replicated (the details of which may depend on the value of `rep`). This is useful in certain situations, e.g., with a grouped `barchart` with `stack = TRUE` with the categorical variable on the vertical axis, where the bars in the plot will usually be ordered from bottom to top, but the corresponding legend will have the levels from top to bottom unless `reverse.rows = TRUE`. Note that in this case, unless all columns have the same number or rows, they will no longer be aligned. `between` Numeric vector giving the amount of space (character widths) surrounding each column (split equally on both sides). `title` String or expression giving a title for the key. `rep` Logical flag, defaults to `TRUE`. By default, it is assumed that all columns in the key (except the `"text"`s) will have the same number of rows, and all components are replicated to be as long as the longest. This can be suppressed by specifying `rep=FALSE`, in which case the length of each column will be determined by components of that column alone. `cex.title` Zoom factor for the title. `lines.title` The amount of vertical space to be occupied by the title in lines (in multiples of itself). Defaults to 2. `padding.text` The amount of space (padding) to be used above and below each row containing text, in multiples of the default, which is currently `0.2 * "lines"`. This padding is in addition to the normal height of any row that contains text, which is the minimum amount necessary to contain all the text entries. `background` Background color for the legend. Defaults to the global background color. `alpha.background` An alpha transparency value between 0 and 1 for the background. `border` Either a color for the border, or a logical flag. In the latter case, the border color is black if `border` is `TRUE`, and no border is drawn if it is `FALSE` (the default). `transparent=FALSE` Logical flag, whether legend should have a transparent background. `just` A character or numeric vector of length one or two giving horizontal and vertical justification for the placement of the legend. See `[grid.layout](../../grid/html/grid.layout)` for more precise details. `columns` The number of column-blocks (drawn side by side) the legend is to be divided into. `between.columns` Space between column blocks, in addition to `between`. `divide` Number of point symbols to divide each line when `type` is `"b"` or `"o"` in `lines`. `legend`: The legend argument can be useful if one wants to place more than one key. It also allows the use of arbitrary `"grob"`s (grid objects) as legends. If used, `legend` must be a list, with an arbitrary number of components. Each component must be named one of `"left"`, `"right"`, `"top"`, `"bottom"`, or `"inside"`. The name `"inside"` can be repeated, but not the others. This name will be used to determine the location for that component, and is similar to the `space` component of `key`. If `key` (or `colorkey` for `<levelplot>` and `[wireframe](cloud)`) is specified, their `space` component must not conflict with the name of any component of `legend`. Each component of `legend` must have a component called `fun`. This can be a `"grob"`, or a function (or the name of a function) that produces a `"grob"` when called. If this function expects any arguments, they must be supplied as a list in another component called `args`. For components named `"inside"`, there can be additional components called `x`, `y` and `corner`, which work in the same way as for `key`. `page`: A function of one argument (page number) to be called after drawing each page. The function must be ‘grid-compliant’, and is called with the whole display area as the default viewport. `xlab.top`, `ylab.right`: Labels for the x-axis on top, and y-axis on the right. Similar to `xlab` and `ylab`, but less commonly used. `main`: Typically a character string or expression describing the main title to be placed on top of each page. Defaults to `NULL`. `main` (as well as `xlab`, `ylab` and `sub`) is usually a character string or an expression that gets used as the label, but can also be a list that controls further details. Expressions are treated as specification of LaTeX-like markup as described in `[plotmath](../../grdevices/html/plotmath)`. The label can be a vector, in which case the components will be spaced out horizontally (or vertically for `ylab`). This feature can be used to provide column or row labels rather than a single axis label. When `main` (etc.) is a list, the actual label should be specified as the `label` component (which may be unnamed if it is the first component). The label can be missing, in which case the default will be used (`xlab` and `ylab` usually have defaults, but `main` and `sub` do not). Further named arguments are passed on to `[textGrob](../../grid/html/grid.text)`; this can include arguments controlling positioning like `just` and `rot` as well as graphical parameters such as `col` and `font` (see `[gpar](../../grid/html/gpar)` for a full list). `main`, `sub`, `xlab`, `ylab`, `xlab.top`, and `ylab.right` can also be arbitrary `"grob"`s (grid graphical objects). `sub`: Character string or expression (or a list or `"grob"`) for a subtitle to be placed at the bottom of each page. See entry for `main` for finer control options. `par.strip.text`: A list of parameters to control the appearance of strip text. Notable components are `col`, `cex`, `font`, and `lines`. The first three control graphical parameters while the last is a means of altering the height of the strips. This can be useful, for example, if the strip labels (derived from factor levels, say) are double height (i.e., contains `"\n"`-s) or if the default height seems too small or too large. Additionally, the `lineheight` component can control the space between multiple lines. The labels can be abbreviated when shown by specifying `abbreviate = TRUE`, in which case the components `minlength` and `dot` (passed along to the `[abbreviate](../../base/html/abbreviate)` function) can be specified to control the details of how this is done. `layout`: In general, a conditioning plot in Lattice consists of several panels arranged in a rectangular array, possibly spanning multiple pages. `layout` determines this arrangement. `layout` is a numeric vector of length 2 or 3 giving the number of columns, rows, and pages (optional) in a multipanel display. By default, the number of columns is the number of levels of the first conditioning variable and the number of rows is the number of levels of the second conditioning variable. If there is only one conditioning variable, the default layout vector is `c(0,n)`, where `n` is the number of levels of the given vector. Any time the first value in the layout vector is 0, the second value is used as the desired number of panels per page and the actual layout is computed from this, taking into account the aspect ratio of the panels and the device dimensions (via `[par](../../graphics/html/par)("din")`). If `NA` is specified for the number of rows or columns (but not both), that dimension will be filled out according to the number of panels. The number of pages is by default set to as many as is required to plot all the panels, and so rarely needs to be specified. However, in certain situations the default calculation may be incorrect, and in that case the number of pages needs to be specified explicitly. `skip`: A logical vector (default `FALSE`), replicated to be as long as the number of panels (spanning all pages). For elements that are `TRUE`, the corresponding panel position is skipped; i.e., nothing is plotted in that position. The panel that was supposed to be drawn there is now drawn in the next available panel position, and the positions of all the subsequent panels are bumped up accordingly. This may be useful for arranging plots in an informative manner. `strip.left`: `strip.left` can be used to draw strips on the left of each panel, which can be useful for wide short panels, as in time-series (or similar) plots. See the entry for `strip` for detailed usage. `xlab.default`, `ylab.default`: Fallback default for `xlab` and `ylab` when they are not specified. If `NULL`, the defaults are parsed from the Trellis formula. This is rarely useful for the end-user, but can be helpful when developing new Lattice functions. `xscale.components`, `yscale.components`: Functions that determine axis annotation for the x and y axes respectively. See documentation for `[xscale.components.default](axis.default)`, the default values of these arguments, to learn more. `axis`: Function responsible for drawing axis annotation. See documentation for `<axis.default>`, the default value of this argument, to learn more. `perm.cond`: An integer vector, a permutation of `1:n`, where `n` is the number of conditioning variables. By default, the order in which panels are drawn depends on the order of the conditioning variables specified in the formula. `perm.cond` can modify this order. If the trellis display is thought of as an `n`-dimensional array, then during printing, its dimensions are permuted using `perm.cond` as the `perm` argument does in `[aperm](../../base/html/aperm)`. `index.cond`: Whereas `perm.cond` permutes the dimensions of the multidimensional array of panels, `index.cond` can be used to subset (or reorder) margins of that array. `index.cond` can be a list or a function, with behavior in each case described below. The panel display order within each conditioning variable depends on the order of their levels. `index.cond` can be used to choose a ‘subset’ (in the R sense) of these levels, which is then used as the display order for that variable. If `index.cond` is a list, it has to be as long as the number of conditioning variables, and the `i`-th component has to be a valid indexing vector for `levels(g_i)`, where `g_i` is the `i`-th conditioning variable in the plot (note that these levels may not contain all levels of the original variable, depending on the effects of the `subset` and `drop.unused.levels` arguments). In particular, this indexing may repeat levels, or drop some altogether. The result of this indexing determines the order of panels within that conditioning variable. To keep the order of a particular variable unchanged, the corresponding component must be set to `TRUE`. Note that the components of `index.cond` are interpreted in the order of the conditioning variables in the original call, and is not affected by `perm.cond`. Another possibility is to specify `index.cond` as a function. In this case, this function is called once for each panel, potentially with all arguments that are passed to the panel function for that panel. (More specifically, if this function has a `...` argument, then all panel arguments are passed, otherwise, only named arguments that match are passed.) If there is only one conditioning variable, the levels of that variable are then sorted so that these values are in ascending order. For multiple conditioning variables, the order for each variable is determined by first taking the average over all other conditioning variables. Although they can be supplied in high-level function calls directly, it is more typical to use `perm.cond` and `index.cond` to update an existing `"trellis"` object, thus allowing it to be displayed in a different arrangement without re-calculating the data subsets that go into each panel. In the `<update.trellis>` method, both can be set to `NULL`, which reverts these back to their defaults. `par.settings`: A list that could be supplied to `[trellis.par.set](trellis.par.get)`. When the resulting object is plotted, these options are applied temporarily for the duration of the plotting, after which the settings revert back to what they were before. This enables the user to attach some display settings to the trellis object itself rather than change the settings globally. See also the `lattice.options` argument described above for a similar treatment of non-graphical options. `plot.args`: A list containing possible arguments to `[plot.trellis](print.trellis)`, which will be used by the `plot` or `print` methods when drawing the object, unless overridden explicitly. This enables the user to attach such arguments to the trellis object itself. Partial matching is not performed. | ### Details The high-level functions documented here, as well as other high-level Lattice functions, are generic, with the `formula` method usually doing the most substantial work. The structure of the plot that is produced is mostly controlled by the formula (implicitly in the case of the non-formula methods). For each unique combination of the levels of the conditioning variables `g1, g2, ...`, a separate “packet” is produced, consisting of the points `(x,y)` for the subset of the data defined by that combination. The display can be thought of as a three-dimensional array of panels, consisting of one two-dimensional matrix per page. The dimensions of this array are determined by the `layout` argument. If there are no conditioning variables, the plot produced consists of a single packet. Each packet usually corresponds to one panel, but this is not strictly necessary (see the entry for `index.cond` above). The coordinate system used by lattice by default is like a graph, with the origin at the bottom left, with axes increasing to the right and top. In particular, panels are by default drawn starting from the bottom left corner, going right and then up, unless `as.table = TRUE`, in which case panels are drawn from the top left corner, going right and then down. It is possible to set a global preference for the table-like arrangement by changing the default to `as.table=TRUE`; this can be done by setting `lattice.options(default.args = list(as.table = TRUE))`. Default values can be set in this manner for the following arguments: `as.table`, `aspect`, `between`, `page`, `main`, `sub`, `par.strip.text`, `layout`, `skip` and `strip`. Note that these global defaults are sometimes overridden by individual functions. The order of the panels depends on the order in which the conditioning variables are specified, with `g1` varying fastest, followed by `g2`, and so on. Within a conditioning variable, the order depends on the order of the levels (which for factors is usually in alphabetical order). Both of these orders can be modified using the `index.cond` and `perm.cond` arguments, possibly using the `[update](update.trellis)` (and other related) method(s). ### Value The high-level functions documented here, as well as other high-level Lattice functions, return an object of class `"trellis"`. The `[update](update.trellis)` method can be used to subsequently update components of the object, and the `[print](print.trellis)` method (usually called by default) will plot it on an appropriate plotting device. ### Note Most of the arguments documented here are also applicable for the other high-level functions in the lattice package. These are not described in any detail elsewhere unless relevant, and this should be considered the canonical documentation for such arguments. Any arguments passed to these functions and not recognized by them will be passed to the panel function. Most predefined panel functions have arguments that customize its output. These arguments are described only in the help pages for these panel functions, but can usually be supplied as arguments to the high-level plot. ### Author(s) Deepayan Sarkar [[email protected]](mailto:[email protected]) ### References Sarkar, Deepayan (2008) *Lattice: Multivariate Data Visualization with R*, Springer. <http://lmdvr.r-forge.r-project.org/> ### See Also `[Lattice](lattice)` for an overview of the package, as well as `<barchart.table>`, `<print.trellis>`, `[shingle](shingles)`, `<banking>`, `[reshape](../../stats/html/reshape)`, `<panel.xyplot>`, `<panel.bwplot>`, `<panel.barchart>`, `<panel.dotplot>`, `<panel.stripplot>`, `<panel.superpose>`, `<panel.loess>`, `[panel.average](panel.functions)`, `<strip.default>`, `[simpleKey](simplekey)` `[trellis.par.set](trellis.par.get)` ### Examples ``` require(stats) ## Tonga Trench Earthquakes Depth <- equal.count(quakes$depth, number=8, overlap=.1) xyplot(lat ~ long | Depth, data = quakes) update(trellis.last.object(), strip = strip.custom(strip.names = TRUE, strip.levels = TRUE), par.strip.text = list(cex = 0.75), aspect = "iso") ## Examples with data from `Visualizing Data' (Cleveland, 1993) obtained ## from http://cm.bell-labs.com/cm/ms/departments/sia/wsc/ EE <- equal.count(ethanol$E, number=9, overlap=1/4) ## Constructing panel functions on the fly; prepanel xyplot(NOx ~ C | EE, data = ethanol, prepanel = function(x, y) prepanel.loess(x, y, span = 1), xlab = "Compression Ratio", ylab = "NOx (micrograms/J)", panel = function(x, y) { panel.grid(h = -1, v = 2) panel.xyplot(x, y) panel.loess(x, y, span=1) }, aspect = "xy") ## Extended formula interface xyplot(Sepal.Length + Sepal.Width ~ Petal.Length + Petal.Width | Species, data = iris, scales = "free", layout = c(2, 2), auto.key = list(x = .6, y = .7, corner = c(0, 0))) ## user defined panel functions states <- data.frame(state.x77, state.name = dimnames(state.x77)[[1]], state.region = state.region) xyplot(Murder ~ Population | state.region, data = states, groups = state.name, panel = function(x, y, subscripts, groups) { ltext(x = x, y = y, labels = groups[subscripts], cex=1, fontfamily = "HersheySans") }) ## Stacked bar chart barchart(yield ~ variety | site, data = barley, groups = year, layout = c(1,6), stack = TRUE, auto.key = list(space = "right"), ylab = "Barley Yield (bushels/acre)", scales = list(x = list(rot = 45))) bwplot(voice.part ~ height, data=singer, xlab="Height (inches)") dotplot(variety ~ yield | year * site, data=barley) ## Grouped dot plot showing anomaly at Morris dotplot(variety ~ yield | site, data = barley, groups = year, key = simpleKey(levels(barley$year), space = "right"), xlab = "Barley Yield (bushels/acre) ", aspect=0.5, layout = c(1,6), ylab=NULL) stripplot(voice.part ~ jitter(height), data = singer, aspect = 1, jitter.data = TRUE, xlab = "Height (inches)") ## Interaction Plot xyplot(decrease ~ treatment, OrchardSprays, groups = rowpos, type = "a", auto.key = list(space = "right", points = FALSE, lines = TRUE)) ## longer version with no x-ticks ## Not run: bwplot(decrease ~ treatment, OrchardSprays, groups = rowpos, panel = "panel.superpose", panel.groups = "panel.linejoin", xlab = "treatment", key = list(lines = Rows(trellis.par.get("superpose.line"), c(1:7, 1)), text = list(lab = as.character(unique(OrchardSprays$rowpos))), columns = 4, title = "Row position")) ## End(Not run) ```
programming_docs
r None `lattice.options` Low-level Options Controlling Behaviour of Lattice --------------------------------------------------------------------- ### Description Functions to handle settings used by lattice. Their main purpose is to make code maintainance easier, and users normally should not need to use these functions. However, fine control at this level maybe useful in certain cases. ### Usage ``` lattice.options(...) lattice.getOption(name) ``` ### Arguments | | | | --- | --- | | `name` | character giving the name of a setting | | `...` | new options can be defined, or existing ones modified, using one or more arguments of the form `name = value` or by passing a list of such tagged values. Existing values can be retrieved by supplying the names (as character strings) of the components as unnamed arguments. | ### Details These functions are modeled on `options` and `getOption`, and behave similarly for the most part. Some of the available components are documented here, but not all. The purpose of the ones not documented are either fairly obvious, or not of interest to the end-user. `panel.error` A function, or `NULL`. If the former, every call to the panel function will be wrapped inside `[tryCatch](../../base/html/conditions)` with the specified function as an error handler. The default is to use the `[panel.error](print.trellis)` function. This prevents the plot from failing due to errors in a single panel, and leaving the grid operations in an unmanageable state. If set to `NULL`, errors in panel functions will not be caught using `tryCatch`. `save.object` Logical flag indicating whether a `"trellis"` object should be saved when plotted for subsequent retrieval and further manipulation. Defaults to `TRUE`. `layout.widths`, `layout.heights` Controls details of the default space allocation in the grid layout created in the course of plotting a `"trellis"` object. Each named component is a list of arguments to the grid function `[unit](../../grid/html/unit)` (`x`, `units`, and optionally `data`). Usually not of interest to the end-user, who should instead use the similiarly named component in the graphical settings, modifiable using `[trellis.par.set](trellis.par.get)`. `drop.unused.levels` A list of two components named `cond` and `data`, both logical flags. The flags indicate whether the unused levels of factors (conditioning variables and primary variables respectively) will be dropped, which is usually relevant when a subsetting operation is performed or an 'interaction' is created. See `<xyplot>` for more details. Note that this does not control dropping of levels of the 'groups' argument. `legend.bbox` A character string, either `"full"` or `"panel"`. This determines the interpretation of `x` and `y` when `space="inside"` in `key` (determining the legend; see `<xyplot>`): either the full figure region ('"full"'), or just the region that bounds the panels and strips ('"panel"'). `default.args` A list giving default values for various standard arguments: `as.table`, `aspect`, `between`, `skip`, `strip`, `xscale.components`, `yscale.components`, and `axis`. `highlight.gpar` A list giving arguments to `[gpar](../../grid/html/gpar)` used to highlight a viewport chosen using `[trellis.focus](interaction)`. `banking` The banking function. See `<banking>`. `axis.padding` List with components named `"numeric"` and `"factor"`, both scalar numbers. Panel limits are extended by this amount, to provide padding for numeric and factor scales respectively. The value for numeric is multiplicative, whereas factor is additive. `skip.boundary.labels` Numeric scalar between 0 and 1. Tick marks that are too close to the limits are not drawn unless explicitly requested. The limits are contracted by this proportion, and anything outside is skipped. `interaction.sep` The separator for creating interactions with the extended formula interface (see `<xyplot>`). `axis.units` List determining default units for axis components. Should not be of interest to the end-user. In addition, there is an option for the default prepanel and panel function for each high-level function; e.g., `panel.xyplot` and `prepanel.default.xyplot` for `<xyplot>`. The options for the others have similarly patterned names. ### Value `lattice.getOption` returns the value of a single component, whereas `lattice.options` always returns a list with one or more named components. When changing the values of components, the old values of the modified components are returned by `lattice.options`. If called without any arguments, the full list is returned. ### Author(s) Deepayan Sarkar [[email protected]](mailto:[email protected]) ### See Also `[options](../../base/html/options)`, `<trellis.device>`, `<trellis.par.get>`, `[Lattice](lattice)` ### Examples ``` names(lattice.options()) str(lattice.getOption("layout.widths"), max.level = 2) ``` r None `Lattice` Lattice Graphics --------------------------- ### Description The lattice add-on package is an implementation of Trellis graphics for **R**. It is a powerful and elegant high-level data visualization system with an emphasis on multivariate data. It is designed to meet most typical graphics needs with minimal tuning, but can also be easily extended to handle most nonstandard requirements. ### Details Trellis Graphics, originally developed for S and S-PLUS at the Bell Labs, is a framework for data visualization developed by R. A. Becker, W. S. Cleveland, et al, extending ideas presented in Cleveland's 1993 book *Visualizing Data*. The Lattice API is based on the original design in S, but extends it in many ways. The Lattice user interface primarily consists of several ‘high-level’ generic functions (listed below in the “See Also” section), each designed to create a particular type of display by default. Although the functions produce different output, they share many common features, reflected in several common arguments that affect the resulting displays in similar ways. These arguments are extensively (sometimes only) documented in the help page for `<xyplot>`, which also includes a discussion of the important topics of *conditioning* and control of the Trellis layout. Features specific to other high-level functions are documented in their respective help pages. Lattice employs an extensive system of user-controllable settings to determine the look and feel of the displays it produces. To learn how to use and customize the graphical parameters used by lattice, see `[trellis.par.set](trellis.par.get)`. For other settings, see `<lattice.options>`. The default graphical settings are (potentially) different for different graphical devices. To learn how to initialize new devices with the desired settings or change the settings of the current device, see `<trellis.device>`. It is usually unnecessary, but sometimes important to be able to plot multiple lattice plots on a single page. Such capabilities are described in the `<print.trellis>` help page. See `<update.trellis>` to learn about manipulating a `"trellis"` object. Tools to augment lattice plots after they are drawn (including `[locator](../../graphics/html/locator)`-like functionality) are described in the `[trellis.focus](interaction)` help page. The online documentation accompanying the package is complete, and effort has been made to present the help pages in a logical sequence, so that one can learn how to use lattice by reading the PDF reference manual available at <https://cran.r-project.org/package=lattice>. However, the format in which the online documentation is written and the breadth of topics covered necessarily makes it somewhat terse and less than ideal as a first introduction. For a more gentle introduction, a book on lattice is available as part of Springer's ‘Use R’ series; see the “References” section below. ### Note High-level lattice functions like `<xyplot>` are different from traditional **R** graphics functions in that they do not perform any plotting themselves. Instead, they return an object, of class `"trellis"`, which has to be then `[print](print.trellis)`-ed or `[plot](print.trellis)`-ted to create the actual plot. Due to **R**'s automatic printing rule, it is usually not necessary to explicitly carry out the second step, and lattice functions appear to behave like their traditional counterparts. However, the automatic plotting is suppressed when the high-level functions are called inside another function (most often `source`) or in other contexts where automatic printing is suppressed (e.g., `[for](../../base/html/control)` or `[while](../../base/html/control)` loops). In such situations, an explicit call to `print` or `plot` is required. The lattice package is based on the Grid graphics engine and requires the grid add-on package. One consquence of this is that it is not (readily) compatible with traditional **R** graphics tools. In particular, changing `par()` settings usually has no effect on Lattice plots; lattice provides its own interface for querying and modifying an extensive set of graphical and non-graphical settings. ### Author(s) Deepayan Sarkar [[email protected]](mailto:[email protected]) ### References Sarkar, Deepayan (2008) *Lattice: Multivariate Data Visualization with R*, Springer. ISBN: 978-0-387-75968-5 <http://lmdvr.r-forge.r-project.org/> Cleveland, William .S. (1993) *Visualizing Data*, Hobart Press, Summit, New Jersey. Becker, R. A. and Cleveland, W. S. and Shyu, M. J. (1996). “The Visual Design and Control of Trellis Display”, *Journal of Computational and Graphical Statistics*, **5(2)**, 123–155. Bell Lab's Trellis Page contains several documents outlining the use of Trellis graphics; these provide a holistic introduction to the Trellis paradigm: <http://web.archive.org/web/20081020164041/http://cm.bell-labs.com/cm/ms/departments/sia/project/trellis/display.writing.html> ### See Also The following is a list of high-level functions in the lattice package and their default displays. In all cases, the actual display is produced by the so-called “panel” function, which has a suitable default, but can be substituted by an user defined function to create customized displays. In many cases, the default panel function will itself have many optional arguments to customize its output. The default panel functions are named as “`panel.`” followed by the name of the corresponding high-level function; i.e., the default panel function for `<xyplot>` is `<panel.xyplot>`, the one for `<histogram>` is `<panel.histogram>`, etc. Each default panel function has a separate help page, linked from the help pages of the corresponding high-level function. Although documented separately, arguments to these panel functions can be supplied directly to the high-level functions, which will pass on the arguments appropriately. **Univariate:** `[barchart](xyplot)`: Bar plots. `[bwplot](xyplot)`: Box-and-whisker plots. `[densityplot](histogram)`: Kernel density estimates. `[dotplot](xyplot)`: Cleveland dot plots. `<histogram>`: Histograms. `<qqmath>`: Theretical quantile plots. `[stripplot](xyplot)`: One-dimensional scatterplots. **Bivariate:** `<qq>`: Quantile plots for comparing two distributions. `<xyplot>`: Scatterplots and time-series plots (and potentially a lot more). **Trivariate:** `<levelplot>`: Level plots (similar to `[image](../../graphics/html/image)` plots). `[contourplot](levelplot)`: Contour plots. `<cloud>`: Three-dimensional scatter plots. `[wireframe](cloud)`: Three-dimensional surface plots (similar to `[persp](../../graphics/html/persp)` plots). **Hypervariate:** `<splom>`: Scatterplot matrices. `[parallel](splom)`: Parallel coordinate plots. **Miscellaneous:** `<rfs>`: Residual and fitted value plots (also see `<oneway>`). `<tmd>`: Tukey Mean-Difference plots. In addition, there are several panel functions that do little by themselves, but can be useful components of custom panel functions. These are documented in `<panel.functions>`. Lattice also provides a collection of convenience functions that correspond to the traditional graphics primitives `[lines](../../graphics/html/lines)`, `[points](../../graphics/html/points)`, etc. These are implemented using Grid graphics, but try to be as close to the traditional versions as possible in terms of their argument list. These functions have names like `<llines>` or `[panel.lines](llines)` and are often useful when writing (or porting from S-PLUS code) nontrivial panel functions. Finally, many useful enhancements that extend the Lattice system are available in the latticeExtra package. ### Examples ``` ## Not run: ## Show brief history of changes to lattice, including ## a summary of new features. RShowDoc("NEWS", package = "lattice") ## End(Not run) ``` r None `panel.dotplot` Default Panel Function for dotplot --------------------------------------------------- ### Description Default panel function for `dotplot`. ### Usage ``` panel.dotplot(x, y, horizontal = TRUE, pch, col, lty, lwd, col.line, levels.fos, groups = NULL, ..., identifier = "dotplot") ``` ### Arguments | | | | --- | --- | | `x,y` | variables to be plotted in the panel. Typically y is the ‘factor’ | | `horizontal` | logical. If FALSE, the plot is ‘transposed’ in the sense that the behaviours of x and y are switched. x is now the ‘factor’. Interpretation of other arguments change accordingly. See documentation of `[bwplot](xyplot)` for a fuller explanation. | | `pch, col, lty, lwd, col.line` | graphical parameters | | `levels.fos` | locations where reference lines will be drawn | | `groups` | grouping variable (affects graphical parameters) | | `...` | extra parameters, passed to `panel.xyplot` which is responsible for drawing the foreground points (`panel.dotplot` only draws the background reference lines). | | `identifier` | A character string that is prepended to the names of grobs that are created by this panel function. | ### Details Creates (possibly grouped) Dotplot of `x` against `y` or vice versa ### Author(s) Deepayan Sarkar [[email protected]](mailto:[email protected]) ### See Also `[dotplot](xyplot)` r None `qqmath` Q-Q Plot with Theoretical Distribution ------------------------------------------------ ### Description Draw quantile-Quantile plots of a sample against a theoretical distribution, possibly conditioned on other variables. ### Usage ``` qqmath(x, data, ...) ## S3 method for class 'formula' qqmath(x, data, allow.multiple = is.null(groups) || outer, outer = !is.null(groups), distribution = qnorm, f.value = NULL, auto.key = FALSE, aspect = "fill", panel = lattice.getOption("panel.qqmath"), prepanel = NULL, scales, strip, groups, xlab, xlim, ylab, ylim, drop.unused.levels = lattice.getOption("drop.unused.levels"), ..., lattice.options = NULL, default.scales = list(), default.prepanel = lattice.getOption("prepanel.default.qqmath"), subscripts, subset) ## S3 method for class 'numeric' qqmath(x, data = NULL, ylab, ...) ``` ### Arguments | | | | --- | --- | | `x` | The object on which method dispatch is carried out. For the `"formula"` method, `x` should be a formula of the form `~ x | g1 * g2 * ...`, where `x` should be a numeric variable. For the `"numeric"` method, `x` should be a numeric vector. | | `data` | For the `formula` method, an optional data source (usually a data frame) in which variables are to be evaluated (see `<xyplot>` for details). `data` should not be specified for the other methods, and is ignored with a warning if it is. | | `distribution` | A quantile function that takes a vector of probabilities as argument and produces the corresponding quantiles from a theoretical distribution. Possible values are `[qnorm](../../stats/html/normal)`, `[qunif](../../stats/html/uniform)`, etc. Distributions with other required arguments need to be provided as user-defined functions (see example with `[qt](../../stats/html/tdist)`). | | `f.value` | An optional numeric vector of probabilities, quantiles corresponding to which should be plotted. This can also be a function of a single integer (representing sample size) that returns such a numeric vector. A typical value for this argument is the function `ppoints`, which is also the S-PLUS default. If specified, the probabilities generated by this function is used for the plotted quantiles, through the `[quantile](../../stats/html/quantile)` function for the sample, and the function specified as the `distribution` argument for the theoretical distribution. `f.value` defaults to `NULL`, which has the effect of using `ppoints` for the quantiles of the theoretical distribution, but the exact data values for the sample. This is similar to what happens for `qqnorm`, but different from the S-PLUS default of `f.value=ppoints`. For large `x`, this argument can be used to restrict the number of points plotted. See also the `tails.n` argument in `<panel.qqmath>`. | | `panel` | A function, called once for each panel, that uses the packet (subset of panel variables) corresponding to the panel to create a display. The default panel function `<panel.qqmath>` is documented separately, and has arguments that can be used to customize its output in various ways. Such arguments can usually be directly supplied to the high-level function. | | `allow.multiple, outer` | See `<xyplot>`. | | `auto.key` | See `<xyplot>`. | | `aspect` | See `<xyplot>`. | | `prepanel` | See `<xyplot>`. | | `scales` | See `<xyplot>`. | | `strip` | See `<xyplot>`. | | `groups` | See `<xyplot>`. | | `xlab, ylab` | See `<xyplot>`. | | `xlim, ylim` | See `<xyplot>`. | | `drop.unused.levels` | See `<xyplot>`. | | `lattice.options` | See `<xyplot>`. | | `default.scales` | See `<xyplot>`. | | `subscripts` | See `<xyplot>`. | | `subset` | See `<xyplot>`. | | `default.prepanel` | Fallback prepanel function. See `<xyplot>`. | | `...` | Further arguments. See corresponding entry in `<xyplot>` for non-trivial details. | ### Details `qqmath` produces Q-Q plots of the given sample against a theoretical distribution. The default behaviour of `qqmath` is different from the corresponding S-PLUS function, but is similar to `qqnorm`. See the entry for `f.value` for specifics. The implementation details are also different from S-PLUS. In particular, all the important calculations are done by the panel (and prepanel function) and not `qqmath` itself. In fact, both the arguments `distribution` and `f.value` are passed unchanged to the panel and prepanel function. This allows, among other things, display of grouped Q-Q plots, which are often useful. See the help page for `<panel.qqmath>` for further details. This and all other high level Trellis functions have several arguments in common. These are extensively documented only in the help page for `<xyplot>`, which should be consulted to learn more detailed usage. ### Value An object of class `"trellis"`. The `[update](update.trellis)` method can be used to update components of the object and the `[print](print.trellis)` method (usually called by default) will plot it on an appropriate plotting device. ### Author(s) Deepayan Sarkar [[email protected]](mailto:[email protected]) ### See Also `<xyplot>`, `<panel.qqmath>`, `<panel.qqmathline>`, `[prepanel.qqmathline](prepanel.functions)`, `[Lattice](lattice)`, `[quantile](../../stats/html/quantile)` ### Examples ``` qqmath(~ rnorm(100), distribution = function(p) qt(p, df = 10)) qqmath(~ height | voice.part, aspect = "xy", data = singer, prepanel = prepanel.qqmathline, panel = function(x, ...) { panel.qqmathline(x, ...) panel.qqmath(x, ...) }) vp.comb <- factor(sapply(strsplit(as.character(singer$voice.part), split = " "), "[", 1), levels = c("Bass", "Tenor", "Alto", "Soprano")) vp.group <- factor(sapply(strsplit(as.character(singer$voice.part), split = " "), "[", 2)) qqmath(~ height | vp.comb, data = singer, groups = vp.group, auto.key = list(space = "right"), aspect = "xy", prepanel = prepanel.qqmathline, panel = function(x, ...) { panel.qqmathline(x, ...) panel.qqmath(x, ...) }) ```
programming_docs
r None `panel.axis` Panel Function for Drawing Axis Ticks and Labels -------------------------------------------------------------- ### Description `panel.axis` is the function used by lattice to draw axes. It is typically not used by users, except those wishing to create advanced annotation. Keep in mind issues of clipping when trying to use it as part of the panel function. `current.panel.limits` can be used to retrieve a panel's x and y limits. ### Usage ``` panel.axis(side = c("bottom", "left", "top", "right"), at, labels = TRUE, draw.labels = TRUE, check.overlap = FALSE, outside = FALSE, ticks = TRUE, half = !outside, which.half, tck = as.numeric(ticks), rot = if (is.logical(labels)) 0 else c(90, 0), text.col, text.alpha, text.cex, text.font, text.fontfamily, text.fontface, text.lineheight, line.col, line.lty, line.lwd, line.alpha) current.panel.limits(unit = "native") ``` ### Arguments | | | | --- | --- | | `side` | A character string indicating which side axes are to be drawn on. Partial specification is allowed. | | `at` | Numeric vector giving location of labels. Can be missing, in which case they are computed from the native coordinates of the active viewport. | | `labels` | The labels to go along with `at`, as a character vector or a vector of expressions. This only makes sense provided `at` is explicitly specified, as otherwise the provided labels may not match the computed `at` values. Alternatively, `labels` can be a logical flag: If `TRUE`, the labels are derived from `at`, otherwise, labels are empty. | | `draw.labels` | A logical indicating whether labels are to be drawn. | | `check.overlap` | A logical, whether to check for overlapping of labels. This also has the effect of removing `at` values that are ‘too close’ to the limits. | | `outside` | A logical flag, indicating whether to draw the labels outside the panel or inside. Note that `outside=TRUE` will only have a visible effect if clipping is disabled for the viewport (panel). | | `ticks` | Logical flag, whether to draw the tickmarks. | | `half` | Logical flag, indicating whether only around half the scales will be drawn for each side. This is primarily used for axis labeling in `<splom>`. | | `which.half` | Character string, either `"lower"` or `"upper"`, indicating which half is to be used for tick locations if `half = TRUE`. Defaults to whichever is suitable for `<splom>`. | | `tck` | A numeric scalar multiplier for tick length. Can be negative, in which case the ticks point inwards. | | `rot` | Rotation angle(s) for labels in degrees. Can be a vector of length 2 for x- and y-axes. | | `text.col` | Color for the axis label text. See `[gpar](../../grid/html/gpar)` for more details on this and the other graphical parameters listed below. | | `text.alpha` | Alpha-transparency value for the axis label text. | | `text.cex` | Size multiplier for the axis label text. | | `text.font, text.fontfamily, text.fontface` | Font for the axis label text. | | `text.lineheight` | Line height for the axis label text. | | `line.col` | Color for the axis label text. | | `line.lty` | Color for the axis. | | `line.lwd` | Color for the axis. | | `line.alpha` | Alpha-transparency value for the axis. | | `unit` | Which grid `[unit](../../grid/html/unit)` the values should be in. | ### Details `panel.axis` can draw axis tick marks inside or outside a panel (more precisely, a grid viewport). It honours the (native) axis scales. Used in `<panel.pairs>` for `<splom>`, as well as for all the usual axis drawing by the print method for `"trellis"` objects. It can also be used to enhance plots ‘after the fact’ by adding axes. ### Value `current.panel.limits` returns a list with components `xlim` and `ylim`, which are both numeric vectors of length 2, giving the scales of the current panel (viewport). The values correspond to the unit system specified by `[unit](../../grid/html/unit)`, by default `"native"`. ### Author(s) Deepayan Sarkar [[email protected]](mailto:[email protected]) ### See Also `[Lattice](lattice)`, `<xyplot>`, `[trellis.focus](interaction)`, `[unit](../../grid/html/unit)` r None `USMortality` Mortality Rates in US by Cause and Gender -------------------------------------------------------- ### Description These datasets record mortality rates across all ages in the USA by cause of death, sex, and rural/urban status, 2011–2013. The two datasets represent the national aggregate rates and the region-wise rates for each administrative region under the Department of Health and Human Services (HHS). ### Usage ``` USMortality USRegionalMortality ``` ### Format `USRegionalMortality` is a data frame with 400 observations on the following 6 variables. `Region` A factor specifying HHS Region. See details. `Status` A factor with levels `Rural` and `Urban` `Sex` A factor with levels `Female` and `Male` `Cause` Cause of death. A factor with levels `Alzheimers`, `Cancer`, `Cerebrovascular diseases`, `Diabetes`, `Flu and pneumonia`, `Heart disease`, `Lower respiratory`, `Nephritis`, `Suicide`, and `Unintentional injuries` `Rate` Age-adjusted death rate per 100,000 population `SE` Standard error for the rate `USMortality` is a data frame with 40 observations, containing the same variables with the exception of `Region`. ### Details The region-wise data give estimated rates separately for each of 10 HHS regions. The location of the regional offices and their coverage area, available from <https://www.hhs.gov/about/agencies/iea/regional-offices/index.html>, is given below. HHS Region 01 - Boston: Connecticut, Maine, Massachusetts, New Hampshire, Rhode Island, and Vermont HHS Region 02 - New York: New Jersey, New York, Puerto Rico, and the Virgin Islands HHS Region 03 - Philadelphia: Delaware, District of Columbia, Maryland, Pennsylvania, Virginia, and West Virginia HHS Region 04 - Atlanta: Alabama, Florida, Georgia, Kentucky, Mississippi, North Carolina, South Carolina, and Tennessee HHS Region 05 - Chicago: Illinois, Indiana, Michigan, Minnesota, Ohio, and Wisconsin HHS Region 06 - Dallas: Arkansas, Louisiana, New Mexico, Oklahoma, and Texas HHS Region 07 - Kansas City: Iowa, Kansas, Missouri, and Nebraska HHS Region 08 - Denver: Colorado, Montana, North Dakota, South Dakota, Utah, and Wyoming HHS Region 09 - San Francisco: Arizona, California, Hawaii, Nevada, American Samoa, Commonwealth of the Northern Mariana Islands, Federated States of Micronesia, Guam, Marshall Islands, and Republic of Palau HHS Region 10 - Seattle: Alaska, Idaho, Oregon, and Washington ### References Rural Health Reform Policy Research Center. \_Exploring Rural and Urban Mortality Differences\_, August 2015 Bethesda, MD. <https://ruralhealth.und.edu/projects/health-reform-policy-research-center/rural-urban-mortality> ### Examples ``` dotplot(reorder(Cause, Rate) ~ Rate | Status, data = USMortality, groups = Sex, par.settings = simpleTheme(pch = 16), auto.key = list(columns = 2), scales = list(x = list(log = TRUE, equispaced.log = FALSE))) dotplot(reorder(Cause, Rate):Sex ~ Rate | Status, data = USRegionalMortality, groups = Sex, scales = list(x = list(log = TRUE, equispaced.log = FALSE))) ``` r None `print.trellis` Plot and Summarize Trellis Objects --------------------------------------------------- ### Description The `print` and `plot` methods produce a graph from a `"trellis"` object. The `print` method is necessary for automatic plotting. `plot` method is essentially an alias, provided for convenience. The `summary` method gives a textual summary of the object. `dim` and `dimnames` describe the cross-tabulation induced by conditioning. `panel.error` is the default handler used when an error occurs while executing the panel function. ### Usage ``` ## S3 method for class 'trellis' plot(x, position, split, more = FALSE, newpage = TRUE, packet.panel = packet.panel.default, draw.in = NULL, panel.height = lattice.getOption("layout.heights")$panel, panel.width = lattice.getOption("layout.widths")$panel, save.object = lattice.getOption("save.object"), panel.error = lattice.getOption("panel.error"), prefix, ...) ## S3 method for class 'trellis' print(x, ...) ## S3 method for class 'trellis' summary(object, ...) ## S3 method for class 'trellis' dim(x) ## S3 method for class 'trellis' dimnames(x) panel.error(e) ``` ### Arguments | | | | --- | --- | | `x, object` | an object of class `"trellis"` | | `position` | a vector of 4 numbers, typically c(xmin, ymin, xmax, ymax) that give the lower-left and upper-right corners of a rectangle in which the Trellis plot of x is to be positioned. The coordinate system for this rectangle is [0-1] in both the x and y directions. | | `split` | a vector of 4 integers, c(x,y,nx,ny) , that says to position the current plot at the x,y position in a regular array of nx by ny plots. (Note: this has origin at top left) | | `more` | A logical specifying whether more plots will follow on this page. | | `newpage` | A logical specifying whether the plot should be on a new page. This option is specific to lattice, and is useful for including lattice plots in an arbitrary grid viewport (see the details section). | | `packet.panel` | a function that determines which packet (data subset) is plotted in which panel. Panels are always drawn in an order such that columns vary the fastest, then rows and then pages. This function determines, given the column, row and page and other relevant information, the packet (if any) which should be used in that panel. By default, the association is determnined by matching panel order with packet order, which is determined by varying the first conditioning variable the fastest, then the second, and so on. This association rule is encoded in the default, namely the function `<packet.panel.default>`, whose help page details the arguments supplied to whichever function is specified as the `packet.panel` argument. | | `draw.in` | An optional (grid) viewport (used as the `name` argument in `downViewport`) in which the plot is to be drawn. If specified, the `newpage` argument is ignored. This feature is not well-tested. | | `panel.width, panel.height` | lists with 2 components, that should be valid `x` and `units` arguments to `unit()` (the `data` argument cannot be specified currently, but can be considered for addition if needed). The resulting `unit` object will be the width/height of each panel in the Lattice plot. These arguments can be used to explicitly control the dimensions of the panel, rather than letting them expand to maximize available space. Vector widths are allowed, and can specify unequal lengths across rows or columns. Note that this option should not be used in conjunction with non-default values of the `aspect` argument in the original high level call (no error will be produced, but the resulting behaviour is undefined). | | `save.object` | logical, specifying whether the object being printed is to be saved. The last object thus saved can be subsequently retrieved. This is an experimental feature that should allow access to a panel's data after the plot is done, making it possible to enhance the plot after the fact. This also allows the user to invoke the `update` method on the current plot, even if it was not assigned to a variable explicitly. For more details, see `[trellis.focus](interaction)`. | | `panel.error` | a function, or a character string naming a function, that is to be executed when an error occurs during the execution of the panel function. The error is caught (using `[tryCatch](../../base/html/conditions)`) and supplied as the only argument to `panel.error`. The default behaviour (implemented as the `panel.error` function) is to print the corresponding error message in the panel and continue. To stop execution on error, use `panel.error = stop`. Normal error recovery and debugging tools are unhelpful when `tryCatch` is used. `tryCatch` can be completely bypassed by setting `panel.error` to NULL. | | `prefix` | A character string acting as a prefix identifying the plot of a `"trellis"` object, primarily used in constructing viewport and grob names, to distinguish similar viewports if a page contains multiple plots. The default is based on the serial number of the current plot on the current page (specifically, `"plot_01"`, `"plot_02"`, etc.). If supplied explicitly, this must be a valid **R** symbol name (briefly, it must start with a letter or a period followed by a letter) and must not contain the grid path separator (currently `"::"`). | | `e` | an error condition caught by `[tryCatch](../../base/html/conditions)` | | `...` | extra arguments, ignored by the `print` method. All arguments to the `plot` method are passed on to the `print` method. | ### Details This is the default print method for objects of class `"trellis"`, produced by calls to functions like `xyplot`, `bwplot` etc. It is usually called automatically when a trellis object is produced. It can also be called explicitly to control plot positioning by means of the arguments `split` and `position`. When `newpage = FALSE`, the current grid viewport is treated as the plotting area, making it possible to embed a Lattice plot inside an arbitrary grid viewport. The `draw.in` argument provides an alternative mechanism that may be simpler to use. The print method uses the information in `x` (the object to be printed) to produce a display using the Grid graphics engine. At the heart of the plot is a grid layout, of which the entries of most interest to the user are the ones containing the display panels. Unlike in older versions of Lattice (and Grid), the grid display tree is retained after the plot is produced, making it possible to access individual viewport locations and make additions to the plot. For more details and a lattice level interface to these viewports, see `[trellis.focus](interaction)`. ### Note Unlike S-PLUS, trying to position a multipage display (using `position` and/or `split`) will mess things up. ### Author(s) Deepayan Sarkar [[email protected]](mailto:[email protected]) ### See Also `[Lattice](lattice)`, `[unit](../../grid/html/unit)`, `<update.trellis>`, `[trellis.focus](interaction)`, `<packet.panel.default>` ### Examples ``` p11 <- histogram( ~ height | voice.part, data = singer, xlab="Height") p12 <- densityplot( ~ height | voice.part, data = singer, xlab = "Height") p2 <- histogram( ~ height, data = singer, xlab = "Height") ## simple positioning by split print(p11, split=c(1,1,1,2), more=TRUE) print(p2, split=c(1,2,1,2)) ## Combining split and position: print(p11, position = c(0,0,.75,.75), split=c(1,1,1,2), more=TRUE) print(p12, position = c(0,0,.75,.75), split=c(1,2,1,2), more=TRUE) print(p2, position = c(.5,.75,1,1), more=FALSE) ## Using seekViewport ## repeat same plot, with different polynomial fits in each panel xyplot(Armed.Forces ~ Year, longley, index.cond = list(rep(1, 6)), layout = c(3, 2), panel = function(x, y, ...) { panel.xyplot(x, y, ...) fm <- lm(y ~ poly(x, panel.number())) llines(x, predict(fm)) }) ## Not run: grid::seekViewport(trellis.vpname("panel", 1, 1)) cat("Click somewhere inside the first panel:\n") ltext(grid::grid.locator(), lab = "linear") ## End(Not run) grid::seekViewport(trellis.vpname("panel", 1, 1)) grid::grid.text("linear") grid::seekViewport(trellis.vpname("panel", 2, 1)) grid::grid.text("quadratic") grid::seekViewport(trellis.vpname("panel", 3, 1)) grid::grid.text("cubic") grid::seekViewport(trellis.vpname("panel", 1, 2)) grid::grid.text("degree 4") grid::seekViewport(trellis.vpname("panel", 2, 2)) grid::grid.text("degree 5") grid::seekViewport(trellis.vpname("panel", 3, 2)) grid::grid.text("degree 6") ``` r None `panel.spline` Panel Function to Add a Spline Smooth ----------------------------------------------------- ### Description A predefined panel function that can be used to add a spline smooth based on the provided data. ### Usage ``` panel.spline(x, y, npoints = 101, lwd = plot.line$lwd, lty = plot.line$lty, col, col.line = plot.line$col, type, horizontal = FALSE, ..., keep.data = FALSE, identifier = "spline") ``` ### Arguments | | | | --- | --- | | `x, y` | Variables defining the data to be used. | | `npoints` | The number of equally spaced points within the range of the predictor at which the fitted model is evaluated for plotting. | | `lwd, lty, col, col.line` | Graphical parameters for the added line. `col.line` overrides `col`. | | `type` | Ignored. The argument is present only to make sure that an explicitly specified `type` argument (perhaps meant for another function) does not affect the display. | | `horizontal` | A logical flag controlling which variable is to be treated as the predictor (by default `x`) and which as the response (by default `y`). If `TRUE`, the plot is ‘transposed’ in the sense that `y` becomes the predictor and `x` the response. (The name ‘horizontal’ may seem an odd choice for this argument, and originates from similar usage in `[bwplot](xyplot)`). | | `keep.data` | Passed on to `[smooth.spline](../../stats/html/smooth.spline)`. The default here (`FALSE`) is different, and results in the original data not being retained in the fitted spline model. It may be useful to set this to `TRUE` if the return value of `panel.spline`, which is the fitted model as returned by `[smooth.spline](../../stats/html/smooth.spline)`, is to be used for subsequent computations. | | `...` | Extra arguments, passed on to `[smooth.spline](../../stats/html/smooth.spline)` and `[panel.lines](llines)` as appropriate. | | `identifier` | A character string that is prepended to the names of grobs that are created by this panel function. | ### Value The fitted model as returned by `[smooth.spline](../../stats/html/smooth.spline)`. ### Author(s) Deepayan Sarkar [[email protected]](mailto:[email protected]) ### See Also [Lattice](lattice), `[smooth.spline](../../stats/html/scatter.smooth)`, `[prepanel.spline](prepanel.functions)` r None `levelplot` Level plots and contour plots ------------------------------------------ ### Description Draws false color level plots and contour plots. ### Usage ``` levelplot(x, data, ...) contourplot(x, data, ...) ## S3 method for class 'formula' levelplot(x, data, allow.multiple = is.null(groups) || outer, outer = TRUE, aspect = "fill", panel = if (useRaster) lattice.getOption("panel.levelplot.raster") else lattice.getOption("panel.levelplot"), prepanel = NULL, scales = list(), strip = TRUE, groups = NULL, xlab, xlim, ylab, ylim, at, cuts = 15, pretty = FALSE, region = TRUE, drop.unused.levels = lattice.getOption("drop.unused.levels"), ..., useRaster = FALSE, lattice.options = NULL, default.scales = list(), default.prepanel = lattice.getOption("prepanel.default.levelplot"), colorkey = region, col.regions, alpha.regions, subset = TRUE) ## S3 method for class 'formula' contourplot(x, data, panel = lattice.getOption("panel.contourplot"), default.prepanel = lattice.getOption("prepanel.default.contourplot"), cuts = 7, labels = TRUE, contour = TRUE, pretty = TRUE, region = FALSE, ...) ## S3 method for class 'table' levelplot(x, data = NULL, aspect = "iso", ..., xlim, ylim) ## S3 method for class 'table' contourplot(x, data = NULL, aspect = "iso", ..., xlim, ylim) ## S3 method for class 'matrix' levelplot(x, data = NULL, aspect = "iso", ..., xlim, ylim, row.values = seq_len(nrow(x)), column.values = seq_len(ncol(x))) ## S3 method for class 'matrix' contourplot(x, data = NULL, aspect = "iso", ..., xlim, ylim, row.values = seq_len(nrow(x)), column.values = seq_len(ncol(x))) ## S3 method for class 'array' levelplot(x, data = NULL, ...) ## S3 method for class 'array' contourplot(x, data = NULL, ...) ``` ### Arguments | | | | --- | --- | | `x` | for the `formula` method, a formula of the form `z ~ x * y | g1 * g2 * ...`, where `z` is a numeric response, and `x`, `y` are numeric values evaluated on a rectangular grid. `g1, g2, ...` are optional conditional variables, and must be either factors or shingles if present. Calculations are based on the assumption that all x and y values are evaluated on a grid (defined by their unique values). The function will not return an error if this is not true, but the display might not be meaningful. However, the x and y values need not be equally spaced. Both `levelplot` and `wireframe` have methods for `matrix`, `array`, and `table` objects, in which case `x` provides the `z` vector described above, while its rows and columns are interpreted as the `x` and `y` vectors respectively. This is similar to the form used in `filled.contour` and `image`. For higher-dimensional arrays and tables, further dimensions are used as conditioning variables. Note that the dimnames may be duplicated; this is handled by calling `[make.unique](../../base/html/make.unique)` to make the names unique (although the original labels are used for the x- and y-axes). | | `data` | For the `formula` methods, an optional data frame in which variables in the formula (as well as `groups` and `subset`, if any) are to be evaluated. Usually ignored with a warning in other cases. | | `row.values, column.values` | Optional vectors of values that define the grid when `x` is a matrix. `row.values` and `column.values` must have the same lengths as `nrow(x)` and `ncol(x)` respectively. By default, row and column numbers. | | `panel` | panel function used to create the display, as described in `<xyplot>` | | `aspect` | For the `matrix` methods, the default aspect ratio is chosen to make each cell square. The usual default is `aspect="fill"`, as described in `<xyplot>`. | | `at` | A numeric vector giving breakpoints along the range of `z`. Contours (if any) will be drawn at these heights, and the regions in between would be colored using `col.regions`. In the latter case, values outside the range of `at` will not be drawn at all. This serves as a way to limit the range of the data shown, similar to what a `zlim` argument might have been used for. However, this also means that when supplying `at` explicitly, one has to be careful to include values outside the range of `z` to ensure that all the data are shown. `at` can have length one only if `region=FALSE`. | | `col.regions` | color vector to be used if regions is TRUE. The general idea is that this should be a color vector of moderately large length (longer than the number of regions. By default this is 100). It is expected that this vector would be gradually varying in color (so that nearby colors would be similar). When the colors are actually chosen, they are chosen to be equally spaced along this vector. When there are more regions than colors in `col.regions`, the colors are recycled. The actual color assignment is performed by `<level.colors>`, which is documented separately. | | `alpha.regions` | Numeric, specifying alpha transparency (works only on some devices) | | `colorkey` | A logical flag specifying whether a colorkey is to be drawn alongside the plot, or a list describing the colorkey. The list may contain the following components: `space`: location of the colorkey, can be one of `"left"`, `"right"`, `"top"` and `"bottom"`. Defaults to `"right"`. `x`, `y`: location, currently unused `col`: A color ramp specification, as in the `col.regions` argument in `<level.colors>` `at`: A numeric vector specifying where the colors change. must be of length 1 more than the col vector. `tri.lower`, `tri.upper`: Logical or numeric controlling whether the first and last intervals should be triangular instead of rectangular. With the default value (`NA`), this happens only if the corresponding extreme `at` values are `-Inf` or `Inf` respectively, and the triangles occupy 5% of the total length of the color key. If numeric and between 0 and 0.25, these give the corresponding fraction, which is again 5% when specified as `TRUE`. `labels`: A character vector for labelling the `at` values, or more commonly, a list describing characteristics of the labels. This list may include components `labels`, `at`, `cex`, `col`, `rot`, `font`, `fontface` and `fontfamily`. `title`: Usually a character vector or expression providing a title for the colorkey, or a list controlling the title in further detail, or an arbitrary `"grob"`. For details of how the list form is interpreted, see the entry for `main` in `<xyplot>`; generally speaking, the actual label should be specified as the `label` component (which may be unnamed if it is the first component), and the remaining arguments are used as appropriate in a call to `[textGrob](../../grid/html/grid.text)`. Further control of the placement of the title is possible through the component `title.control`. In particular, if a `rot` component is not specified, its default depends on the value of `title.control$side` (0 for top or bottom, and 90 for left or right). `title` defaults to `NULL`, which means no title is drawn. `title`: A list providing control over the placement of a title, if specified. Currently two components are honoured: `side` can take values `"top"`, `"bottom"`, `"left"`, and `"right"`, and specifies the side of the colorkey on which the title is to be placed. Defaults to the value of the `"space"` component. `padding` is a multiplier for the default amount of padding between the title and the colorkey. `tick.number`: The approximate number of ticks desired. `tck`: A (scalar) multipler for tick lengths. `corner`: Interacts with x, y; currently unimplemented `width`: The width of the key `height`: The length of key as a fraction of the appropriate side of plot. `raster`: A logical flag indicating whether the colorkey should be rendered as a raster image using `[grid.raster](../../grid/html/grid.raster)`. See also `[panel.levelplot.raster](panel.levelplot)`. `interpolate`: Logical flag, passed to `[rasterGrob](../../grid/html/grid.raster)` when `raster=TRUE`. `axis.line`: A list giving graphical parameters for the color key boundary and tick marks. Defaults to `trellis.par.get("axis.line")`. `axis.text`: A list giving graphical parameters for the tick mark labels on the color key. Defaults to `trellis.par.get("axis.text")`. | | `contour` | A logical flag, indicating whether to draw contour lines. | | `cuts` | The number of levels the range of `z` would be divided into. | | `labels` | Typically a logical indicating whether contour lines should be labelled, but other possibilities for more sophisticated control exists. Details are documented in the help page for `<panel.levelplot>`, to which this argument is passed on unchanged. That help page also documents the `label.style` argument, which affects how the labels are rendered. | | `pretty` | A logical flag, indicating whether to use pretty cut locations and labels. | | `region` | A logical flag, indicating whether regions between contour lines should be filled as in a level plot. | | `allow.multiple, outer, prepanel, scales, strip, groups, xlab, xlim, ylab, ylim, drop.unused.levels, lattice.options, default.scales, subset` | These arguments are described in the help page for `<xyplot>`. | | `default.prepanel` | Fallback prepanel function. See `<xyplot>`. | | `...` | Further arguments may be supplied. Some are processed by `levelplot` or `contourplot`, and those that are unrecognized are passed on to the panel function. | | `useRaster` | A logical flag indicating whether raster representations should be used, both for the false color image and the color key (if present). Effectively, setting this to `TRUE` changes the default panel function from `<panel.levelplot>` to `[panel.levelplot.raster](panel.levelplot)`, and sets the default value of `colorkey$raster` to `TRUE`. Note that `[panel.levelplot.raster](panel.levelplot)` provides only a subset of the features of `<panel.levelplot>`, but setting `useRaster=TRUE` will not check whether any of the additional features have been requested. Not all devices support raster images. For devices that appear to lack support, `useRaster=TRUE` will be ignored with a warning. | ### Details These and all other high level Trellis functions have several arguments in common. These are extensively documented only in the help page for `xyplot`, which should be consulted to learn more detailed usage. Other useful arguments are mentioned in the help page for the default panel function `<panel.levelplot>` (these are formally arguments to the panel function, but can be specified in the high level calls directly). ### Value An object of class `"trellis"`. The `[update](update.trellis)` method can be used to update components of the object and the `[print](print.trellis)` method (usually called by default) will plot it on an appropriate plotting device. ### Author(s) Deepayan Sarkar [[email protected]](mailto:[email protected]) ### References Sarkar, Deepayan (2008) *Lattice: Multivariate Data Visualization with R*, Springer. <http://lmdvr.r-forge.r-project.org/> ### See Also `<xyplot>`, `[Lattice](lattice)`, `<panel.levelplot>` ### Examples ``` x <- seq(pi/4, 5 * pi, length.out = 100) y <- seq(pi/4, 5 * pi, length.out = 100) r <- as.vector(sqrt(outer(x^2, y^2, "+"))) grid <- expand.grid(x=x, y=y) grid$z <- cos(r^2) * exp(-r/(pi^3)) levelplot(z ~ x * y, grid, cuts = 50, scales=list(log="e"), xlab="", ylab="", main="Weird Function", sub="with log scales", colorkey = FALSE, region = TRUE) ## triangular end-points in color key, with a title levelplot(z ~ x * y, grid, col.regions = topo.colors(10), at = c(-Inf, seq(-0.8, 0.8, by = 0.2), Inf)) #S-PLUS example require(stats) attach(environmental) ozo.m <- loess((ozone^(1/3)) ~ wind * temperature * radiation, parametric = c("radiation", "wind"), span = 1, degree = 2) w.marginal <- seq(min(wind), max(wind), length.out = 50) t.marginal <- seq(min(temperature), max(temperature), length.out = 50) r.marginal <- seq(min(radiation), max(radiation), length.out = 4) wtr.marginal <- list(wind = w.marginal, temperature = t.marginal, radiation = r.marginal) grid <- expand.grid(wtr.marginal) grid[, "fit"] <- c(predict(ozo.m, grid)) contourplot(fit ~ wind * temperature | radiation, data = grid, cuts = 10, region = TRUE, xlab = "Wind Speed (mph)", ylab = "Temperature (F)", main = "Cube Root Ozone (cube root ppb)") detach() ```
programming_docs
r None `panel.violin` Panel Function to create Violin Plots ----------------------------------------------------- ### Description This is a panel function that can create a violin plot. It is typically used in a high-level call to `bwplot`. ### Usage ``` panel.violin(x, y, box.ratio = 1, box.width, horizontal = TRUE, alpha, border, lty, lwd, col, varwidth = FALSE, bw, adjust, kernel, window, width, n = 50, from, to, cut, na.rm, ..., identifier = "violin") ``` ### Arguments | | | | --- | --- | | `x, y` | numeric vector or factor. Violin plots are drawn for each unique value of `y` (`x`) if `horizontal` is `TRUE` (`FALSE`) | | `box.ratio` | ratio of the thickness of each violin and inter violin space | | `box.width` | thickness of the violins in absolute units; overrides `box.ratio`. Useful for specifying thickness when the categorical variable is not a factor, as use of `box.ratio` alone cannot achieve a thickness greater than 1. | | `horizontal` | logical. If FALSE, the plot is ‘transposed’ in the sense that the behaviours of `x` and `y` are switched. `x` is now the ‘factor’. See documentation of `[bwplot](xyplot)` for a fuller explanation. | | `alpha, border, lty, lwd, col` | graphical parameters controlling the violin. Defaults are taken from the `"plot.polygon"` settings. | | `varwidth` | logical. If `FALSE`, the densities are scaled separately for each group, so that the maximum value of the density reaches the limit of the allocated space for each violin (as determined by `box.ratio`). If `TRUE`, densities across violins will have comparable scale. | | `bw, adjust, kernel, window, width, n, from, to, cut, na.rm` | arguments to `[density](../../stats/html/density)`, passed on as appropriate | | `...` | arguments passed on to `density`. | | `identifier` | A character string that is prepended to the names of grobs that are created by this panel function. | ### Details Creates Violin plot of `x` for every level of `y`. Note that most arguments controlling the display can be supplied to the high-level (typically `bwplot`) call directly. ### Author(s) Deepayan Sarkar [[email protected]](mailto:[email protected]) ### See Also `[bwplot](xyplot)`, `[density](../../stats/html/density)` ### Examples ``` bwplot(voice.part ~ height, singer, panel = function(..., box.ratio) { panel.violin(..., col = "transparent", varwidth = FALSE, box.ratio = box.ratio) panel.bwplot(..., fill = NULL, box.ratio = .1) } ) ``` r None `panel.densityplot` Default Panel Function for densityplot ----------------------------------------------------------- ### Description This is the default panel function for `densityplot`. ### Usage ``` panel.densityplot(x, darg, plot.points = "jitter", ref = FALSE, groups = NULL, weights = NULL, jitter.amount, type, ..., identifier = "density") ``` ### Arguments | | | | --- | --- | | `x` | data points for which density is to be estimated | | `darg` | list of arguments to be passed to the `density` function. Typically, this should be a list with zero or more of the following components : `bw`, `adjust`, `kernel`, `window`, `width`, `give.Rkern`, `n`, `from`, `to`, `cut`, `na.rm` (see `[density](../../stats/html/density)` for details) | | `plot.points` | logical specifying whether or not the data points should be plotted along with the estimated density. Alternatively, a character string specifying how the points should be plotted. Meaningful values are `"rug"`, in which case `[panel.rug](panel.functions)` is used to plot a ‘rug’, and `"jitter"`, in which case the points are jittered vertically to better distinguish overlapping points. | | `ref` | logical, whether to draw x-axis | | `groups` | an optional grouping variable. If present, `<panel.superpose>` will be used instead to display each subgroup | | `weights` | numeric vector of weights for the density calculations. If this is specified, the `...` part must also include a `subscripts` argument that matches the weights to `x`. | | `jitter.amount` | when `plot.points="jitter"`, the value to use as the `amount` argument to `[jitter](../../base/html/jitter)`. | | `type` | `type` argument used to plot points, if requested. This is not expected to be useful, it is available mostly to protect a `type` argument, if specified, from affecting the density curve. | | `...` | extra graphical parameters. Note that additional arguments to `[panel.rug](panel.functions)` cannot be passed on through `panel.densityplot`. | | `identifier` | A character string that is prepended to the names of grobs that are created by this panel function. | ### Author(s) Deepayan Sarkar [[email protected]](mailto:[email protected]) ### See Also `[densityplot](histogram)`, `[jitter](../../base/html/jitter)` r None `histogram` Histograms and Kernel Density Plots ------------------------------------------------ ### Description Draw Histograms and Kernel Density Plots, possibly conditioned on other variables. ### Usage ``` histogram(x, data, ...) densityplot(x, data, ...) ## S3 method for class 'formula' histogram(x, data, allow.multiple, outer = TRUE, auto.key = FALSE, aspect = "fill", panel = lattice.getOption("panel.histogram"), prepanel, scales, strip, groups, xlab, xlim, ylab, ylim, type = c("percent", "count", "density"), nint = if (is.factor(x)) nlevels(x) else round(log2(length(x)) + 1), endpoints = extend.limits(range(as.numeric(x), finite = TRUE), prop = 0.04), breaks, equal.widths = TRUE, drop.unused.levels = lattice.getOption("drop.unused.levels"), ..., lattice.options = NULL, default.scales = list(), default.prepanel = lattice.getOption("prepanel.default.histogram"), subscripts, subset) ## S3 method for class 'numeric' histogram(x, data = NULL, xlab, ...) ## S3 method for class 'factor' histogram(x, data = NULL, xlab, ...) ## S3 method for class 'formula' densityplot(x, data, allow.multiple = is.null(groups) || outer, outer = !is.null(groups), auto.key = FALSE, aspect = "fill", panel = lattice.getOption("panel.densityplot"), prepanel, scales, strip, groups, weights, xlab, xlim, ylab, ylim, bw, adjust, kernel, window, width, give.Rkern, n = 512, from, to, cut, na.rm, drop.unused.levels = lattice.getOption("drop.unused.levels"), ..., lattice.options = NULL, default.scales = list(), default.prepanel = lattice.getOption("prepanel.default.densityplot"), subscripts, subset) ## S3 method for class 'numeric' densityplot(x, data = NULL, xlab, ...) do.breaks(endpoints, nint) ``` ### Arguments | | | | --- | --- | | `x` | The object on which method dispatch is carried out. For the `formula` method, `x` can be a formula of the form `~ x | g1 * g2 * ...`, indicating that histograms or kernel density estimates of the `x` variable should be produced conditioned on the levels of the (optional) variables `g1`, `g2`, .... `x` should be numeric (or possibly a factor in the case of `histogram`), and each of `g1`, `g2`, ... should be either factors or shingles. As a special case, the right hand side of the formula can contain more than one term separated by ‘+’ signs (e.g., `~ x1 + x2 | g1 * g2`). What happens in this case is described in the documentation for `<xyplot>`. Note that in either form, all the terms in the formula must have the same length after evaluation. For the `numeric` and `factor` methods, `x` is the variable whose histogram or Kernel density estimate is drawn. Conditioning is not allowed in these cases. | | `data` | For the `formula` method, an optional data source (usually a data frame) in which variables are to be evaluated (see `<xyplot>` for details). `data` should not be specified for the other methods, and is ignored with a warning if it is. | | `type` | A character string indicating the type of histogram that is to be drawn. `"percent"` and `"count"` give relative frequency and frequency histograms respectively, and can be misleading when breakpoints are not equally spaced. `"density"` produces a density histogram. `type` defaults to `"density"` when the breakpoints are unequally spaced, and when `breaks` is `NULL` or a function, and to `"percent"` otherwise. | | `nint` | An integer specifying the number of histogram bins, applicable only when `breaks` is unspecified or `NULL` in the call. Ignored when the variable being plotted is a factor. | | `endpoints` | A numeric vector of length 2 indicating the range of x-values that is to be covered by the histogram. This applies only when `breaks` is unspecified and the variable being plotted is not a factor. In `do.breaks`, this specifies the interval that is to be divided up. | | `breaks` | Usually a numeric vector of length (number of bins + 1) defining the breakpoints of the bins. Note that when breakpoints are not equally spaced, the only value of `type` that makes sense is density. When `breaks` is unspecified, the value of `lattice.getOption("histogram.breaks")` is first checked. If this value is `NULL`, then the default is to use ``` breaks = seq_len(1 + nlevels(x)) - 0.5 ``` when `x` is a factor, and ``` breaks = do.breaks(endpoints, nint) ``` otherwise. Breakpoints calculated in such a manner are used in all panels. If the retrieved value is not `NULL`, or if `breaks` is explicitly specified, it affects the display in each panel independently. Valid values are those accepted as the `breaks` argument in `[hist](../../graphics/html/hist)`. In particular, this allows specification of `breaks` as an integer giving the number of bins (similar to `nint`), as a character string denoting a method, or as a function. When specified explicitly, a special value of `breaks` is `NULL`, in which case the number of bins is determined by `nint` and then breakpoints are chosen according to the value of `equal.widths`. | | `equal.widths` | A logical flag, relevant only when `breaks=NULL`. If `TRUE`, equally spaced bins will be selected, otherwise, approximately equal area bins will be selected (typically producing unequally spaced breakpoints). | | `n` | Integer, giving the number of points at which the kernel density is to be evaluated. Passed on as an argument to `[density](../../stats/html/density)`. | | `panel` | A function, called once for each panel, that uses the packet (subset of panel variables) corresponding to the panel to create a display. The default panel functions `<panel.histogram>` and `<panel.densityplot>` are documented separately, and have arguments that can be used to customize its output in various ways. Such arguments can usually be directly supplied to the high-level function. | | `allow.multiple, outer` | See `<xyplot>`. | | `auto.key` | See `<xyplot>`. | | `aspect` | See `<xyplot>`. | | `prepanel` | See `<xyplot>`. | | `scales` | See `<xyplot>`. | | `strip` | See `<xyplot>`. | | `groups` | See `<xyplot>`. Note that the default panel function for `histogram` does not support grouped displays, whereas the one for `densityplot` does. | | `xlab, ylab` | See `<xyplot>`. | | `xlim, ylim` | See `<xyplot>`. | | `drop.unused.levels` | See `<xyplot>`. | | `lattice.options` | See `<xyplot>`. | | `default.scales` | See `<xyplot>`. | | `subscripts` | See `<xyplot>`. | | `subset` | See `<xyplot>`. | | `default.prepanel` | Fallback prepanel function. See `<xyplot>`. | | `weights` | numeric vector of weights for the density calculations, evaluated in the non-standard manner used for `groups` and terms in the formula, if any. If this is specified, it is subsetted using `subscripts` inside the panel function to match it to the corresponding `x` values. At the time of writing, `weights` do not work in conjunction with an extended formula specification (this is not too hard to fix, so just bug the maintainer if you need this feature). | | `bw, adjust, width` | Arguments controlling bandwidth. Passed on as arguments to `[density](../../stats/html/density)`. | | `kernel, window` | The choice of kernel. Passed on as arguments to `[density](../../stats/html/density)`. | | `give.Rkern` | Logical flag, passed on as argument to `[density](../../stats/html/density)`. This argument is made available only for ease of implementation, and will produce an error if `TRUE`. | | `from, to, cut` | Controls range over which density is evaluated. Passed on as arguments to `[density](../../stats/html/density)`. | | `na.rm` | Logical flag specifying whether `NA` values should be ignored. Passed on as argument to `[density](../../stats/html/density)`, but unlike in `density`, the default is `TRUE`. | | `...` | Further arguments. See corresponding entry in `<xyplot>` for non-trivial details. | ### Details `histogram` draws Conditional Histograms, and `densityplot` draws Conditional Kernel Density Plots. The default panel function uses the `[density](../../stats/html/density)` function to compute the density estimate, and all arguments accepted by `density` can be specified in the call to `densityplot` to control the output. See documentation of `density` for details. These and all other high level Trellis functions have several arguments in common. These are extensively documented only in the help page for `xyplot`, which should be consulted to learn more detailed usage. `do.breaks` is an utility function that calculates breakpoints given an interval and the number of pieces to break it into. ### Value An object of class `"trellis"`. The `[update](update.trellis)` method can be used to update components of the object and the `[print](print.trellis)` method (usually called by default) will plot it on an appropriate plotting device. ### Note The form of the arguments accepted by the default panel function `panel.histogram` is different from that in S-PLUS. Whereas S-PLUS calculates the heights inside `histogram` and passes only the breakpoints and the heights to the panel function, lattice simply passes along the original variable `x` along with the breakpoints. This approach is more flexible; see the example below with an estimated density superimposed over the histogram. ### Author(s) Deepayan Sarkar [[email protected]](mailto:[email protected]) ### References Sarkar, Deepayan (2008) *Lattice: Multivariate Data Visualization with R*, Springer. <http://lmdvr.r-forge.r-project.org/> ### See Also `<xyplot>`, `<panel.histogram>`, `[density](../../stats/html/density)`, `<panel.densityplot>`, `[panel.mathdensity](panel.functions)`, `[Lattice](lattice)` ### Examples ``` require(stats) histogram( ~ height | voice.part, data = singer, nint = 17, endpoints = c(59.5, 76.5), layout = c(2,4), aspect = 1, xlab = "Height (inches)") histogram( ~ height | voice.part, data = singer, xlab = "Height (inches)", type = "density", panel = function(x, ...) { panel.histogram(x, ...) panel.mathdensity(dmath = dnorm, col = "black", args = list(mean=mean(x),sd=sd(x))) } ) densityplot( ~ height | voice.part, data = singer, layout = c(2, 4), xlab = "Height (inches)", bw = 5) ``` r None `lset` Interface to modify Trellis Settings - Defunct ------------------------------------------------------ ### Description A (hopefully) simpler alternative to `trellis.par.get/set`. This is deprecated, and the same functionality is now available with `trellis.par.set` ### Usage ``` lset(theme = col.whitebg()) ``` ### Arguments | | | | --- | --- | | `theme` | a list decribing how to change the settings of the current active device. Valid components are those in the list returned by `trellis.par.get()`. Each component must itself be a list, with one or more of the appropriate components (need not have all components). Changes are made to the settings for the currently active device only. | ### Author(s) Deepayan Sarkar [[email protected]](mailto:[email protected]) r None `strip.default` Default Trellis Strip Function ----------------------------------------------- ### Description `strip.default` is the function that draws the strips by default in Trellis plots. Users can write their own strip functions, but most commonly this involves calling `strip.default` with a slightly different arguments. `strip.custom` provides a convenient way to obtain new strip functions that differ from `strip.default` only in the default values of certain arguments. ### Usage ``` strip.default(which.given, which.panel, var.name, factor.levels, shingle.intervals, strip.names = c(FALSE, TRUE), strip.levels = c(TRUE, FALSE), sep = " : ", style = 1, horizontal = TRUE, bg = trellis.par.get("strip.background")$col[which.given], fg = trellis.par.get("strip.shingle")$col[which.given], par.strip.text = trellis.par.get("add.text")) strip.custom(...) ``` ### Arguments | | | | --- | --- | | `which.given` | integer index specifying which of the conditioning variables this strip corresponds to. | | `which.panel` | vector of integers as long as the number of conditioning variables. The contents are indices specifying the current levels of each of the conditioning variables (thus, this would be unique for each distinct packet). This is identical to the return value of `[which.packet](panel.number)`, which is a more accurate name. | | | | | --- | --- | | `var.name` | vector of character strings or expressions as long as the number of conditioning variables. The contents are interpreted as names for the conditioning variables. Whether they are shown on the strip depends on the values of `strip.names` and `style` (see below). By default, the names are shown for shingles, but not for factors. | | `factor.levels` | vector of character strings or expressions giving the levels of the conditioning variable currently being drawn. For more than one conditioning variable, this will vary with `which.given`. Whether these levels are shown on the strip depends on the values of `strip.levels` and `style` (see below). `factor.levels` may be specified for both factors and shingles (despite the name), but by default they are shown only for factors. If shown, the labels may optionally be abbreviated by specifying suitable components in `par.strip.text` (see `<xyplot>`) | | `shingle.intervals` | if the current strip corresponds to a shingle, this should be a 2-column matrix giving the levels of the shingle. (of the form that would be produced by **printing** `levels(shingle)`). Otherwise, it should be `NULL` | | `strip.names` | a logical vector of length 2, indicating whether or not the name of the conditioning variable that corresponds to the strip being drawn is to be written on the strip. The two components give the values for factors and shingles respectively. This argument is ignored for a factor when `style` is not one of 1 and 3. | | `strip.levels` | a logical vector of length 2, indicating whether or not the level of the conditioning variable that corresponds to the strip being drawn is to be written on the strip. The two components give the values for factors and shingles respectively. | | `sep` | character or expression, serving as a separator if the name and level are both to be shown. | | `style` | integer, with values 1, 2, 3, 4 and 5 currently supported, controlling how the current level of a factor is encoded. Ignored for shingles (actually, when `shingle.intervals` is non-null. The best way to find out what effect the value of `style` has is to try them out. Here is a short description: for a style value of 1, the strip is colored in the background color with the strip text (as determined by other arguments) centered on it. A value of 3 is the same, except that a part of the strip is colored in the foreground color, indicating the current level of the factor. For styles 2 and 4, the part corresponding to the current level remains colored in the foreground color, however, for style = 2, the remaining part is not colored at all, whereas for 4, it is colored with the background color. For both these, the names of all the levels of the factor are placed on the strip from left to right. Styles 5 and 6 produce the same effect (they are subtly different in S, this implementation corresponds to 5), they are similar to style 1, except that the strip text is not centered, it is instead positioned according to the current level. Note that unlike S-PLUS, the default value of `style` is 1. `strip.names` and `strip.levels` have no effect if `style` is not 1 or 3. | | `horizontal` | logical, specifying whether the labels etc should be horizontal. `horizontal=FALSE` is useful for strips on the left of panels using `strip.left=TRUE` | | `par.strip.text` | list with parameters controlling the text on each strip, with components `col`, `cex`, `font`, etc. | | `bg` | strip background color. | | `fg` | strip foreground color. | | `...` | arguments to be passed on to `strip.default`, overriding whatever value it would have normally assumed | ### Details default strip function for trellis functions. Useful mostly because of the `style` argument — non-default styles are often more informative, especially when the names of the levels of the factor `x` are small. Traditional use is as `strip = function(...) strip.default(style=2,...)`, though this can be simplified by the use of `strip.custom`. ### Value `strip.default` is called for its side-effect, which is to draw a strip appropriate for multi-panel Trellis conditioning plots. `strip.custom` returns a function that is similar to `strip.default`, but with different defaults for the arguments specified in the call. ### Author(s) Deepayan Sarkar [[email protected]](mailto:[email protected]) ### See Also `<xyplot>`, `[Lattice](lattice)` ### Examples ``` ## Traditional use xyplot(Petal.Length ~ Petal.Width | Species, iris, strip = function(..., style) strip.default(..., style = 4)) ## equivalent call using strip.custom xyplot(Petal.Length ~ Petal.Width | Species, iris, strip = strip.custom(style = 4)) xyplot(Petal.Length ~ Petal.Width | Species, iris, strip = FALSE, strip.left = strip.custom(style = 4, horizontal = FALSE)) ```
programming_docs
r None `prepanel.functions` Useful Prepanel Function for Lattice ---------------------------------------------------------- ### Description These are predefined prepanel functions available in Lattice. ### Usage ``` prepanel.lmline(x, y, ...) prepanel.qqmathline(x, y = x, distribution = qnorm, probs = c(0.25, 0.75), qtype = 7, groups, subscripts, ...) prepanel.loess(x, y, span, degree, family, evaluation, horizontal = FALSE, ...) prepanel.spline(x, y, npoints = 101, horizontal = FALSE, ..., keep.data = FALSE) ``` ### Arguments | | | | --- | --- | | `x, y` | x and y values, numeric or factor | | `distribution` | quantile function for theoretical distribution. This is automatically passed in when this is used as a prepanel function in `qqmath`. | | `qtype` | type of `[quantile](../../stats/html/quantile)` | | `probs` | numeric vector of length two, representing probabilities. If used with `aspect="xy"`, the aspect ratio will be chosen to make the line passing through the corresponding quantile pairs as close to 45 degrees as possible. | | `span, degree, family, evaluation` | Arguments controlling the underlying `[loess](../../stats/html/loess)` smooth. | | `horizontal, npoints` | See documentation for corresponding panel function. | | `keep.data` | Ignored. Present to capture argument of the same name in `[smooth.spline](../../stats/html/smooth.spline)`. | | `groups, subscripts` | See `<xyplot>`. Whenever appropriate, calculations are done separately for each group and then combined. | | `...` | Other arguments. These are passed on to other functions if appropriate (in particular, `[smooth.spline](../../stats/html/smooth.spline)`), and ignored otherwise. | ### Details All these prepanel functions compute the limits to be large enough to contain all points as well as the relevant smooth. In addition, `prepanel.lmline` computes the `dx` and `dy` such that it reflects the slope of the linear regression line; for `prepanel.qqmathline`, this is the slope of the line passing through the quantile pairs specified by `probs`. For `prepanel.loess` and `prepanel.spline`, `dx` and `dy` reflect the piecewise slopes of the nonlinear smooth. ### Value usually a list with components `xlim`, `ylim`, `dx` and `dy`, the first two being used to calculate panel axes limits, the last two for banking computations. The form of these components are described under `<xyplot>`. There are also several prepanel functions that serve as the default for high level functions, see `[prepanel.default.xyplot](prepanel.default)` ### Author(s) Deepayan Sarkar [[email protected]](mailto:[email protected]) ### See Also [Lattice](lattice), `<xyplot>`, `<banking>`, `<panel.loess>`, `<panel.spline>`. r None `panel.smoothScatter` Lattice panel function analogous to smoothScatter ------------------------------------------------------------------------ ### Description This function allows the user to place `smoothScatter` plots in lattice graphics. ### Usage ``` panel.smoothScatter(x, y = NULL, nbin = 64, cuts = 255, bandwidth, colramp, nrpoints = 100, transformation = function(x) x^0.25, pch = ".", cex = 1, col="black", range.x, ..., raster = FALSE, subscripts, identifier = "smoothScatter") ``` ### Arguments | | | | --- | --- | | `x` | Numeric vector containing x-values or n by 2 matrix containing x and y values. | | `y` | Numeric vector containing y-values (optional). The length of `x` must be the same as that of `y`. | | `nbin` | Numeric vector of length 1 (for both directions) or 2 (for x and y separately) containing the number of equally spaced grid points for the density estimation. | | `cuts` | number of cuts defining the color gradient | | `bandwidth` | Numeric vector: the smoothing bandwidth. If missing, these functions come up with a more or less useful guess. This parameter then gets passed on to the function `[bkde2D](../../kernsmooth/html/bkde2d)`. | | `colramp` | Function accepting an integer `n` as an argument and returning `n` colors. | | `nrpoints` | Numeric vector of length 1 giving number of points to be superimposed on the density image. The first `nrpoints` points from those areas of lowest regional densities will be plotted. Adding points to the plot allows for the identification of outliers. If all points are to be plotted, choose `nrpoints = Inf`. | | `transformation` | Function that maps the density scale to the color scale. | | `pch, cex` | graphical parameters for the `nrpoints` “outlying” points shown in the display | | `range.x` | see `[bkde2D](../../kernsmooth/html/bkde2d)` for details. | | `col` | `[points](../../graphics/html/points)` color parameter | | `...` | Further arguments that are passed on to `<panel.levelplot>`. | | `raster` | logical; if `TRUE`, `[panel.levelplot.raster](panel.levelplot)` is used, making potentially smaller output files. | | `subscripts` | ignored, but necessary for handling of ... in certain situations. Likely to be removed in future. | | `identifier` | A character string that is prepended to the names of grobs that are created by this panel function. | ### Details This replicates the display part of the `smoothScatter` function by replacing standard graphics calls by grid-compatible ones. ### Value The function is called for its side effects, namely the production of the appropriate plots on a graphics device. ### Author(s) Deepayan Sarkar [[email protected]](mailto:[email protected]) ### Examples ``` ddf <- as.data.frame(matrix(rnorm(40000), ncol = 4) + 3 * rnorm(10000)) ddf[, c(2,4)] <- (-ddf[, c(2,4)]) xyplot(V1 ~ V2 + V3, ddf, outer = TRUE, panel = panel.smoothScatter, aspect = "iso") splom(ddf, panel = panel.smoothScatter, nbin = 64, raster = TRUE) ``` r None `oneway` Fit One-way Model --------------------------- ### Description Fits a One-way model to univariate data grouped by a factor, the result often being displayed using `rfs` ### Usage ``` oneway(formula, data, location=mean, spread=function(x) sqrt(var(x))) ``` ### Arguments | | | | --- | --- | | `formula` | formula of the form `y ~ x` where `y` is the numeric response and `x` is the grouping factor | | `data` | data frame in which the model is to be evaluated | | `location` | function or numeric giving the location statistic to be used for centering the observations, e.g. `median`, 0 (to avoid centering). | | `spread` | function or numeric giving the spread statistic to be used for scaling the observations, e.g. `sd`, 1 (to avoid scaling). | ### Value A list with components | | | | --- | --- | | `location` | vector of locations for each group. | | `spread` | vector of spreads for each group. | | `fitted.values` | vector of locations for each observation. | | `residuals` | residuals (`y - fitted.values`). | | `scaled.residuals` | residuals scaled by `spread` for their group | ### Author(s) Deepayan Sarkar [[email protected]](mailto:[email protected]) ### See Also `<rfs>`, `[Lattice](lattice)` r None `simpleKey` Function to generate a simple key ---------------------------------------------- ### Description Simple interface to generate a list appropriate for `draw.key` ### Usage ``` simpleKey(text, points = TRUE, rectangles = FALSE, lines = FALSE, col, cex, alpha, font, fontface, fontfamily, lineheight, ...) ``` ### Arguments | | | | --- | --- | | `text` | character or expression vector, to be used as labels for levels of the grouping variable | | `points` | logical | | `rectangles` | logical | | `lines` | logical | | `col, cex, alpha, font, fontface, fontfamily, lineheight` | Used as top-level components of the list produced, to be used for the text labels. Defaults to the values in `trellis.par.get("add.text")` | | `...` | further arguments added to the list, eventually passed to `draw.key` | ### Details A lattice plot can include a legend (key) if an appropriate list is specified as the `key` argument to a high level Lattice function such as `xyplot`. This key can be very flexible, but that flexibility comes at a cost: this list needs to be fairly complicated even in simple situations. `simpleKey` is designed as a useful shortcut in the common case of a key drawn in conjunction with a grouping variable, using the default graphical settings. The `simpleKey` function produces a suitable `key` argument using a simpler interface. The resulting list will use the `text` argument as a text component, along with at most one set each of points, rectangles, and lines. The number of entries (rows) in the key will be the length of the `text` component. The graphical parameters for the additional components will be derived from the default graphical settings (wherein lies the simplification, as otherwise these would have to be provided explicitly). Calling `simpleKey` directly is usually unnecessary. It is most commonly invoked (during the plotting of the `"trellis"` object) when the `auto.key` argument is supplied in a high-level plot with a `groups` argument. In that case, the `text` argument of `simpleKey` defaults to `levels(groups)`, and the defaults for the other arguments depend on the relevant high-level function. Note that these defaults can be overridden by supplying `auto.key` as a list containing the replacement values. ### Value A list that would work as the `key` argument to `<xyplot>`, etc. ### Author(s) Deepayan Sarkar [[email protected]](mailto:[email protected]) ### See Also `[Lattice](lattice)`, `<draw.key>`, `<trellis.par.get>`, and `<xyplot>`, specifically the entry for `auto.key`. r None `xyplot.ts` Time series plotting methods ----------------------------------------- ### Description This function handles time series plotting, including cut-and-stack plots. Examples are given of superposing, juxtaposing and styling different time series. ### Usage ``` ## S3 method for class 'ts' xyplot(x, data = NULL, screens = if (superpose) 1 else colnames(x), ..., superpose = FALSE, cut = FALSE, type = "l", col = NULL, lty = NULL, lwd = NULL, pch = NULL, cex = NULL, fill = NULL, auto.key = superpose, panel = if (superpose) "panel.superpose" else "panel.superpose.plain", par.settings = list(), layout = NULL, as.table = TRUE, xlab = "Time", ylab = NULL, default.scales = list(y = list(relation = if (missing(cut)) "free" else "same"))) ``` ### Arguments | | | | --- | --- | | `x` | an object of class `[ts](../../stats/html/ts)`, which may be multi-variate, i.e. have a matrix structure with multiple columns. | | `data` | not used, and must be left as `NULL`. | | `...` | additional arguments passed to `<xyplot>`, which may pass them on to `<panel.xyplot>`. | | `screens` | factor (or coerced to factor) whose levels specify which panel each series is to be plotted in. `screens = c(1, 2, 1)` would plot series 1, 2 and 3 in panels 1, 2 and 1. May also be a named list, see Details below. | | `superpose` | overlays all series in one panel (via `screens = 1`) and uses grouped style settings (from `trellis.par.get("superpose.line")`, etc). Note that this is just a convenience argument: its only action is to change the default values of other arguments. | | `cut` | defines a cut-and-stack plot. `cut` can be a `list` of arguments to the function `[equal.count](shingles)`, i.e. `number` (number of intervals to divide into) and `overlap` (the fraction of overlap between cuts, default 0.5). If `cut` is numeric this is passed as the `number` argument. `cut = TRUE` tries to choose an appropriate number of cuts (up to a maximum of 6), using `<banking>`, and assuming a square plot region. This should have the effect of minimising wasted space when `aspect = "xy"`. | | `type, col, lty, lwd, pch, cex, fill` | graphical arguments, which are processed and eventually passed to `<panel.xyplot>`. These arguments can also be vectors or (named) lists, see Details for more information. | | `auto.key` | a logical, or a list describing how to draw a key. See the `auto.key` entry in `<xyplot>`. The default here is to draw lines, not points, and any specified style arguments should show up automatically. | | `panel` | the panel function. It is recommended to leave this alone, but one can pass a `panel.groups` argument which is handled by `<panel.superpose>` for each series. | | `par.settings` | style settings beyond the standard `col`, `lty`, `lwd`, etc; see `[trellis.par.set](trellis.par.get)` and `[simpleTheme](simpletheme)`. | | `layout` | numeric vector of length 2 specifying number of columns and rows in the plot. The default is to fill columns with up to 6 rows. | | `as.table` | to draw panels from top to bottom. The order is determined by the order of columns in `x`. | | `xlab, ylab` | X axis and Y axis labels; see `<xyplot>`. Note in particular that `ylab` may be a character vector, in which case the labels are spaced out equally, to correspond to the panels; but *NOTE* in this case the vector should be reversed OR the argument `as.table` set to `FALSE`. | | `default.scales` | `scales` specification. The default is set to have `"free"` Y axis scales unless `cut` is given. Note, users should pass the `scales` argument rather than `default.scales`. | ### Details The handling of several graphical parameters is more flexible for multivariate series. These parameters can be vectors of the same length as the number of series plotted or are recycled if shorter. They can also be (partially) named list, e.g., `list(A = c(1,2), c(3,4))` in which `c(3, 4)` is the default value and `c(1, 2)` the value only for series `A`. The `screens` argument can be specified in a similar way. Some examples are given below. ### Value An object of class `"trellis"`. The `[update](update.trellis)` method can be used to update components of the object and the `[print](print.trellis)` method (usually called by default) will plot it on an appropriate plotting device. ### Author(s) Gabor Grothendieck, Achim Zeileis, Deepayan Sarkar and Felix Andrews [[email protected]](mailto:[email protected]). The first two authors developed `xyplot.ts` in their zoo package, including the `screens` approach. The third author developed a different `xyplot.ts` for cut-and-stack plots in the latticeExtra package. The final author fused these together. ### References Sarkar, Deepayan (2008) *Lattice: Multivariate Data Visualization with R*, Springer. <http://lmdvr.r-forge.r-project.org/> (cut-and-stack plots) ### See Also `<xyplot>`, `<panel.xyplot>`, `[plot.ts](../../stats/html/plot.ts)`, `[ts](../../stats/html/ts)`, `[xyplot.zoo](../../zoo/html/xyplot.zoo)` in the zoo package. ### Examples ``` xyplot(ts(c(1:10,10:1))) ### Figure 14.1 from Sarkar (2008) xyplot(sunspot.year, aspect = "xy", strip = FALSE, strip.left = TRUE, cut = list(number = 4, overlap = 0.05)) ### A multivariate example; first juxtaposed, then superposed xyplot(EuStockMarkets, scales = list(y = "same")) xyplot(EuStockMarkets, superpose = TRUE, aspect = "xy", lwd = 2, type = c("l","g"), ylim = c(0, max(EuStockMarkets))) ### Examples using screens (these two are identical) xyplot(EuStockMarkets, screens = c(rep("Continental", 3), "UK")) xyplot(EuStockMarkets, screens = list(FTSE = "UK", "Continental")) ### Automatic group styles xyplot(EuStockMarkets, screens = list(FTSE = "UK", "Continental"), superpose = TRUE) xyplot(EuStockMarkets, screens = list(FTSE = "UK", "Continental"), superpose = TRUE, xlim = extendrange(1996:1998), par.settings = standard.theme(color = FALSE)) ### Specifying styles for series by name xyplot(EuStockMarkets, screens = list(FTSE = "UK", "Continental"), col = list(DAX = "red", FTSE = "blue", "black"), auto.key = TRUE) xyplot(EuStockMarkets, screens = list(FTSE = "UK", "Continental"), col = list(DAX = "red"), lty = list(SMI = 2), lwd = 1:2, auto.key = TRUE) ### Example with simpler data, few data points set.seed(1) z <- ts(cbind(a = 1:5, b = 11:15, c = 21:25) + rnorm(5)) xyplot(z, screens = 1) xyplot(z, screens = list(a = "primary (a)", "other (b & c)"), type = list(a = c("p", "h"), b = c("p", "s"), "o"), pch = list(a = 2, c = 3), auto.key = list(type = "o")) ``` r None `melanoma` Melanoma skin cancer incidence ------------------------------------------ ### Description These data from the Connecticut Tumor Registry present age-adjusted numbers of melanoma skin-cancer incidences per 100,000 people in Connectict for the years from 1936 to 1972. ### Usage ``` melanoma ``` ### Format A data frame with 37 observations on the following 2 variables. year Years 1936 to 1972. incidence Rate of melanoma cancer per 100,000 population. ### Note This dataset is not related to the `[melanoma](../../boot/html/melanoma)` dataset in the **boot** package with the same name. The S-PLUS 6.2 help for the melanoma data says that the incidence rate is per *million*, but this is not consistent with data found at the National Cancer Institute (<https://www.cancer.gov/>). ### Author(s) Documentation contributed by Kevin Wright. ### Source Houghton, A., E. W. Munster, and M. V. Viola. (1978). Increased Incidence of Malignant Melanoma After Peaks of Sunspot Activity. *The Lancet*, **8**, 759–760. ### References Cleveland, William S. (1993) *Visualizing Data*. Hobart Press, Summit, New Jersey. ### Examples ``` # Time-series plot. Figure 3.64 from Cleveland. xyplot(incidence ~ year, data = melanoma, aspect = "xy", panel = function(x, y) panel.xyplot(x, y, type="o", pch = 16), ylim = c(0, 6), xlab = "Year", ylab = "Incidence") ``` r None `barley` Yield data from a Minnesota barley trial -------------------------------------------------- ### Description Total yield in bushels per acre for 10 varieties at 6 sites in each of two years. ### Usage ``` barley ``` ### Format A data frame with 120 observations on the following 4 variables. yield Yield (averaged across three blocks) in bushels/acre. variety Factor with levels `"Svansota"`, `"No. 462"`, `"Manchuria"`, `"No. 475"`, `"Velvet"`, `"Peatland"`, `"Glabron"`, `"No. 457"`, `"Wisconsin No. 38"`, `"Trebi"`. year Factor with levels `1932`, `1931` site Factor with 6 levels: `"Grand Rapids"`, `"Duluth"`, `"University Farm"`, `"Morris"`, `"Crookston"`, `"Waseca"` ### Details These data are yields in bushels per acre, of 10 varieties of barley grown in 1/40 acre plots at University Farm, St. Paul, and at the five branch experiment stations located at Waseca, Morris, Crookston, Grand Rapids, and Duluth (all in Minnesota). The varieties were grown in three randomized blocks at each of the six stations during 1931 and 1932, different land being used each year of the test. Immer et al. (1934) present the data for each Year\*Site\*Variety\*Block. The data here is the average yield across the three blocks. Immer et al. (1934) refer (once) to the experiment as being conducted in 1930 and 1931, then later refer to it (repeatedly) as being conducted in 1931 and 1932. Later authors have continued the confusion. Cleveland (1993) suggests that the data for the Morris site may have had the years switched. ### Author(s) Documentation contributed by Kevin Wright. ### Source Immer, R. F., H. K. Hayes, and LeRoy Powers. (1934). Statistical Determination of Barley Varietal Adaptation. *Journal of the American Society of Agronomy*, **26**, 403–419. Wright, Kevin (2013). Revisiting Immer's Barley Data. *The American Statistician*, **67(3)**, 129–133. ### References Cleveland, William S. (1993) *Visualizing Data*. Hobart Press, Summit, New Jersey. Fisher, R. A. (1971) *The Design of Experiments*. Hafner, New York, 9th edition. ### See Also `[immer](../../mass/html/immer)` in the MASS package for data from the same experiment (expressed as total yield for 3 blocks) for a subset of varieties. ### Examples ``` # Graphic suggesting the Morris data switched the years 1931 and 1932 # Figure 1.1 from Cleveland dotplot(variety ~ yield | site, data = barley, groups = year, key = simpleKey(levels(barley$year), space = "right"), xlab = "Barley Yield (bushels/acre) ", aspect=0.5, layout = c(1,6), ylab=NULL) ```
programming_docs
r None `panel.parallel` Default Panel Function for parallel ----------------------------------------------------- ### Description This is the default panel function for `parallel`. ### Usage ``` panel.parallel(x, y, z, subscripts, groups = NULL, col, lwd, lty, alpha, common.scale = FALSE, lower, upper, ..., horizontal.axis = TRUE, identifier = "parallel") ``` ### Arguments | | | | --- | --- | | `x, y` | dummy variables, ignored. | | `z` | The data frame used for the plot. Each column will be coerced to numeric before being plotted, and an error will be issued if this fails. | | `subscripts` | The indices of the rows of `z` that are to be displyed in this panel. | | `groups` | An optional grouping variable. If specified, different groups are distinguished by use of different graphical parameters (i.e., rows of `z` in the same group share parameters). | | `col, lwd, lty, alpha` | graphical parameters (defaults to the settings for `superpose.line`). If `groups` is non-null, these parameters used one for each group. Otherwise, they are recycled and used to distinguish between rows of the data frame `z`. | | `common.scale` | logical, whether a common scale should be used columns of `z`. Defaults to `FALSE`, in which case the horizontal range for each column is different (as determined by `lower` and `upper`). | | `lower, upper` | numeric vectors replicated to be as long as the number of columns in `z`. Determines the lower and upper bounds to be used for scaling the corresponding columns of `z` after coercing them to numeric. Defaults to the minimum and maximum of each column. Alternatively, these could be functions (to be applied on each column) that return a scalar. | | `...` | other arguments (ignored) | | `horizontal.axis` | logical indicating whether the parallel axes should be laid out horizontally (`TRUE`) or vertically (`FALSE`). | | `identifier` | A character string that is prepended to the names of grobs that are created by this panel function. | ### Details Produces parallel coordinate plots, which are easier to understand from an example than through a verbal description. See example for `[parallel](splom)` ### Author(s) Deepayan Sarkar [[email protected]](mailto:[email protected]) ### References Inselberg, Alfred (2009) *Parallel Coordinates: Visual Multidimensional Geometry and Its Applications*, Springer. ISBN: 978-0-387-21507-5. Inselberg, A. (1985) “The Plane with Parallel Coordinates”, *The Visual Computer*. ### See Also `[parallel](splom)` r None `barchart.table` table methods for barchart and dotplot -------------------------------------------------------- ### Description Contingency tables are often displayed using bar charts and dot plots. These methods operate directly on tables, bypassing the need to convert them to data frames for use with the formula interface. Matrices and arrays are also supported, by coercing them to tables. ### Usage ``` ## S3 method for class 'table' barchart(x, data, groups = TRUE, origin = 0, stack = TRUE, ..., horizontal = TRUE) ## S3 method for class 'array' barchart(x, data, ...) ## S3 method for class 'matrix' barchart(x, data, ...) ## S3 method for class 'table' dotplot(x, data, groups = TRUE, ..., horizontal = TRUE) ## S3 method for class 'array' dotplot(x, data, ...) ## S3 method for class 'matrix' dotplot(x, data, ...) ``` ### Arguments | | | | --- | --- | | `x` | A `table`, `array` or `matrix` object. | | `data` | Should not be specified. If specified, will be ignored with a warning. | | `groups` | A logical flag, indicating whether to use the last dimension as a grouping variable in the display. | | `origin, stack` | Arguments to `<panel.barchart>`. The defaults for the `table` method are different. | | `horizontal` | Logical flag, indicating whether the plot should be horizontal (with the categorical variable on the y-axis) or vertical. | | `...` | Other arguments, passed to the underlying `formula` method. | ### Details The first dimension is used as the variable on the categorical axis. The last dimension is optionally used as a grouping variable (to produce stacked barcharts by default). All other dimensions are used as conditioning variables. The order of these variables cannot be altered (except by permuting the original argument beforehand using `[t](../../base/html/t)` or `[aperm](../../base/html/aperm)`). For more flexibility, use the formula method after converting the table to a data frame using the relevant `[as.data.frame](../../base/html/table)` method. ### Value An object of class `"trellis"`. The `[update](update.trellis)` method can be used to update components of the object and the `[print](print.trellis)` method (usually called by default) will plot it on an appropriate plotting device. ### Author(s) Deepayan Sarkar [[email protected]](mailto:[email protected]) ### See Also `[barchart](xyplot)`, `[t](../../base/html/t)`, `[aperm](../../base/html/aperm)`, `[table](../../base/html/table)`, `<panel.barchart>`, `[Lattice](lattice)` ### Examples ``` barchart(Titanic, scales = list(x = "free"), auto.key = list(title = "Survived")) ``` r None `getData.lme` Extract lme Object Data -------------------------------------- ### Description If present in the calling sequence used to produce `object`, the data frame used to fit the model is obtained. ### Usage ``` ## S3 method for class 'lme' getData(object) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `lme`, representing a linear mixed-effects fitted model. | ### Value if a `data` argument is present in the calling sequence that produced `object`, the corresponding data frame (with `na.action` and `subset` applied to it, if also present in the call that produced `object`) is returned; else, `NULL` is returned. Note that as from version 3.1-102, this only omits rows omitted in the fit if `na.action = na.omit`, and does not omit at all if `na.action = na.exclude`. That is generally what is wanted for plotting, the main use of this function. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `<lme>`, `[getData](getdata)` ### Examples ``` fm1 <- lme(follicles ~ sin(2*pi*Time) + cos(2*pi*Time), data = Ovary, random = ~ sin(2*pi*Time)) getData(fm1) ``` r None `intervals.lmList` Confidence Intervals on lmList Coefficients --------------------------------------------------------------- ### Description Confidence intervals on the linear model coefficients are obtained for each `lm` component of `object` and organized into a three dimensional array. The first dimension corresponding to the names of the `object` components. The second dimension is given by `lower`, `est.`, and `upper` corresponding, respectively, to the lower confidence limit, estimated coefficient, and upper confidence limit. The third dimension is given by the coefficients names. ### Usage ``` ## S3 method for class 'lmList' intervals(object, level = 0.95, pool = attr(object, "pool"), ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"[lmList](lmlist)"`, representing a list of `lm` objects with a common model. | | `level` | an optional numeric value with the confidence level for the intervals. Defaults to 0.95. | | `pool` | an optional logical value indicating whether a pooled estimate of the residual standard error should be used. Default is `attr(object, "pool")`. | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value a three dimensional array with the confidence intervals and estimates for the coefficients of each `lm` component of `object`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Pinheiro, J.C., and Bates, D.M. (2000) "Mixed-Effects Models in S and S-PLUS", Springer. ### See Also `[lmList](lmlist)`, `<intervals>`, `[plot.intervals.lmList](plot.intervals.lmlist)` ### Examples ``` fm1 <- lmList(distance ~ age | Subject, Orthodont) intervals(fm1) ``` r None `corMatrix.corStruct` Matrix of a corStruct Object --------------------------------------------------- ### Description This method function extracts the correlation matrix (or its transpose inverse square-root factor), or list of correlation matrices (or their transpose inverse square-root factors) corresponding to `covariate` and `object`. Letting *S* denote a correlation matrix, a square-root factor of *S* is any square matrix *L* such that *S=L'L*. When `corr = FALSE`, this method extracts *L^(-t)*. ### Usage ``` ## S3 method for class 'corStruct' corMatrix(object, covariate, corr, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"[corStruct](corclasses)"` representing a correlation structure. | | `covariate` | an optional covariate vector (matrix), or list of covariate vectors (matrices), at which values the correlation matrix, or list of correlation matrices, are to be evaluated. Defaults to `getCovariate(object)`. | | `corr` | a logical value. If `TRUE` the function returns the correlation matrix, or list of correlation matrices, represented by `object`. If `FALSE` the function returns a transpose inverse square-root of the correlation matrix, or a list of transpose inverse square-root factors of the correlation matrices. | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value If `covariate` is a vector (matrix), the returned value will be an array with the corresponding correlation matrix (or its transpose inverse square-root factor). If the `covariate` is a list of vectors (matrices), the returned value will be a list with the correlation matrices (or their transpose inverse square-root factors) corresponding to each component of `covariate`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Pinheiro, J.C., and Bates, D.M. (2000) "Mixed-Effects Models in S and S-PLUS", Springer. ### See Also `[corFactor.corStruct](corfactor.corstruct)`, `[Initialize.corStruct](initialize.corstruct)` ### Examples ``` cs1 <- corAR1(0.3) corMatrix(cs1, covariate = 1:4) corMatrix(cs1, covariate = 1:4, corr = FALSE) # Pinheiro and Bates, p. 225 cs1CompSymm <- corCompSymm(value = 0.3, form = ~ 1 | Subject) cs1CompSymm <- Initialize(cs1CompSymm, data = Orthodont) corMatrix(cs1CompSymm) # Pinheiro and Bates, p. 226 cs1Symm <- corSymm(value = c(0.2, 0.1, -0.1, 0, 0.2, 0), form = ~ 1 | Subject) cs1Symm <- Initialize(cs1Symm, data = Orthodont) corMatrix(cs1Symm) # Pinheiro and Bates, p. 236 cs1AR1 <- corAR1(0.8, form = ~ 1 | Subject) cs1AR1 <- Initialize(cs1AR1, data = Orthodont) corMatrix(cs1AR1) # Pinheiro and Bates, p. 237 cs1ARMA <- corARMA(0.4, form = ~ 1 | Subject, q = 1) cs1ARMA <- Initialize(cs1ARMA, data = Orthodont) corMatrix(cs1ARMA) # Pinheiro and Bates, p. 238 spatDat <- data.frame(x = (0:4)/4, y = (0:4)/4) cs1Exp <- corExp(1, form = ~ x + y) cs1Exp <- Initialize(cs1Exp, spatDat) corMatrix(cs1Exp) ``` r None `Assay` Bioassay on Cell Culture Plate --------------------------------------- ### Description The `Assay` data frame has 60 rows and 4 columns. ### Format This data frame contains the following columns: Block an ordered factor with levels `2` < `1` identifying the block where the wells are measured. sample a factor with levels `a` to `f` identifying the sample corresponding to the well. dilut a factor with levels `1` to `5` indicating the dilution applied to the well logDens a numeric vector of the log-optical density ### Details These data, courtesy of Rich Wolfe and David Lansky from Searle, Inc., come from a bioassay run on a 96-well cell culture plate. The assay is performed using a split-block design. The 8 rows on the plate are labeled A–H from top to bottom and the 12 columns on the plate are labeled 1–12 from left to right. Only the central 60 wells of the plate are used for the bioassay (the intersection of rows B–G and columns 2–11). There are two blocks in the design: Block 1 contains columns 2–6 and Block 2 contains columns 7–11. Within each block, six samples are assigned randomly to rows and five (serial) dilutions are assigned randomly to columns. The response variable is the logarithm of the optical density. The cells are treated with a compound that they metabolize to produce the stain. Only live cells can make the stain, so the optical density is a measure of the number of cells that are alive and healthy. ### Source Pinheiro, J. C. and Bates, D. M. (2000), *Mixed-Effects Models in S and S-PLUS*, Springer, New York. (Appendix A.2) r None `Variogram.corGaus` Calculate Semi-variogram for a corGaus Object ------------------------------------------------------------------ ### Description This method function calculates the semi-variogram values corresponding to the Gaussian correlation model, using the estimated coefficients corresponding to `object`, at the distances defined by `distance`. ### Usage ``` ## S3 method for class 'corGaus' Variogram(object, distance, sig2, length.out, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"[corGaus](corgaus)"`, representing an Gaussian spatial correlation structure. | | `distance` | an optional numeric vector with the distances at which the semi-variogram is to be calculated. Defaults to `NULL`, in which case a sequence of length `length.out` between the minimum and maximum values of `getCovariate(object)` is used. | | `sig2` | an optional numeric value representing the process variance. Defaults to `1`. | | `length.out` | an optional integer specifying the length of the sequence of distances to be used for calculating the semi-variogram, when `distance = NULL`. Defaults to `50`. | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value a data frame with columns `variog` and `dist` representing, respectively, the semi-variogram values and the corresponding distances. The returned value inherits from class `Variogram`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Cressie, N.A.C. (1993), "Statistics for Spatial Data", J. Wiley & Sons. ### See Also `[corGaus](corgaus)`, `[plot.Variogram](plot.variogram)`, `[Variogram](variogram)` ### Examples ``` cs1 <- corGaus(3, form = ~ Time | Rat) cs1 <- Initialize(cs1, BodyWeight) Variogram(cs1)[1:10,] ``` r None `Relaxin` Assay for Relaxin ---------------------------- ### Description The `Relaxin` data frame has 198 rows and 3 columns. ### Format This data frame contains the following columns: Run an ordered factor with levels `5` < `8` < `9` < `3` < `4` < `2` < `7` < `1` < `6` conc a numeric vector cAMP a numeric vector ### Source Pinheiro, J. C. and Bates, D. M. (2000), *Mixed-Effects Models in S and S-PLUS*, Springer, New York. r None `Wheat` Yields by growing conditions ------------------------------------- ### Description The `Wheat` data frame has 48 rows and 4 columns. ### Format This data frame contains the following columns: Tray an ordered factor with levels `3` < `1` < `2` < `4` < `5` < `6` < `8` < `9` < `7` < `12` < `11` < `10` Moisture a numeric vector fertilizer a numeric vector DryMatter a numeric vector ### Source Pinheiro, J. C. and Bates, D. M. (2000), *Mixed-Effects Models in S and S-PLUS*, Springer, New York. r None `formula.reStruct` Extract reStruct Object Formula --------------------------------------------------- ### Description This method function extracts a formula from each of the components of `x`, returning a list of formulas. ### Usage ``` ## S3 method for class 'reStruct' formula(x, asList, ...) ``` ### Arguments | | | | --- | --- | | `x` | an object inheriting from class `"[reStruct](restruct)"`, representing a random effects structure and consisting of a list of `pdMat` objects. | | `asList` | logical. Should the asList argument be applied to each of the components? | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value a list with the formulas of each component of `x`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[formula](../../stats/html/formula)` ### Examples ``` rs1 <- reStruct(list(A = pdDiag(diag(2), ~age), B = ~1)) formula(rs1) ``` r None `solve.pdMat` Calculate Inverse of a Positive-Definite Matrix -------------------------------------------------------------- ### Description The positive-definite matrix represented by `a` is inverted and assigned to `a`. ### Usage ``` ## S3 method for class 'pdMat' solve(a, b, ...) ``` ### Arguments | | | | --- | --- | | `a` | an object inheriting from class `"[pdMat](pdmat)"`, representing a positive definite matrix. | | `b` | this argument is only included for consistency with the generic function and is not used in this method function. | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value a `pdMat` object similar to `a`, but with coefficients corresponding to the inverse of the positive-definite matrix represented by `a`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[pdMat](pdmat)` ### Examples ``` pd1 <- pdCompSymm(3 * diag(3) + 1) solve(pd1) ``` r None `getGroups.corStruct` Extract corStruct Groups ----------------------------------------------- ### Description This method function extracts the grouping factor associated with `object`, if any is present. ### Usage ``` ## S3 method for class 'corStruct' getGroups(object, form, level, data, sep) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `corStruct` representing a correlation structure. | | `form` | this argument is included to make the method function compatible with the generic. It will be assigned the value of `formula(object)` and should not be modified. | | `level` | this argument is included to make the method function compatible with the generic and is not used. | | `data` | an optional data frame in which to evaluate the variables defined in `form`, in case `object` is not initialized and the grouping factor needs to be evaluated. | | `sep` | character, the separator to use between group levels when multiple levels are collapsed. The default is `'/'`. | ### Value if a grouping factor is present in the correlation structure represented by `object`, the function returns the corresponding factor vector; else the function returns `NULL`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[getGroups](getgroups)` ### Examples ``` cs1 <- corAR1(form = ~ 1 | Subject) getGroups(cs1, data = Orthodont) ``` r None `plot.ACF` Plot an ACF Object ------------------------------ ### Description an `xyplot` of the autocorrelations versus the lags, with `type = "h"`, is produced. If `alpha > 0`, curves representing the critical limits for a two-sided test of level `alpha` for the autocorrelations are added to the plot. ### Usage ``` ## S3 method for class 'ACF' plot(x, alpha, xlab, ylab, grid, ...) ``` ### Arguments | | | | --- | --- | | `x` | an object inheriting from class `ACF`, consisting of a data frame with two columns named `lag` and `ACF`, representing the autocorrelation values and the corresponding lags. | | `alpha` | an optional numeric value with the significance level for testing if the autocorrelations are zero. Lines corresponding to the lower and upper critical values for a test of level `alpha` are added to the plot. Default is `0`, in which case no lines are plotted. | | `xlab,ylab` | optional character strings with the x- and y-axis labels. Default respectively to `"Lag"` and `"Autocorrelation"`. | | `grid` | an optional logical value indicating whether a grid should be added to plot. Default is `FALSE`. | | `...` | optional arguments passed to the `xyplot` function. | ### Value an `xyplot` Trellis plot. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[ACF](acf)`, `[xyplot](../../lattice/html/xyplot)` ### Examples ``` fm1 <- lme(follicles ~ sin(2*pi*Time) + cos(2*pi*Time), Ovary) plot(ACF(fm1, maxLag = 10), alpha = 0.01) ```
programming_docs
r None `plot.Variogram` Plot a Variogram Object ----------------------------------------- ### Description an `xyplot` of the semi-variogram versus the distances is produced. If `smooth = TRUE`, a `loess` smoother is added to the plot. If `showModel = TRUE` and `x` includes an `"modelVariog"` attribute, the corresponding semi-variogram is added to the plot. ### Usage ``` ## S3 method for class 'Variogram' plot(x, smooth, showModel, sigma, span, xlab, ylab, type, ylim, grid, ...) ``` ### Arguments | | | | --- | --- | | `x` | an object inheriting from class `"[Variogram](variogram)"`, consisting of a data frame with two columns named `variog` and `dist`, representing the semi-variogram values and the corresponding distances. | | `smooth` | an optional logical value controlling whether a `loess` smoother should be added to the plot. Defaults to `TRUE`, when `showModel` is `FALSE`. | | `showModel` | an optional logical value controlling whether the semi-variogram corresponding to an `"modelVariog"` attribute of `x`, if any is present, should be added to the plot. Defaults to `TRUE`, when the `"modelVariog"` attribute is present. | | `sigma` | an optional numeric value used as the height of a horizontal line displayed in the plot. Can be used to represent the process standard deviation. Default is `NULL`, implying that no horizontal line is drawn. | | `span` | an optional numeric value with the smoothing parameter for the `loess` fit. Default is 0.6. | | `xlab,ylab` | optional character strings with the x- and y-axis labels. Default respectively to `"Distance"` and `"SemiVariogram"`. | | `type` | an optional character indicating the type of plot. Defaults to `"p"`. | | `ylim` | an optional numeric vector with the limits for the y-axis. Defaults to `c(0, max(x$variog))`. | | `grid` | an optional logical value indicating whether a grid should be added to plot. Default is `FALSE`. | | `...` | optional arguments passed to the Trellis `xyplot` function. | ### Value an `xyplot` Trellis plot. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[Variogram](variogram)`, `[xyplot](../../lattice/html/xyplot)`, `[loess](../../stats/html/loess)` ### Examples ``` fm1 <- lme(follicles ~ sin(2*pi*Time) + cos(2*pi*Time), Ovary) plot(Variogram(fm1, form = ~ Time | Mare, maxDist = 0.7)) ``` r None `Milk` Protein content of cows' milk ------------------------------------- ### Description The `Milk` data frame has 1337 rows and 4 columns. ### Format This data frame contains the following columns: protein a numeric vector giving the protein content of the milk. Time a numeric vector giving the time since calving (weeks). Cow an ordered factor giving a unique identifier for each cow. Diet a factor with levels `barley`, `barley+lupins`, and `lupins` identifying the diet for each cow. ### Details Diggle, Liang, and Zeger (1994) describe data on the protein content of cows' milk in the weeks following calving. The cattle are grouped according to whether they are fed a diet with barley alone, with barley and lupins, or with lupins alone. ### Source Diggle, Peter J., Liang, Kung-Yee and Zeger, Scott L. (1994), *Analysis of longitudinal data*, Oxford University Press, Oxford. r None `nlmeStruct` Nonlinear Mixed-Effects Structure ----------------------------------------------- ### Description A nonlinear mixed-effects structure is a list of model components representing different sets of parameters in the nonlinear mixed-effects model. An `nlmeStruct` list must contain at least a `reStruct` object, but may also contain `corStruct` and `varFunc` objects. `NULL` arguments are not included in the `nlmeStruct` list. ### Usage ``` nlmeStruct(reStruct, corStruct, varStruct) ``` ### Arguments | | | | --- | --- | | `reStruct` | a `reStruct` representing a random effects structure. | | `corStruct` | an optional `corStruct` object, representing a correlation structure. Default is `NULL`. | | `varStruct` | an optional `varFunc` object, representing a variance function structure. Default is `NULL`. | ### Value a list of model components determining the parameters to be estimated for the associated nonlinear mixed-effects model. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[corClasses](corclasses)`, `<nlme>`, `[residuals.nlmeStruct](residuals.nlmestruct)`, `[reStruct](restruct)`, `[varFunc](varfunc)` ### Examples ``` nlms1 <- nlmeStruct(reStruct(~age), corAR1(), varPower()) ``` r None `pdSymm` General Positive-Definite Matrix ------------------------------------------ ### Description This function is a constructor for the `pdSymm` class, representing a general positive-definite matrix. If the matrix associated with `object` is of dimension *n*, it is represented by *n\*(n+1)/2* unrestricted parameters, using the matrix-logarithm parametrization described in Pinheiro and Bates (1996). When `value` is `numeric(0)`, an uninitialized `pdMat` object, a one-sided formula, or a vector of character strings, `object` is returned as an uninitialized `pdSymm` object (with just some of its attributes and its class defined) and needs to have its coefficients assigned later, generally using the `coef` or `matrix` replacement functions. If `value` is an initialized `pdMat` object, `object` will be constructed from `as.matrix(value)`. Finally, if `value` is a numeric vector, it is assumed to represent the unrestricted coefficients of the matrix-logarithm parametrization of the underlying positive-definite matrix. ### Usage ``` pdSymm(value, form, nam, data) ``` ### Arguments | | | | --- | --- | | `value` | an optional initialization value, which can be any of the following: a `pdMat` object, a positive-definite matrix, a one-sided linear formula (with variables separated by `+`), a vector of character strings, or a numeric vector. Defaults to `numeric(0)`, corresponding to an uninitialized object. | | `form` | an optional one-sided linear formula specifying the row/column names for the matrix represented by `object`. Because factors may be present in `form`, the formula needs to be evaluated on a data.frame to resolve the names it defines. This argument is ignored when `value` is a one-sided formula. Defaults to `NULL`. | | `nam` | an optional vector of character strings specifying the row/column names for the matrix represented by object. It must have length equal to the dimension of the underlying positive-definite matrix and unreplicated elements. This argument is ignored when `value` is a vector of character strings. Defaults to `NULL`. | | `data` | an optional data frame in which to evaluate the variables named in `value` and `form`. It is used to obtain the levels for `factors`, which affect the dimensions and the row/column names of the underlying matrix. If `NULL`, no attempt is made to obtain information on `factors` appearing in the formulas. Defaults to the parent frame from which the function was called. | ### Value a `pdSymm` object representing a general positive-definite matrix, also inheriting from class `pdMat`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Pinheiro, J.C. and Bates., D.M. (1996) "Unconstrained Parametrizations for Variance-Covariance Matrices", Statistics and Computing, 6, 289-296. Pinheiro, J.C., and Bates, D.M. (2000) "Mixed-Effects Models in S and S-PLUS", Springer. ### See Also `[as.matrix.pdMat](as.matrix.pdmat)`, `[coef.pdMat](coef.pdmat)`, `[pdClasses](pdclasses)`, `[matrix<-.pdMat](matrix.pdmat)` ### Examples ``` pd1 <- pdSymm(diag(1:3), nam = c("A","B","C")) pd1 ``` r None `coef.corStruct` Coefficients of a corStruct Object ---------------------------------------------------- ### Description This method function extracts the coefficients associated with the correlation structure represented by `object`. ### Usage ``` ## S3 method for class 'corStruct' coef(object, unconstrained, ...) ## S3 replacement method for class 'corStruct' coef(object, ...) <- value ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"[corStruct](corclasses)"`, representing a correlation structure. | | `unconstrained` | a logical value. If `TRUE` the coefficients are returned in unconstrained form (the same used in the optimization algorithm). If `FALSE` the coefficients are returned in "natural", possibly constrained, form. Defaults to `TRUE`. | | `value` | a vector with the replacement values for the coefficients associated with `object`. It must be a vector with the same length of `coef{object}` and must be given in unconstrained form. | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value a vector with the coefficients corresponding to `object`. ### SIDE EFFECTS On the left side of an assignment, sets the values of the coefficients of `object` to `value`. `Object` must be initialized (using `Initialize`) before new values can be assigned to its coefficients. ### Author(s) José Pinheiro and Douglas Bates ### References Pinheiro, J. C. and Bates, D. M. (2000), *Mixed-Effects Models in S and S-PLUS*, Springer, New York. ### See Also `[corAR1](corar1)`, `[corARMA](corarma)`, `[corCAR1](corcar1)`, `[corCompSymm](corcompsymm)`, `[corExp](corexp)`, `[corGaus](corgaus)`, `[corLin](corlin)`, `[corRatio](corratio)`, `[corSpatial](corspatial)`, `[corSpher](corspher)`, `[corSymm](corsymm)`,`[Initialize](initialize)` ### Examples ``` cst1 <- corARMA(p = 1, q = 1) coef(cst1) ``` r None `phenoModel` Model function for the Phenobarb data --------------------------------------------------- ### Description A model function for a model used with the `Phenobarb` data. This function uses compiled C code to improve execution speed. ### Usage ``` phenoModel(Subject, time, dose, lCl, lV) ``` ### Arguments | | | | --- | --- | | `Subject` | an integer vector of subject identifiers. These should be sorted in increasing order. | | `time` | numeric. A vector of the times at which the sample was drawn or the drug administered (hr). | | `dose` | numeric. A vector of doses of drug administered (*μ*g/kg). | | `lCl` | numeric. A vector of values of the natural log of the clearance parameter according to `Subject` and `time`. | | `lV` | numeric. A vector of values of the natural log of the effective volume of distribution according to `Subject` and `time`. | ### Details See the details section of `[Phenobarb](phenobarb)` for a description of the model function that `phenoModel` evaluates. ### Value a numeric vector of predicted phenobarbital concentrations. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Pinheiro, J. C. and Bates, D. M. (2000) *Mixed-effects Models in S and S-PLUS*, Springer. (section 6.4) r None `isBalanced` Check a Design for Balance ---------------------------------------- ### Description Check the design of the experiment or study for balance. ### Usage ``` isBalanced(object, countOnly, level) ``` ### Arguments | | | | --- | --- | | `object` | A `groupedData` object containing a data frame and a formula that describes the roles of variables in the data frame. The object will have one or more nested grouping factors and a primary covariate. | | `countOnly` | A logical value indicating if the check for balance should only consider the number of observations at each level of the grouping factor(s). Defaults to `FALSE`. | | `level` | an optional integer vector specifying the desired prediction levels. Levels increase from outermost to innermost grouping, with level 0 representing the population (fixed effects) predictions. Defaults to the innermost level. | ### Details A design is balanced with respect to the grouping factor(s) if there are the same number of observations at each distinct value of the grouping factor or each combination of distinct levels of the nested grouping factors. If `countOnly` is `FALSE` the design is also checked for balance with respect to the primary covariate, which is often the time of the observation. A design is balanced with respect to the grouping factor and the covariate if the number of observations at each distinct level (or combination of levels for nested factors) is constant and the times at which the observations are taken (in general, the values of the primary covariates) also are constant. ### Value `TRUE` or `FALSE` according to whether the data are balanced or not ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[table](../../base/html/table)`, `[groupedData](groupeddata)` ### Examples ``` isBalanced(Orthodont) # should return TRUE isBalanced(Orthodont, countOnly = TRUE) # should return TRUE isBalanced(Pixel) # should return FALSE isBalanced(Pixel, level = 1) # should return FALSE ``` r None `Variogram` Calculate Semi-variogram ------------------------------------- ### Description This function is generic; method functions can be written to handle specific classes of objects. Classes which already have methods for this function include `default`, `gls` and `lme`. See the appropriate method documentation for a description of the arguments. ### Usage ``` Variogram(object, distance, ...) ``` ### Arguments | | | | --- | --- | | `object` | a numeric vector with the values to be used for calculating the semi-variogram, usually a residual vector from a fitted model. | | `distance` | a numeric vector with the pairwise distances corresponding to the elements of `object`. The order of the elements in `distance` must correspond to the pairs `(1,2), (1,3), ..., (n-1,n)`, with `n` representing the length of `object`, and must have length `n(n-1)/2`. | | `...` | some methods for this generic function require additional arguments. | ### Value will depend on the method function used; see the appropriate documentation. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Cressie, N.A.C. (1993), "Statistics for Spatial Data", J. Wiley & Sons. Pinheiro, J.C., and Bates, D.M. (2000) "Mixed-Effects Models in S and S-PLUS", Springer. ### See Also `[Variogram.corExp](variogram.corexp)`, `[Variogram.corGaus](variogram.corgaus)`, `[Variogram.corLin](variogram.corlin)`, `[Variogram.corRatio](variogram.corratio)`, `[Variogram.corSpatial](variogram.corspatial)`, `[Variogram.corSpher](variogram.corspher)`, `[Variogram.default](variogram.default)`, `[Variogram.gls](variogram.gls)`, `[Variogram.lme](variogram.lme)`, `[plot.Variogram](plot.variogram)` ### Examples ``` ## see the method function documentation ``` r None `corExp` Exponential Correlation Structure ------------------------------------------- ### Description This function is a constructor for the `"corExp"` class, representing an exponential spatial correlation structure. Letting *d* denote the range and *n* denote the nugget effect, the correlation between two observations a distance *r* apart is *exp(-r/d)* when no nugget effect is present and *(1-n)\*exp(-r/d)* when a nugget effect is assumed. Objects created using this constructor must later be initialized using the appropriate `Initialize` method. ### Usage ``` corExp(value, form, nugget, metric, fixed) ``` ### Arguments | | | | --- | --- | | `value` | an optional vector with the parameter values in constrained form. If `nugget` is `FALSE`, `value` can have only one element, corresponding to the "range" of the exponential correlation structure, which must be greater than zero. If `nugget` is `TRUE`, meaning that a nugget effect is present, `value` can contain one or two elements, the first being the "range" and the second the "nugget effect" (one minus the correlation between two observations taken arbitrarily close together); the first must be greater than zero and the second must be between zero and one. Defaults to `numeric(0)`, which results in a range of 90% of the minimum distance and a nugget effect of 0.1 being assigned to the parameters when `object` is initialized. | | `form` | a one sided formula of the form `~ S1+...+Sp`, or `~ S1+...+Sp | g`, specifying spatial covariates `S1` through `Sp` and, optionally, a grouping factor `g`. When a grouping factor is present in `form`, the correlation structure is assumed to apply only to observations within the same grouping level; observations with different grouping levels are assumed to be uncorrelated. Defaults to `~ 1`, which corresponds to using the order of the observations in the data as a covariate, and no groups. | | `nugget` | an optional logical value indicating whether a nugget effect is present. Defaults to `FALSE`. | | `metric` | an optional character string specifying the distance metric to be used. The currently available options are `"euclidean"` for the root sum-of-squares of distances; `"maximum"` for the maximum difference; and `"manhattan"` for the sum of the absolute differences. Partial matching of arguments is used, so only the first three characters need to be provided. Defaults to `"euclidean"`. | | `fixed` | an optional logical value indicating whether the coefficients should be allowed to vary in the optimization, or kept fixed at their initial value. Defaults to `FALSE`, in which case the coefficients are allowed to vary. | ### Value an object of class `"corExp"`, also inheriting from class `"corSpatial"`, representing an exponential spatial correlation structure. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Cressie, N.A.C. (1993), "Statistics for Spatial Data", J. Wiley & Sons. Venables, W.N. and Ripley, B.D. (2002) "Modern Applied Statistics with S", 4th Edition, Springer-Verlag. Littel, Milliken, Stroup, and Wolfinger (1996) "SAS Systems for Mixed Models", SAS Institute. Pinheiro, J.C., and Bates, D.M. (2000) "Mixed-Effects Models in S and S-PLUS", Springer, esp. p. 238. ### See Also `[corClasses](corclasses)`, `[Initialize.corStruct](initialize.corstruct)`, `[summary.corStruct](summary.corstruct)`, `[dist](../../stats/html/dist)` ### Examples ``` sp1 <- corExp(form = ~ x + y + z) # Pinheiro and Bates, p. 238 spatDat <- data.frame(x = (0:4)/4, y = (0:4)/4) cs1Exp <- corExp(1, form = ~ x + y) cs1Exp <- Initialize(cs1Exp, spatDat) corMatrix(cs1Exp) cs2Exp <- corExp(1, form = ~ x + y, metric = "man") cs2Exp <- Initialize(cs2Exp, spatDat) corMatrix(cs2Exp) cs3Exp <- corExp(c(1, 0.2), form = ~ x + y, nugget = TRUE) cs3Exp <- Initialize(cs3Exp, spatDat) corMatrix(cs3Exp) # example lme(..., corExp ...) # Pinheiro and Bates, pp. 222-247 # p. 222 options(contrasts = c("contr.treatment", "contr.poly")) fm1BW.lme <- lme(weight ~ Time * Diet, BodyWeight, random = ~ Time) # p. 223 fm2BW.lme <- update(fm1BW.lme, weights = varPower()) # p. 246 fm3BW.lme <- update(fm2BW.lme, correlation = corExp(form = ~ Time)) # p. 247 fm4BW.lme <- update(fm3BW.lme, correlation = corExp(form = ~ Time, nugget = TRUE)) anova(fm3BW.lme, fm4BW.lme) ``` r None `gls` Fit Linear Model Using Generalized Least Squares ------------------------------------------------------- ### Description This function fits a linear model using generalized least squares. The errors are allowed to be correlated and/or have unequal variances. ### Usage ``` gls(model, data, correlation, weights, subset, method, na.action, control, verbose) ## S3 method for class 'gls' update(object, model., ..., evaluate = TRUE) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"gls"`, representing a generalized least squares fitted linear model. | | `model` | a two-sided linear formula object describing the model, with the response on the left of a `~` operator and the terms, separated by `+` operators, on the right. | | `model.` | Changes to the model – see `[update.formula](../../stats/html/update.formula)` for details. | | `data` | an optional data frame containing the variables named in `model`, `correlation`, `weights`, and `subset`. By default the variables are taken from the environment from which `gls` is called. | | `correlation` | an optional `[corStruct](corclasses)` object describing the within-group correlation structure. See the documentation of `[corClasses](corclasses)` for a description of the available `corStruct` classes. If a grouping variable is to be used, it must be specified in the `form` argument to the `corStruct` constructor. Defaults to `NULL`, corresponding to uncorrelated errors. | | `weights` | an optional `[varFunc](varfunc)` object or one-sided formula describing the within-group heteroscedasticity structure. If given as a formula, it is used as the argument to `[varFixed](varfixed)`, corresponding to fixed variance weights. See the documentation on `[varClasses](varclasses)` for a description of the available `[varFunc](varfunc)` classes. Defaults to `NULL`, corresponding to homoscedastic errors. | | `subset` | an optional expression indicating which subset of the rows of `data` should be used in the fit. This can be a logical vector, or a numeric vector indicating which observation numbers are to be included, or a character vector of the row names to be included. All observations are included by default. | | `method` | a character string. If `"REML"` the model is fit by maximizing the restricted log-likelihood. If `"ML"` the log-likelihood is maximized. Defaults to `"REML"`. | | `na.action` | a function that indicates what should happen when the data contain `NA`s. The default action (`[na.fail](../../stats/html/na.fail)`) causes `gls` to print an error message and terminate if there are any incomplete observations. | | `control` | a list of control values for the estimation algorithm to replace the default values returned by the function `[glsControl](glscontrol)`. Defaults to an empty list. | | `verbose` | an optional logical value. If `TRUE` information on the evolution of the iterative algorithm is printed. Default is `FALSE`. | | `...` | some methods for this generic require additional arguments. None are used in this method. | | `evaluate` | If `TRUE` evaluate the new call else return the call. | ### Value an object of class `"gls"` representing the linear model fit. Generic functions such as `print`, `plot`, and `summary` have methods to show the results of the fit. See `[glsObject](glsobject)` for the components of the fit. The functions `[resid](../../stats/html/residuals)`, `[coef](../../stats/html/coef)` and `[fitted](../../stats/html/fitted.values)`, can be used to extract some of its components. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References The different correlation structures available for the `correlation` argument are described in Box, G.E.P., Jenkins, G.M., and Reinsel G.C. (1994), Littel, R.C., Milliken, G.A., Stroup, W.W., and Wolfinger, R.D. (1996), and Venables, W.N. and Ripley, B.D. (2002). The use of variance functions for linear and nonlinear models is presented in detail in Carroll, R.J. and Ruppert, D. (1988) and Davidian, M. and Giltinan, D.M. (1995). Box, G.E.P., Jenkins, G.M., and Reinsel G.C. (1994) "Time Series Analysis: Forecasting and Control", 3rd Edition, Holden-Day. Carroll, R.J. and Ruppert, D. (1988) "Transformation and Weighting in Regression", Chapman and Hall. Davidian, M. and Giltinan, D.M. (1995) "Nonlinear Mixed Effects Models for Repeated Measurement Data", Chapman and Hall. Littel, R.C., Milliken, G.A., Stroup, W.W., and Wolfinger, R.D. (1996) "SAS Systems for Mixed Models", SAS Institute. Pinheiro, J.C., and Bates, D.M. (2000) "Mixed-Effects Models in S and S-PLUS", Springer, esp. pp. 100, 461. Venables, W.N. and Ripley, B.D. (2002) "Modern Applied Statistics with S", 4th Edition, Springer-Verlag. ### See Also `[corClasses](corclasses)`, `[glsControl](glscontrol)`, `[glsObject](glsobject)`, `[glsStruct](glsstruct)`, `<plot.gls>`, `<predict.gls>`, `<qqnorm.gls>`, `<residuals.gls>`, `<summary.gls>`, `[varClasses](varclasses)`, `[varFunc](varfunc)` ### Examples ``` # AR(1) errors within each Mare fm1 <- gls(follicles ~ sin(2*pi*Time) + cos(2*pi*Time), Ovary, correlation = corAR1(form = ~ 1 | Mare)) # variance increases as a power of the absolute fitted values fm2 <- update(fm1, weights = varPower()) ```
programming_docs
r None `nlmeControl` Control Values for nlme Fit ------------------------------------------ ### Description The values supplied in the function call replace the defaults and a list with all possible arguments is returned. The returned list is used as the `control` argument to the `nlme` function. ### Usage ``` nlmeControl(maxIter, pnlsMaxIter, msMaxIter, minScale, tolerance, niterEM, pnlsTol, msTol, returnObject, msVerbose, msWarnNoConv, gradHess, apVar, .relStep, minAbsParApVar = 0.05, opt = c("nlminb", "nlm"), natural = TRUE, sigma = NULL, ...) ``` ### Arguments | | | | --- | --- | | `maxIter` | maximum number of iterations for the `nlme` optimization algorithm. Default is 50. | | `pnlsMaxIter` | maximum number of iterations for the `PNLS` optimization step inside the `nlme` optimization. Default is 7. | | `msMaxIter` | maximum number of iterations for `[nlminb](../../stats/html/nlminb)` (`iter.max`) or the `[nlm](../../stats/html/nlm)` (`iterlim`, from the 10-th step) optimization step inside the `nlme` optimization. Default is 50 (which may be too small for e.g. for overparametrized cases). | | `minScale` | minimum factor by which to shrink the default step size in an attempt to decrease the sum of squares in the `PNLS` step. Default `0.001`. | | `tolerance` | tolerance for the convergence criterion in the `nlme` algorithm. Default is `1e-6`. | | `niterEM` | number of iterations for the EM algorithm used to refine the initial estimates of the random effects variance-covariance coefficients. Default is 25. | | `pnlsTol` | tolerance for the convergence criterion in `PNLS` step. Default is `1e-3`. | | `msTol` | tolerance for the convergence criterion in `nlm`, passed as the `gradtol` argument to the function (see documentation on `nlm`). Default is `1e-7`. | | `returnObject` | a logical value indicating whether the fitted object should be returned when the maximum number of iterations is reached without convergence of the algorithm. Default is `FALSE`. | | `msVerbose` | a logical value passed as the `trace` to `[nlminb](../../stats/html/nlminb)(.., control= list(trace = *, ..))` or as argument `print.level` to `[nlm](../../stats/html/nlm)()`. Default is `FALSE`. | | `msWarnNoConv` | logical indicating if a `[warning](../../base/html/warning)` should be signalled whenever the minimization by (`opt`) in the LME step does not converge; defaults to `TRUE`. | | `gradHess` | a logical value indicating whether numerical gradient vectors and Hessian matrices of the log-likelihood function should be used in the `nlm` optimization. This option is only available when the correlation structure (`corStruct`) and the variance function structure (`varFunc`) have no "varying" parameters and the `pdMat` classes used in the random effects structure are `pdSymm` (general positive-definite), `pdDiag` (diagonal), `pdIdent` (multiple of the identity), or `pdCompSymm` (compound symmetry). Default is `TRUE`. | | `apVar` | a logical value indicating whether the approximate covariance matrix of the variance-covariance parameters should be calculated. Default is `TRUE`. | | `.relStep` | relative step for numerical derivatives calculations. Default is `.Machine$double.eps^(1/3)`. | | `minAbsParApVar` | numeric value - minimum absolute parameter value in the approximate variance calculation. The default is `0.05`. | | `opt` | the optimizer to be used, either `"[nlminb](../../stats/html/nlminb)"` (the default) or `"[nlm](../../stats/html/nlm)"`. | | `natural` | a logical value indicating whether the `pdNatural` parametrization should be used for general positive-definite matrices (`pdSymm`) in `reStruct`, when the approximate covariance matrix of the estimators is calculated. Default is `TRUE`. | | `sigma` | optionally a positive number to fix the residual error at. If `NULL`, as by default, or `0`, sigma is estimated. | | `...` | Further, named control arguments to be passed to `[nlminb](../../stats/html/nlminb)` (apart from `trace` and `iter.max` mentioned above), where used (`eval.max` and those from `abs.tol` down). | ### Value a list with components for each of the possible arguments. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]); the `sigma` option: Siem Heisterkamp and Bert van Willigen. ### See Also `<nlme>`, `[nlm](../../stats/html/nlm)`, `[optim](../../stats/html/optim)`, `[nlmeStruct](nlmestruct)` ### Examples ``` # decrease the maximum number iterations in the ms call and # request that information on the evolution of the ms iterations be printed nlmeControl(msMaxIter = 20, msVerbose = TRUE) ``` r None `pdConstruct` Construct pdMat Objects -------------------------------------- ### Description This function is an alternative constructor for the `pdMat` class associated with `object` and is mostly used internally in other functions. See the documentation on the principal constructor function, generally with the same name as the `pdMat` class of object. ### Usage ``` pdConstruct(object, value, form, nam, data, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `pdMat`, representing a positive definite matrix. | | `value` | an optional initialization value, which can be any of the following: a `pdMat` object, a positive-definite matrix, a one-sided linear formula (with variables separated by `+`), a vector of character strings, or a numeric vector. Defaults to `numeric(0)`, corresponding to an uninitialized object. | | `form` | an optional one-sided linear formula specifying the row/column names for the matrix represented by `object`. Because factors may be present in `form`, the formula needs to be evaluated on a data.frame to resolve the names it defines. This argument is ignored when `value` is a one-sided formula. Defaults to `NULL`. | | `nam` | an optional vector of character strings specifying the row/column names for the matrix represented by object. It must have length equal to the dimension of the underlying positive-definite matrix and unreplicated elements. This argument is ignored when `value` is a vector of character strings. Defaults to `NULL`. | | `data` | an optional data frame in which to evaluate the variables named in `value` and `form`. It is used to obtain the levels for `factors`, which affect the dimensions and the row/column names of the underlying matrix. If `NULL`, no attempt is made to obtain information on `factors` appearing in the formulas. Defaults to the parent frame from which the function was called. | | `...` | optional arguments for some methods. | ### Value a `pdMat` object representing a positive-definite matrix, inheriting from the same classes as `object`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[pdCompSymm](pdcompsymm)`, `[pdDiag](pddiag)`, `[pdIdent](pdident)`, `[pdNatural](pdnatural)`, `[pdSymm](pdsymm)` ### Examples ``` pd1 <- pdSymm() pdConstruct(pd1, diag(1:4)) ``` r None `coef.gnls` Extract gnls Coefficients -------------------------------------- ### Description The estimated coefficients for the nonlinear model represented by `object` are extracted. ### Usage ``` ## S3 method for class 'gnls' coef(object, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"<gnls>"`, representing a generalized nonlinear least squares fitted model. | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value a vector with the estimated coefficients for the nonlinear model represented by `object`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `<gnls>` ### Examples ``` fm1 <- gnls(weight ~ SSlogis(Time, Asym, xmid, scal), Soybean, weights = varPower()) coef(fm1) ``` r None `comparePred` Compare Predictions ---------------------------------- ### Description Predicted values are obtained at the specified values of `primary` for each object. If either `object1` or `object2` have a grouping structure (i.e. `getGroups(object)` is not `NULL`), predicted values are obtained for each group. When both objects determine groups, the group levels must be the same. If other covariates besides `primary` are used in the prediction model, their group-wise averages (numeric covariates) or most frequent values (categorical covariates) are used to obtain the predicted values. The original observations are also included in the returned object. ### Usage ``` comparePred(object1, object2, primary, minimum, maximum, length.out, level, ...) ``` ### Arguments | | | | --- | --- | | `object1,object2` | fitted model objects, from which predictions can be extracted using the `predict` method. | | `primary` | an optional one-sided formula specifying the primary covariate to be used to generate the augmented predictions. By default, if a covariate can be extracted from the data used to generate the objects (using `getCovariate`), it will be used as `primary`. | | `minimum` | an optional lower limit for the primary covariate. Defaults to `min(primary)`, after `primary` is evaluated in the `data` used in fitting `object1`. | | `maximum` | an optional upper limit for the primary covariate. Defaults to `max(primary)`, after `primary` is evaluated in the `data` used in fitting `object1`. | | `length.out` | an optional integer with the number of primary covariate values at which to evaluate the predictions. Defaults to 51. | | `level` | an optional integer specifying the desired prediction level. Levels increase from outermost to innermost grouping, with level 0 representing the population (fixed effects) predictions. Only one level can be specified. Defaults to the innermost level. | | `...` | some methods for the generic may require additional arguments. | ### Value a data frame with four columns representing, respectively, the values of the primary covariate, the groups (if `object` does not have a grouping structure, all elements will be `1`), the predicted or observed values, and the type of value in the third column: the objects' names are used to classify the predicted values and `original` is used for the observed values. The returned object inherits from classes `comparePred` and `augPred`. ### Note This function is generic; method functions can be written to handle specific classes of objects. Classes which already have methods for this function include: `gls`, `lme`, and `lmList`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[augPred](augpred)`, `[getGroups](getgroups)` ### Examples ``` fm1 <- lme(distance ~ age * Sex, data = Orthodont, random = ~ age) fm2 <- update(fm1, distance ~ age) comparePred(fm1, fm2, length.out = 2) ``` r None `summary.corStruct` Summarize a corStruct Object ------------------------------------------------- ### Description This method function prepares `object` to be printed using the `print.summary` method, by changing its class and adding a `structName` attribute to it. ### Usage ``` ## S3 method for class 'corStruct' summary(object, structName, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"[corStruct](corclasses)"`, representing a correlation structure. | | `structName` | an optional character string defining the type of correlation structure associated with `object`, to be used in the `print.summary` method. Defaults to `class(object)[1]`. | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value an object identical to `object`, but with its class changed to `summary.corStruct` and an additional attribute `structName`. The returned value inherits from the same classes as `object`. ### Author(s) José Pinheiro and Douglas Bates ### See Also `[corClasses](corclasses)`, `[corNatural](cornatural)`, `[Initialize.corStruct](initialize.corstruct)`, `[summary](../../base/html/summary)` ### Examples ``` cs1 <- corAR1(0.2) summary(cs1) ``` r None `allCoef` Extract Coefficients from a Set of Objects ----------------------------------------------------- ### Description The extractor function is applied to each object in `...`, with the result being converted to a vector. A `map` attribute is included to indicate which pieces of the returned vector correspond to the original objects in `dots`. ### Usage ``` allCoef(..., extract) ``` ### Arguments | | | | --- | --- | | `...` | objects to which `extract` will be applied. Generally these will be model components, such as `corStruct` and `varFunc` objects. | | `extract` | an optional extractor function. Defaults to `coef`. | ### Value a vector with all elements, generally coefficients, obtained by applying `extract` to the objects in `...`. ### Author(s) José' Pinheiro and Douglas Bates ### See Also `[lmeStruct](lmestruct)`,`[nlmeStruct](nlmestruct)` ### Examples ``` cs1 <- corAR1(0.1) vf1 <- varPower(0.5) allCoef(cs1, vf1) ``` r None `predict.nlme` Predictions from an nlme Object ----------------------------------------------- ### Description The predictions at level *i* are obtained by adding together the contributions from the estimated fixed effects and the estimated random effects at levels less or equal to *i* and evaluating the model function at the resulting estimated parameters. If group values not included in the original grouping factors are present in `newdata`, the corresponding predictions will be set to `NA` for levels greater or equal to the level at which the unknown groups occur. ### Usage ``` ## S3 method for class 'nlme' predict(object, newdata, level = Q, asList = FALSE, na.action = na.fail, naPattern = NULL, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"<nlme>"`, representing a fitted nonlinear mixed-effects model. | | `newdata` | an optional data frame to be used for obtaining the predictions. All variables used in the nonlinear model, the fixed and the random effects models, as well as the grouping factors, must be present in the data frame. If missing, the fitted values are returned. | | `level` | an optional integer vector giving the level(s) of grouping to be used in obtaining the predictions. Level values increase from outermost to innermost grouping, with level zero corresponding to the population predictions. Defaults to the highest or innermost level of grouping (and is `object$dims$Q`). | | `asList` | an optional logical value. If `TRUE` and a single value is given in `level`, the returned object is a list with the predictions split by groups; else the returned value is either a vector or a data frame, according to the length of `level`. | | `na.action` | a function that indicates what should happen when `newdata` contains `NA`s. The default action (`na.fail`) causes the function to print an error message and terminate if there are any incomplete observations. | | `naPattern` | an expression or formula object, specifying which returned values are to be regarded as missing. | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value if a single level of grouping is specified in `level`, the returned value is either a list with the predictions split by groups (`asList = TRUE`) or a vector with the predictions (`asList = FALSE`); else, when multiple grouping levels are specified in `level`, the returned object is a data frame with columns given by the predictions at different levels and the grouping factors. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `<nlme>`, `<fitted.lme>` ### Examples ``` head(Loblolly) # groupedData w/ 'Seed' is grouping variable : ## Grouped Data: height ~ age | Seed ## height age Seed ## 1 4.51 3 301 ## 15 10.89 5 301 ## .. ..... . ... fm1 <- nlme(height ~ SSasymp(age, Asym, R0, lrc), data = Loblolly, fixed = Asym + R0 + lrc ~ 1, random = Asym ~ 1, ## <---grouping---> Asym ~ 1 | Seed start = c(Asym = 103, R0 = -8.5, lrc = -3.3)) fm1 age. <- seq(from = 2, to = 30, by = 2) newLL.301 <- data.frame(age = age., Seed = 301) newLL.329 <- data.frame(age = age., Seed = 329) (p301 <- predict(fm1, newLL.301, level = 0:1)) (p329 <- predict(fm1, newLL.329, level = 0:1)) ## Prediction are the same at level 0 : all.equal(p301[,"predict.fixed"], p329[,"predict.fixed"]) ## and differ by the 'Seed' effect at level 1 : p301[,"predict.Seed"] - p329[,"predict.Seed"] ``` r None `logLik.gnls` Log-Likelihood of a gnls Object ---------------------------------------------- ### Description Returns the log-likelihood value of the nonlinear model represented by `object` evaluated at the estimated coefficients. ### Usage ``` ## S3 method for class 'gnls' logLik(object, REML, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"<gnls>"`, representing a generalized nonlinear least squares fitted model. | | `REML` | an logical value for consistency with `logLik,gls`, but only `FALSE` is accepted.. | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value the log-likelihood of the linear model represented by `object` evaluated at the estimated coefficients. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `<gnls>`, `[logLik.lme](loglik.lme)` ### Examples ``` fm1 <- gnls(weight ~ SSlogis(Time, Asym, xmid, scal), Soybean, weights = varPower()) logLik(fm1) ``` r None `Dim.pdMat` Dimensions of a pdMat Object ----------------------------------------- ### Description This method function returns the dimensions of the matrix represented by `object`. ### Usage ``` ## S3 method for class 'pdMat' Dim(object, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"[pdMat](pdmat)"`, representing a positive-definite matrix. | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value an integer vector with the number of rows and columns of the matrix represented by `object`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[Dim](dim)` ### Examples ``` Dim(pdSymm(diag(3))) ``` r None `coef.pdMat` pdMat Object Coefficients --------------------------------------- ### Description This method function extracts the coefficients associated with the positive-definite matrix represented by `object`. ### Usage ``` ## S3 method for class 'pdMat' coef(object, unconstrained, ...) ## S3 replacement method for class 'pdMat' coef(object, ...) <- value ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"[pdMat](pdmat)"`, representing a positive-definite matrix. | | `unconstrained` | a logical value. If `TRUE` the coefficients are returned in unconstrained form (the same used in the optimization algorithm). If `FALSE` the upper triangular elements of the positive-definite matrix represented by `object` are returned. Defaults to `TRUE`. | | `value` | a vector with the replacement values for the coefficients associated with `object`. It must be a vector with the same length of `coef{object}` and must be given in unconstrained form. | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value a vector with the coefficients corresponding to `object`. ### SIDE EFFECTS On the left side of an assignment, sets the values of the coefficients of `object` to `value`. ### Author(s) José Pinheiro and Douglas Bates ### References Pinheiro, J.C. and Bates., D.M. (1996) "Unconstrained Parametrizations for Variance-Covariance Matrices", Statistics and Computing, 6, 289-296. ### See Also `[pdMat](pdmat)` ### Examples ``` coef(pdSymm(diag(3))) ```
programming_docs
r None `intervals.gls` Confidence Intervals on gls Parameters ------------------------------------------------------- ### Description Approximate confidence intervals for the parameters in the linear model represented by `object` are obtained, using a normal approximation to the distribution of the (restricted) maximum likelihood estimators (the estimators are assumed to have a normal distribution centered at the true parameter values and with covariance matrix equal to the negative inverse Hessian matrix of the (restricted) log-likelihood evaluated at the estimated parameters). Confidence intervals are obtained in an unconstrained scale first, using the normal approximation, and, if necessary, transformed to the constrained scale. ### Usage ``` ## S3 method for class 'gls' intervals(object, level, which, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"<gls>"`, representing a generalized least squares fitted linear model. | | `level` | an optional numeric value for the interval confidence level. Defaults to 0.95. | | `which` | an optional character string specifying the subset of parameters for which to construct the confidence intervals. Possible values are `"all"` for all parameters, `"var-cov"` for the variance-covariance parameters only, and `"coef"` for the linear model coefficients only. Defaults to `"all"`. | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value a list with components given by data frames with rows corresponding to parameters and columns `lower`, `est.`, and `upper` representing respectively lower confidence limits, the estimated values, and upper confidence limits for the parameters. Possible components are: | | | | --- | --- | | `coef` | linear model coefficients, only present when `which` is not equal to `"var-cov"`. | | `corStruct` | correlation parameters, only present when `which` is not equal to `"coef"` and a correlation structure is used in `object`. | | `varFunc` | variance function parameters, only present when `which` is not equal to `"coef"` and a variance function structure is used in `object`. | | `sigma` | residual standard error. | ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Pinheiro, J.C., and Bates, D.M. (2000) "Mixed-Effects Models in S and S-PLUS", Springer. ### See Also `<gls>`, `<intervals>`, `[print.intervals.gls](intervals.gls)` ### Examples ``` fm1 <- gls(follicles ~ sin(2*pi*Time) + cos(2*pi*Time), Ovary, correlation = corAR1(form = ~ 1 | Mare)) intervals(fm1) ``` r None `Rail` Evaluation of Stress in Railway Rails --------------------------------------------- ### Description The `Rail` data frame has 18 rows and 2 columns. ### Format This data frame contains the following columns: Rail an ordered factor identifying the rail on which the measurement was made. travel a numeric vector giving the travel time for ultrasonic head-waves in the rail (nanoseconds). The value given is the original travel time minus 36,100 nanoseconds. ### Details Devore (2000, Example 10.10, p. 427) cites data from an article in *Materials Evaluation* on “a study of travel time for a certain type of wave that results from longitudinal stress of rails used for railroad track.” ### Source Pinheiro, J. C. and Bates, D. M. (2000), *Mixed-Effects Models in S and S-PLUS*, Springer, New York. (Appendix A.26) Devore, J. L. (2000), *Probability and Statistics for Engineering and the Sciences (5th ed)*, Duxbury, Boston, MA. r None `model.matrix.reStruct` reStruct Model Matrix ---------------------------------------------- ### Description The model matrices for each element of `formula(object)`, calculated using `data`, are bound together column-wise. When multiple grouping levels are present (i.e. when `length(object) > 1`), the individual model matrices are combined from innermost (at the leftmost position) to outermost (at the rightmost position). ### Usage ``` ## S3 method for class 'reStruct' model.matrix(object, data, contrast, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"[reStruct](restruct)"`, representing a random effects structure and consisting of a list of `pdMat` objects. | | `data` | a data frame in which to evaluate the variables defined in `formula(object)`. | | `contrast` | an optional named list specifying the contrasts to be used for representing the `factor` variables in `data`. The components names should match the names of the variables in `data` for which the contrasts are to be specified. The components of this list will be used as the `contrasts` attribute of the corresponding factor. If missing, the default contrast specification is used. | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value a matrix obtained by binding together, column-wise, the model matrices for each element of `formula(object)`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[model.matrix](../../stats/html/model.matrix)`, `[contrasts](../../stats/html/contrasts)`, `[reStruct](restruct)`, `[formula.reStruct](formula.restruct)` ### Examples ``` rs1 <- reStruct(list(Dog = ~day, Side = ~1), data = Pixel) model.matrix(rs1, Pixel) ``` r None `ACF.lme` Autocorrelation Function for lme Residuals ----------------------------------------------------- ### Description This method function calculates the empirical autocorrelation function for the within-group residuals from an `lme` fit. The autocorrelation values are calculated using pairs of residuals within the innermost group level. The autocorrelation function is useful for investigating serial correlation models for equally spaced data. ### Usage ``` ## S3 method for class 'lme' ACF(object, maxLag, resType, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"<lme>"`, representing a fitted linear mixed-effects model. | | `maxLag` | an optional integer giving the maximum lag for which the autocorrelation should be calculated. Defaults to maximum lag in the within-group residuals. | | `resType` | an optional character string specifying the type of residuals to be used. If `"response"`, the "raw" residuals (observed - fitted) are used; else, if `"pearson"`, the standardized residuals (raw residuals divided by the corresponding standard errors) are used; else, if `"normalized"`, the normalized residuals (standardized residuals pre-multiplied by the inverse square-root factor of the estimated error correlation matrix) are used. Partial matching of arguments is used, so only the first character needs to be provided. Defaults to `"pearson"`. | | `...` | some methods for this generic require additional arguments – not used. | ### Value a data frame with columns `lag` and `ACF` representing, respectively, the lag between residuals within a pair and the corresponding empirical autocorrelation. The returned value inherits from class `ACF`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Box, G.E.P., Jenkins, G.M., and Reinsel G.C. (1994) "Time Series Analysis: Forecasting and Control", 3rd Edition, Holden-Day. Pinheiro, J.C., and Bates, D.M. (2000) "Mixed-Effects Models in S and S-PLUS", Springer. ### See Also `[ACF.gls](acf.gls)`, `[plot.ACF](plot.acf)` ### Examples ``` fm1 <- lme(follicles ~ sin(2*pi*Time) + cos(2*pi*Time), Ovary, random = ~ sin(2*pi*Time) | Mare) ACF(fm1, maxLag = 11) # Pinheiro and Bates, p240-241 fm1Over.lme <- lme(follicles ~ sin(2*pi*Time) + cos(2*pi*Time), data=Ovary, random=pdDiag(~sin(2*pi*Time)) ) (ACF.fm1Over <- ACF(fm1Over.lme, maxLag=10)) plot(ACF.fm1Over, alpha=0.01) ``` r None `lme.lmList` LME fit from lmList Object ---------------------------------------- ### Description If the random effects names defined in `random` are a subset of the `lmList` object coefficient names, initial estimates for the covariance matrix of the random effects are obtained (overwriting any values given in `random`). `formula(fixed)` and the `data` argument in the calling sequence used to obtain `fixed` are passed as the `fixed` and `data` arguments to `lme.formula`, together with any other additional arguments in the function call. See the documentation on `lme.formula` for a description of that function. ### Usage ``` ## S3 method for class 'lmList' lme(fixed, data, random, correlation, weights, subset, method, na.action, control, contrasts, keep.data) ``` ### Arguments | | | | --- | --- | | `fixed` | an object inheriting from class `"[lmList](lmlist)."`, representing a list of `lm` fits with a common model. | | `data` | this argument is included for consistency with the generic function. It is ignored in this method function. | | `random` | an optional one-sided linear formula with no conditioning expression, or a `pdMat` object with a `formula` attribute. Multiple levels of grouping are not allowed with this method function. Defaults to a formula consisting of the right hand side of `formula(fixed)`. | | `correlation` | an optional `corStruct` object describing the within-group correlation structure. See the documentation of `corClasses` for a description of the available `corStruct` classes. Defaults to `NULL`, corresponding to no within-group correlations. | | `weights` | an optional `varFunc` object or one-sided formula describing the within-group heteroscedasticity structure. If given as a formula, it is used as the argument to `varFixed`, corresponding to fixed variance weights. See the documentation on `varClasses` for a description of the available `varFunc` classes. Defaults to `NULL`, corresponding to homoscedastic within-group errors. | | `subset` | an optional expression indicating the subset of the rows of `data` that should be used in the fit. This can be a logical vector, or a numeric vector indicating which observation numbers are to be included, or a character vector of the row names to be included. All observations are included by default. | | `method` | a character string. If `"REML"` the model is fit by maximizing the restricted log-likelihood. If `"ML"` the log-likelihood is maximized. Defaults to `"REML"`. | | `na.action` | a function that indicates what should happen when the data contain `NA`s. The default action (`na.fail`) causes `lme` to print an error message and terminate if there are any incomplete observations. | | `control` | a list of control values for the estimation algorithm to replace the default values returned by the function `lmeControl`. Defaults to an empty list. | | `contrasts` | an optional list. See the `contrasts.arg` of `model.matrix.default`. | | `keep.data` | logical: should the `data` argument (if supplied and a data frame) be saved as part of the model object? | ### Value an object of class `lme` representing the linear mixed-effects model fit. Generic functions such as `print`, `plot` and `summary` have methods to show the results of the fit. See `lmeObject` for the components of the fit. The functions `resid`, `coef`, `fitted`, `fixed.effects`, and `random.effects` can be used to extract some of its components. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References The computational methods follow the general framework of Lindstrom and Bates (1988). The model formulation is described in Laird and Ware (1982). The variance-covariance parametrizations are described in Pinheiro and Bates (1996). The different correlation structures available for the `correlation` argument are described in Box, Jenkins and Reinse (1994), Littel *et al* (1996), and Venables and Ripley, (2002). The use of variance functions for linear and nonlinear mixed effects models is presented in detail in Davidian and Giltinan (1995). Box, G.E.P., Jenkins, G.M., and Reinsel G.C. (1994) "Time Series Analysis: Forecasting and Control", 3rd Edition, Holden–Day. Davidian, M. and Giltinan, D.M. (1995) "Nonlinear Mixed Effects Models for Repeated Measurement Data", Chapman and Hall. Laird, N.M. and Ware, J.H. (1982) "Random-Effects Models for Longitudinal Data", Biometrics, 38, 963–974. Lindstrom, M.J. and Bates, D.M. (1988) "Newton-Raphson and EM Algorithms for Linear Mixed-Effects Models for Repeated-Measures Data", Journal of the American Statistical Association, 83, 1014–1022. Littel, R.C., Milliken, G.A., Stroup, W.W., and Wolfinger, R.D. (1996) "SAS Systems for Mixed Models", SAS Institute. Pinheiro, J.C. and Bates., D.M. (1996) "Unconstrained Parametrizations for Variance-Covariance Matrices", Statistics and Computing, 6, 289–296. Venables, W.N. and Ripley, B.D. (2002) "Modern Applied Statistics with S", 4th Edition, Springer-Verlag. ### See Also `<lme>`, `[lmList](lmlist)`, `[lmeObject](lmeobject)` ### Examples ``` fm1 <- lmList(Orthodont) fm2 <- lme(fm1) summary(fm1) summary(fm2) ``` r None `summary.nlsList` Summarize an nlsList Object ---------------------------------------------- ### Description The `summary` function is applied to each `nls` component of `object` to produce summary information on the individual fits, which is organized into a list of summary statistics. The returned object is suitable for printing with the `print.summary.nlsList` method. ### Usage ``` ## S3 method for class 'nlsList' summary(object, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"[nlsList](nlslist)"`, representing a list of `nls` fitted objects. | | `...` | optional arguments to the `summary.lmList` method. One such optional argument is `pool`, a logical value indicating whether a pooled estimate of the residual standard error should be used. Default is `attr(object, "pool")`. | ### Value a list with summary statistics obtained by applying `summary` to the elements of `object`, inheriting from class `summary.nlsList`. The components of `value` are: | | | | --- | --- | | `call` | a list containing an image of the `nlsList` call that produced `object`. | | `parameters` | a three dimensional array with summary information on the `nls` coefficients. The first dimension corresponds to the names of the `object` components, the second dimension is given by `"Value"`, `"Std. Error"`, `"t value"`, and `"Pr(>|t|)"`, corresponding, respectively, to the coefficient estimates and their associated standard errors, t-values, and p-values. The third dimension is given by the coefficients names. | | `correlation` | a three dimensional array with the correlations between the individual `nls` coefficient estimates. The first dimension corresponds to the names of the `object` components. The third dimension is given by the coefficients names. For each coefficient, the rows of the associated array give the correlations between that coefficient and the remaining coefficients, by `nls` component. | | `cov.unscaled` | a three dimensional array with the unscaled variances/covariances for the individual `lm` coefficient estimates (giving the estimated variance/covariance for the coefficients, when multiplied by the estimated residual errors). The first dimension corresponds to the names of the `object` components. The third dimension is given by the coefficients names. For each coefficient, the rows of the associated array give the unscaled covariances between that coefficient and the remaining coefficients, by `nls` component. | | `df` | an array with the number of degrees of freedom for the model and for residuals, for each `nls` component. | | `df.residual` | the total number of degrees of freedom for residuals, corresponding to the sum of residuals df of all `nls` components. | | `pool` | the value of the `pool` argument to the function. | | `RSE` | the pooled estimate of the residual standard error. | | `sigma` | a vector with the residual standard error estimates for the individual `lm` fits. | ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[nlsList](nlslist)`, `[summary](../../base/html/summary)` ### Examples ``` fm1 <- nlsList(SSasymp, Loblolly) summary(fm1) ``` r None `summary.varFunc` Summarize "varFunc" Object --------------------------------------------- ### Description A `structName` attribute, with the value of corresponding argument, is appended to `object` and its class is changed to `summary.varFunc`. ### Usage ``` ## S3 method for class 'varFunc' summary(object, structName, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"[varFunc](varfunc)"`, representing a variance function structure. | | `structName` | an optional character string with a description of the `varFunc` class. Default depends on the method function: for `varComb`: `"Combination of variance functions"`, for `varConstPower`: `"Constant plus power of variance covariate"`, for `varConstProp`: `"Constant plus proportion of variance covariate"`, for `varExp`: `"Exponential of variance covariate"`, for `varIdent`: `"Different standard deviations per stratum"`, for `varPower`: `"Power of variance covariate"`, for `varFunc`: `data.class(object)`. | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value an object similar to `object`, with an additional attribute `structName`, inheriting from class `summary.varFunc`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[varClasses](varclasses)`, `[varFunc](varfunc)` ### Examples ``` vf1 <- varPower(0.3, form = ~age) vf1 <- Initialize(vf1, Orthodont) summary(vf1) ``` r None `predict.lmList` Predictions from an lmList Object --------------------------------------------------- ### Description If the grouping factor corresponding to `object` is included in `newdata`, the data frame is partitioned according to the grouping factor levels; else, `newdata` is repeated for all `lm` components. The predictions and, optionally, the standard errors for the predictions, are obtained for each `lm` component of `object`, using the corresponding element of the partitioned `newdata`, and arranged into a list with as many components as `object`, or combined into a single vector or data frame (if `se.fit=TRUE`). ### Usage ``` ## S3 method for class 'lmList' predict(object, newdata, subset, pool, asList, se.fit, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"[lmList](lmlist)"`, representing a list of `lm` objects with a common model. | | `newdata` | an optional data frame to be used for obtaining the predictions. All variables used in the `object` model formula must be present in the data frame. If missing, the same data frame used to produce `object` is used. | | `subset` | an optional character or integer vector naming the `lm` components of `object` from which the predictions are to be extracted. Default is `NULL`, in which case all components are used. | | `asList` | an optional logical value. If `TRUE`, the returned object is a list with the predictions split by groups; else the returned value is a vector. Defaults to `FALSE`. | | `pool` | an optional logical value indicating whether a pooled estimate of the residual standard error should be used. Default is `attr(object, "pool")`. | | `se.fit` | an optional logical value indicating whether pointwise standard errors should be computed along with the predictions. Default is `FALSE`. | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value a list with components given by the predictions (and, optionally, the standard errors for the predictions) from each `lm` component of `object`, a vector with the predictions from all `lm` components of `object`, or a data frame with columns given by the predictions and their corresponding standard errors. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[lmList](lmlist)`, `[predict.lm](../../stats/html/predict.lm)` ### Examples ``` fm1 <- lmList(distance ~ age | Subject, Orthodont) predict(fm1, se.fit = TRUE) ```
programming_docs
r None `fdHess` Finite difference Hessian ----------------------------------- ### Description Evaluate an approximate Hessian and gradient of a scalar function using finite differences. ### Usage ``` fdHess(pars, fun, ..., .relStep = .Machine$double.eps^(1/3), minAbsPar = 0) ``` ### Arguments | | | | --- | --- | | `pars` | the numeric values of the parameters at which to evaluate the function `fun` and its derivatives. | | `fun` | a function depending on the parameters `pars` that returns a numeric scalar. | | `...` | Optional additional arguments to `fun` | | `.relStep` | The relative step size to use in the finite differences. It defaults to the cube root of `.Machine$double.eps` | | `minAbsPar` | The minimum magnitude of a parameter value that is considered non-zero. It defaults to zero meaning that any non-zero value will be considered different from zero. | ### Details This function uses a second-order response surface design known as a “Koschal design” to determine the parameter values at which the function is evaluated. ### Value A list with components | | | | --- | --- | | `mean` | the value of function `fun` evaluated at the parameter values `pars` | | `gradient` | an approximate gradient (of length `length(pars)`). | | `Hessian` | a matrix whose upper triangle contains an approximate Hessian. | ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### Examples ``` (fdH <- fdHess(c(12.3, 2.34), function(x) x[1]*(1-exp(-0.4*x[2])))) stopifnot(length(fdH$ mean) == 1, length(fdH$ gradient) == 2, identical(dim(fdH$ Hessian), c(2L, 2L))) ``` r None `nlme` Nonlinear Mixed-Effects Models -------------------------------------- ### Description This generic function fits a nonlinear mixed-effects model in the formulation described in Lindstrom and Bates (1990) but allowing for nested random effects. The within-group errors are allowed to be correlated and/or have unequal variances. ### Usage ``` nlme(model, data, fixed, random, groups, start, correlation, weights, subset, method, na.action, naPattern, control, verbose) ``` ### Arguments | | | | --- | --- | | `model` | a nonlinear model formula, with the response on the left of a `~` operator and an expression involving parameters and covariates on the right, or an `nlsList` object. If `data` is given, all names used in the formula should be defined as parameters or variables in the data frame. The method function `nlme.nlsList` is documented separately. | | `data` | an optional data frame containing the variables named in `model`, `fixed`, `random`, `correlation`, `weights`, `subset`, and `naPattern`. By default the variables are taken from the environment from which `nlme` is called. | | `fixed` | a two-sided linear formula of the form `f1+...+fn~x1+...+xm`, or a list of two-sided formulas of the form `f1~x1+...+xm`, with possibly different models for different parameters. The `f1,...,fn` are the names of parameters included on the right hand side of `model` and the `x1+...+xm` expressions define linear models for these parameters (when the left hand side of the formula contains several parameters, they all are assumed to follow the same linear model, described by the right hand side expression). A `1` on the right hand side of the formula(s) indicates a single fixed effects for the corresponding parameter(s). | | `random` | optionally, any of the following: (i) a two-sided formula of the form `r1+...+rn~x1+...+xm | g1/.../gQ`, with `r1,...,rn` naming parameters included on the right hand side of `model`, `x1+...+xm` specifying the random-effects model for these parameters and `g1/.../gQ` the grouping structure (`Q` may be equal to 1, in which case no `/` is required). The random effects formula will be repeated for all levels of grouping, in the case of multiple levels of grouping; (ii) a two-sided formula of the form `r1+...+rn~x1+..+xm`, a list of two-sided formulas of the form `r1~x1+...+xm`, with possibly different random-effects models for different parameters, a `pdMat` object with a two-sided formula, or list of two-sided formulas (i.e. a non-`NULL` value for `formula(random)`), or a list of pdMat objects with two-sided formulas, or lists of two-sided formulas. In this case, the grouping structure formula will be given in `groups`, or derived from the data used to fit the nonlinear mixed-effects model, which should inherit from class `groupedData`,; (iii) a named list of formulas, lists of formulas, or `pdMat` objects as in (ii), with the grouping factors as names. The order of nesting will be assumed the same as the order of the order of the elements in the list; (iv) an `reStruct` object. See the documentation on `pdClasses` for a description of the available `pdMat` classes. Defaults to `fixed`, resulting in all fixed effects having also random effects. | | `groups` | an optional one-sided formula of the form `~g1` (single level of nesting) or `~g1/.../gQ` (multiple levels of nesting), specifying the partitions of the data over which the random effects vary. `g1,...,gQ` must evaluate to factors in `data`. The order of nesting, when multiple levels are present, is taken from left to right (i.e. `g1` is the first level, `g2` the second, etc.). | | `start` | an optional numeric vector, or list of initial estimates for the fixed effects and random effects. If declared as a numeric vector, it is converted internally to a list with a single component `fixed`, given by the vector. The `fixed` component is required, unless the model function inherits from class `selfStart`, in which case initial values will be derived from a call to `nlsList`. An optional `random` component is used to specify initial values for the random effects and should consist of a matrix, or a list of matrices with length equal to the number of grouping levels. Each matrix should have as many rows as the number of groups at the corresponding level and as many columns as the number of random effects in that level. | | `correlation` | an optional `corStruct` object describing the within-group correlation structure. See the documentation of `corClasses` for a description of the available `corStruct` classes. Defaults to `NULL`, corresponding to no within-group correlations. | | `weights` | an optional `varFunc` object or one-sided formula describing the within-group heteroscedasticity structure. If given as a formula, it is used as the argument to `varFixed`, corresponding to fixed variance weights. See the documentation on `varClasses` for a description of the available `varFunc` classes. Defaults to `NULL`, corresponding to homoscedastic within-group errors. | | `subset` | an optional expression indicating the subset of the rows of `data` that should be used in the fit. This can be a logical vector, or a numeric vector indicating which observation numbers are to be included, or a character vector of the row names to be included. All observations are included by default. | | `method` | a character string. If `"REML"` the model is fit by maximizing the restricted log-likelihood. If `"ML"` the log-likelihood is maximized. Defaults to `"ML"`. | | `na.action` | a function that indicates what should happen when the data contain `NA`s. The default action (`na.fail`) causes `nlme` to print an error message and terminate if there are any incomplete observations. | | `naPattern` | an expression or formula object, specifying which returned values are to be regarded as missing. | | `control` | a list of control values for the estimation algorithm to replace the default values returned by the function `nlmeControl`. Defaults to an empty list. | | `verbose` | an optional logical value. If `TRUE` information on the evolution of the iterative algorithm is printed. Default is `FALSE`. | ### Value an object of class `nlme` representing the nonlinear mixed-effects model fit. Generic functions such as `print`, `plot` and `summary` have methods to show the results of the fit. See `nlmeObject` for the components of the fit. The functions `resid`, `coef`, `fitted`, `fixed.effects`, and `random.effects` can be used to extract some of its components. ### Note The function does not do any scaling internally: the optimization will work best when the response is scaled so its variance is of the order of one. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References The model formulation and computational methods are described in Lindstrom, M.J. and Bates, D.M. (1990). The variance-covariance parametrizations are described in Pinheiro, J.C. and Bates., D.M. (1996). The different correlation structures available for the `correlation` argument are described in Box, G.E.P., Jenkins, G.M., and Reinsel G.C. (1994), Littel, R.C., Milliken, G.A., Stroup, W.W., and Wolfinger, R.D. (1996), and Venables, W.N. and Ripley, B.D. (2002). The use of variance functions for linear and nonlinear mixed effects models is presented in detail in Davidian, M. and Giltinan, D.M. (1995). Box, G.E.P., Jenkins, G.M., and Reinsel G.C. (1994) "Time Series Analysis: Forecasting and Control", 3rd Edition, Holden-Day. Davidian, M. and Giltinan, D.M. (1995) "Nonlinear Mixed Effects Models for Repeated Measurement Data", Chapman and Hall. Laird, N.M. and Ware, J.H. (1982) "Random-Effects Models for Longitudinal Data", Biometrics, 38, 963-974. Littel, R.C., Milliken, G.A., Stroup, W.W., and Wolfinger, R.D. (1996) "SAS Systems for Mixed Models", SAS Institute. Lindstrom, M.J. and Bates, D.M. (1990) "Nonlinear Mixed Effects Models for Repeated Measures Data", Biometrics, 46, 673-687. Pinheiro, J.C. and Bates., D.M. (1996) "Unconstrained Parametrizations for Variance-Covariance Matrices", Statistics and Computing, 6, 289-296. Pinheiro, J.C., and Bates, D.M. (2000) "Mixed-Effects Models in S and S-PLUS", Springer. Venables, W.N. and Ripley, B.D. (2002) "Modern Applied Statistics with S", 4th Edition, Springer-Verlag. ### See Also `[nlmeControl](nlmecontrol)`, `[nlme.nlsList](nlme.nlslist)`, `[nlmeObject](nlmeobject)`, `[nlsList](nlslist)`, `[nlmeStruct](nlmestruct)`, `[pdClasses](pdclasses)`, `[reStruct](restruct)`, `[varFunc](varfunc)`, `[corClasses](corclasses)`, `[varClasses](varclasses)` ### Examples ``` fm1 <- nlme(height ~ SSasymp(age, Asym, R0, lrc), data = Loblolly, fixed = Asym + R0 + lrc ~ 1, random = Asym ~ 1, start = c(Asym = 103, R0 = -8.5, lrc = -3.3)) summary(fm1) fm2 <- update(fm1, random = pdDiag(Asym + lrc ~ 1)) summary(fm2) ``` r None `summary.lmList` Summarize an lmList Object -------------------------------------------- ### Description The `summary.lm` method is applied to each `lm` component of `object` to produce summary information on the individual fits, which is organized into a list of summary statistics. The returned object is suitable for printing with the `print.summary.lmList` method. ### Usage ``` ## S3 method for class 'lmList' summary(object, pool, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"[lmList](lmlist)"`, representing a list of `lm` fitted objects. | | `pool` | an optional logical value indicating whether a pooled estimate of the residual standard error should be used. Default is `attr(object, "pool")`. | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value a list with summary statistics obtained by applying `summary.lm` to the elements of `object`, inheriting from class `summary.lmList`. The components of `value` are: | | | | --- | --- | | `call` | a list containing an image of the `lmList` call that produced `object`. | | `coefficients` | a three dimensional array with summary information on the `lm` coefficients. The first dimension corresponds to the names of the `object` components, the second dimension is given by `"Value"`, `"Std. Error"`, `"t value"`, and `"Pr(>|t|)"`, corresponding, respectively, to the coefficient estimates and their associated standard errors, t-values, and p-values. The third dimension is given by the coefficients names. | | `correlation` | a three dimensional array with the correlations between the individual `lm` coefficient estimates. The first dimension corresponds to the names of the `object` components. The third dimension is given by the coefficients names. For each coefficient, the rows of the associated array give the correlations between that coefficient and the remaining coefficients, by `lm` component. | | `cov.unscaled` | a three dimensional array with the unscaled variances/covariances for the individual `lm` coefficient estimates (giving the estimated variance/covariance for the coefficients, when multiplied by the estimated residual errors). The first dimension corresponds to the names of the `object` components. The third dimension is given by the coefficients names. For each coefficient, the rows of the associated array give the unscaled covariances between that coefficient and the remaining coefficients, by `lm` component. | | `df` | an array with the number of degrees of freedom for the model and for residuals, for each `lm` component. | | `df.residual` | the total number of degrees of freedom for residuals, corresponding to the sum of residuals df of all `lm` components. | | `fstatistics` | an array with the F test statistics and corresponding degrees of freedom, for each `lm` component. | | `pool` | the value of the `pool` argument to the function. | | `r.squared` | a vector with the multiple R-squared statistics for each `lm` component. | | `residuals` | a list with components given by the residuals from individual `lm` fits. | | `RSE` | the pooled estimate of the residual standard error. | | `sigma` | a vector with the residual standard error estimates for the individual `lm` fits. | | `terms` | the terms object used in fitting the individual `lm` components. | ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[lmList](lmlist)`, `[summary](../../base/html/summary)` ### Examples ``` fm1 <- lmList(distance ~ age | Subject, Orthodont) summary(fm1) ``` r None `logLik.lmeStruct` Log-Likelihood of an lmeStruct Object --------------------------------------------------------- ### Description `Pars` is used to update the coefficients of the model components of `object` and the individual (restricted) log-likelihood contributions of each component are added together. The type of log-likelihood (restricted or not) is determined by the `settings` attribute of `object`. ### Usage ``` ## S3 method for class 'lmeStruct' logLik(object, Pars, conLin, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"[lmeStruct](lmestruct)"`, representing a list of linear mixed-effects model components, such as `reStruct`, `corStruct`, and `varFunc` objects. | | `Pars` | the parameter values at which the (restricted) log-likelihood is to be evaluated. | | `conLin` | an optional condensed linear model object, consisting of a list with components `"Xy"`, corresponding to a regression matrix (`X`) combined with a response vector (`y`), and `"logLik"`, corresponding to the log-likelihood of the underlying lme model. Defaults to `attr(object, "conLin")`. | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value the (restricted) log-likelihood for the linear mixed-effects model described by `object`, evaluated at `Pars`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `<lme>`, `[lmeStruct](lmestruct)`, `[logLik.lme](loglik.lme)` r None `bdf` Language scores ---------------------- ### Description The `bdf` data frame has 2287 rows and 25 columns of language scores from grade 8 pupils in elementary schools in The Netherlands. ### Usage ``` data(bdf) ``` ### Format schoolNR a factor denoting the school. pupilNR a factor denoting the pupil. IQ.verb a numeric vector of verbal IQ scores IQ.perf a numeric vector of IQ scores. sex Sex of the student. Minority a factor indicating if the student is a member of a minority group. repeatgr an ordered factor indicating if one or more grades have been repeated. aritPRET a numeric vector classNR a numeric vector aritPOST a numeric vector langPRET a numeric vector langPOST a numeric vector ses a numeric vector of socioeconomic status indicators. denomina a factor indicating of the school is a public school, a Protestant private school, a Catholic private school, or a non-denominational private school. schoolSES a numeric vector satiprin a numeric vector natitest a factor with levels `0` and `1` meetings a numeric vector currmeet a numeric vector mixedgra a factor indicating if the class is a mixed-grade class. percmino a numeric vector aritdiff a numeric vector homework a numeric vector classsiz a numeric vector groupsiz a numeric vector ### Source http://stat.gamma.rug.nl/snijders/multilevel.htm, the first edition of <http://www.stats.ox.ac.uk/~snijders/mlbook.htm>. ### References Snijders, Tom and Bosker, Roel (1999), *Multilevel Analysis: An Introduction to Basic and Advanced Multilevel Modeling*, Sage. ### Examples ``` summary(bdf) ## More examples, including lme() fits reproducing parts in the above ## book, are available in the R script files system.file("mlbook", "ch04.R", package ="nlme") # and system.file("mlbook", "ch05.R", package ="nlme") ``` r None `ranef.lmList` Extract lmList Random Effects --------------------------------------------- ### Description The difference between the individual `lm` components coefficients and their average is calculated. ### Usage ``` ## S3 method for class 'lmList' ranef(object, augFrame, data, which, FUN, standard, omitGroupingFactor, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"[lmList](lmlist)"`, representing a list of `lm` objects with a common model. | | `augFrame` | an optional logical value. If `TRUE`, the returned data frame is augmented with variables defined in `data`; else, if `FALSE`, only the coefficients are returned. Defaults to `FALSE`. | | `data` | an optional data frame with the variables to be used for augmenting the returned data frame when `augFrame = TRUE`. Defaults to the data frame used to fit `object`. | | `which` | an optional positive integer vector specifying which columns of `data` should be used in the augmentation of the returned data frame. Defaults to all columns in `data`. | | `FUN` | an optional summary function or a list of summary functions to be applied to group-varying variables, when collapsing `data` by groups. Group-invariant variables are always summarized by the unique value that they assume within that group. If `FUN` is a single function it will be applied to each non-invariant variable by group to produce the summary for that variable. If `FUN` is a list of functions, the names in the list should designate classes of variables in the frame such as `ordered`, `factor`, or `numeric`. The indicated function will be applied to any group-varying variables of that class. The default functions to be used are `mean` for numeric factors, and `Mode` for both `factor` and `ordered`. The `Mode` function, defined internally in `gsummary`, returns the modal or most popular value of the variable. It is different from the `mode` function that returns the S-language mode of the variable. | | `standard` | an optional logical value indicating whether the estimated random effects should be "standardized" (i.e. divided by the corresponding estimated standard error). Defaults to `FALSE`. | | `omitGroupingFactor` | an optional logical value. When `TRUE` the grouping factor itself will be omitted from the group-wise summary of `data` but the levels of the grouping factor will continue to be used as the row names for the returned data frame. Defaults to `FALSE`. | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value a vector with the differences between the individual `lm` coefficients in `object` and their average. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Pinheiro, J.C., and Bates, D.M. (2000) "Mixed-Effects Models in S and S-PLUS", Springer, esp. pp. 100, 461. ### See Also `[fixed.effects.lmList](fixef.lmlist)`, `[lmList](lmlist)`, `<random.effects>` ### Examples ``` fm1 <- lmList(distance ~ age | Subject, Orthodont) ranef(fm1) random.effects(fm1) # same as above ```
programming_docs
r None `Initialize` Initialize Object ------------------------------- ### Description This function is generic; method functions can be written to handle specific classes of objects. Classes which already have methods for this function include: `corStruct`, `lmeStruct`, `reStruct`, and `varFunc`. ### Usage ``` Initialize(object, data, ...) ``` ### Arguments | | | | --- | --- | | `object` | any object requiring initialization, e.g. "plug-in" structures such as `corStruct` and `varFunc` objects. | | `data` | a data frame to be used in the initialization procedure. | | `...` | some methods for this generic function require additional arguments. | ### Value an initialized object with the same class as `object`. Changes introduced by the initialization procedure will depend on the method function used; see the appropriate documentation. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Pinheiro, J.C., and Bates, D.M. (2000) "Mixed-Effects Models in S and S-PLUS", Springer. ### See Also `[Initialize.corStruct](initialize.corstruct)`, `[Initialize.lmeStruct](initialize.lmestruct)`, `[Initialize.glsStruct](initialize.glsstruct)`, `[Initialize.varFunc](initialize.varfunc)`, `[isInitialized](isinitialized)` ### Examples ``` ## see the method function documentation ``` r None `corClasses` Correlation Structure Classes ------------------------------------------- ### Description Standard classes of correlation structures (`corStruct`) available in the `nlme` package. ### Value Available standard classes: | | | | --- | --- | | `corAR1` | autoregressive process of order 1. | | `corARMA` | autoregressive moving average process, with arbitrary orders for the autoregressive and moving average components. | | `corCAR1` | continuous autoregressive process (AR(1) process for a continuous time covariate). | | `corCompSymm` | compound symmetry structure corresponding to a constant correlation. | | `corExp` | exponential spatial correlation. | | `corGaus` | Gaussian spatial correlation. | | `corLin` | linear spatial correlation. | | `corRatio` | Rational quadratics spatial correlation. | | `corSpher` | spherical spatial correlation. | | `corSymm` | general correlation matrix, with no additional structure. | ### Note Users may define their own `corStruct` classes by specifying a `constructor` function and, at a minimum, methods for the functions `corMatrix` and `coef`. For examples of these functions, see the methods for classes `corSymm` and `corAR1`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Pinheiro, J.C., and Bates, D.M. (2000) "Mixed-Effects Models in S and S-PLUS", Springer. ### See Also `[corAR1](corar1)`, `[corARMA](corarma)`, `[corCAR1](corcar1)`, `[corCompSymm](corcompsymm)`, `[corExp](corexp)`, `[corGaus](corgaus)`, `[corLin](corlin)`, `[corRatio](corratio)`, `[corSpher](corspher)`, `[corSymm](corsymm)`, `[summary.corStruct](summary.corstruct)` r None `update.modelStruct` Update a modelStruct Object ------------------------------------------------- ### Description This method function updates each element of `object`, allowing the access to `data`. ### Usage ``` ## S3 method for class 'modelStruct' update(object, data, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"modelStruct"`, representing a list of model components, such as `corStruct` and `varFunc` objects. | | `data` | a data frame in which to evaluate the variables needed for updating the elements of `object`. | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value an object similar to `object` (same class, length, and names), but with updated elements. ### Note This method function is primarily used within model fitting functions, such as `lme` and `gls`, that allow model components such as variance functions. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[reStruct](restruct)` r None `logLik.lmList` Log-Likelihood of an lmList Object --------------------------------------------------- ### Description If `pool=FALSE`, the (restricted) log-likelihoods of the `lm` components of `object` are summed together. Else, the (restricted) log-likelihood of the `lm` fit with different coefficients for each level of the grouping factor associated with the partitioning of the `object` components is obtained. ### Usage ``` ## S3 method for class 'lmList' logLik(object, REML, pool, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"[lmList](lmlist)"`, representing a list of `lm` objects with a common model. | | `REML` | an optional logical value. If `TRUE` the restricted log-likelihood is returned, else, if `FALSE`, the log-likelihood is returned. Defaults to `FALSE`. | | `pool` | an optional logical value indicating whether all `lm` components of `object` may be assumed to have the same error variance. Default is `attr(object, "pool")`. | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value either the sum of the (restricted) log-likelihoods of each `lm` component in `object`, or the (restricted) log-likelihood for the `lm` fit with separate coefficients for each component of `object`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[lmList](lmlist)`, `[logLik.lme](loglik.lme)`, ### Examples ``` fm1 <- lmList(distance ~ age | Subject, Orthodont) logLik(fm1) # returns NA when it should not ``` r None `getData` Extract Data from an Object -------------------------------------- ### Description This function is generic; method functions can be written to handle specific classes of objects. Classes which already have methods for this function include `gls`, `lme`, and `lmList`. ### Usage ``` getData(object) ``` ### Arguments | | | | --- | --- | | `object` | an object from which a data.frame can be extracted, generally a fitted model object. | ### Value will depend on the method function used; see the appropriate documentation. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[getData.gls](getdata.gls)`, `[getData.lme](getdata.lme)`, `[getData.lmList](getdata.lmlist)` ### Examples ``` ## see the method function documentation ``` r None `Quinidine` Quinidine Kinetics ------------------------------- ### Description The `Quinidine` data frame has 1471 rows and 14 columns. ### Format This data frame contains the following columns: Subject a factor identifying the patient on whom the data were collected. time a numeric vector giving the time (hr) at which the drug was administered or the blood sample drawn. This is measured from the time the patient entered the study. conc a numeric vector giving the serum quinidine concentration (mg/L). dose a numeric vector giving the dose of drug administered (mg). Although there were two different forms of quinidine administered, the doses were adjusted for differences in salt content by conversion to milligrams of quinidine base. interval a numeric vector giving the when the drug has been given at regular intervals for a sufficiently long period of time to assume steady state behavior, the interval is recorded. Age a numeric vector giving the age of the subject on entry to the study (yr). Height a numeric vector giving the height of the subject on entry to the study (in.). Weight a numeric vector giving the body weight of the subject (kg). Race a factor with levels `Caucasian`, `Latin`, and `Black` identifying the race of the subject. Smoke a factor with levels `no` and `yes` giving smoking status at the time of the measurement. Ethanol a factor with levels `none`, `current`, `former` giving ethanol (alcohol) abuse status at the time of the measurement. Heart a factor with levels `No/Mild`, `Moderate`, and `Severe` indicating congestive heart failure for the subject. Creatinine an ordered factor with levels `< 50` < `>= 50` indicating the creatine clearance (mg/min). glyco a numeric vector giving the alpha-1 acid glycoprotein concentration (mg/dL). Often measured at the same time as the quinidine concentration. ### Details Verme et al. (1992) analyze routine clinical data on patients receiving the drug quinidine as a treatment for cardiac arrythmia (atrial fibrillation of ventricular arrythmias). All patients were receiving oral quinidine doses. At irregular intervals blood samples were drawn and serum concentrations of quinidine were determined. These data are analyzed in several publications, including Davidian and Giltinan (1995, section 9.3). ### Source Pinheiro, J. C. and Bates, D. M. (2000), *Mixed-Effects Models in S and S-PLUS*, Springer, New York. (Appendix A.25) Davidian, M. and Giltinan, D. M. (1995), *Nonlinear Models for Repeated Measurement Data*, Chapman and Hall, London. Verme, C. N., Ludden, T. M., Clementi, W. A. and Harris, S. C. (1992), Pharmacokinetics of quinidine in male patients: A population analysis, *Clinical Pharmacokinetics*, **22**, 468-480. r None `Cefamandole` Pharmacokinetics of Cefamandole ---------------------------------------------- ### Description The `Cefamandole` data frame has 84 rows and 3 columns. ### Format This data frame contains the following columns: Subject a factor giving the subject from which the sample was drawn. Time a numeric vector giving the time at which the sample was drawn (minutes post-injection). conc a numeric vector giving the observed plasma concentration of cefamandole (mcg/ml). ### Details Davidian and Giltinan (1995, 1.1, p. 2) describe data obtained during a pilot study to investigate the pharmacokinetics of the drug cefamandole. Plasma concentrations of the drug were measured on six healthy volunteers at 14 time points following an intraveneous dose of 15 mg/kg body weight of cefamandole. ### Source Pinheiro, J. C. and Bates, D. M. (2000), *Mixed-Effects Models in S and S-PLUS*, Springer, New York. (Appendix A.4) Davidian, M. and Giltinan, D. M. (1995), *Nonlinear Models for Repeated Measurement Data*, Chapman and Hall, London. ### Examples ``` plot(Cefamandole) fm1 <- nlsList(SSbiexp, data = Cefamandole) summary(fm1) ``` r None `glsStruct` Generalized Least Squares Structure ------------------------------------------------ ### Description A generalized least squares structure is a list of model components representing different sets of parameters in the linear model. A `glsStruct` may contain `corStruct` and `varFunc` objects. `NULL` arguments are not included in the `glsStruct` list. ### Usage ``` glsStruct(corStruct, varStruct) ``` ### Arguments | | | | --- | --- | | `corStruct` | an optional `corStruct` object, representing a correlation structure. Default is `NULL`. | | `varStruct` | an optional `varFunc` object, representing a variance function structure. Default is `NULL`. | ### Value a list of model variance-covariance components determining the parameters to be estimated for the associated linear model. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[corClasses](corclasses)`, `<gls>`, `[residuals.glsStruct](residuals.glsstruct)`, `[varFunc](varfunc)` ### Examples ``` gls1 <- glsStruct(corAR1(), varPower()) ``` r None `pairs.compareFits` Pairs Plot of compareFits Object ----------------------------------------------------- ### Description Scatter plots of the values being compared are generated for each pair of coefficients in `x`. Different symbols (colors) are used for each object being compared and values corresponding to the same group are joined by a line, to facilitate comparison of fits. If only two coefficients are present, the `trellis` function `xyplot` is used; otherwise the `trellis` function `splom` is used. ### Usage ``` ## S3 method for class 'compareFits' pairs(x, subset, key, ...) ``` ### Arguments | | | | --- | --- | | `x` | an object of class `compareFits`. | | `subset` | an optional logical or integer vector specifying which rows of `x` should be used in the plots. If missing, all rows are used. | | `key` | an optional logical value, or list. If `TRUE`, a legend is included at the top of the plot indicating which symbols (colors) correspond to which objects being compared. If `FALSE`, no legend is included. If given as a list, `key` is passed down as an argument to the `trellis` function generating the plots (`splom` or `xyplot`). Defaults to `TRUE`. | | `...` | optional arguments passed down to the `trellis` function generating the plots. | ### Value Pairwise scatter plots of the values being compared, with different symbols (colors) used for each object under comparison. ### Author(s) José Pinheiro and Douglas Bates ### See Also `[compareFits](comparefits)`, `[plot.compareFits](plot.comparefits)`, `<pairs.lme>`, `[pairs.lmList](pairs.lmlist)`, `[xyplot](../../lattice/html/xyplot)`, `[splom](../../lattice/html/splom)` ### Examples ``` example(compareFits) # cF12 <- compareFits(coef(lmList(Orthodont)), .. lme(*)) pairs(cF12) ``` r None `Initialize.reStruct` Initialize reStruct Object ------------------------------------------------- ### Description Initial estimates for the parameters in the `pdMat` objects forming `object`, which have not yet been initialized, are obtained using the methodology described in Bates and Pinheiro (1998). These estimates may be refined using a series of EM iterations, as described in Bates and Pinheiro (1998). The number of EM iterations to be used is defined in `control`. ### Usage ``` ## S3 method for class 'reStruct' Initialize(object, data, conLin, control, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"[reStruct](restruct)"`, representing a random effects structure and consisting of a list of `pdMat` objects. | | `data` | a data frame in which to evaluate the variables defined in `formula(object)`. | | `conLin` | a condensed linear model object, consisting of a list with components `"Xy"`, corresponding to a regression matrix (`X`) combined with a response vector (`y`), and `"logLik"`, corresponding to the log-likelihood of the underlying model. | | `control` | an optional list with a single component `niterEM` controlling the number of iterations for the EM algorithm used to refine initial parameter estimates. It is given as a list for compatibility with other `Initialize` methods. Defaults to `list(niterEM = 20)`. | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value an `reStruct` object similar to `object`, but with all `pdMat` components initialized. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[reStruct](restruct)`, `[pdMat](pdmat)`, `[Initialize](initialize)` r None `quinModel` Model function for the Quinidine data -------------------------------------------------- ### Description A model function for a model used with the `Quinidine` data. This function calls compiled C code. ### Usage ``` quinModel(Subject, time, conc, dose, interval, lV, lKa, lCl) ``` ### Arguments | | | | --- | --- | | `Subject` | a factor identifying the patient on whom the data were collected. | | `time` | a numeric vector giving the time (hr) at which the drug was administered or the blood sample drawn. This is measured from the time the patient entered the study. | | `conc` | a numeric vector giving the serum quinidine concentration (mg/L). | | `dose` | a numeric vector giving the dose of drug administered (mg). Although there were two different forms of quinidine administered, the doses were adjusted for differences in salt content by conversion to milligrams of quinidine base. | | `interval` | a numeric vector giving the when the drug has been given at regular intervals for a sufficiently long period of time to assume steady state behavior, the interval is recorded. | | `lV` | numeric. A vector of values of the natural log of the effective volume of distribution according to `Subject` and `time`. | | `lKa` | numeric. A vector of values of the natural log of the absorption rate constant according to `Subject` and `time`. | | `lCl` | numeric. A vector of values of the natural log of the clearance parameter according to `Subject` and `time`. | ### Details See the details section of `[Quinidine](quinidine)` for a description of the model function that `quinModel` evaluates. ### Value a numeric vector of predicted quinidine concentrations. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Pinheiro, J. C. and Bates, D. M. (2000) *Mixed-effects Models in S and S-PLUS*, Springer. (section 8.2) r None `plot.nmGroupedData` Plot an nmGroupedData Object -------------------------------------------------- ### Description The `groupedData` object is summarized by the values of the `displayLevel` grouping factor (or the combination of its values and the values of the covariate indicated in `preserve`, if any is present). The collapsed data is used to produce a new `groupedData` object, with grouping factor given by the `displayLevel` factor, which is plotted using the appropriate `plot` method for `groupedData` objects with single level of grouping. ### Usage ``` ## S3 method for class 'nmGroupedData' plot(x, collapseLevel, displayLevel, outer, inner, preserve, FUN, subset, key, grid, ...) ``` ### Arguments | | | | --- | --- | | `x` | an object inheriting from class `nmGroupedData`, representing a `groupedData` object with multiple grouping factors. | | `collapseLevel` | an optional positive integer or character string indicating the grouping level to use when collapsing the data. Level values increase from outermost to innermost grouping. Default is the highest or innermost level of grouping. | | `displayLevel` | an optional positive integer or character string indicating the grouping level to use for determining the panels in the Trellis display, when `outer` is missing. Default is `collapseLevel`. | | `outer` | an optional logical value or one-sided formula, indicating covariates that are outer to the `displayLevel` grouping factor, which are used to determine the panels of the Trellis plot. If equal to `TRUE`, the `displayLevel` element `attr(object, "outer")` is used to indicate the outer covariates. An outer covariate is invariant within the sets of rows defined by the grouping factor. Ordering of the groups is done in such a way as to preserve adjacency of groups with the same value of the outer variables. Defaults to `NULL`, meaning that no outer covariates are to be used. | | `inner` | an optional logical value or one-sided formula, indicating a covariate that is inner to the `displayLevel` grouping factor, which is used to associate points within each panel of the Trellis plot. If equal to `TRUE`, `attr(object, "outer")` is used to indicate the inner covariate. An inner covariate can change within the sets of rows defined by the grouping factor. Defaults to `NULL`, meaning that no inner covariate is present. | | `preserve` | an optional one-sided formula indicating a covariate whose levels should be preserved when collapsing the data according to the `collapseLevel` grouping factor. The collapsing factor is obtained by pasting together the levels of the `collapseLevel` grouping factor and the values of the covariate to be preserved. Default is `NULL`, meaning that no covariates need to be preserved. | | `FUN` | an optional summary function or a list of summary functions to be used for collapsing the data. The function or functions are applied only to variables in `object` that vary within the groups defined by `collapseLevel`. Invariant variables are always summarized by group using the unique value that they assume within that group. If `FUN` is a single function it will be applied to each non-invariant variable by group to produce the summary for that variable. If `FUN` is a list of functions, the names in the list should designate classes of variables in the data such as `ordered`, `factor`, or `numeric`. The indicated function will be applied to any non-invariant variables of that class. The default functions to be used are `mean` for numeric factors, and `Mode` for both `factor` and `ordered`. The `Mode` function, defined internally in `gsummary`, returns the modal or most popular value of the variable. It is different from the `mode` function that returns the S-language mode of the variable. | | `subset` | an optional named list. Names can be either positive integers representing grouping levels, or names of grouping factors. Each element in the list is a vector indicating the levels of the corresponding grouping factor to be used for plotting the data. Default is `NULL`, meaning that all levels are used. | | `key` | an optional logical value, or list. If `TRUE`, a legend is included at the top of the plot indicating which symbols (colors) correspond to which prediction levels. If `FALSE`, no legend is included. If given as a list, `key` is passed down as an argument to the `trellis` function generating the plots (`xyplot`). Defaults to `TRUE`. | | `grid` | an optional logical value indicating whether a grid should be added to plot. Default is `TRUE`. | | `...` | optional arguments passed to the Trellis plot function. | ### Value a Trellis display of the data collapsed over the values of the `collapseLevel` grouping factor and grouped according to the `displayLevel` grouping factor. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Bates, D.M. and Pinheiro, J.C. (1997), "Software Design for Longitudinal Data", in "Modelling Longitudinal and Spatially Correlated Data: Methods, Applications and Future Directions", T.G. Gregoire (ed.), Springer-Verlag, New York. ### See Also `[groupedData](groupeddata)`, `[collapse.groupedData](collapse.groupeddata)`, `[plot.nfnGroupedData](plot.nfngroupeddata)`, `[plot.nffGroupedData](plot.nffgroupeddata)` ### Examples ``` # no collapsing, panels by Dog plot(Pixel, display = "Dog", inner = ~Side) # collapsing by Dog, preserving day plot(Pixel, collapse = "Dog", preserve = ~day) ```
programming_docs
r None `nlsList.selfStart` nlsList Fit from a selfStart Function ---------------------------------------------------------- ### Description The response variable and primary covariate in `formula(data)` are used together with `model` to construct the nonlinear model formula. This is used in the `nls` calls and, because a selfStarting model function can calculate initial estimates for its parameters from the data, no starting estimates need to be provided. ### Usage ``` ## S3 method for class 'selfStart' nlsList(model, data, start, control, level, subset, na.action = na.fail, pool = TRUE, warn.nls = NA) ``` ### Arguments | | | | --- | --- | | `model` | a `"[selfStart](../../stats/html/selfstart)"` model function, which calculates initial estimates for the model parameters from `data`. | | `data` | a data frame in which to interpret the variables in `model`. Because no grouping factor can be specified in `model`, `data` must inherit from class `"[groupedData](groupeddata)"`. | | `start` | an optional named list with initial values for the parameters to be estimated in `model`. It is passed as the `start` argument to each `nls` call and is required when the nonlinear function in `model` does not inherit from class `selfStart`. | | `control` | a list of control values passed as the `control` argument to `nls`. Defaults to an empty list. | | `level` | an optional integer specifying the level of grouping to be used when multiple nested levels of grouping are present. | | `subset` | an optional expression indicating the subset of the rows of `data` that should be used in the fit. This can be a logical vector, or a numeric vector indicating which observation numbers are to be included, or a character vector of the row names to be included. All observations are included by default. | | `na.action` | a function that indicates what should happen when the data contain `NA`s. The default action (`na.fail`) causes `nlsList` to print an error message and terminate if there are any incomplete observations. | | `pool, warn.nls` | optional `[logical](../../base/html/logical)`s, see `[nlsList](nlslist)`. | ### Value a list of `nls` objects with as many components as the number of groups defined by the grouping factor. A `NULL` value is assigned to the components corresponding to clusters for which the `nls` algorithm failed to converge. Generic functions such as `coef`, `fixed.effects`, `lme`, `pairs`, `plot`, `predict`, `random.effects`, `summary`, and `update` have methods that can be applied to an `nlsList` object. ### See Also `[selfStart](../../stats/html/selfstart)`, `[groupedData](groupeddata)`, `[nls](../../stats/html/nls)`, `[nlsList](nlslist)`, `[nlme.nlsList](nlme.nlslist)`, `[nlsList.formula](nlslist)` ### Examples ``` fm1 <- nlsList(SSasympOff, CO2) summary(fm1) ``` r None `gnlsStruct` Generalized Nonlinear Least Squares Structure ----------------------------------------------------------- ### Description A generalized nonlinear least squares structure is a list of model components representing different sets of parameters in the nonlinear model. A `gnlsStruct` may contain `corStruct` and `varFunc` objects. `NULL` arguments are not included in the `gnlsStruct` list. ### Usage ``` gnlsStruct(corStruct, varStruct) ``` ### Arguments | | | | --- | --- | | `corStruct` | an optional `corStruct` object, representing a correlation structure. Default is `NULL`. | | `varStruct` | an optional `varFunc` object, representing a variance function structure. Default is `NULL`. | ### Value a list of model variance-covariance components determining the parameters to be estimated for the associated nonlinear model. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `<gnls>`, `[corClasses](corclasses)`, `[residuals.gnlsStruct](residuals.gnlsstruct)` `[varFunc](varfunc)` ### Examples ``` gnls1 <- gnlsStruct(corAR1(), varPower()) ``` r None `logDet.corStruct` Extract corStruct Log-Determinant ----------------------------------------------------- ### Description This method function extracts the logarithm of the determinant of a square-root factor of the correlation matrix associated with `object`, or the sum of the log-determinants of square-root factors of the list of correlation matrices associated with `object`. ### Usage ``` ## S3 method for class 'corStruct' logDet(object, covariate, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"[corStruct](corclasses)"`, representing a correlation structure. | | `covariate` | an optional covariate vector (matrix), or list of covariate vectors (matrices), at which values the correlation matrix, or list of correlation matrices, are to be evaluated. Defaults to `getCovariate(object)`. | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value the log-determinant of a square-root factor of the correlation matrix associated with `object`, or the sum of the log-determinants of square-root factors of the list of correlation matrices associated with `object`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[logLik.corStruct](loglik.corstruct)`, `[corMatrix.corStruct](cormatrix.corstruct)`, `[logDet](logdet)` ### Examples ``` cs1 <- corAR1(0.3) logDet(cs1, covariate = 1:4) ``` r None `BodyWeight` Rat weight over time for different diets ------------------------------------------------------ ### Description The `BodyWeight` data frame has 176 rows and 4 columns. ### Format This data frame contains the following columns: weight a numeric vector giving the body weight of the rat (grams). Time a numeric vector giving the time at which the measurement is made (days). Rat an ordered factor with levels `2` < `3` < `4` < `1` < `8` < `5` < `6` < `7` < `11` < `9` < `10` < `12` < `13` < `15` < `14` < `16` identifying the rat whose weight is measured. Diet a factor with levels `1` to `3` indicating the diet that the rat receives. ### Details Hand and Crowder (1996) describe data on the body weights of rats measured over 64 days. These data also appear in Table 2.4 of Crowder and Hand (1990). The body weights of the rats (in grams) are measured on day 1 and every seven days thereafter until day 64, with an extra measurement on day 44. The experiment started several weeks before “day 1.” There are three groups of rats, each on a different diet. ### Source Pinheiro, J. C. and Bates, D. M. (2000), *Mixed-Effects Models in S and S-PLUS*, Springer, New York. (Appendix A.3) Crowder, M. and Hand, D. (1990), *Analysis of Repeated Measures*, Chapman and Hall, London. Hand, D. and Crowder, M. (1996), *Practical Longitudinal Data Analysis*, Chapman and Hall, London. r None `varIdent` Constant Variance Function -------------------------------------- ### Description This function is a constructor for the `varIdent` class, representing a constant variance function structure. If no grouping factor is present in `form`, the variance function is constant and equal to one, and no coefficients required to represent it. When `form` includes a grouping factor with *M > 1* levels, the variance function allows M different variances, one for each level of the factor. For identifiability reasons, the coefficients of the variance function represent the ratios between the variances and a reference variance (corresponding to a reference group level). Therefore, only *M-1* coefficients are needed to represent the variance function. By default, if the elements in `value` are unnamed, the first group level is taken as the reference level. ### Usage ``` varIdent(value, form, fixed) ``` ### Arguments | | | | --- | --- | | `value` | an optional numeric vector, or list of numeric values, with the variance function coefficients. If no grouping factor is present in `form`, this argument is ignored, as the resulting variance function contains no coefficients. If `value` has length one, its value is repeated for all coefficients in the variance function. If `value` has length greater than one, it must have length equal to the number of grouping levels minus one and names which identify its elements to the levels of the grouping factor. Only positive values are allowed for this argument. Default is `numeric(0)`, which results in a vector of zeros of appropriate length being assigned to the coefficients when `object` is initialized (corresponding to constant variance equal to one). | | `form` | an optional one-sided formula of the form `~ v`, or `~ v | g`, specifying a variance covariate `v` and, optionally, a grouping factor `g` for the coefficients. The variance covariate is ignored in this variance function. When a grouping factor is present in `form`, a different coefficient value is used for each of its levels less one reference level (see description section below). Several grouping variables may be simultaneously specified, separated by the `*` operator, like in `~ v | g1 * g2 * g3`. In this case, the levels of each grouping variable are pasted together and the resulting factor is used to group the observations. Defaults to `~ 1`. | | `fixed` | an optional numeric vector, or list of numeric values, specifying the values at which some or all of the coefficients in the variance function should be fixed. It must have names identifying which coefficients are to be fixed. Coefficients included in `fixed` are not allowed to vary during the optimization of an objective function. Defaults to `NULL`, corresponding to no fixed coefficients. | ### Value a `varIdent` object representing a constant variance function structure, also inheriting from class `varFunc`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Pinheiro, J.C., and Bates, D.M. (2000) "Mixed-Effects Models in S and S-PLUS", Springer. ### See Also `[varClasses](varclasses)`, `[varWeights.varFunc](varweights)`, `[coef.varIdent](coef.varfunc)` ### Examples ``` vf1 <- varIdent(c(Female = 0.5), form = ~ 1 | Sex) ``` r None `pairs.lmList` Pairs Plot of an lmList Object ---------------------------------------------- ### Description Diagnostic plots for the linear model fits corresponding to the `x` components are obtained. The `form` argument gives considerable flexibility in the type of plot specification. A conditioning expression (on the right side of a `|` operator) always implies that different panels are used for each level of the conditioning factor, according to a Trellis display. The expression on the right hand side of the formula, before a `|` operator, must evaluate to a data frame with at least two columns. If the data frame has two columns, a scatter plot of the two variables is displayed (the Trellis function `xyplot` is used). Otherwise, if more than two columns are present, a scatter plot matrix with pairwise scatter plots of the columns in the data frame is displayed (the Trellis function `splom` is used). ### Usage ``` ## S3 method for class 'lmList' pairs(x, form, label, id, idLabels, grid, ...) ``` ### Arguments | | | | --- | --- | | `x` | an object inheriting from class `"[lmList](lmlist)"`, representing a list of `lm` objects with a common model. | | `form` | an optional one-sided formula specifying the desired type of plot. Any variable present in the original data frame used to obtain `x` can be referenced. In addition, `x` itself can be referenced in the formula using the symbol `"."`. Conditional expressions on the right of a `|` operator can be used to define separate panels in a Trellis display. The expression on the right hand side of `form`, and to the left of the `|` operator, must evaluate to a data frame with at least two columns. Default is `~ coef(.)` , corresponding to a pairs plot of the coefficients of `x`. | | `label` | an optional character vector of labels for the variables in the pairs plot. | | `id` | an optional numeric value, or one-sided formula. If given as a value, it is used as a significance level for an outlier test based on the Mahalanobis distances of the estimated random effects. Groups with random effects distances greater than the *1-value* percentile of the appropriate chi-square distribution are identified in the plot using `idLabels`. If given as a one-sided formula, its right hand side must evaluate to a logical, integer, or character vector which is used to identify points in the plot. If missing, no points are identified. | | `idLabels` | an optional vector, or one-sided formula. If given as a vector, it is converted to character and used to label the points identified according to `id`. If given as a one-sided formula, its right hand side must evaluate to a vector which is converted to character and used to label the identified points. Default is the innermost grouping factor. | | `grid` | an optional logical value indicating whether a grid should be added to plot. Default is `FALSE`. | | `...` | optional arguments passed to the Trellis plot function. | ### Value a diagnostic Trellis plot. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[lmList](lmlist)`, `<pairs.lme>`, `[pairs.compareFits](pairs.comparefits)`, `[xyplot](../../lattice/html/xyplot)`, `[splom](../../lattice/html/splom)` ### Examples ``` fm1 <- lmList(distance ~ age | Subject, Orthodont) # scatter plot of coefficients by gender, identifying unusual subjects pairs(fm1, ~coef(.) | Sex, id = 0.1, adj = -0.5) # scatter plot of estimated random effects -- "bivariate Gaussian (?)" pairs(fm1, ~ranef(.)) ``` r None `plot.augPred` Plot an augPred Object -------------------------------------- ### Description A Trellis `xyplot` of predictions versus the primary covariate is generated, with a different panel for each value of the grouping factor. Predicted values are joined by lines, with different line types (colors) being used for each level of grouping. Original observations are represented by circles. ### Usage ``` ## S3 method for class 'augPred' plot(x, key, grid, ...) ``` ### Arguments | | | | --- | --- | | `x` | an object of class `"[augPred](augpred)"`. | | `key` | an optional logical value, or list. If `TRUE`, a legend is included at the top of the plot indicating which symbols (colors) correspond to which prediction levels. If `FALSE`, no legend is included. If given as a list, `key` is passed down as an argument to the `trellis` function generating the plots (`xyplot`). Defaults to `TRUE`. | | `grid` | an optional logical value indicating whether a grid should be added to plot. Default is `FALSE`. | | `...` | optional arguments passed down to the `trellis` function generating the plots. | ### Value A Trellis plot of predictions versus the primary covariate, with panels determined by the grouping factor. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[augPred](augpred)`, `[xyplot](../../lattice/html/xyplot)` ### Examples ``` fm1 <- lme(Orthodont) plot(augPred(fm1, level = 0:1, length.out = 2)) ``` r None `corSpher` Spherical Correlation Structure ------------------------------------------- ### Description This function is a constructor for the `corSpher` class, representing a spherical spatial correlation structure. Letting *d* denote the range and *n* denote the nugget effect, the correlation between two observations a distance *r < d* apart is *1-1.5(r/d)+0.5(r/d)^3* when no nugget effect is present and *(1-n)\*(1-1.5(r/d)+0.5(r/d)^3)* when a nugget effect is assumed. If *r >= d* the correlation is zero. Objects created using this constructor must later be initialized using the appropriate `Initialize` method. ### Usage ``` corSpher(value, form, nugget, metric, fixed) ``` ### Arguments | | | | --- | --- | | `value` | an optional vector with the parameter values in constrained form. If `nugget` is `FALSE`, `value` can have only one element, corresponding to the "range" of the spherical correlation structure, which must be greater than zero. If `nugget` is `TRUE`, meaning that a nugget effect is present, `value` can contain one or two elements, the first being the "range" and the second the "nugget effect" (one minus the correlation between two observations taken arbitrarily close together); the first must be greater than zero and the second must be between zero and one. Defaults to `numeric(0)`, which results in a range of 90% of the minimum distance and a nugget effect of 0.1 being assigned to the parameters when `object` is initialized. | | `form` | a one sided formula of the form `~ S1+...+Sp`, or `~ S1+...+Sp | g`, specifying spatial covariates `S1` through `Sp` and, optionally, a grouping factor `g`. When a grouping factor is present in `form`, the correlation structure is assumed to apply only to observations within the same grouping level; observations with different grouping levels are assumed to be uncorrelated. Defaults to `~ 1`, which corresponds to using the order of the observations in the data as a covariate, and no groups. | | `nugget` | an optional logical value indicating whether a nugget effect is present. Defaults to `FALSE`. | | `metric` | an optional character string specifying the distance metric to be used. The currently available options are `"euclidean"` for the root sum-of-squares of distances; `"maximum"` for the maximum difference; and `"manhattan"` for the sum of the absolute differences. Partial matching of arguments is used, so only the first three characters need to be provided. Defaults to `"euclidean"`. | | `fixed` | an optional logical value indicating whether the coefficients should be allowed to vary in the optimization, or kept fixed at their initial value. Defaults to `FALSE`, in which case the coefficients are allowed to vary. | ### Value an object of class `corSpher`, also inheriting from class `corSpatial`, representing a spherical spatial correlation structure. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Cressie, N.A.C. (1993), "Statistics for Spatial Data", J. Wiley & Sons. Venables, W.N. and Ripley, B.D. (2002) "Modern Applied Statistics with S", 4th Edition, Springer-Verlag. Littel, Milliken, Stroup, and Wolfinger (1996) "SAS Systems for Mixed Models", SAS Institute. Pinheiro, J.C., and Bates, D.M. (2000) "Mixed-Effects Models in S and S-PLUS", Springer. ### See Also `[Initialize.corStruct](initialize.corstruct)`, `[summary.corStruct](summary.corstruct)`, `[dist](../../stats/html/dist)` ### Examples ``` sp1 <- corSpher(form = ~ x + y) # example lme(..., corSpher ...) # Pinheiro and Bates, pp. 222-249 fm1BW.lme <- lme(weight ~ Time * Diet, BodyWeight, random = ~ Time) # p. 223 fm2BW.lme <- update(fm1BW.lme, weights = varPower()) # p 246 fm3BW.lme <- update(fm2BW.lme, correlation = corExp(form = ~ Time)) # p. 249 fm6BW.lme <- update(fm3BW.lme, correlation = corSpher(form = ~ Time)) # example gls(..., corSpher ...) # Pinheiro and Bates, pp. 261, 263 fm1Wheat2 <- gls(yield ~ variety - 1, Wheat2) # p. 262 fm2Wheat2 <- update(fm1Wheat2, corr = corSpher(c(28, 0.2), form = ~ latitude + longitude, nugget = TRUE)) ``` r None `anova.gls` Compare Likelihoods of Fitted Objects -------------------------------------------------- ### Description When only one fitted model object is present, a data frame with the sums of squares, numerator degrees of freedom, F-values, and P-values for Wald tests for the terms in the model (when `Terms` and `L` are `NULL`), a combination of model terms (when `Terms` in not `NULL`), or linear combinations of the model coefficients (when `L` is not `NULL`). Otherwise, when multiple fitted objects are being compared, a data frame with the degrees of freedom, the (restricted) log-likelihood, the Akaike Information Criterion (AIC), and the Bayesian Information Criterion (BIC) of each object is returned. If `test=TRUE`, whenever two consecutive objects have different number of degrees of freedom, a likelihood ratio statistic, with the associated p-value is included in the returned data frame. ### Usage ``` ## S3 method for class 'gls' anova(object, ..., test, type, adjustSigma, Terms, L, verbose) ``` ### Arguments | | | | --- | --- | | `object` | a fitted model object inheriting from class `gls`, representing a generalized least squares fit. | | `...` | other optional fitted model objects inheriting from classes `"gls"`, `"gnls"`, `"lm"`, `"lme"`, `"lmList"`, `"nlme"`, `"nlsList"`, or `"nls"`. | | `test` | an optional logical value controlling whether likelihood ratio tests should be used to compare the fitted models represented by `object` and the objects in `...`. Defaults to `TRUE`. | | `type` | an optional character string specifying the type of sum of squares to be used in F-tests for the terms in the model. If `"sequential"`, the sequential sum of squares obtained by including the terms in the order they appear in the model is used; else, if `"marginal"`, the marginal sum of squares obtained by deleting a term from the model at a time is used. This argument is only used when a single fitted object is passed to the function. Partial matching of arguments is used, so only the first character needs to be provided. Defaults to `"sequential"`. | | `adjustSigma` | an optional logical value. If `TRUE` and the estimation method used to obtain `object` was maximum likelihood, the residual standard error is multiplied by *sqrt(nobs/(nobs - npar))*, converting it to a REML-like estimate. This argument is only used when a single fitted object is passed to the function. Default is `TRUE`. | | `Terms` | an optional integer or character vector specifying which terms in the model should be jointly tested to be zero using a Wald F-test. If given as a character vector, its elements must correspond to term names; else, if given as an integer vector, its elements must correspond to the order in which terms are included in the model. This argument is only used when a single fitted object is passed to the function. Default is `NULL`. | | `L` | an optional numeric vector or array specifying linear combinations of the coefficients in the model that should be tested to be zero. If given as an array, its rows define the linear combinations to be tested. If names are assigned to the vector elements (array columns), they must correspond to coefficients names and will be used to map the linear combination(s) to the coefficients; else, if no names are available, the vector elements (array columns) are assumed in the same order as the coefficients appear in the model. This argument is only used when a single fitted object is passed to the function. Default is `NULL`. | | `verbose` | an optional logical value. If `TRUE`, the calling sequences for each fitted model object are printed with the rest of the output, being omitted if `verbose = FALSE`. Defaults to `FALSE`. | ### Value a data frame inheriting from class `"anova.lme"`. ### Note Likelihood comparisons are not meaningful for objects fit using restricted maximum likelihood and with different fixed effects. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Pinheiro, J. C. and Bates, D. M. (2000), *Mixed-Effects Models in S and S-PLUS*, Springer, New York. ### See Also `<gls>`, `<gnls>`, `<lme>`, `[logLik.gls](loglik.lme)`, `[AIC](../../stats/html/aic)`, `[BIC](../../stats/html/aic)`, `[print.anova.lme](anova.lme)` ### Examples ``` # AR(1) errors within each Mare fm1 <- gls(follicles ~ sin(2*pi*Time) + cos(2*pi*Time), Ovary, correlation = corAR1(form = ~ 1 | Mare)) anova(fm1) # variance changes with a power of the absolute fitted values? fm2 <- update(fm1, weights = varPower()) anova(fm1, fm2) # Pinheiro and Bates, p. 251-252 fm1Orth.gls <- gls(distance ~ Sex * I(age - 11), Orthodont, correlation = corSymm(form = ~ 1 | Subject), weights = varIdent(form = ~ 1 | age)) fm2Orth.gls <- update(fm1Orth.gls, corr = corCompSymm(form = ~ 1 | Subject)) anova(fm1Orth.gls, fm2Orth.gls) # Pinheiro and Bates, pp. 215-215, 255-260 #p. 215 fm1Dial.lme <- lme(rate ~(pressure + I(pressure^2) + I(pressure^3) + I(pressure^4))*QB, Dialyzer, ~ pressure + I(pressure^2)) # p. 216 fm2Dial.lme <- update(fm1Dial.lme, weights = varPower(form = ~ pressure)) # p. 255 fm1Dial.gls <- gls(rate ~ (pressure + I(pressure^2) + I(pressure^3) + I(pressure^4))*QB, Dialyzer) fm2Dial.gls <- update(fm1Dial.gls, weights = varPower(form = ~ pressure)) anova(fm1Dial.gls, fm2Dial.gls) fm3Dial.gls <- update(fm2Dial.gls, corr = corAR1(0.771, form = ~ 1 | Subject)) anova(fm2Dial.gls, fm3Dial.gls) # anova.gls to compare a gls and an lme fit anova(fm3Dial.gls, fm2Dial.lme, test = FALSE) # Pinheiro and Bates, pp. 261-266 fm1Wheat2 <- gls(yield ~ variety - 1, Wheat2) fm3Wheat2 <- update(fm1Wheat2, corr = corRatio(c(12.5, 0.2), form = ~ latitude + longitude, nugget = TRUE)) # Test a specific contrast anova(fm3Wheat2, L = c(-1, 0, 1)) ```
programming_docs
r None `predict.gls` Predictions from a gls Object -------------------------------------------- ### Description The predictions for the linear model represented by `object` are obtained at the covariate values defined in `newdata`. ### Usage ``` ## S3 method for class 'gls' predict(object, newdata, na.action, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"<gls>"`, representing a generalized least squares fitted linear model. | | `newdata` | an optional data frame to be used for obtaining the predictions. All variables used in the linear model must be present in the data frame. If missing, the fitted values are returned. | | `na.action` | a function that indicates what should happen when `newdata` contains `NA`s. The default action (`na.fail`) causes the function to print an error message and terminate if there are any incomplete observations. | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value a vector with the predicted values. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `<gls>` ### Examples ``` fm1 <- gls(follicles ~ sin(2*pi*Time) + cos(2*pi*Time), Ovary, correlation = corAR1(form = ~ 1 | Mare)) newOvary <- data.frame(Time = c(-0.75, -0.5, 0, 0.5, 0.75)) predict(fm1, newOvary) ``` r None `balancedGrouped` Create a groupedData object from a matrix ------------------------------------------------------------ ### Description Create a `groupedData` object from a data matrix. This function can be used only with balanced data. The opposite conversion, from a `groupedData` object to a `matrix`, is done with `asTable`. ### Usage ``` balancedGrouped(form, data, labels=NULL, units=NULL) ``` ### Arguments | | | | --- | --- | | `form` | A formula of the form `y ~ x | g` giving the name of the response, the primary covariate, and the grouping factor. | | `data` | A matrix or data frame containing the values of the response grouped according to the levels of the grouping factor (rows) and the distinct levels of the primary covariate (columns). The `dimnames` of the matrix are used to construct the levels of the grouping factor and the primary covariate. | | `labels` | an optional list of character strings giving labels for the response and the primary covariate. The label for the primary covariate is named `x` and that for the response is named `y`. Either label can be omitted. | | `units` | an optional list of character strings giving the units for the response and the primary covariate. The units string for the primary covariate is named `x` and that for the response is named `y`. Either units string can be omitted. | ### Value A balanced `groupedData` object. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Pinheiro, J. C. and Bates, D. M. (2000), *Mixed-Effects Models in S and S-PLUS*, Springer, New York. ### See Also `[groupedData](groupeddata)`, `[isBalanced](isbalanced)`, `[asTable](astable)` ### Examples ``` OrthoMat <- asTable( Orthodont ) Orth2 <- balancedGrouped(distance ~ age | Subject, data = OrthoMat, labels = list(x = "Age", y = "Distance from pituitary to pterygomaxillary fissure"), units = list(x = "(yr)", y = "(mm)")) Orth2[ 1:10, ] ## check the first few entries # Pinheiro and Bates, p. 109 ergoStool.mat <- asTable(ergoStool) balancedGrouped(effort~Type|Subject, data=ergoStool.mat) ``` r None `print.varFunc` Print a varFunc Object --------------------------------------- ### Description The class and the coefficients associated with `x` are printed. ### Usage ``` ## S3 method for class 'varFunc' print(x, ...) ``` ### Arguments | | | | --- | --- | | `x` | an object inheriting from class `"[varFunc](varfunc)"`, representing a variance function structure. | | `...` | optional arguments passed to `print.default`; see the documentation on that method function. | ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[summary.varFunc](summary.varfunc)` ### Examples ``` vf1 <- varPower(0.3, form = ~age) vf1 <- Initialize(vf1, Orthodont) print(vf1) ``` r None `corFactor.corStruct` Factor of a corStruct Object Matrix ---------------------------------------------------------- ### Description This method function extracts a transpose inverse square-root factor, or a series of transpose inverse square-root factors, of the correlation matrix, or list of correlation matrices, represented by `object`. Letting *S* denote a correlation matrix, a square-root factor of *S* is any square matrix *L* such that *S = L'L*. This method extracts *L^(-t)*. ### Usage ``` ## S3 method for class 'corStruct' corFactor(object, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"[corStruct](corclasses)"` representing a correlation structure, which must have been initialized (using `Initialize`). | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value If the correlation structure does not include a grouping factor, the returned value will be a vector with a transpose inverse square-root factor of the correlation matrix associated with `object` stacked column-wise. If the correlation structure includes a grouping factor, the returned value will be a vector with transpose inverse square-root factors of the correlation matrices for each group, stacked by group and stacked column-wise within each group. ### Note This method function is used intensively in optimization algorithms and its value is returned as a vector for efficiency reasons. The `corMatrix` method function can be used to obtain transpose inverse square-root factors in matrix form. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[corFactor](corfactor)`, `[corMatrix.corStruct](cormatrix.corstruct)`, `[recalc.corStruct](recalc.corstruct)`, `[Initialize.corStruct](initialize.corstruct)` ### Examples ``` cs1 <- corAR1(form = ~1 | Subject) cs1 <- Initialize(cs1, data = Orthodont) corFactor(cs1) ``` r None `summary.modelStruct` Summarize a modelStruct Object ----------------------------------------------------- ### Description This method function applies `summary` to each element of `object`. ### Usage ``` ## S3 method for class 'modelStruct' summary(object, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"modelStruct"`, representing a list of model components, such as `reStruct`, `corStruct` and `varFunc` objects. | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value a list with elements given by the summarized components of `object`. The returned value is of class `summary.modelStruct`, also inheriting from the same classes as `object`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[reStruct](restruct)`, `[summary](../../base/html/summary)` ### Examples ``` lms1 <- lmeStruct(reStruct = reStruct(pdDiag(diag(2), ~age)), corStruct = corAR1(0.3)) summary(lms1) ``` r None `summary.gls` Summarize a Generalized Least Squares gls Object --------------------------------------------------------------- ### Description Additional information about the linear model fit represented by `object` is extracted and included as components of `object`. ### Usage ``` ## S3 method for class 'gls' summary(object, verbose, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"<gls>"`, representing a generalized least squares fitted linear model. | | `verbose` | an optional logical value used to control the amount of output when the object is printed. Defaults to `FALSE`. | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value an object inheriting from class `summary.gls` with all components included in `object` (see `[glsObject](glsobject)` for a full description of the components) plus the following components: | | | | --- | --- | | `corBeta` | approximate correlation matrix for the coefficients estimates | | `tTable` | a matrix with columns `Value`, `Std. Error`, `t-value`, and `p-value` representing respectively the coefficients estimates, their approximate standard errors, the ratios between the estimates and their standard errors, and the associated p-value under a *t* approximation. Rows correspond to the different coefficients. | | `residuals` | if more than five observations are used in the `gls` fit, a vector with the minimum, first quartile, median, third quartile, and maximum of the residuals distribution; else the residuals. | | `AIC` | the Akaike Information Criterion corresponding to `object`. | | `BIC` | the Bayesian Information Criterion corresponding to `object`. | ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[AIC](../../stats/html/aic)`, `[BIC](../../stats/html/aic)`, `<gls>`, `[summary](../../base/html/summary)` ### Examples ``` fm1 <- gls(follicles ~ sin(2*pi*Time) + cos(2*pi*Time), Ovary, correlation = corAR1(form = ~ 1 | Mare)) summary(fm1) coef(summary(fm1)) # "the matrix" ``` r None `getGroups.lmList` Extract lmList Object Groups ------------------------------------------------ ### Description The grouping factor determining the partitioning of the observations used to produce the `lm` components of `object` is extracted. ### Usage ``` ## S3 method for class 'lmList' getGroups(object, form, level, data, sep) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `lmList`, representing a list of `lm` objects with a common model. | | `form` | an optional formula with a conditioning expression on its right hand side (i.e. an expression involving the `|` operator). Defaults to `formula(object)`. Not used. | | `level` | a positive integer vector with the level(s) of grouping to be used when multiple nested levels of grouping are present. This argument is optional for most methods of this generic function and defaults to all levels of nesting. Not used. | | `data` | a data frame in which to interpret the variables named in `form`. Optional for most methods. Not used. | | `sep` | character, the separator to use between group levels when multiple levels are collapsed. The default is `'/'`. Not used. | ### Value a vector with the grouping factor corresponding to the `lm` components of `object`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[lmList](lmlist)` ### Examples ``` fm1 <- lmList(distance ~ age | Subject, Orthodont) getGroups(fm1) ``` r None `formula.pdMat` Extract pdMat Formula -------------------------------------- ### Description This method function extracts the formula associated with a `pdMat` object, in which the column and row names are specified. ### Usage ``` ## S3 method for class 'pdMat' formula(x, asList, ...) ``` ### Arguments | | | | --- | --- | | `x` | an object inheriting from class `"[pdMat](pdmat)"`, representing a positive definite matrix. | | `asList` | logical. Should the asList argument be applied to each of the components? Never used. | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value if `x` has a `formula` attribute, its value is returned, else `NULL` is returned. ### Note Because factors may be present in `formula(x)`, the `pdMat` object needs to have access to a data frame where the variables named in the formula can be evaluated, before it can resolve its row and column names from the formula. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[pdMat](pdmat)` ### Examples ``` pd1 <- pdSymm(~Sex*age) formula(pd1) ``` r None `logLik.varFunc` Extract varFunc logLik ---------------------------------------- ### Description This method function extracts the component of a Gaussian log-likelihood associated with the variance function structure represented by `object`, which is equal to the sum of the logarithms of the corresponding weights. ### Usage ``` ## S3 method for class 'varFunc' logLik(object, data, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"[varFunc](varfunc)"`, representing a variance function structure. | | `data` | this argument is included to make this method function compatible with other `logLik` methods and will be ignored. | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value the sum of the logarithms of the weights corresponding to the variance function structure represented by `object`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[logLik.lme](loglik.lme)` ### Examples ``` vf1 <- varPower(form = ~age) vf1 <- Initialize(vf1, Orthodont) coef(vf1) <- 0.1 logLik(vf1) ``` r None `corNatural` General correlation in natural parameterization ------------------------------------------------------------- ### Description This function is a constructor for the `corNatural` class, representing a general correlation structure in the “natural” parameterization, which is described under `[pdNatural](pdnatural)`. Objects created using this constructor must later be initialized using the appropriate `Initialize` method. ### Usage ``` corNatural(value, form, fixed) ``` ### Arguments | | | | --- | --- | | `value` | an optional vector with the parameter values. Default is `numeric(0)`, which results in a vector of zeros of appropriate dimension being assigned to the parameters when `object` is initialized (corresponding to an identity correlation structure). | | `form` | a one sided formula of the form `~ t`, or `~ t | g`, specifying a time covariate `t` and, optionally, a grouping factor `g`. A covariate for this correlation structure must be integer valued. When a grouping factor is present in `form`, the correlation structure is assumed to apply only to observations within the same grouping level; observations with different grouping levels are assumed to be uncorrelated. Defaults to `~ 1`, which corresponds to using the order of the observations in the data as a covariate, and no groups. | | `fixed` | an optional logical value indicating whether the coefficients should be allowed to vary in the optimization, or kept fixed at their initial value. Defaults to `FALSE`, in which case the coefficients are allowed to vary. | ### Value an object of class `corNatural` representing a general correlation structure. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[Initialize.corNatural](initialize.corstruct)`, `[pdNatural](pdnatural)`, `[summary.corNatural](summary.corstruct)` ### Examples ``` ## covariate is observation order and grouping factor is Subject cs1 <- corNatural(form = ~ 1 | Subject) ``` r None `getCovariate` Extract Covariate from an Object ------------------------------------------------ ### Description This function is generic; method functions can be written to handle specific classes of objects. Classes which already have methods for this function include `corStruct`, `corSpatial`, `data.frame`, and `varFunc`. ### Usage ``` getCovariate(object, form, data) ``` ### Arguments | | | | --- | --- | | `object` | any object with a `covariate` component | | `form` | an optional one-sided formula specifying the covariate(s) to be extracted. Defaults to `formula(object)`. | | `data` | a data frame in which to evaluate the variables defined in `form`. | ### Value will depend on the method function used; see the appropriate documentation. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Pinheiro, J.C., and Bates, D.M. (2000) "Mixed-Effects Models in S and S-PLUS", Springer, esp. p. 100. ### See Also `[getCovariate.corStruct](getcovariate.corstruct)`, `[getCovariate.data.frame](getcovariate.data.frame)`, `[getCovariate.varFunc](getcovariate.varfunc)`, `[getCovariateFormula](getcovariateformula)` ### Examples ``` ## see the method function documentation ``` r None `Dialyzer` High-Flux Hemodialyzer ---------------------------------- ### Description The `Dialyzer` data frame has 140 rows and 5 columns. ### Format This data frame contains the following columns: Subject an ordered factor with levels `10` < `8` < `2` < `6` < `3` < `5` < `9` < `7` < `1` < `4` < `17` < `20` < `11` < `12` < `16` < `13` < `14` < `18` < `15` < `19` giving the unique identifier for each subject QB a factor with levels `200` and `300` giving the bovine blood flow rate (dL/min). pressure a numeric vector giving the transmembrane pressure (dmHg). rate the hemodialyzer ultrafiltration rate (mL/hr). index index of observation within subject—1 through 7. ### Details Vonesh and Carter (1992) describe data measured on high-flux hemodialyzers to assess their *in vivo* ultrafiltration characteristics. The ultrafiltration rates (in mL/hr) of 20 high-flux dialyzers were measured at seven different transmembrane pressures (in dmHg). The *in vitro* evaluation of the dialyzers used bovine blood at flow rates of either 200~dl/min or 300~dl/min. The data, are also analyzed in Littell, Milliken, Stroup, and Wolfinger (1996). ### Source Pinheiro, J. C. and Bates, D. M. (2000), *Mixed-Effects Models in S and S-PLUS*, Springer, New York. (Appendix A.6) Vonesh, E. F. and Carter, R. L. (1992), Mixed-effects nonlinear regression for unbalanced repeated measures, *Biometrics*, **48**, 1-18. Littell, R. C., Milliken, G. A., Stroup, W. W. and Wolfinger, R. D. (1996), *SAS System for Mixed Models*, SAS Institute, Cary, NC. r None `pdIdent` Multiple of the Identity Positive-Definite Matrix ------------------------------------------------------------ ### Description This function is a constructor for the `pdIdent` class, representing a multiple of the identity positive-definite matrix. The matrix associated with `object` is represented by 1 unrestricted parameter, given by the logarithm of the square-root of the diagonal value. When `value` is `numeric(0)`, an uninitialized `pdMat` object, a one-sided formula, or a vector of character strings, `object` is returned as an uninitialized `pdIdent` object (with just some of its attributes and its class defined) and needs to have its coefficients assigned later, generally using the `coef` or `matrix` replacement functions. If `value` is an initialized `pdMat` object, `object` will be constructed from `as.matrix(value)`. Finally, if `value` is a numeric value, it is assumed to represent the unrestricted coefficient of the underlying positive-definite matrix. ### Usage ``` pdIdent(value, form, nam, data) ``` ### Arguments | | | | --- | --- | | `value` | an optional initialization value, which can be any of the following: a `pdMat` object, a positive-definite matrix, a one-sided linear formula (with variables separated by `+`), a vector of character strings, or a numeric value. Defaults to `numeric(0)`, corresponding to an uninitialized object. | | `form` | an optional one-sided linear formula specifying the row/column names for the matrix represented by `object`. Because factors may be present in `form`, the formula needs to be evaluated on a data.frame to resolve the names it defines. This argument is ignored when `value` is a one-sided formula. Defaults to `NULL`. | | `nam` | an optional vector of character strings specifying the row/column names for the matrix represented by object. It must have length equal to the dimension of the underlying positive-definite matrix and unreplicated elements. This argument is ignored when `value` is a vector of character strings. Defaults to `NULL`. | | `data` | an optional data frame in which to evaluate the variables named in `value` and `form`. It is used to obtain the levels for `factors`, which affect the dimensions and the row/column names of the underlying matrix. If `NULL`, no attempt is made to obtain information on `factors` appearing in the formulas. Defaults to the parent frame from which the function was called. | ### Value a `pdIdent` object representing a multiple of the identity positive-definite matrix, also inheriting from class `pdMat`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Pinheiro, J.C., and Bates, D.M. (2000) "Mixed-Effects Models in S and S-PLUS", Springer. ### See Also `[as.matrix.pdMat](as.matrix.pdmat)`, `[coef.pdMat](coef.pdmat)`, `[pdClasses](pdclasses)`, `[matrix<-.pdMat](matrix.pdmat)` ### Examples ``` pd1 <- pdIdent(4 * diag(3), nam = c("A","B","C")) pd1 ```
programming_docs
r None `fitted.glsStruct` Calculate glsStruct Fitted Values ----------------------------------------------------- ### Description The fitted values for the linear model represented by `object` are extracted. ### Usage ``` ## S3 method for class 'glsStruct' fitted(object, glsFit, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"[glsStruct](glsstruct)"`, representing a list of linear model components, such as `corStruct` and `"[varFunc](varfunc)"` objects. | | `glsFit` | an optional list with components `logLik` (log-likelihood), `beta` (coefficients), `sigma` (standard deviation for error term), `varBeta` (coefficients' covariance matrix), `fitted` (fitted values), and `residuals` (residuals). Defaults to `attr(object, "glsFit")`. | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value a vector with the fitted values for the linear model represented by `object`. ### Note This method function is generally only used inside `gls` and `fitted.gls`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `<gls>`, `[residuals.glsStruct](residuals.glsstruct)` r None `Initialize.varFunc` Initialize varFunc Object ----------------------------------------------- ### Description This method initializes `object` by evaluating its associated covariate(s) and grouping factor, if any is present, in `data`; determining if the covariate(s) need to be updated when the values of the coefficients associated with `object` change; initializing the log-likelihood and the weights associated with `object`; and assigning initial values for the coefficients in `object`, if none were present. The covariate(s) will only be initialized if no update is needed when `coef(object)` changes. ### Usage ``` ## S3 method for class 'varFunc' Initialize(object, data, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"[varFunc](varfunc)"`, representing a variance function structure. | | `data` | a data frame in which to evaluate the variables named in `formula(object)`. | | `...` | this argument is included to make this method compatible with the generic. | ### Value an initialized object with the same class as `object` representing a variance function structure. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[Initialize](initialize)` ### Examples ``` vf1 <- varPower( form = ~ age | Sex ) vf1 <- Initialize( vf1, Orthodont ) ``` r None `pdMatrix.reStruct` Extract Matrix or Square-Root Factor from Components of an reStruct Object ----------------------------------------------------------------------------------------------- ### Description This method function extracts the positive-definite matrices corresponding to the `pdMat` elements of `object`, or square-root factors of the positive-definite matrices. ### Usage ``` ## S3 method for class 'reStruct' pdMatrix(object, factor) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"[reStruct](restruct)"`, representing a random effects structure and consisting of a list of `pdMat` objects. | | `factor` | an optional logical value. If `TRUE`, square-root factors of the positive-definite matrices represented by the elements of `object` are returned; else, if `FALSE`, the positive-definite matrices are returned. Defaults to `FALSE`. | ### Value a list with components given by the positive-definite matrices corresponding to the elements of `object`, or square-root factors of the positive-definite matrices. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Pinheiro, J.C., and Bates, D.M. (2000) "Mixed-Effects Models in S and S-PLUS", Springer, esp. p. 162. ### See Also `[as.matrix.reStruct](as.matrix.restruct)`, `[reStruct](restruct)`, `[pdMat](pdmat)`, `[pdMatrix](pdmatrix)`, `[pdMatrix.pdMat](pdmatrix)` ### Examples ``` rs1 <- reStruct(pdSymm(diag(3), ~age+Sex, data = Orthodont)) pdMatrix(rs1) ``` r None `residuals.lmeStruct` Calculate lmeStruct Residuals ---------------------------------------------------- ### Description The residuals at level *i* are obtained by subtracting the fitted values at that level from the response vector. The fitted values at level *i* are obtained by adding together the population fitted values (based only on the fixed effects estimates) and the estimated contributions of the random effects to the fitted values at grouping levels less or equal to *i*. ### Usage ``` ## S3 method for class 'lmeStruct' residuals(object, level, conLin, lmeFit, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"[lmeStruct](lmestruct)"`, representing a list of linear mixed-effects model components, such as `reStruct`, `corStruct`, and `varFunc` objects. | | `level` | an optional integer vector giving the level(s) of grouping to be used in extracting the residuals from `object`. Level values increase from outermost to innermost grouping, with level zero corresponding to the population fitted values. Defaults to the highest or innermost level of grouping. | | `conLin` | an optional condensed linear model object, consisting of a list with components `"Xy"`, corresponding to a regression matrix (`X`) combined with a response vector (`y`), and `"logLik"`, corresponding to the log-likelihood of the underlying lme model. Defaults to `attr(object, "conLin")`. | | `lmeFit` | an optional list with components `beta` and `b` containing respectively the fixed effects estimates and the random effects estimates to be used to calculate the residuals. Defaults to `attr(object, "lmeFit")`. | | `...` | some methods for this generic accept optional arguments. | ### Value if a single level of grouping is specified in `level`, the returned value is a vector with the residuals at the desired level; else, when multiple grouping levels are specified in `level`, the returned object is a matrix with columns given by the residuals at different levels. ### Note This method function is primarily used within the `<lme>` function. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `<lme>`, `<residuals.lme>`, `[fitted.lmeStruct](fitted.lmestruct)` r None `Initialize.corStruct` Initialize corStruct Object --------------------------------------------------- ### Description This method initializes `object` by evaluating its associated covariate(s) and grouping factor, if any is present, in `data`, calculating various dimensions and constants used by optimization algorithms involving `corStruct` objects (see the appropriate `Dim` method documentation), and assigning initial values for the coefficients in `object`, if none were present. ### Usage ``` ## S3 method for class 'corStruct' Initialize(object, data, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"[corStruct](corclasses)"` representing a correlation structure. | | `data` | a data frame in which to evaluate the variables defined in `formula(object)`. | | `...` | this argument is included to make this method compatible with the generic. | ### Value an initialized object with the same class as `object` representing a correlation structure. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Pinheiro, J.C., and Bates, D.M. (2000) "Mixed-Effects Models in S and S-PLUS", Springer. ### See Also `[Dim.corStruct](dim.corstruct)` ### Examples ``` cs1 <- corAR1(form = ~ 1 | Subject) cs1 <- Initialize(cs1, data = Orthodont) ``` r None `Gasoline` Refinery yield of gasoline -------------------------------------- ### Description The `Gasoline` data frame has 32 rows and 6 columns. ### Format This data frame contains the following columns: yield a numeric vector giving the percentage of crude oil converted to gasoline after distillation and fractionation endpoint a numeric vector giving the temperature (degrees F) at which all the gasoline is vaporized Sample an ordered factor giving the inferred crude oil sample number API a numeric vector giving the crude oil gravity (degrees API) vapor a numeric vector giving the vapor pressure of the crude oil *(lbf/in^2)* ASTM a numeric vector giving the crude oil 10% point ASTM—the temperature at which 10% of the crude oil has become vapor. ### Details Prater (1955) provides data on crude oil properties and gasoline yields. Atkinson (1985) uses these data to illustrate the use of diagnostics in multiple regression analysis. Three of the covariates—`API`, `vapor`, and `ASTM`—measure characteristics of the crude oil used to produce the gasoline. The other covariate — `endpoint`—is a characteristic of the refining process. Daniel and Wood (1980) notice that the covariates characterizing the crude oil occur in only ten distinct groups and conclude that the data represent responses measured on ten different crude oil samples. ### Source Prater, N. H. (1955), Estimate gasoline yields from crudes, *Petroleum Refiner*, **35** (5). Atkinson, A. C. (1985), *Plots, Transformations, and Regression*, Oxford Press, New York. Daniel, C. and Wood, F. S. (1980), *Fitting Equations to Data*, Wiley, New York Venables, W. N. and Ripley, B. D. (2002) *Modern Applied Statistics with S (4th ed)*, Springer, New York. r None `plot.nfnGroupedData` Plot an nfnGroupedData Object ---------------------------------------------------- ### Description A Trellis plot of the response versus the primary covariate is generated. If outer variables are specified, the combination of their levels are used to determine the panels of the Trellis display. Otherwise, the levels of the grouping variable determine the panels. A scatter plot of the response versus the primary covariate is displayed in each panel, with observations corresponding to same inner group joined by line segments. The Trellis function `xyplot` is used. ### Usage ``` ## S3 method for class 'nfnGroupedData' plot(x, outer, inner, innerGroups, xlab, ylab, strip, aspect, panel, key, grid, ...) ``` ### Arguments | | | | --- | --- | | `x` | an object inheriting from class `nfnGroupedData`, representing a `groupedData` object with a numeric primary covariate and a single grouping level. | | `outer` | an optional logical value or one-sided formula, indicating covariates that are outer to the grouping factor, which are used to determine the panels of the Trellis plot. If equal to `TRUE`, `attr(object, "outer")` is used to indicate the outer covariates. An outer covariate is invariant within the sets of rows defined by the grouping factor. Ordering of the groups is done in such a way as to preserve adjacency of groups with the same value of the outer variables. Defaults to `NULL`, meaning that no outer covariates are to be used. | | `inner` | an optional logical value or one-sided formula, indicating a covariate that is inner to the grouping factor, which is used to associate points within each panel of the Trellis plot. If equal to `TRUE`, `attr(object, "inner")` is used to indicate the inner covariate. An inner covariate can change within the sets of rows defined by the grouping factor. Defaults to `NULL`, meaning that no inner covariate is present. | | `innerGroups` | an optional one-sided formula specifying a factor to be used for grouping the levels of the `inner` covariate. Different colors, or line types, are used for each level of the `innerGroups` factor. Default is `NULL`, meaning that no `innerGroups` covariate is present. | | `xlab, ylab` | optional character strings with the labels for the plot. Default is the corresponding elements of `attr(object, "labels")` and `attr(object, "units")` pasted together. | | `strip` | an optional function passed as the `strip` argument to the `xyplot` function. Default is `strip.default(..., style = 1)` (see `trellis.args`). | | `aspect` | an optional character string indicating the aspect ratio for the plot passed as the `aspect` argument to the `xyplot` function. Default is `"xy"` (see `trellis.args`). | | `panel` | an optional function used to generate the individual panels in the Trellis display, passed as the `panel` argument to the `xyplot` function. | | `key` | an optional logical function or function. If `TRUE` and `innerGroups` is non-`NULL`, a legend for the different `innerGroups` levels is included at the top of the plot. If given as a function, it is passed as the `key` argument to the `xyplot` function. Default is `TRUE` if `innerGroups` is non-`NULL` and `FALSE` otherwise. | | `grid` | an optional logical value indicating whether a grid should be added to plot. Default is `TRUE`. | | `...` | optional arguments passed to the `xyplot` function. | ### Value a Trellis plot of the response versus the primary covariate. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Bates, D.M. and Pinheiro, J.C. (1997), "Software Design for Longitudinal Data", in "Modelling Longitudinal and Spatially Correlated Data: Methods, Applications and Future Directions", T.G. Gregoire (ed.), Springer-Verlag, New York. ### See Also `[groupedData](groupeddata)`, `[xyplot](../../lattice/html/xyplot)` ### Examples ``` # different panels per Subject plot(Orthodont) # different panels per gender plot(Orthodont, outer = TRUE) ``` r None `needUpdate.modelStruct` Check if a modelStruct Object Needs Updating ---------------------------------------------------------------------- ### Description This method function checks if any of the elements of `object` needs to be updated. Updating of objects usually takes place in iterative algorithms in which auxiliary quantities associated with the object, and not being optimized over, may change. ### Usage ``` ## S3 method for class 'modelStruct' needUpdate(object) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"modelStruct"`, representing a list of model components, such as `corStruct` and `varFunc` objects. | ### Value a logical value indicating whether any element of `object` needs to be updated. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[needUpdate](needupdate)` ### Examples ``` lms1 <- lmeStruct(reStruct = reStruct(pdDiag(diag(2), ~age)), varStruct = varPower(form = ~age)) needUpdate(lms1) ``` r None `solve.reStruct` Apply Solve to an reStruct Object --------------------------------------------------- ### Description `Solve` is applied to each `pdMat` component of `a`, which results in inverting the positive-definite matrices they represent. ### Usage ``` ## S3 method for class 'reStruct' solve(a, b, ...) ``` ### Arguments | | | | --- | --- | | `a` | an object inheriting from class `"[reStruct](restruct)"`, representing a random effects structure and consisting of a list of `pdMat` objects. | | `b` | this argument is only included for consistency with the generic function and is not used in this method function. | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value an `reStruct` object similar to `a`, but with the `pdMat` components representing the inverses of the matrices represented by the components of `a`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[solve.pdMat](solve.pdmat)`, `[reStruct](restruct)` ### Examples ``` rs1 <- reStruct(list(A = pdSymm(diag(1:3), form = ~Score), B = pdDiag(2 * diag(4), form = ~Educ))) solve(rs1) ``` r None `ACF.gls` Autocorrelation Function for gls Residuals ----------------------------------------------------- ### Description This method function calculates the empirical autocorrelation function for the residuals from a `gls` fit. If a grouping variable is specified in `form`, the autocorrelation values are calculated using pairs of residuals within the same group; otherwise all possible residual pairs are used. The autocorrelation function is useful for investigating serial correlation models for equally spaced data. ### Usage ``` ## S3 method for class 'gls' ACF(object, maxLag, resType, form, na.action, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"<gls>"`, representing a generalized least squares fitted model. | | `maxLag` | an optional integer giving the maximum lag for which the autocorrelation should be calculated. Defaults to maximum lag in the residuals. | | `resType` | an optional character string specifying the type of residuals to be used. If `"response"`, the "raw" residuals (observed - fitted) are used; else, if `"pearson"`, the standardized residuals (raw residuals divided by the corresponding standard errors) are used; else, if `"normalized"`, the normalized residuals (standardized residuals pre-multiplied by the inverse square-root factor of the estimated error correlation matrix) are used. Partial matching of arguments is used, so only the first character needs to be provided. Defaults to `"pearson"`. | | `form` | an optional one sided formula of the form `~ t`, or `~ t | g`, specifying a time covariate `t` and, optionally, a grouping factor `g`. The time covariate must be integer valued. When a grouping factor is present in `form`, the autocorrelations are calculated using residual pairs within the same group. Defaults to `~ 1`, which corresponds to using the order of the observations in the data as a covariate, and no groups. | | `na.action` | a function that indicates what should happen when the data contain `NA`s. The default action (`na.fail`) causes `ACF.gls` to print an error message and terminate if there are any incomplete observations. | | `...` | some methods for this generic require additional arguments. | ### Value a data frame with columns `lag` and `ACF` representing, respectively, the lag between residuals within a pair and the corresponding empirical autocorrelation. The returned value inherits from class `ACF`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Box, G.E.P., Jenkins, G.M., and Reinsel G.C. (1994) "Time Series Analysis: Forecasting and Control", 3rd Edition, Holden-Day. Pinheiro, J.C., and Bates, D.M. (2000) "Mixed-Effects Models in S and S-PLUS", Springer. ### See Also `[ACF.lme](acf.lme)`, `[plot.ACF](plot.acf)` ### Examples ``` fm1 <- gls(follicles ~ sin(2*pi*Time) + cos(2*pi*Time), Ovary) ACF(fm1, form = ~ 1 | Mare) # Pinheiro and Bates, p. 255-257 fm1Dial.gls <- gls(rate ~ (pressure+I(pressure^2)+I(pressure^3)+I(pressure^4))*QB, Dialyzer) fm2Dial.gls <- update(fm1Dial.gls, weights = varPower(form = ~ pressure)) ACF(fm2Dial.gls, form = ~ 1 | Subject) ``` r None `corLin` Linear Correlation Structure -------------------------------------- ### Description This function is a constructor for the `corLin` class, representing a linear spatial correlation structure. Letting *d* denote the range and *n* denote the nugget effect, the correlation between two observations a distance *r < d* apart is *1-(r/d)* when no nugget effect is present and *(1-n)\*(1-(r/d))* when a nugget effect is assumed. If *r >= d* the correlation is zero. Objects created using this constructor must later be initialized using the appropriate `Initialize` method. ### Usage ``` corLin(value, form, nugget, metric, fixed) ``` ### Arguments | | | | --- | --- | | `value` | an optional vector with the parameter values in constrained form. If `nugget` is `FALSE`, `value` can have only one element, corresponding to the "range" of the linear correlation structure, which must be greater than zero. If `nugget` is `TRUE`, meaning that a nugget effect is present, `value` can contain one or two elements, the first being the "range" and the second the "nugget effect" (one minus the correlation between two observations taken arbitrarily close together); the first must be greater than zero and the second must be between zero and one. Defaults to `numeric(0)`, which results in a range of 90% of the minimum distance and a nugget effect of 0.1 being assigned to the parameters when `object` is initialized. | | `form` | a one sided formula of the form `~ S1+...+Sp`, or `~ S1+...+Sp | g`, specifying spatial covariates `S1` through `Sp` and, optionally, a grouping factor `g`. When a grouping factor is present in `form`, the correlation structure is assumed to apply only to observations within the same grouping level; observations with different grouping levels are assumed to be uncorrelated. Defaults to `~ 1`, which corresponds to using the order of the observations in the data as a covariate, and no groups. | | `nugget` | an optional logical value indicating whether a nugget effect is present. Defaults to `FALSE`. | | `metric` | an optional character string specifying the distance metric to be used. The currently available options are `"euclidean"` for the root sum-of-squares of distances; `"maximum"` for the maximum difference; and `"manhattan"` for the sum of the absolute differences. Partial matching of arguments is used, so only the first three characters need to be provided. Defaults to `"euclidean"`. | | `fixed` | an optional logical value indicating whether the coefficients should be allowed to vary in the optimization, or kept fixed at their initial value. Defaults to `FALSE`, in which case the coefficients are allowed to vary. | ### Value an object of class `corLin`, also inheriting from class `corSpatial`, representing a linear spatial correlation structure. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Cressie, N.A.C. (1993), "Statistics for Spatial Data", J. Wiley & Sons. Venables, W.N. and Ripley, B.D. (2002) "Modern Applied Statistics with S", 4th Edition, Springer-Verlag. Littel, Milliken, Stroup, and Wolfinger (1996) "SAS Systems for Mixed Models", SAS Institute. Pinheiro, J.C., and Bates, D.M. (2000) "Mixed-Effects Models in S and S-PLUS", Springer. ### See Also `[Initialize.corStruct](initialize.corstruct)`, `[summary.corStruct](summary.corstruct)`, `[dist](../../stats/html/dist)` ### Examples ``` sp1 <- corLin(form = ~ x + y) # example lme(..., corLin ...) # Pinheiro and Bates, pp. 222-249 fm1BW.lme <- lme(weight ~ Time * Diet, BodyWeight, random = ~ Time) # p. 223 fm2BW.lme <- update(fm1BW.lme, weights = varPower()) # p 246 fm3BW.lme <- update(fm2BW.lme, correlation = corExp(form = ~ Time)) # p. 249 fm7BW.lme <- update(fm3BW.lme, correlation = corLin(form = ~ Time)) ```
programming_docs
r None `corAR1` AR(1) Correlation Structure ------------------------------------- ### Description This function is a constructor for the `corAR1` class, representing an autocorrelation structure of order 1. Objects created using this constructor must later be initialized using the appropriate `Initialize` method. ### Usage ``` corAR1(value, form, fixed) ``` ### Arguments | | | | --- | --- | | `value` | the value of the lag 1 autocorrelation, which must be between -1 and 1. Defaults to 0 (no autocorrelation). | | `form` | a one sided formula of the form `~ t`, or `~ t | g`, specifying a time covariate `t` and, optionally, a grouping factor `g`. A covariate for this correlation structure must be integer valued. When a grouping factor is present in `form`, the correlation structure is assumed to apply only to observations within the same grouping level; observations with different grouping levels are assumed to be uncorrelated. Defaults to `~ 1`, which corresponds to using the order of the observations in the data as a covariate, and no groups. | | `fixed` | an optional logical value indicating whether the coefficients should be allowed to vary in the optimization, or kept fixed at their initial value. Defaults to `FALSE`, in which case the coefficients are allowed to vary. | ### Value an object of class `corAR1`, representing an autocorrelation structure of order 1. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Box, G.E.P., Jenkins, G.M., and Reinsel G.C. (1994) "Time Series Analysis: Forecasting and Control", 3rd Edition, Holden-Day. Pinheiro, J.C., and Bates, D.M. (2000) "Mixed-Effects Models in S and S-PLUS", Springer, esp. pp. 235, 397. ### See Also `[ACF.lme](acf.lme)`, `[corARMA](corarma)`, `[corClasses](corclasses)`, `[Dim.corSpatial](dim.corspatial)`, `[Initialize.corStruct](initialize.corstruct)`, `[summary.corStruct](summary.corstruct)` ### Examples ``` ## covariate is observation order and grouping factor is Mare cs1 <- corAR1(0.2, form = ~ 1 | Mare) # Pinheiro and Bates, p. 236 cs1AR1 <- corAR1(0.8, form = ~ 1 | Subject) cs1AR1. <- Initialize(cs1AR1, data = Orthodont) corMatrix(cs1AR1.) # Pinheiro and Bates, p. 240 fm1Ovar.lme <- lme(follicles ~ sin(2*pi*Time) + cos(2*pi*Time), data = Ovary, random = pdDiag(~sin(2*pi*Time))) fm2Ovar.lme <- update(fm1Ovar.lme, correlation = corAR1()) # Pinheiro and Bates, pp. 255-258: use in gls fm1Dial.gls <- gls(rate ~(pressure + I(pressure^2) + I(pressure^3) + I(pressure^4))*QB, Dialyzer) fm2Dial.gls <- update(fm1Dial.gls, weights = varPower(form = ~ pressure)) fm3Dial.gls <- update(fm2Dial.gls, corr = corAR1(0.771, form = ~ 1 | Subject)) # Pinheiro and Bates use in nlme: # from p. 240 needed on p. 396 fm1Ovar.lme <- lme(follicles ~ sin(2*pi*Time) + cos(2*pi*Time), data = Ovary, random = pdDiag(~sin(2*pi*Time))) fm5Ovar.lme <- update(fm1Ovar.lme, corr = corARMA(p = 1, q = 1)) # p. 396 fm1Ovar.nlme <- nlme(follicles~ A+B*sin(2*pi*w*Time)+C*cos(2*pi*w*Time), data=Ovary, fixed=A+B+C+w~1, random=pdDiag(A+B+w~1), start=c(fixef(fm5Ovar.lme), 1) ) # p. 397 fm2Ovar.nlme <- update(fm1Ovar.nlme, corr=corAR1(0.311) ) ``` r None `summary.lme` Summarize an lme Object -------------------------------------- ### Description Additional information about the linear mixed-effects fit represented by `object` is extracted and included as components of `object`. The returned object has a `[print](../../base/html/print)` and a `[coef](../../stats/html/coef)` method, the latter returning the coefficient's `tTtable`. ### Usage ``` ## S3 method for class 'lme' summary(object, adjustSigma, verbose, ...) ## S3 method for class 'summary.lme' print(x, verbose = FALSE, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"<lme>"`, representing a fitted linear mixed-effects model. | | `adjustSigma` | an optional logical value. If `TRUE` and the estimation method used to obtain `object` was maximum likelihood, the residual standard error is multiplied by *sqrt(nobs/(nobs - npar))*, converting it to a REML-like estimate. This argument is only used when a single fitted object is passed to the function. Default is `TRUE`. | | `verbose` | an optional logical value used to control the amount of output in the `print.summary.lme` method. Defaults to `FALSE`. | | `...` | additional optional arguments passed to methods, mainly for the `[print](../../base/html/print)` method. | | `x` | a `"summary.lme"` object. | ! ### Value an object inheriting from class `summary.lme` with all components included in `object` (see `[lmeObject](lmeobject)` for a full description of the components) plus the following components: | | | | --- | --- | | `corFixed` | approximate correlation matrix for the fixed effects estimates. | | `tTable` | a matrix with columns named `Value`, `Std. Error`, `DF`, `t-value`, and `p-value` representing respectively the fixed effects estimates, their approximate standard errors, the denominator degrees of freedom, the ratios between the estimates and their standard errors, and the associated p-value from a t distribution. Rows correspond to the different fixed effects. | | `residuals` | if more than five observations are used in the `lme` fit, a vector with the minimum, first quartile, median, third quartile, and maximum of the innermost grouping level residuals distribution; else the innermost grouping level residuals. | | `AIC` | the Akaike Information Criterion corresponding to `object`. | | `BIC` | the Bayesian Information Criterion corresponding to `object`. | ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[AIC](../../stats/html/aic)`, `[BIC](../../stats/html/aic)`, `<lme>`. ### Examples ``` fm1 <- lme(distance ~ age, Orthodont, random = ~ age | Subject) (s1 <- summary(fm1)) coef(s1) # the (coef | Std.E | t | P-v ) matrix ``` r None `recalc.modelStruct` Recalculate for a modelStruct Object ---------------------------------------------------------- ### Description This method function recalculates the condensed linear model object using each element of `object` sequentially from last to first. ### Usage ``` ## S3 method for class 'modelStruct' recalc(object, conLin, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"modelStruct"`, representing a list of model components, such as `corStruct` and `varFunc` objects. | | `conLin` | an optional condensed linear model object, consisting of a list with components `"Xy"`, corresponding to a regression matrix (`X`) combined with a response vector (`y`), and `"logLik"`, corresponding to the log-likelihood of the underlying model. Defaults to `attr(object, "conLin")`. | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value the recalculated condensed linear model object. ### Note This method function is generally only used inside model fitting functions, such as `lme` and `gls`, that allow model components, such as correlated error terms and variance functions. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[recalc.corStruct](recalc.corstruct)`, `[recalc.reStruct](recalc.restruct)`, `[recalc.varFunc](recalc.varfunc)` r None `Matrix` Assign Matrix Values ------------------------------ ### Description This function is generic; method functions can be written to handle specific classes of objects. Classes which already have methods for this function include `pdMat`, `pdBlocked`, and `reStruct`. ### Usage ``` matrix(object) <- value ``` ### Arguments | | | | --- | --- | | `object` | any object to which `as.matrix` can be applied. | | `value` | a matrix, or list of matrices, with the same dimensions as `as.matrix(object)` with the new values to be assigned to the matrix associated with `object`. | ### Value will depend on the method function; see the appropriate documentation. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[as.matrix](../../base/html/matrix)`, also for examples, `[matrix<-.pdMat](matrix.pdmat)`, `[matrix<-.reStruct](matrix.restruct)`. r None `Names.pdBlocked` Names of a pdBlocked Object ---------------------------------------------- ### Description This method function extracts the first element of the `Dimnames` attribute, which contains the column names, for each block diagonal element in the matrix represented by `object`. ### Usage ``` ## S3 method for class 'pdBlocked' Names(object, asList, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"[pdBlocked](pdblocked)"` representing a positive-definite matrix with block diagonal structure | | `asList` | a logical value. If `TRUE` a `list` with the names for each block diagonal element is returned. If `FALSE` a character vector with all column names is returned. Defaults to `FALSE`. | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value if `asList` is `FALSE`, a character vector with column names of the matrix represented by `object`; otherwise, if `asList` is `TRUE`, a list with components given by the column names of the individual block diagonal elements in the matrix represented by `object`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[Names](names)`, `[Names.pdMat](names.pdmat)` ### Examples ``` pd1 <- pdBlocked(list(~Sex - 1, ~age - 1), data = Orthodont) Names(pd1) ``` r None `RatPupWeight` The weight of rat pups -------------------------------------- ### Description The `RatPupWeight` data frame has 322 rows and 5 columns. ### Format This data frame contains the following columns: weight a numeric vector sex a factor with levels `Male` `Female` Litter an ordered factor with levels `9` < `8` < `7` < `4` < `2` < `10` < `1` < `3` < `5` < `6` < `21` < `22` < `24` < `27` < `26` < `25` < `23` < `17` < `11` < `14` < `13` < `15` < `16` < `20` < `19` < `18` < `12` Lsize a numeric vector Treatment an ordered factor with levels `Control` < `Low` < `High` ### Source Pinheiro, J. C. and Bates, D. M. (2000), *Mixed-Effects Models in S and S-PLUS*, Springer, New York. r None `anova.lme` Compare Likelihoods of Fitted Objects -------------------------------------------------- ### Description When only one fitted model object is present, a data frame with the numerator degrees of freedom, denominator degrees of freedom, F-values, and P-values for Wald tests for the terms in the model (when `Terms` and `L` are `NULL`), a combination of model terms (when `Terms` in not `NULL`), or linear combinations of the model coefficients (when `L` is not `NULL`). Otherwise, when multiple fitted objects are being compared, a data frame with the degrees of freedom, the (restricted) log-likelihood, the Akaike Information Criterion (AIC), and the Bayesian Information Criterion (BIC) of each object is returned. If `test=TRUE`, whenever two consecutive objects have different number of degrees of freedom, a likelihood ratio statistic with the associated p-value is included in the returned data frame. ### Usage ``` ## S3 method for class 'lme' anova(object, ..., test, type, adjustSigma, Terms, L, verbose) ## S3 method for class 'anova.lme' print(x, verbose, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"<lme>"`, representing a fitted linear mixed-effects model. | | `...` | other optional fitted model objects inheriting from classes `"gls"`, `"gnls"`, `"lm"`, `"lme"`, `"lmList"`, `"nlme"`, `"nlsList"`, or `"nls"`. | | `test` | an optional logical value controlling whether likelihood ratio tests should be used to compare the fitted models represented by `object` and the objects in `...`. Defaults to `TRUE`. | | `type` | an optional character string specifying the type of sum of squares to be used in F-tests for the terms in the model. If `"sequential"`, the sequential sum of squares obtained by including the terms in the order they appear in the model is used; else, if `"marginal"`, the marginal sum of squares obtained by deleting a term from the model at a time is used. This argument is only used when a single fitted object is passed to the function. Partial matching of arguments is used, so only the first character needs to be provided. Defaults to `"sequential"`. | | `adjustSigma` | an optional logical value. If `TRUE` and the estimation method used to obtain `object` was maximum likelihood, the residual standard error is multiplied by *sqrt(nobs/(nobs - npar))*, converting it to a REML-like estimate. This argument is only used when a single fitted object is passed to the function. Default is `TRUE`. | | `Terms` | an optional integer or character vector specifying which terms in the model should be jointly tested to be zero using a Wald F-test. If given as a character vector, its elements must correspond to term names; else, if given as an integer vector, its elements must correspond to the order in which terms are included in the model. This argument is only used when a single fitted object is passed to the function. Default is `NULL`. | | `L` | an optional numeric vector or array specifying linear combinations of the coefficients in the model that should be tested to be zero. If given as an array, its rows define the linear combinations to be tested. If names are assigned to the vector elements (array columns), they must correspond to coefficients names and will be used to map the linear combination(s) to the coefficients; else, if no names are available, the vector elements (array columns) are assumed in the same order as the coefficients appear in the model. This argument is only used when a single fitted object is passed to the function. Default is `NULL`. | | `x` | an object inheriting from class `"anova.lme"` | | `verbose` | an optional logical value. If `TRUE`, the calling sequences for each fitted model object are printed with the rest of the output, being omitted if `verbose = FALSE`. Defaults to `FALSE`. | ### Value a data frame inheriting from class `"anova.lme"`. ### Note Likelihood comparisons are not meaningful for objects fit using restricted maximum likelihood and with different fixed effects. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Pinheiro, J.C., and Bates, D.M. (2000) "Mixed-Effects Models in S and S-PLUS", Springer. ### See Also `<gls>`, `<gnls>`, `<nlme>`, `<lme>`, `[AIC](../../stats/html/aic)`, `[BIC](../../stats/html/aic)`, `[print.anova.lme](anova.lme)`, `[logLik.lme](loglik.lme)`, ### Examples ``` fm1 <- lme(distance ~ age, Orthodont, random = ~ age | Subject) anova(fm1) fm2 <- update(fm1, random = pdDiag(~age)) anova(fm1, fm2) ## Pinheiro and Bates, pp. 251-254 ------------------------------------------ fm1Orth.gls <- gls(distance ~ Sex * I(age - 11), Orthodont, correlation = corSymm(form = ~ 1 | Subject), weights = varIdent(form = ~ 1 | age)) fm2Orth.gls <- update(fm1Orth.gls, corr = corCompSymm(form = ~ 1 | Subject)) ## anova.gls examples: anova(fm1Orth.gls, fm2Orth.gls) fm3Orth.gls <- update(fm2Orth.gls, weights = NULL) anova(fm2Orth.gls, fm3Orth.gls) fm4Orth.gls <- update(fm3Orth.gls, weights = varIdent(form = ~ 1 | Sex)) anova(fm3Orth.gls, fm4Orth.gls) # not in book but needed for the following command fm3Orth.lme <- lme(distance ~ Sex*I(age-11), data = Orthodont, random = ~ I(age-11) | Subject, weights = varIdent(form = ~ 1 | Sex)) # Compare an "lme" object with a "gls" object (test would be non-sensical!) anova(fm3Orth.lme, fm4Orth.gls, test = FALSE) ## Pinheiro and Bates, pp. 222-225 ------------------------------------------ op <- options(contrasts = c("contr.treatment", "contr.poly")) fm1BW.lme <- lme(weight ~ Time * Diet, BodyWeight, random = ~ Time) fm2BW.lme <- update(fm1BW.lme, weights = varPower()) # Test a specific contrast anova(fm2BW.lme, L = c("Time:Diet2" = 1, "Time:Diet3" = -1)) ## Pinheiro and Bates, pp. 352-365 ------------------------------------------ fm1Theo.lis <- nlsList( conc ~ SSfol(Dose, Time, lKe, lKa, lCl), data=Theoph) fm1Theo.lis fm1Theo.nlme <- nlme(fm1Theo.lis) fm2Theo.nlme <- update(fm1Theo.nlme, random= pdDiag(lKe+lKa+lCl~1) ) fm3Theo.nlme <- update(fm2Theo.nlme, random= pdDiag( lKa+lCl~1) ) # Comparing the 3 nlme models anova(fm1Theo.nlme, fm3Theo.nlme, fm2Theo.nlme) options(op) # (set back to previous state) ``` r None `predict.lme` Predictions from an lme Object --------------------------------------------- ### Description The predictions at level *i* are obtained by adding together the population predictions (based only on the fixed effects estimates) and the estimated contributions of the random effects to the predictions at grouping levels less or equal to *i*. The resulting values estimate the best linear unbiased predictions (BLUPs) at level *i*. If group values not included in the original grouping factors are present in `newdata`, the corresponding predictions will be set to `NA` for levels greater or equal to the level at which the unknown groups occur. ### Usage ``` ## S3 method for class 'lme' predict(object, newdata, level = Q, asList = FALSE, na.action = na.fail, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"<lme>"`, representing a fitted linear mixed-effects model. | | `newdata` | an optional data frame to be used for obtaining the predictions. All variables used in the fixed and random effects models, as well as the grouping factors, must be present in the data frame. If missing, the fitted values are returned. | | `level` | an optional integer vector giving the level(s) of grouping to be used in obtaining the predictions. Level values increase from outermost to innermost grouping, with level zero corresponding to the population predictions. Defaults to the highest or innermost level of grouping. | | `asList` | an optional logical value. If `TRUE` and a single value is given in `level`, the returned object is a list with the predictions split by groups; else the returned value is either a vector or a data frame, according to the length of `level`. | | `na.action` | a function that indicates what should happen when `newdata` contains `NA`s. The default action (`na.fail`) causes the function to print an error message and terminate if there are any incomplete observations. | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value if a single level of grouping is specified in `level`, the returned value is either a list with the predictions split by groups (`asList = TRUE`) or a vector with the predictions (`asList = FALSE`); else, when multiple grouping levels are specified in `level`, the returned object is a data frame with columns given by the predictions at different levels and the grouping factors. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `<lme>`, `<fitted.lme>` ### Examples ``` fm1 <- lme(distance ~ age, Orthodont, random = ~ age | Subject) newOrth <- data.frame(Sex = c("Male","Male","Female","Female","Male","Male"), age = c(15, 20, 10, 12, 2, 4), Subject = c("M01","M01","F30","F30","M04","M04")) ## The 'Orthodont' data has *no* 'F30', so predict NA at level 1 : predict(fm1, newOrth, level = 0:1) ```
programming_docs
r None `random.effects` Extract Random Effects ---------------------------------------- ### Description This function is generic; method functions can be written to handle specific classes of objects. Classes which already have methods for this function include `lmList` and `lme`. ### Usage ``` random.effects(object, ...) ranef(object, ...) ``` ### Arguments | | | | --- | --- | | `object` | any fitted model object from which random effects estimates can be extracted. | | `...` | some methods for this generic function require additional arguments. | ### Value will depend on the method function used; see the appropriate documentation. ### References Pinheiro, J.C., and Bates, D.M. (2000) "Mixed-Effects Models in S and S-PLUS", Springer, esp. pp. 100, 461. ### See Also `[ranef.lmList](ranef.lmlist)`,`<ranef.lme>` ### Examples ``` ## see the method function documentation ``` r None `Variogram.corSpher` Calculate Semi-variogram for a corSpher Object -------------------------------------------------------------------- ### Description This method function calculates the semi-variogram values corresponding to the Spherical correlation model, using the estimated coefficients corresponding to `object`, at the distances defined by `distance`. ### Usage ``` ## S3 method for class 'corSpher' Variogram(object, distance, sig2, length.out, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"[corSpher](corspher)"`, representing an Spherical spatial correlation structure. | | `distance` | an optional numeric vector with the distances at which the semi-variogram is to be calculated. Defaults to `NULL`, in which case a sequence of length `length.out` between the minimum and maximum values of `getCovariate(object)` is used. | | `sig2` | an optional numeric value representing the process variance. Defaults to `1`. | | `length.out` | an optional integer specifying the length of the sequence of distances to be used for calculating the semi-variogram, when `distance = NULL`. Defaults to `50`. | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value a data frame with columns `variog` and `dist` representing, respectively, the semi-variogram values and the corresponding distances. The returned value inherits from class `Variogram`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Cressie, N.A.C. (1993), "Statistics for Spatial Data", J. Wiley & Sons. ### See Also `[corSpher](corspher)`, `[plot.Variogram](plot.variogram)`, `[Variogram](variogram)` ### Examples ``` cs1 <- corSpher(15, form = ~ Time | Rat) cs1 <- Initialize(cs1, BodyWeight) Variogram(cs1)[1:10,] ``` r None `nlme.nlsList` NLME fit from nlsList Object -------------------------------------------- ### Description If the random effects names defined in `random` are a subset of the `lmList` object coefficient names, initial estimates for the covariance matrix of the random effects are obtained (overwriting any values given in `random`). `formula(fixed)` and the `data` argument in the calling sequence used to obtain `fixed` are passed as the `fixed` and `data` arguments to `nlme.formula`, together with any other additional arguments in the function call. See the documentation on `nlme.formula` for a description of that function. ### Usage ``` ## S3 method for class 'nlsList' nlme(model, data, fixed, random, groups, start, correlation, weights, subset, method, na.action, naPattern, control, verbose) ``` ### Arguments | | | | --- | --- | | `model` | an object inheriting from class `"[nlsList](nlslist)"`, representing a list of `nls` fits with a common model. | | `data` | this argument is included for consistency with the generic function. It is ignored in this method function. | | `fixed` | this argument is included for consistency with the generic function. It is ignored in this method function. | | `random` | an optional one-sided linear formula with no conditioning expression, or a `pdMat` object with a `formula` attribute. Multiple levels of grouping are not allowed with this method function. Defaults to a formula consisting of the right hand side of `formula(fixed)`. | | `groups` | an optional one-sided formula of the form `~g1` (single level of nesting) or `~g1/.../gQ` (multiple levels of nesting), specifying the partitions of the data over which the random effects vary. `g1,...,gQ` must evaluate to factors in `data`. The order of nesting, when multiple levels are present, is taken from left to right (i.e. `g1` is the first level, `g2` the second, etc.). | | `start` | an optional numeric vector, or list of initial estimates for the fixed effects and random effects. If declared as a numeric vector, it is converted internally to a list with a single component `fixed`, given by the vector. The `fixed` component is required, unless the model function inherits from class `selfStart`, in which case initial values will be derived from a call to `nlsList`. An optional `random` component is used to specify initial values for the random effects and should consist of a matrix, or a list of matrices with length equal to the number of grouping levels. Each matrix should have as many rows as the number of groups at the corresponding level and as many columns as the number of random effects in that level. | | `correlation` | an optional `corStruct` object describing the within-group correlation structure. See the documentation of `corClasses` for a description of the available `corStruct` classes. Defaults to `NULL`, corresponding to no within-group correlations. | | `weights` | an optional `varFunc` object or one-sided formula describing the within-group heteroscedasticity structure. If given as a formula, it is used as the argument to `varFixed`, corresponding to fixed variance weights. See the documentation on `varClasses` for a description of the available `varFunc` classes. Defaults to `NULL`, corresponding to homoscedastic within-group errors. | | `subset` | an optional expression indicating the subset of the rows of `data` that should be used in the fit. This can be a logical vector, or a numeric vector indicating which observation numbers are to be included, or a character vector of the row names to be included. All observations are included by default. | | `method` | a character string. If `"REML"` the model is fit by maximizing the restricted log-likelihood. If `"ML"` the log-likelihood is maximized. Defaults to `"ML"`. | | `na.action` | a function that indicates what should happen when the data contain `NA`s. The default action (`na.fail`) causes `nlme` to print an error message and terminate if there are any incomplete observations. | | `naPattern` | an expression or formula object, specifying which returned values are to be regarded as missing. | | `control` | a list of control values for the estimation algorithm to replace the default values returned by the function `nlmeControl`. Defaults to an empty list. | | `verbose` | an optional logical value. If `TRUE` information on the evolution of the iterative algorithm is printed. Default is `FALSE`. | ### Value an object of class `nlme` representing the linear mixed-effects model fit. Generic functions such as `print`, `plot` and `summary` have methods to show the results of the fit. See `nlmeObject` for the components of the fit. The functions `resid`, `coef`, `fitted`, `fixed.effects`, and `random.effects` can be used to extract some of its components. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References The computational methods follow on the general framework of Lindstrom, M.J. and Bates, D.M. (1988). The model formulation is described in Laird, N.M. and Ware, J.H. (1982). The variance-covariance parametrizations are described in <Pinheiro, J.C. and Bates., D.M. (1996). The different correlation structures available for the `correlation` argument are described in Box, G.E.P., Jenkins, G.M., and Reinsel G.C. (1994), Littel, R.C., Milliken, G.A., Stroup, W.W., and Wolfinger, R.D. (1996), and Venables, W.N. and Ripley, B.D. (2002). The use of variance functions for linear and nonlinear mixed effects models is presented in detail in Davidian, M. and Giltinan, D.M. (1995). Box, G.E.P., Jenkins, G.M., and Reinsel G.C. (1994) "Time Series Analysis: Forecasting and Control", 3rd Edition, Holden-Day. Davidian, M. and Giltinan, D.M. (1995) "Nonlinear Mixed Effects Models for Repeated Measurement Data", Chapman and Hall. Laird, N.M. and Ware, J.H. (1982) "Random-Effects Models for Longitudinal Data", Biometrics, 38, 963-974. Lindstrom, M.J. and Bates, D.M. (1988) "Newton-Raphson and EM Algorithms for Linear Mixed-Effects Models for Repeated-Measures Data", Journal of the American Statistical Association, 83, 1014-1022. Littel, R.C., Milliken, G.A., Stroup, W.W., and Wolfinger, R.D. (1996) "SAS Systems for Mixed Models", SAS Institute. Pinheiro, J.C. and Bates., D.M. (1996) "Unconstrained Parametrizations for Variance-Covariance Matrices", Statistics and Computing, 6, 289-296. Venables, W.N. and Ripley, B.D. (2002) "Modern Applied Statistics with S", 4th Edition, Springer-Verlag. ### See Also `<nlme>`, `[lmList](lmlist)`, `[nlmeObject](nlmeobject)` ### Examples ``` fm1 <- nlsList(SSasymp, data = Loblolly) fm2 <- nlme(fm1, random = Asym ~ 1) summary(fm1) summary(fm2) ``` r None `varWeights.glsStruct` Variance Weights for glsStruct Object ------------------------------------------------------------- ### Description If `object` includes a `varStruct` component, the inverse of the standard deviations of the variance function structure represented by the corresponding `varFunc` object are returned; else, a vector of ones of length equal to the number of observations in the data frame used to fit the associated linear model is returned. ### Usage ``` ## S3 method for class 'glsStruct' varWeights(object) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"[glsStruct](glsstruct)"`, representing a list of linear model components, such as `corStruct` and `"[varFunc](varfunc)"` objects. | ### Value if `object` includes a `varStruct` component, a vector with the corresponding variance weights; else, or a vector of ones. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Pinheiro, J.C., and Bates, D.M. (2000) "Mixed-Effects Models in S and S-PLUS", Springer. ### See Also `[varWeights](varweights)` r None `nlsList` List of nls Objects with a Common Model -------------------------------------------------- ### Description `Data` is partitioned according to the levels of the grouping factor defined in `model` and individual `nls` fits are obtained for each `data` partition, using the model defined in `model`. ### Usage ``` nlsList(model, data, start, control, level, subset, na.action = na.fail, pool = TRUE, warn.nls = NA) ## S3 method for class 'nlsList' update(object, model., ..., evaluate = TRUE) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `nlsList`, representing a list of fitted `nls` objects. | | `model` | either a nonlinear model formula, with the response on the left of a `~` operator and an expression involving parameters, covariates, and a grouping factor separated by the `|` operator on the right, or a `selfStart` function. The method function `[nlsList.selfStart](nlslist.selfstart)` is documented separately. | | `model.` | changes to the model – see `[update.formula](../../stats/html/update.formula)` for details. | | `data` | a data frame in which to interpret the variables named in `model`. | | `start` | an optional named list with initial values for the parameters to be estimated in `model`. It is passed as the `start` argument to each `nls` call and is required when the nonlinear function in `model` does not inherit from class `selfStart`. | | `control` | a list of control values passed as the `control` argument to `nls`. Defaults to an empty list. | | `level` | an optional integer specifying the level of grouping to be used when multiple nested levels of grouping are present. | | `subset` | an optional expression indicating the subset of the rows of `data` that should be used in the fit. This can be a logical vector, or a numeric vector indicating which observation numbers are to be included, or a character vector of the row names to be included. All observations are included by default. | | `na.action` | a function that indicates what should happen when the data contain `NA`s. The default action (`na.fail`) causes `nlsList` to print an error message and terminate if there are any incomplete observations. | | `pool` | an optional logical value that is preserved as an attribute of the returned value. This will be used as the default for `pool` in calculations of standard deviations or standard errors for summaries. | | `warn.nls` | `[logical](../../base/html/logical)` indicating if `[nls](../../stats/html/nls)()` errors (all of which are caught by `[tryCatch](../../base/html/conditions)`) should be signalled as a “summarizing” `[warning](../../base/html/warning)`. | | `...` | some methods for this generic require additional arguments. None are used in this method. | | `evaluate` | If `TRUE` evaluate the new call else return the call. | ### Details As `[nls](../../stats/html/nls)(.)` is called on each sub group, and convergence of these may be problematic, these calls happen with error catching. Since nlme version `3.1-127` (2016-04), all the errors are caught (via `[tryCatch](../../base/html/conditions)`) and if present, a “summarizing” `[warning](../../base/html/warning)` is stored as attribute of the resulting `"nlsList"` object and signalled unless suppressed by `warn.nls = FALSE` or currently also when `warn.nls = NA` (default) *and* `[getOption](../../base/html/options)("show.error.messages")` is false. `nlsList()` originally had used `[try](../../base/html/try)(*)` (with its default `silent=FALSE)` and hence all errors were printed to the console *unless* the global option `show.error.messages` was set to true. This still works, but has been *deprecated*. ### Value a list of `nls` objects with as many components as the number of groups defined by the grouping factor. Generic functions such as `coef`, `fixed.effects`, `lme`, `pairs`, `plot`, `predict`, `random.effects`, `summary`, and `update` have methods that can be applied to an `nlsList` object. ### References Pinheiro, J.C., and Bates, D.M. (2000), *Mixed-Effects Models in S and S-PLUS*, Springer. ### See Also `[nls](../../stats/html/nls)`, `[nlme.nlsList](nlme.nlslist)`, `[nlsList.selfStart](nlslist.selfstart)`, `[summary.nlsList](summary.nlslist)` ### Examples ``` fm1 <- nlsList(uptake ~ SSasympOff(conc, Asym, lrc, c0), data = CO2, start = c(Asym = 30, lrc = -4.5, c0 = 52)) summary(fm1) cfm1 <- confint(fm1) # via profiling each % FIXME: only *one* message instead of one *each* mat.class <- class(matrix(1)) # ("matrix", "array") for R >= 4.0.0; ("matrix" in older R) i.ok <- which(vapply(cfm1, function(r) identical(class(r), mat.class), NA)) stopifnot(length(i.ok) > 0, !anyNA(match(c(2:4, 6:9, 12), i.ok))) ## where as (some of) the others gave errors during profile re-fitting : str(cfm1[- i.ok]) ``` r None `varFunc` Variance Function Structure -------------------------------------- ### Description If `object` is a one-sided formula, it is used as the argument to `varFixed` and the resulting object is returned. Else, if `object` inherits from class `varFunc`, it is returned unchanged. ### Usage ``` varFunc(object) ``` ### Arguments | | | | --- | --- | | `object` | either an one-sided formula specifying a variance covariate, or an object inheriting from class `varFunc`, representing a variance function structure. | ### Value an object from class `varFunc`, representing a variance function structure. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[summary.varFunc](summary.varfunc)`, `[varFixed](varfixed)`, `[varWeights.varFunc](varweights)`, `[coef.varFunc](coef.varfunc)` ### Examples ``` vf1 <- varFunc(~age) ``` r None `Dim.corStruct` Dimensions of a corStruct Object ------------------------------------------------- ### Description if `groups` is missing, it returns the `Dim` attribute of `object`; otherwise, calculates the dimensions associated with the grouping factor. ### Usage ``` ## S3 method for class 'corStruct' Dim(object, groups, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"[corStruct](corclasses)"`, representing a correlation structure. | | `groups` | an optional factor defining the grouping of the observations; observations within a group are correlated and observations in different groups are uncorrelated. | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value a list with components: | | | | --- | --- | | `N` | length of `groups` | | `M` | number of groups | | `maxLen` | maximum number of observations in a group | | `sumLenSq` | sum of the squares of the number of observations per group | | `len` | an integer vector with the number of observations per group | | `start` | an integer vector with the starting position for the observations in each group, beginning from zero | ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[Dim](dim)`, `[Dim.corSpatial](dim.corspatial)` ### Examples ``` Dim(corAR1(), getGroups(Orthodont)) ``` r None `Covariate` Assign Covariate Values ------------------------------------ ### Description This function is generic; method functions can be written to handle specific classes of objects. Classes which already have methods for this function include all `"[varFunc](varfunc)"` classes. ### Usage ``` covariate(object) <- value ``` ### Arguments | | | | --- | --- | | `object` | any object with a `covariate` component. | | `value` | a value to be assigned to the covariate associated with `object`. | ### Value will depend on the method function; see the appropriate documentation. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[getCovariate](getcovariate)` ### Examples ``` ## see the method function documentation ``` r None `logLik.lme` Log-Likelihood of an lme Object --------------------------------------------- ### Description If `REML=FALSE`, returns the log-likelihood value of the linear mixed-effects model represented by `object` evaluated at the estimated coefficients; else, the restricted log-likelihood evaluated at the estimated coefficients is returned. ### Usage ``` ## S3 method for class 'lme' logLik(object, REML, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"<lme>"`, representing a fitted linear mixed-effects model. | | `REML` | an optional logical value. If `TRUE` the restricted log-likelihood is returned, else, if `FALSE`, the log-likelihood is returned. Defaults to the method of estimation used, that is `TRUE` if and only `object` was fitted with `method = "REML"` (the default for these fitting functions) . | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value the (restricted) log-likelihood of the model represented by `object` evaluated at the estimated coefficients. ### Author(s) José Pinheiro and Douglas Bates ### References Harville, D.A. (1974) “Bayesian Inference for Variance Components Using Only Error Contrasts”, *Biometrika*, **61**, 383–385. Pinheiro, J.C., and Bates, D.M. (2000) "Mixed-Effects Models in S and S-PLUS", Springer. ### See Also `<lme>`,`<gls>`, `[logLik.corStruct](loglik.corstruct)`, `[logLik.glsStruct](loglik.glsstruct)`, `[logLik.lmeStruct](loglik.lmestruct)`, `[logLik.lmList](loglik.lmlist)`, `[logLik.reStruct](loglik.restruct)`, `[logLik.varFunc](loglik.varfunc)`, ### Examples ``` fm1 <- lme(distance ~ Sex * age, Orthodont, random = ~ age, method = "ML") logLik(fm1) logLik(fm1, REML = TRUE) ```
programming_docs
r None `Oxide` Variability in Semiconductor Manufacturing --------------------------------------------------- ### Description The `Oxide` data frame has 72 rows and 5 columns. ### Format This data frame contains the following columns: Source a factor with levels `1` and `2` Lot a factor giving a unique identifier for each lot. Wafer a factor giving a unique identifier for each wafer within a lot. Site a factor with levels `1`, `2`, and `3` Thickness a numeric vector giving the thickness of the oxide layer. ### Details These data are described in Littell et al. (1996, p. 155) as coming “from a passive data collection study in the semiconductor industry where the objective is to estimate the variance components to determine the assignable causes of the observed variability.” The observed response is the thickness of the oxide layer on silicon wafers, measured at three different sites of each of three wafers selected from each of eight lots sampled from the population of lots. ### Source Pinheiro, J. C. and Bates, D. M. (2000), *Mixed-Effects Models in S and S-PLUS*, Springer, New York. (Appendix A.20) Littell, R. C., Milliken, G. A., Stroup, W. W. and Wolfinger, R. D. (1996), *SAS System for Mixed Models*, SAS Institute, Cary, NC. r None `lmList` List of lm Objects with a Common Model ------------------------------------------------ ### Description `Data` is partitioned according to the levels of the grouping factor `g` and individual `lm` fits are obtained for each `data` partition, using the model defined in `object`. ### Usage ``` lmList(object, data, level, subset, na.action = na.fail, pool = TRUE, warn.lm = TRUE) ## S3 method for class 'lmList' update(object, formula., ..., evaluate = TRUE) ## S3 method for class 'lmList' print(x, pool, ...) ``` ### Arguments | | | | --- | --- | | `object` | For `lmList`, either a linear formula object of the form `y ~ x1+...+xn | g` or a `groupedData` object. In the formula object, `y` represents the response, `x1,...,xn` the covariates, and `g` the grouping factor specifying the partitioning of the data according to which different `lm` fits should be performed. The grouping factor `g` may be omitted from the formula, in which case the grouping structure will be obtained from `data`, which must inherit from class `groupedData`. The method function `[lmList.groupedData](lmlist.groupeddata)` is documented separately. For the method `update.lmList`, `object` is an object inheriting from class `lmList`. | | `formula` | (used in `update.lmList` only) a two-sided linear formula with the common model for the individuals `lm` fits. | | `formula.` | Changes to the formula – see `update.formula` for details. | | `data` | a data frame in which to interpret the variables named in `object`. | | `level` | an optional integer specifying the level of grouping to be used when multiple nested levels of grouping are present. | | `subset` | an optional expression indicating which subset of the rows of `data` should be used in the fit. This can be a logical vector, or a numeric vector indicating which observation numbers are to be included, or a character vector of the row names to be included. All observations are included by default. | | `na.action` | a function that indicates what should happen when the data contain `NA`s. The default action (`na.fail`) causes `lmList` to print an error message and terminate if there are any incomplete observations. | | `pool` | an optional logical value indicating whether a pooled estimate of the residual standard error should be used in calculations of standard deviations or standard errors for summaries. | | `warn.lm` | `[logical](../../base/html/logical)` indicating if `[lm](../../stats/html/lm)()` errors (all of which are caught by `[tryCatch](../../base/html/conditions)`) should be signalled as a “summarizing” `[warning](../../base/html/warning)`. | | `x` | an object inheriting from class `lmList` to be printed. | | `...` | some methods for this generic require additional arguments. None are used in this method. | | `evaluate` | If `TRUE` evaluate the new call else return the call. | ### Value a list of `lm` objects with as many components as the number of groups defined by the grouping factor. Generic functions such as `coef`, `fixed.effects`, `lme`, `pairs`, `plot`, `predict`, `random.effects`, `summary`, and `update` have methods that can be applied to an `lmList` object. ### References Pinheiro, J.C., and Bates, D.M. (2000) "Mixed-Effects Models in S and S-PLUS", Springer. ### See Also `[lm](../../stats/html/lm)`, `[lme.lmList](lme.lmlist)`, `[plot.lmList](plot.lmlist)`, `[pooledSD](pooledsd)`, `[predict.lmList](predict.lmlist)`, `[residuals.lmList](residuals.lmlist)`, `[summary.lmList](summary.lmlist)` ### Examples ``` fm1 <- lmList(distance ~ age | Subject, Orthodont) summary(fm1) ``` r None `Initialize.glsStruct` Initialize a glsStruct Object ----------------------------------------------------- ### Description The individual linear model components of the `glsStruct` list are initialized. ### Usage ``` ## S3 method for class 'glsStruct' Initialize(object, data, control, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"[glsStruct](glsstruct)"`, representing a list of linear model components, such as `corStruct` and `varFunc` objects. | | `data` | a data frame in which to evaluate the variables defined in `formula(object)`. | | `control` | an optional list with control parameters for the initialization and optimization algorithms used in `gls`. Defaults to `list(singular.ok = FALSE)`, implying that linear dependencies are not allowed in the model. | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value a `glsStruct` object similar to `object`, but with initialized model components. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `<gls>`, `[Initialize.corStruct](initialize.corstruct)`, `[Initialize.varFunc](initialize.varfunc)`, `[Initialize](initialize)` r None `fitted.lme` Extract lme Fitted Values --------------------------------------- ### Description The fitted values at level *i* are obtained by adding together the population fitted values (based only on the fixed effects estimates) and the estimated contributions of the random effects to the fitted values at grouping levels less or equal to *i*. The resulting values estimate the best linear unbiased predictions (BLUPs) at level *i*. ### Usage ``` ## S3 method for class 'lme' fitted(object, level, asList, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"<lme>"`, representing a fitted linear mixed-effects model. | | `level` | an optional integer vector giving the level(s) of grouping to be used in extracting the fitted values from `object`. Level values increase from outermost to innermost grouping, with level zero corresponding to the population fitted values. Defaults to the highest or innermost level of grouping. | | `asList` | an optional logical value. If `TRUE` and a single value is given in `level`, the returned object is a list with the fitted values split by groups; else the returned value is either a vector or a data frame, according to the length of `level`. Defaults to `FALSE`. | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value If a single level of grouping is specified in `level`, the returned value is either a list with the fitted values split by groups (`asList = TRUE`) or a vector with the fitted values (`asList = FALSE`); else, when multiple grouping levels are specified in `level`, the returned object is a data frame with columns given by the fitted values at different levels and the grouping factors. For a vector or data frame result the `[napredict](../../stats/html/nafns)` method is applied. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Bates, D.M. and Pinheiro, J.C. (1998) "Computational methods for multilevel models" available in PostScript or PDF formats at http://nlme.stat.wisc.edu/pub/NLME/ Pinheiro, J.C., and Bates, D.M. (2000) "Mixed-Effects Models in S and S-PLUS", Springer, esp. pp. 235, 397. ### See Also `<lme>`, `<residuals.lme>` ### Examples ``` fm1 <- lme(distance ~ age + Sex, data = Orthodont, random = ~ 1) fitted(fm1, level = 0:1) ``` r None `MathAchSchool` School demographic data for MathAchieve -------------------------------------------------------- ### Description The `MathAchSchool` data frame has 160 rows and 7 columns. ### Format This data frame contains the following columns: School a factor giving the school on which the measurement is made. Size a numeric vector giving the number of students in the school Sector a factor with levels `Public` `Catholic` PRACAD a numeric vector giving the percentage of students on the academic track DISCLIM a numeric vector measuring the discrimination climate HIMINTY a factor with levels `0` `1` MEANSES a numeric vector giving the mean SES score. ### Details These variables give the school-level demographic data to accompany the `MathAchieve` data. r None `PBG` Effect of Phenylbiguanide on Blood Pressure -------------------------------------------------- ### Description The `PBG` data frame has 60 rows and 5 columns. ### Format This data frame contains the following columns: deltaBP a numeric vector dose a numeric vector Run an ordered factor with levels `T5` < `T4` < `T3` < `T2` < `T1` < `P5` < `P3` < `P2` < `P4` < `P1` Treatment a factor with levels `MDL 72222` `Placebo` Rabbit an ordered factor with levels `5` < `3` < `2` < `4` < `1` ### Details Data on an experiment to examine the effect of a antagonist MDL 72222 on the change in blood pressure experienced with increasing dosage of phenylbiguanide are described in Ludbrook (1994) and analyzed in Venables and Ripley (2002, section 10.3). Each of five rabbits was exposed to increasing doses of phenylbiguanide after having either a placebo or the HD5-antagonist MDL 72222 administered. ### Source Pinheiro, J. C. and Bates, D. M. (2000), *Mixed-Effects Models in S and S-PLUS*, Springer, New York. (Appendix A.21) Venables, W. N. and Ripley, B. D. (2002) *Modern Applied Statistics with S (4th ed)*, Springer, New York. Ludbrook, J. (1994), Repeated measurements and multiple comparisons in cardiovascular research, *Cardiovascular Research*, **28**, 303-311. r None `Variogram.corSpatial` Calculate Semi-variogram for a corSpatial Object ------------------------------------------------------------------------ ### Description This method function calculates the semi-variogram values corresponding to the model defined in `FUN`, using the estimated coefficients corresponding to `object`, at the distances defined by `distance`. ### Usage ``` ## S3 method for class 'corSpatial' Variogram(object, distance, sig2, length.out, FUN, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"[corSpatial](corspatial)"`, representing spatial correlation structure. | | `distance` | an optional numeric vector with the distances at which the semi-variogram is to be calculated. Defaults to `NULL`, in which case a sequence of length `length.out` between the minimum and maximum values of `getCovariate(object)` is used. | | `sig2` | an optional numeric value representing the process variance. Defaults to `1`. | | `length.out` | an optional integer specifying the length of the sequence of distances to be used for calculating the semi-variogram, when `distance = NULL`. Defaults to `50`. | | `FUN` | a function of two arguments, the distance and the range corresponding to `object`, specifying the semi-variogram model. | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value a data frame with columns `variog` and `dist` representing, respectively, the semi-variogram values and the corresponding distances. The returned value inherits from class `Variogram`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Cressie, N.A.C. (1993), "Statistics for Spatial Data", J. Wiley & Sons. ### See Also `[corSpatial](corspatial)`, `[Variogram](variogram)`, `[Variogram.default](variogram.default)`, `[Variogram.corExp](variogram.corexp)`, `[Variogram.corGaus](variogram.corgaus)`, `[Variogram.corLin](variogram.corlin)`, `[Variogram.corRatio](variogram.corratio)`, `[Variogram.corSpher](variogram.corspher)`, `[plot.Variogram](plot.variogram)` ### Examples ``` cs1 <- corExp(3, form = ~ Time | Rat) cs1 <- Initialize(cs1, BodyWeight) Variogram(cs1, FUN = function(x, y) (1 - exp(-x/y)))[1:10,] ``` r None `Coef` Assign Values to Coefficients ------------------------------------- ### Description This function is generic; method functions can be written to handle specific classes of objects. Classes which already have methods for this function include all `"[pdMat](pdmat)"`, `"[corStruct](corclasses)"` and `"[varFunc](varfunc)"` classes, `"[reStruct](restruct)"`, and `"modelStruct"`. ### Usage ``` coef(object, ...) <- value ``` ### Arguments | | | | --- | --- | | `object` | any object representing a fitted model, or, by default, any object with a `coef` component. | | `...` | some methods for this generic function may require additional arguments. | | `value` | a value to be assigned to the coefficients associated with `object`. | ### Value will depend on the method function; see the appropriate documentation. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[coef](../../stats/html/coef)` ### Examples ``` ## see the method function documentation ``` r None `fixef.lmList` Extract lmList Fixed Effects -------------------------------------------- ### Description The average of the coefficients corresponding to the `lm` components of `object` is calculated. ### Usage ``` ## S3 method for class 'lmList' fixef(object, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"[lmList](lmlist)"`, representing a list of `lm` objects with a common model. | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value a vector with the average of the individual `lm` coefficients in `object`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[lmList](lmlist)`, `[random.effects.lmList](ranef.lmlist)` ### Examples ``` fm1 <- lmList(distance ~ age | Subject, Orthodont) fixed.effects(fm1) ``` r None `Remifentanil` Pharmacokinetics of Remifentanil ------------------------------------------------ ### Description Intravenous infusion of remifentanil (a strong analgesic) in different rates over varying time periods was applied to a total of 65 patients. Concentration measurements of remifentanil were taken along with several covariates resulting in the `Remifentanil` data frame with 2107 rows and 12 columns. ### Usage ``` data("Remifentanil", package = "nlme") ``` ### Format This data frame (of class `"[groupedData](groupeddata)"`, specifically `"nfnGroupedData"`) contains the following columns: `ID`: numerical (patient) IDs. `Subject`: an `[ordered](../../base/html/factor)` factor with 65 levels (of the `ID`s): `30` < `21` < `25` < `23` < `29` < ... ... < `36` < `6` < `5` < `10` < `9`. `Time`: time from beginning of infusion in minutes (`[numeric](../../base/html/numeric)`). `conc`: remifentanil concentration in [ng / ml] (numeric). `Rate`: infusion rate in [µg / min]. `Amt`: amount of remifentanil given in the current time interval in [µg]. `Age`: age of the patient in years. `Sex`: gender of the patient, a `[factor](../../base/html/factor)` with levels `Female` and `Male`. `Ht`: height of the patient in cm. `Wt`: weight of the patient in kg. `BSA`: body surface area (DuBois and DuBois 1916): *BSA := Wt^0.425 \* Ht^0.725 \* 0.007184*. `LBM`: lean body mass (James 1976), with slightly different formula for men *LBM\_m := 1.1 Wt - 128 (Wt/Ht)^2*, and women *LBM\_f := 1.07 Wt - 148 (Wt/Ht)^2*. ### Author(s) of this help page: Niels Hagenbuch and Martin Maechler, SfS ETH Zurich. ### Source Pinheiro, J. C. and Bates, D. M. (2000). *Mixed-Effects Models in S and S-PLUS*, Springer, New York. ### References Minto CF, Schnider TW, Egan TD, Youngs E, Lemmens HJM, Gambus PL, Billard V, Hoke JF, Moore KHP, Hermann DJ, Muir KT, Mandema JW, Shafer SL (1997). Influence of age and gender on the pharmacokinetics and pharmacodynamics of remifentanil: I. Model development. *Anesthesiology* **86** 1, 10–23. <https://pubs.asahq.org/anesthesiology/article/86/1/10/35947/Influence-of-Age-and-Gender-on-the> Charles F. Minto, Thomas W. Schnider and Steven L. Shafer (1997). Pharmacokinetics and Pharmacodynamics of Remifentanil: II. Model Application. *Anesthesiology* **86** 1, 24–33. <https://pubs.asahq.org/anesthesiology/article/86/1/24/35925/Pharmacokinetics-and-Pharmacodynamics-of> ### Examples ``` plot(Remifentanil, type = "l", lwd = 2) # shows the 65 patients' remi profiles ## The same on log-log scale (*more* sensible for modeling ?): plot(Remifentanil, type = "l", lwd = 2, scales = list(log=TRUE)) str(Remifentanil) summary(Remifentanil) plot(xtabs(~Subject, Remifentanil)) summary(unclass(table(Remifentanil$Subject))) ## between 20 and 54 measurements per patient (median: 24; mean: 32.42) ## Only first measurement of each patient : dim(Remi.1 <- Remifentanil[!duplicated(Remifentanil[,"ID"]),]) # 65 x 12 LBMfn <- function(Wt, Ht, Sex) ifelse(Sex == "Female", 1.07 * Wt - 148*(Wt/Ht)^2, 1.1 * Wt - 128*(Wt/Ht)^2) with(Remi.1, stopifnot(all.equal(BSA, Wt^{0.425} * Ht^{0.725} * 0.007184, tol = 1.5e-5), all.equal(LBM, LBMfn(Wt, Ht, Sex), tol = 7e-7) )) ## Rate: typically 3 µg / kg body weight, but : sunflowerplot(Rate ~ Wt, Remifentanil) abline(0,3, lty=2, col=adjustcolor("black", 0.5)) ``` r None `Tetracycline2` Pharmacokinetics of tetracycline ------------------------------------------------- ### Description The `Tetracycline2` data frame has 40 rows and 4 columns. ### Format This data frame contains the following columns: conc a numeric vector Time a numeric vector Subject an ordered factor with levels `4` < `5` < `2` < `1` < `3` Formulation a factor with levels `Berkmycin` `tetramycin` ### Source Pinheiro, J. C. and Bates, D. M. (2000), *Mixed-Effects Models in S and S-PLUS*, Springer, New York. r None `logLik.reStruct` Calculate reStruct Log-Likelihood ---------------------------------------------------- ### Description Calculates the log-likelihood, or restricted log-likelihood, of the Gaussian linear mixed-effects model represented by `object` and `conLin` (assuming spherical within-group covariance structure), evaluated at `coef(object)`. The `settings` attribute of `object` determines whether the log-likelihood, or the restricted log-likelihood, is to be calculated. The computational methods are described in Bates and Pinheiro (1998). ### Usage ``` ## S3 method for class 'reStruct' logLik(object, conLin, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"[reStruct](restruct)"`, representing a random effects structure and consisting of a list of `pdMat` objects. | | `conLin` | a condensed linear model object, consisting of a list with components `"Xy"`, corresponding to a regression matrix (`X`) combined with a response vector (`y`), and `"logLik"`, corresponding to the log-likelihood of the underlying model. | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value the log-likelihood, or restricted log-likelihood, of linear mixed-effects model represented by `object` and `conLin`, evaluated at `coef{object}`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[reStruct](restruct)`, `[pdMat](pdmat)`, `[logLik.lme](loglik.lme)`
programming_docs
r None `lmeControl` Specifying Control Values for lme Fit --------------------------------------------------- ### Description The values supplied in the `lmeControl()` call replace the defaults, and a `[list](../../base/html/list)` with all settings (i.e., values for all possible arguments) is returned. The returned list is used as the `control` argument to the `lme` function. ### Usage ``` lmeControl(maxIter = 50, msMaxIter = 50, tolerance = 1e-6, niterEM = 25, msMaxEval = 200, msTol = 1e-7, msVerbose = FALSE, returnObject = FALSE, gradHess = TRUE, apVar = TRUE, .relStep = .Machine$double.eps^(1/3), minAbsParApVar = 0.05, opt = c("nlminb", "optim"), optimMethod = "BFGS", natural = TRUE, sigma = NULL, allow.n.lt.q = FALSE, ...) ``` ### Arguments | | | | --- | --- | | `maxIter` | maximum number of iterations for the `lme` optimization algorithm. Default is `50`. | | `msMaxIter` | maximum number of iterations for the optimization step inside the `lme` optimization. Default is `50`. | | `tolerance` | tolerance for the convergence criterion in the `lme` algorithm. Default is `1e-6`. | | `niterEM` | number of iterations for the EM algorithm used to refine the initial estimates of the random effects variance-covariance coefficients. Default is `25`. | | `msMaxEval` | maximum number of evaluations of the objective function permitted for nlminb. Default is `200`. | | `msTol` | tolerance for the convergence criterion on the first iteration when `optim` is used. Default is `1e-7`. | | `msVerbose` | a logical value passed as the `trace` argument to `[nlminb](../../stats/html/nlminb)` or `[optim](../../stats/html/optim)`. Default is `FALSE`. | | `returnObject` | a logical value indicating whether the fitted object should be returned with a `[warning](../../base/html/warning)` (instead of an error via `[stop](../../base/html/stop)()`) when the maximum number of iterations is reached without convergence of the algorithm. Default is `FALSE`. | | `gradHess` | a logical value indicating whether numerical gradient vectors and Hessian matrices of the log-likelihood function should be used in the internal optimization. This option is only available when the correlation structure (`corStruct`) and the variance function structure (`varFunc`) have no "varying" parameters and the `pdMat` classes used in the random effects structure are `pdSymm` (general positive-definite), `pdDiag` (diagonal), `pdIdent` (multiple of the identity), or `pdCompSymm` (compound symmetry). Default is `TRUE`. | | `apVar` | a logical value indicating whether the approximate covariance matrix of the variance-covariance parameters should be calculated. Default is `TRUE`. | | `.relStep` | relative step for numerical derivatives calculations. Default is `.Machine$double.eps^(1/3)`. | | `opt` | the optimizer to be used, either `"[nlminb](../../stats/html/nlminb)"` (the default) or `"[optim](../../stats/html/optim)"`. | | `optimMethod` | character - the optimization method to be used with the `[optim](../../stats/html/optim)` optimizer. The default is `"BFGS"`. An alternative is `"L-BFGS-B"`. | | `minAbsParApVar` | numeric value - minimum absolute parameter value in the approximate variance calculation. The default is `0.05`. | | `natural` | a logical value indicating whether the `pdNatural` parametrization should be used for general positive-definite matrices (`pdSymm`) in `reStruct`, when the approximate covariance matrix of the estimators is calculated. Default is `TRUE`. | | `sigma` | optionally a positive number to fix the residual error at. If `NULL`, as by default, or `0`, sigma is estimated. | | `allow.n.lt.q` | `[logical](../../base/html/logical)` indicating if it is ok to have less observations than random effects for each group. The default, `FALSE` signals an error; if `NA`, such a situation only gives a warning, as in nlme versions prior to 2019; if true, no message is given at all. | | | | | --- | --- | | `...` | further named control arguments to be passed, depending on `opt`, to `[nlminb](../../stats/html/nlminb)` (those from `abs.tol` down) or `[optim](../../stats/html/optim)` (those except `trace` and `maxit`; `reltol` is used only from the second iteration). | ### Value a list with components for each of the possible arguments. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]); the `sigma` option: Siem Heisterkamp and Bert van Willigen. ### See Also `<lme>`, `[nlminb](../../stats/html/nlminb)`, `[optim](../../stats/html/optim)` ### Examples ``` # decrease the maximum number iterations in the ms call and # request that information on the evolution of the ms iterations be printed str(lCtr <- lmeControl(msMaxIter = 20, msVerbose = TRUE)) ## This should always work: do.call(lmeControl, lCtr) ``` r None `Oats` Split-plot Experiment on Varieties of Oats -------------------------------------------------- ### Description The `Oats` data frame has 72 rows and 4 columns. ### Format This data frame contains the following columns: Block an ordered factor with levels `VI` < `V` < `III` < `IV` < `II` < `I` Variety a factor with levels `Golden Rain` `Marvellous` `Victory` nitro a numeric vector yield a numeric vector ### Details These data have been introduced by Yates (1935) as an example of a split-plot design. The treatment structure used in the experiment was a *3 x 4* full factorial, with three varieties of oats and four concentrations of nitrogen. The experimental units were arranged into six blocks, each with three whole-plots subdivided into four subplots. The varieties of oats were assigned randomly to the whole-plots and the concentrations of nitrogen to the subplots. All four concentrations of nitrogen were used on each whole-plot. ### Source Pinheiro, J. C. and Bates, D. M. (2000), *Mixed-Effects Models in S and S-PLUS*, Springer, New York. (Appendix A.15) Venables, W. N. and Ripley, B. D. (2002) *Modern Applied Statistics with S. (4th ed)*, Springer, New York. r None `corCompSymm` Compound Symmetry Correlation Structure ------------------------------------------------------ ### Description This function is a constructor for the `corCompSymm` class, representing a compound symmetry structure corresponding to uniform correlation. Objects created using this constructor must later be initialized using the appropriate `Initialize` method. ### Usage ``` corCompSymm(value, form, fixed) ``` ### Arguments | | | | --- | --- | | `value` | the correlation between any two correlated observations. Defaults to 0. | | `form` | a one sided formula of the form `~ t`, or `~ t | g`, specifying a time covariate `t` and, optionally, a grouping factor `g`. When a grouping factor is present in `form`, the correlation structure is assumed to apply only to observations within the same grouping level; observations with different grouping levels are assumed to be uncorrelated. Defaults to `~ 1`, which corresponds to using the order of the observations in the data as a covariate, and no groups. | | `fixed` | an optional logical value indicating whether the coefficients should be allowed to vary in the optimization, or kept fixed at their initial value. Defaults to `FALSE`, in which case the coefficients are allowed to vary. | ### Value an object of class `corCompSymm`, representing a compound symmetry correlation structure. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Milliken, G. A. and Johnson, D. E. (1992) "Analysis of Messy Data, Volume I: Designed Experiments", Van Nostrand Reinhold. Pinheiro, J.C., and Bates, D.M. (2000) "Mixed-Effects Models in S and S-PLUS", Springer, esp. pp. 233-234. ### See Also `[corClasses](corclasses)`, `[Initialize.corStruct](initialize.corstruct)`, `[summary.corStruct](summary.corstruct)` ### Examples ``` ## covariate is observation order and grouping factor is Subject cs1 <- corCompSymm(0.5, form = ~ 1 | Subject) # Pinheiro and Bates, pp. 222-225 fm1BW.lme <- lme(weight ~ Time * Diet, BodyWeight, random = ~ Time) # p. 223 fm2BW.lme <- update(fm1BW.lme, weights = varPower()) # p. 225 cs1CompSymm <- corCompSymm(value = 0.3, form = ~ 1 | Subject) cs2CompSymm <- corCompSymm(value = 0.3, form = ~ age | Subject) cs1CompSymm <- Initialize(cs1CompSymm, data = Orthodont) corMatrix(cs1CompSymm) ## Print/Summary methods for the empty case: (cCS <- corCompSymm()) # Uninitialized correlation struc.. summary(cCS) # (ditto) ``` r None `getData.gls` Extract gls Object Data -------------------------------------- ### Description If present in the calling sequence used to produce `object`, the data frame used to fit the model is obtained. ### Usage ``` ## S3 method for class 'gls' getData(object) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `gls`, representing a generalized least squares fitted linear model. | ### Value if a `data` argument is present in the calling sequence that produced `object`, the corresponding data frame (with `na.action` and `subset` applied to it, if also present in the call that produced `object`) is returned; else, `NULL` is returned. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `<gls>`, `[getData](getdata)` ### Examples ``` fm1 <- gls(follicles ~ sin(2*pi*Time) + cos(2*pi*Time), data = Ovary, correlation = corAR1(form = ~ 1 | Mare)) getData(fm1) ``` r None `coef.modelStruct` Extract modelStruct Object Coefficients ----------------------------------------------------------- ### Description This method function extracts the coefficients associated with each component of the `modelStruct` list. ### Usage ``` ## S3 method for class 'modelStruct' coef(object, unconstrained, ...) ## S3 replacement method for class 'modelStruct' coef(object, ...) <- value ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"modelStruct"`, representing a list of model components, such as `"[corStruct](corclasses)"` and `"[varFunc](varfunc)"` objects. | | `unconstrained` | a logical value. If `TRUE` the coefficients are returned in unconstrained form (the same used in the optimization algorithm). If `FALSE` the coefficients are returned in "natural", possibly constrained, form. Defaults to `TRUE`. | | `value` | a vector with the replacement values for the coefficients associated with `object`. It must be a vector with the same length of `coef{object}` and must be given in unconstrained form. | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value a vector with all coefficients corresponding to the components of `object`. ### SIDE EFFECTS On the left side of an assignment, sets the values of the coefficients of `object` to `value`. `Object` must be initialized (using `Initialize`) before new values can be assigned to its coefficients. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[Initialize](initialize)` ### Examples ``` lms1 <- lmeStruct(reStruct = reStruct(pdDiag(diag(2), ~age)), corStruct = corAR1(0.3)) coef(lms1) ``` r None `plot.nffGroupedData` Plot an nffGroupedData Object ---------------------------------------------------- ### Description A Trellis dot-plot of the response by group is generated. If outer variables are specified, the combination of their levels are used to determine the panels of the Trellis display. The Trellis function `dotplot` is used. ### Usage ``` ## S3 method for class 'nffGroupedData' plot(x, outer, inner, innerGroups, xlab, ylab, strip, panel, key, grid, ...) ``` ### Arguments | | | | --- | --- | | `x` | an object inheriting from class `nffGroupedData`, representing a `groupedData` object with a factor primary covariate and a single grouping level. | | `outer` | an optional logical value or one-sided formula, indicating covariates that are outer to the grouping factor, which are used to determine the panels of the Trellis plot. If equal to `TRUE`, `attr(object, "outer")` is used to indicate the outer covariates. An outer covariate is invariant within the sets of rows defined by the grouping factor. Ordering of the groups is done in such a way as to preserve adjacency of groups with the same value of the outer variables. Defaults to `NULL`, meaning that no outer covariates are to be used. | | `inner` | an optional logical value or one-sided formula, indicating a covariate that is inner to the grouping factor, which is used to associate points within each panel of the Trellis plot. If equal to `TRUE`, `attr(object, "inner")` is used to indicate the inner covariate. An inner covariate can change within the sets of rows defined by the grouping factor. Defaults to `NULL`, meaning that no inner covariate is present. | | `innerGroups` | an optional one-sided formula specifying a factor to be used for grouping the levels of the `inner` covariate. Different colors, or symbols, are used for each level of the `innerGroups` factor. Default is `NULL`, meaning that no `innerGroups` covariate is present. | | `xlab` | an optional character string with the label for the horizontal axis. Default is the `y` elements of `attr(object, "labels")` and `attr(object, "units")` pasted together. | | `ylab` | an optional character string with the label for the vertical axis. Default is the grouping factor name. | | `strip` | an optional function passed as the `strip` argument to the `dotplot` function. Default is `strip.default(..., style = 1)` (see `trellis.args`). | | `panel` | an optional function used to generate the individual panels in the Trellis display, passed as the `panel` argument to the `dotplot` function. | | `key` | an optional logical function or function. If `TRUE` and either `inner` or `innerGroups` are non-`NULL`, a legend for the different `inner` (`innerGroups`) levels is included at the top of the plot. If given as a function, it is passed as the `key` argument to the `dotplot` function. Default is `TRUE` is either `inner` or `innerGroups` are non-`NULL` and `FALSE` otherwise. | | `grid` | this argument is included for consistency with the `plot.nfnGroupedData` method calling sequence. It is ignored in this method function. | | `...` | optional arguments passed to the `dotplot` function. | ### Value a Trellis dot-plot of the response by group. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Bates, D.M. and Pinheiro, J.C. (1997), "Software Design for Longitudinal Data", in "Modelling Longitudinal and Spatially Correlated Data: Methods, Applications and Future Directions", T.G. Gregoire (ed.), Springer-Verlag, New York. ### See Also `[groupedData](groupeddata)`, `[dotplot](../../lattice/html/xyplot)` ### Examples ``` plot(Machines) plot(Machines, inner = TRUE) ``` r None `logDet.pdMat` Extract Log-Determinant from a pdMat Object ----------------------------------------------------------- ### Description This method function extracts the logarithm of the determinant of a square-root factor of the positive-definite matrix represented by `object`. ### Usage ``` ## S3 method for class 'pdMat' logDet(object, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"[pdMat](pdmat)"`, representing a positive definite matrix. | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value the log-determinant of a square-root factor of the positive-definite matrix represented by `object`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[pdMat](pdmat)`, `[logDet](logdet)` ### Examples ``` pd1 <- pdSymm(diag(1:3)) logDet(pd1) ``` r None `lmeObject` Fitted lme Object ------------------------------ ### Description An object returned by the `lme` function, inheriting from class `lme` and representing a fitted linear mixed-effects model. Objects of this class have methods for the generic functions `anova`, `coef`, `fitted`, `fixed.effects`, `formula`, `getGroups`, `getResponse`, `intervals`, `logLik`, `pairs`, `plot`, `predict`, `print`, `random.effects`, `residuals`, `sigma`, `summary`, `update`, and `vcov`. ### Value The following components must be included in a legitimate `lme` object. | | | | --- | --- | | `apVar` | an approximate covariance matrix for the variance-covariance coefficients. If `apVar = FALSE` in the control values used in the call to `lme`, this component is `NULL`. | | `call` | a list containing an image of the `lme` call that produced the object. | | `coefficients` | a list with two components, `fixed` and `random`, where the first is a vector containing the estimated fixed effects and the second is a list of matrices with the estimated random effects for each level of grouping. For each matrix in the `random` list, the columns refer to the random effects and the rows to the groups. | | `contrasts` | a list with the contrasts used to represent factors in the fixed effects formula and/or random effects formula. This information is important for making predictions from a new data frame in which not all levels of the original factors are observed. If no factors are used in the lme model, this component will be an empty list. | | `dims` | a list with basic dimensions used in the lme fit, including the components `N` - the number of observations in the data, `Q` - the number of grouping levels, `qvec` - the number of random effects at each level from innermost to outermost (last two values are equal to zero and correspond to the fixed effects and the response), `ngrps` - the number of groups at each level from innermost to outermost (last two values are one and correspond to the fixed effects and the response), and `ncol` - the number of columns in the model matrix for each level of grouping from innermost to outermost (last two values are equal to the number of fixed effects and one). | | `fitted` | a data frame with the fitted values as columns. The leftmost column corresponds to the population fixed effects (corresponding to the fixed effects only) and successive columns from left to right correspond to increasing levels of grouping. | | `fixDF` | a list with components `X` and `terms` specifying the denominator degrees of freedom for, respectively, t-tests for the individual fixed effects and F-tests for the fixed-effects terms in the models. | | `groups` | a data frame with the grouping factors as columns. The grouping level increases from left to right. | | `logLik` | the (restricted) log-likelihood at convergence. | | `method` | the estimation method: either `"ML"` for maximum likelihood, or `"REML"` for restricted maximum likelihood. | | `modelStruct` | an object inheriting from class `lmeStruct`, representing a list of mixed-effects model components, such as `reStruct`, `corStruct`, and `varFunc` objects. | | `numIter` | the number of iterations used in the iterative algorithm. | | `residuals` | a data frame with the residuals as columns. The leftmost column corresponds to the population residuals and successive columns from left to right correspond to increasing levels of grouping. | | `sigma` | the estimated within-group error standard deviation. | | `varFix` | an approximate covariance matrix of the fixed effects estimates. | ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `<lme>`, `lmeStruct` r None `corMatrix.pdMat` Extract Correlation Matrix from a pdMat Object ----------------------------------------------------------------- ### Description The correlation matrix corresponding to the positive-definite matrix represented by `object` is obtained. ### Usage ``` ## S3 method for class 'pdMat' corMatrix(object, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"[pdMat](pdmat)"`, representing a positive definite matrix. | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value the correlation matrix corresponding to the positive-definite matrix represented by `object`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[as.matrix.pdMat](as.matrix.pdmat)`, `[pdMatrix](pdmatrix)` ### Examples ``` pd1 <- pdSymm(diag(1:4)) corMatrix(pd1) ```
programming_docs
r None `groupedData` Construct a groupedData Object --------------------------------------------- ### Description An object of the `groupedData` class is constructed from the `formula` and `data` by attaching the `formula` as an attribute of the data, along with any of `outer`, `inner`, `labels`, and `units` that are given. If `order.groups` is `TRUE` the grouping factor is converted to an ordered factor with the ordering determined by `FUN`. Depending on the number of grouping levels and the type of primary covariate, the returned object will be of one of three classes: `nfnGroupedData` - numeric covariate, single level of nesting; `nffGroupedData` - factor covariate, single level of nesting; and `nmGroupedData` - multiple levels of nesting. Several modeling and plotting functions can use the formula stored with a `groupedData` object to construct default plots and models. ### Usage ``` groupedData(formula, data, order.groups, FUN, outer, inner, labels, units) ## S3 method for class 'groupedData' update(object, formula, data, order.groups, FUN, outer, inner, labels, units, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `groupedData`. | | `formula` | a formula of the form `resp ~ cov | group` where `resp` is the response, `cov` is the primary covariate, and `group` is the grouping factor. The expression `1` can be used for the primary covariate when there is no other suitable candidate. Multiple nested grouping factors can be listed separated by the `/` symbol as in `fact1/fact2`. In an expression like this the `fact2` factor is nested within the `fact1` factor. | | `data` | a data frame in which the expressions in `formula` can be evaluated. The resulting `groupedData` object will consist of the same data values in the same order but with additional attributes. | | `order.groups` | an optional logical value, or list of logical values, indicating if the grouping factors should be converted to ordered factors according to the function `FUN` applied to the response from each group. If multiple levels of grouping are present, this argument can be either a single logical value (which will be repeated for all grouping levels) or a list of logical values. If no names are assigned to the list elements, they are assumed in the same order as the group levels (outermost to innermost grouping). Ordering within a level of grouping is done within the levels of the grouping factors which are outer to it. Changing the grouping factor to an ordered factor does not affect the ordering of the rows in the data frame but it does affect the order of the panels in a trellis display of the data or models fitted to the data. Defaults to `TRUE`. | | `FUN` | an optional summary function that will be applied to the values of the response for each level of the grouping factor, when `order.groups = TRUE`, to determine the ordering. Defaults to the `max` function. | | `outer` | an optional one-sided formula, or list of one-sided formulas, indicating covariates that are outer to the grouping factor(s). If multiple levels of grouping are present, this argument can be either a single one-sided formula, or a list of one-sided formulas. If no names are assigned to the list elements, they are assumed in the same order as the group levels (outermost to innermost grouping). An outer covariate is invariant within the sets of rows defined by the grouping factor. Ordering of the groups is done in such a way as to preserve adjacency of groups with the same value of the outer variables. When plotting a groupedData object, the argument `outer = TRUE` causes the panels to be determined by the `outer` formula. The points within the panels are associated by level of the grouping factor. Defaults to `NULL`, meaning that no outer covariates are present. | | `inner` | an optional one-sided formula, or list of one-sided formulas, indicating covariates that are inner to the grouping factor(s). If multiple levels of grouping are present, this argument can be either a single one-sided formula, or a list of one-sided formulas. If no names are assigned to the list elements, they are assumed in the same order as the group levels (outermost to innermost grouping). An inner covariate can change within the sets of rows defined by the grouping factor. An inner formula can be used to associate points in a plot of a groupedData object. Defaults to `NULL`, meaning that no inner covariates are present. | | `labels` | an optional list of character strings giving labels for the response and the primary covariate. The label for the primary covariate is named `x` and that for the response is named `y`. Either label can be omitted. | | `units` | an optional list of character strings giving the units for the response and the primary covariate. The units string for the primary covariate is named `x` and that for the response is named `y`. Either units string can be omitted. | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value an object of one of the classes `nfnGroupedData`, `nffGroupedData`, or `nmGroupedData`, and also inheriting from classes `groupedData` and `data.frame`. ### Author(s) Douglas Bates and José Pinheiro ### References Bates, D.M. and Pinheiro, J.C. (1997), "Software Design for Longitudinal Data", in "Modelling Longitudinal and Spatially Correlated Data: Methods, Applications and Future Directions", T.G. Gregoire (ed.), Springer-Verlag, New York. Pinheiro, J.C. and Bates, D.M. (1997) "Future Directions in Mixed-Effects Software: Design of NLME 3.0" available at http://nlme.stat.wisc.edu/ Pinheiro, J.C., and Bates, D.M. (2000) "Mixed-Effects Models in S and S-PLUS", Springer. ### See Also `[formula](../../stats/html/formula)`, `<gapply>`, `<gsummary>`, `<lme>`, `[plot.nffGroupedData](plot.nffgroupeddata)`, `[plot.nfnGroupedData](plot.nfngroupeddata)`, `[plot.nmGroupedData](plot.nmgroupeddata)`, `[reStruct](restruct)` ### Examples ``` Orth.new <- # create a new copy of the groupedData object groupedData( distance ~ age | Subject, data = as.data.frame( Orthodont ), FUN = mean, outer = ~ Sex, labels = list( x = "Age", y = "Distance from pituitary to pterygomaxillary fissure" ), units = list( x = "(yr)", y = "(mm)") ) plot( Orth.new ) # trellis plot by Subject formula( Orth.new ) # extractor for the formula gsummary( Orth.new ) # apply summary by Subject fm1 <- lme( Orth.new ) # fixed and groups formulae extracted from object Orthodont2 <- update(Orthodont, FUN = mean) ``` r None `Names.formula` Extract Names from a formula --------------------------------------------- ### Description This method function returns the names of the terms corresponding to the right hand side of `object` (treated as a linear formula), obtained as the column names of the corresponding `model.matrix`. ### Usage ``` ## S3 method for class 'formula' Names(object, data, exclude, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"[formula](../../stats/html/formula)"`. | | `data` | an optional data frame containing the variables specified in `object`. By default the variables are taken from the environment from which `Names.formula` is called. | | `exclude` | an optional character vector with names to be excluded from the returned value. Default is `c("pi",".")`. | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value a character vector with the column names of the `model.matrix` corresponding to the right hand side of `object` which are not listed in `excluded`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[model.matrix](../../stats/html/model.matrix)`, `[terms](../../stats/html/terms)`, `[Names](names)` ### Examples ``` Names(distance ~ Sex * age, data = Orthodont) ``` r None `Names` Names Associated with an Object ---------------------------------------- ### Description This function is generic; method functions can be written to handle specific classes of objects. Classes which already have methods for this function include: `formula`, `modelStruct`, `pdBlocked`, `pdMat`, and `reStruct`. ### Usage ``` Names(object, ...) Names(object, ...) <- value ``` ### Arguments | | | | --- | --- | | `object` | any object for which names can be extracted and/or assigned. | | `...` | some methods for this generic function require additional arguments. | | `value` | names to be assigned to `object`. | ### Value will depend on the method function used; see the appropriate documentation. ### SIDE EFFECTS On the left side of an assignment, sets the names associated with `object` to `value`, which must have an appropriate length. ### Note If `names` were generic, there would be no need for this generic function. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[Names.formula](names.formula)`, `[Names.pdMat](names.pdmat)` ### Examples ``` ## see the method function documentation ``` r None `intervals.lme` Confidence Intervals on lme Parameters ------------------------------------------------------- ### Description Approximate confidence intervals for the parameters in the linear mixed-effects model represented by `object` are obtained, using a normal approximation to the distribution of the (restricted) maximum likelihood estimators (the estimators are assumed to have a normal distribution centered at the true parameter values and with covariance matrix equal to the negative inverse Hessian matrix of the (restricted) log-likelihood evaluated at the estimated parameters). Confidence intervals are obtained in an unconstrained scale first, using the normal approximation, and, if necessary, transformed to the constrained scale. The `pdNatural` parametrization is used for general positive-definite matrices. ### Usage ``` ## S3 method for class 'lme' intervals(object, level = 0.95, which = c("all", "var-cov", "fixed"), ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"<lme>"`, representing a fitted linear mixed-effects model. | | `level` | an optional numeric value with the confidence level for the intervals. Defaults to 0.95. | | `which` | an optional character string specifying the subset of parameters for which to construct the confidence intervals. Possible values are `"all"` for all parameters, `"var-cov"` for the variance-covariance parameters only, and `"fixed"` for the fixed effects only. Defaults to `"all"`. | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value a list with components given by data frames with rows corresponding to parameters and columns `lower`, `est.`, and `upper` representing respectively lower confidence limits, the estimated values, and upper confidence limits for the parameters. Possible components are: | | | | --- | --- | | `fixed` | fixed effects, only present when `which` is not equal to `"var-cov"`. | | `reStruct` | random effects variance-covariance parameters, only present when `which` is not equal to `"fixed"`. | | `corStruct` | within-group correlation parameters, only present when `which` is not equal to `"fixed"` and a correlation structure is used in `object`. | | `varFunc` | within-group variance function parameters, only present when `which` is not equal to `"fixed"` and a variance function structure is used in `object`. | | `sigma` | within-group standard deviation. | ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Pinheiro, J.C., and Bates, D.M. (2000) "Mixed-Effects Models in S and S-PLUS", Springer. ### See Also `<lme>`, `<intervals>`, `[print.intervals.lme](intervals.lme)`, `[pdNatural](pdnatural)` ### Examples ``` fm1 <- lme(distance ~ age, Orthodont, random = ~ age | Subject) intervals(fm1) ``` r None `plot.intervals.lmList` Plot lmList Confidence Intervals --------------------------------------------------------- ### Description A Trellis dot-plot of the confidence intervals on the linear model coefficients is generated, with a different panel for each coefficient. Rows in the dot-plot correspond to the names of the `lm` components of the `lmList` object used to produce `x`. The lower and upper confidence limits are connected by a line segment and the estimated coefficients are marked with a `"+"`. This is based on function `[dotplot](../../lattice/html/xyplot)()` from package [lattice](https://CRAN.R-project.org/package=lattice). ### Usage ``` ## S3 method for class 'intervals.lmList' plot(x, xlab = "", ylab = attr(x, "groupsName"), strip = function(...) strip.default(..., style = 1), ...) ``` ### Arguments | | | | --- | --- | | `x` | an object inheriting from class `"[intervals.lmList](intervals.lmlist)"`, representing confidence intervals and estimates for the coefficients in the `lm` components of the `lmList` object used to produce `x`. | | `xlab, ylab` | axis labels, each with a sensible default. | | `strip` | a `[function](../../base/html/function)` or `FALSE`, see `[dotplot](../../lattice/html/xyplot)()` from package [lattice](https://CRAN.R-project.org/package=lattice). | | `...` | optional arguments passed to the `dotplot` function (see above). | ### Value a Trellis plot with the confidence intervals on the coefficients of the individual `lm` components of the `lmList` that generated `x`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[intervals.lmList](intervals.lmlist)`, `[lmList](lmlist)`, `[dotplot](../../lattice/html/xyplot)` ### Examples ``` fm1 <- lmList(distance ~ age | Subject, Orthodont) plot(intervals(fm1)) ``` r None `recalc.corStruct` Recalculate for corStruct Object ---------------------------------------------------- ### Description This method function pre-multiples the `"Xy"` component of `conLin` by the transpose square-root factor(s) of the correlation matrix (matrices) associated with `object` and adds the log-likelihood contribution of `object`, given by `logLik(object)`, to the `"logLik"` component of `conLin`. ### Usage ``` ## S3 method for class 'corStruct' recalc(object, conLin, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"[corStruct](corclasses)"`, representing a correlation structure. | | `conLin` | a condensed linear model object, consisting of a list with components `"Xy"`, corresponding to a regression matrix (`X`) combined with a response vector (`y`), and `"logLik"`, corresponding to the log-likelihood of the underlying model. | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value the recalculated condensed linear model object. ### Note This method function is only used inside model fitting functions, such as `lme` and `gls`, that allow correlated error terms. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[corFactor](corfactor)`, `[logLik.corStruct](loglik.corstruct)` r None `Covariate.varFunc` Assign varFunc Covariate --------------------------------------------- ### Description The covariate(s) used in the calculation of the weights of the variance function represented by `object` is (are) replaced by `value`. If `object` has been initialized, `value` must have the same dimensions as `getCovariate(object)`. ### Usage ``` ## S3 replacement method for class 'varFunc' covariate(object) <- value ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"[varFunc](varfunc)"`, representing a variance function structure. | | `value` | a value to be assigned to the covariate associated with `object`. | ### Value a `varFunc` object similar to `object`, but with its `covariate` attribute replaced by `value`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[getCovariate.varFunc](getcovariate.varfunc)` ### Examples ``` vf1 <- varPower(1.1, form = ~age) covariate(vf1) <- Orthodont[["age"]] ``` r None `VarCorr` Extract variance and correlation components ------------------------------------------------------ ### Description This function calculates the estimated variances, standard deviations, and correlations between the random-effects terms in a linear mixed-effects model, of class `"<lme>"`, or a nonlinear mixed-effects model, of class `"<nlme>"`. The within-group error variance and standard deviation are also calculated. ### Usage ``` VarCorr(x, sigma = 1, ...) ## S3 method for class 'lme' VarCorr(x, sigma = x$sigma, rdig = 3, ...) ## S3 method for class 'pdMat' VarCorr(x, sigma = 1, rdig = 3, ...) ## S3 method for class 'pdBlocked' VarCorr(x, sigma = 1, rdig = 3, ...) ``` ### Arguments | | | | --- | --- | | `x` | a fitted model object, usually an object inheriting from class `"<lme>"`. | | `sigma` | an optional numeric value used as a multiplier for the standard deviations. The default is `x$sigma` or `1` depending on `[class](../../base/html/class)(x)`. | | `rdig` | an optional integer value specifying the number of digits used to represent correlation estimates. Default is `3`. | | `...` | further optional arguments passed to other methods (none for the methods documented here). | ### Value a matrix with the estimated variances, standard deviations, and correlations for the random effects. The first two columns, named `Variance` and `StdDev`, give, respectively, the variance and the standard deviations. If there are correlation components in the random effects model, the third column, named `Corr`, and the remaining unnamed columns give the estimated correlations among random effects within the same level of grouping. The within-group error variance and standard deviation are included as the last row in the matrix. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Pinheiro, J.C., and Bates, D.M. (2000) *Mixed-Effects Models in S and S-PLUS*, Springer, esp. pp. 100, 461. ### See Also `<lme>`, `<nlme>` ### Examples ``` fm1 <- lme(distance ~ age, data = Orthodont, random = ~age) VarCorr(fm1) ``` r None `coef.lme` Extract lme Coefficients ------------------------------------ ### Description The estimated coefficients at level *i* are obtained by adding together the fixed effects estimates and the corresponding random effects estimates at grouping levels less or equal to *i*. The resulting estimates are returned as a data frame, with rows corresponding to groups and columns to coefficients. Optionally, the returned data frame may be augmented with covariates summarized over groups. ### Usage ``` ## S3 method for class 'lme' coef(object, augFrame, level, data, which, FUN, omitGroupingFactor, subset, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"<lme>"`, representing a fitted linear mixed-effects model. | | `augFrame` | an optional logical value. If `TRUE`, the returned data frame is augmented with variables defined in `data`; else, if `FALSE`, only the coefficients are returned. Defaults to `FALSE`. | | `level` | an optional positive integer giving the level of grouping to be used in extracting the coefficients from an object with multiple nested grouping levels. Defaults to the highest or innermost level of grouping. | | `data` | an optional data frame with the variables to be used for augmenting the returned data frame when `augFrame = TRUE`. Defaults to the data frame used to fit `object`. | | `which` | an optional positive integer or character vector specifying which columns of `data` should be used in the augmentation of the returned data frame. Defaults to all columns in `data`. | | `FUN` | an optional summary function or a list of summary functions to be applied to group-varying variables, when collapsing `data` by groups. Group-invariant variables are always summarized by the unique value that they assume within that group. If `FUN` is a single function it will be applied to each non-invariant variable by group to produce the summary for that variable. If `FUN` is a list of functions, the names in the list should designate classes of variables in the frame such as `ordered`, `factor`, or `numeric`. The indicated function will be applied to any group-varying variables of that class. The default functions to be used are `mean` for numeric factors, and `Mode` for both `factor` and `ordered`. The `Mode` function, defined internally in `gsummary`, returns the modal or most popular value of the variable. It is different from the `mode` function that returns the S-language mode of the variable. | | `omitGroupingFactor` | an optional logical value. When `TRUE` the grouping factor itself will be omitted from the group-wise summary of `data` but the levels of the grouping factor will continue to be used as the row names for the returned data frame. Defaults to `FALSE`. | | `subset` | an optional expression specifying a subset | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value a data frame inheriting from class `"coef.lme"` with the estimated coefficients at level `level` and, optionally, other covariates summarized over groups. The returned object also inherits from classes `"ranef.lme"` and `"data.frame"`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Pinheiro, J. C. and Bates, D. M. (2000), *Mixed-Effects Models in S and S-PLUS*, Springer, New York, esp. pp. 455-457. ### See Also `<lme>`, `<ranef.lme>`, `<plot.ranef.lme>`, `<gsummary>` ### Examples ``` fm1 <- lme(distance ~ age, Orthodont, random = ~ age | Subject) coef(fm1) coef(fm1, augFrame = TRUE) ```
programming_docs
r None `recalc.reStruct` Recalculate for an reStruct Object ----------------------------------------------------- ### Description The log-likelihood, or restricted log-likelihood, of the Gaussian linear mixed-effects model represented by `object` and `conLin` (assuming spherical within-group covariance structure), evaluated at `coef(object)` is calculated and added to the `logLik` component of `conLin`. The `settings` attribute of `object` determines whether the log-likelihood, or the restricted log-likelihood, is to be calculated. The computational methods for the (restricted) log-likelihood calculations are described in Bates and Pinheiro (1998). ### Usage ``` ## S3 method for class 'reStruct' recalc(object, conLin, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"[reStruct](restruct)"`, representing a random effects structure and consisting of a list of `pdMat` objects. | | `conLin` | a condensed linear model object, consisting of a list with components `"Xy"`, corresponding to a regression matrix (`X`) combined with a response vector (`y`), and `"logLik"`, corresponding to the log-likelihood of the underlying model. | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value the condensed linear model with its `logLik` component updated. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[logLik](../../stats/html/loglik)`, `<lme>`, `<recalc>`, `[reStruct](restruct)` r None `residuals.lmList` Extract lmList Residuals -------------------------------------------- ### Description The residuals are extracted from each `lm` component of `object` and arranged into a list with as many components as `object`, or combined into a single vector. ### Usage ``` ## S3 method for class 'lmList' residuals(object, type, subset, asList, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"[lmList](lmlist)"`, representing a list of `lm` objects with a common model. | | `subset` | an optional character or integer vector naming the `lm` components of `object` from which the residuals are to be extracted. Default is `NULL`, in which case all components are used. | | `type` | an optional character string specifying the type of residuals to be extracted. Options include `"response"` for the "raw" residuals (observed - fitted), `"pearson"` for the standardized residuals (raw residuals divided by the estimated residual standard error) using different standard errors for each `lm` fit, and `"pooled.pearson"` for the standardized residuals using a pooled estimate of the residual standard error. Partial matching of arguments is used, so only the first character needs to be provided. Defaults to `"response"`. | | `asList` | an optional logical value. If `TRUE`, the returned object is a list with the residuals split by groups; else the returned value is a vector. Defaults to `FALSE`. | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value a list with components given by the residuals of each `lm` component of `object`, or a vector with the residuals for all `lm` components of `object`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[lmList](lmlist)`, `[fitted.lmList](fitted.lmlist)` ### Examples ``` fm1 <- lmList(distance ~ age | Subject, Orthodont) residuals(fm1) ``` r None `needUpdate` Check if Update is Needed --------------------------------------- ### Description This function is generic; method functions can be written to handle specific classes of objects. By default, it tries to extract a `needUpdate` attribute of `object`. If this is `NULL` or `FALSE` it returns `FALSE`; else it returns `TRUE`. Updating of objects usually takes place in iterative algorithms in which auxiliary quantities associated with the object, and not being optimized over, may change. ### Usage ``` needUpdate(object) ``` ### Arguments | | | | --- | --- | | `object` | any object | ### Value a logical value indicating whether `object` needs to be updated. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[needUpdate.modelStruct](needupdate.modelstruct)` ### Examples ``` vf1 <- varExp() vf1 <- Initialize(vf1, data = Orthodont) needUpdate(vf1) ``` r None `reStruct` Random Effects Structure ------------------------------------ ### Description This function is a constructor for the `reStruct` class, representing a random effects structure and consisting of a list of `pdMat` objects, plus a `settings` attribute containing information for the optimization algorithm used to fit the associated mixed-effects model. ### Usage ``` reStruct(object, pdClass, REML, data) ## S3 method for class 'reStruct' print(x, sigma, reEstimates, verbose, ...) ``` ### Arguments | | | | --- | --- | | `object` | any of the following: (i) a one-sided formula of the form `~x1+...+xn | g1/.../gm`, with `x1+...+xn` specifying the model for the random effects and `g1/.../gm` the grouping structure (`m` may be equal to 1, in which case no `/` is required). The random effects formula will be repeated for all levels of grouping, in the case of multiple levels of grouping; (ii) a list of one-sided formulas of the form `~x1+...+xn | g`, with possibly different random effects models for each grouping level. The order of nesting will be assumed the same as the order of the elements in the list; (iii) a one-sided formula of the form `~x1+...+xn`, or a `pdMat` object with a formula (i.e. a non-`NULL` value for `formula(object)`), or a list of such formulas or `pdMat` objects. In this case, the grouping structure formula will be derived from the data used to to fit the mixed-effects model, which should inherit from class `groupedData`; (iv) a named list of formulas or `pdMat` objects as in (iii), with the grouping factors as names. The order of nesting will be assumed the same as the order of the order of the elements in the list; (v) an `reStruct` object. | | `pdClass` | an optional character string with the name of the `pdMat` class to be used for the formulas in `object`. Defaults to `"pdSymm"` which corresponds to a general positive-definite matrix. | | `REML` | an optional logical value. If `TRUE`, the associated mixed-effects model will be fitted using restricted maximum likelihood; else, if `FALSE`, maximum likelihood will be used. Defaults to `FALSE`. | | `data` | an optional data frame in which to evaluate the variables used in the random effects formulas in `object`. It is used to obtain the levels for `factors`, which affect the dimensions and the row/column names of the underlying `pdMat` objects. If `NULL`, no attempt is made to obtain information on `factors` appearing in the formulas. Defaults to the parent frame from which the function was called. | | `x` | an object inheriting from class `reStruct` to be printed. | | `sigma` | an optional numeric value used as a multiplier for the square-root factors of the `pdMat` components (usually the estimated within-group standard deviation from a mixed-effects model). Defaults to 1. | | `reEstimates` | an optional list with the random effects estimates for each level of grouping. Only used when `verbose = TRUE`. | | `verbose` | an optional logical value determining if the random effects estimates should be printed. Defaults to `FALSE`. | | `...` | Optional arguments can be given to other methods for this generic. None are used in this method. | ### Value an object inheriting from class `reStruct`, representing a random effects structure. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[groupedData](groupeddata)`, `<lme>`, `[pdMat](pdmat)`, `[solve.reStruct](solve.restruct)`, `[summary.reStruct](summary.modelstruct)`, `[update.reStruct](update.modelstruct)` ### Examples ``` rs1 <- reStruct(list(Dog = ~day, Side = ~1), data = Pixel) rs1 ``` r None `corCAR1` Continuous AR(1) Correlation Structure ------------------------------------------------- ### Description This function is a constructor for the `corCAR1` class, representing an autocorrelation structure of order 1, with a continuous time covariate. Objects created using this constructor must be later initialized using the appropriate `Initialize` method. ### Usage ``` corCAR1(value, form, fixed) ``` ### Arguments | | | | --- | --- | | `value` | the correlation between two observations one unit of time apart. Must be between 0 and 1. Defaults to 0.2. | | `form` | a one sided formula of the form `~ t`, or `~ t | g`, specifying a time covariate `t` and, optionally, a grouping factor `g`. Covariates for this correlation structure need not be integer valued. When a grouping factor is present in `form`, the correlation structure is assumed to apply only to observations within the same grouping level; observations with different grouping levels are assumed to be uncorrelated. Defaults to `~ 1`, which corresponds to using the order of the observations in the data as a covariate, and no groups. | | `fixed` | an optional logical value indicating whether the coefficients should be allowed to vary in the optimization, or kept fixed at their initial value. Defaults to `FALSE`, in which case the coefficients are allowed to vary. | ### Value an object of class `corCAR1`, representing an autocorrelation structure of order 1, with a continuous time covariate. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Box, G.E.P., Jenkins, G.M., and Reinsel G.C. (1994) "Time Series Analysis: Forecasting and Control", 3rd Edition, Holden-Day. Jones, R.H. (1993) "Longitudinal Data with Serial Correlation: A State-space Approach", Chapman and Hall. Pinheiro, J.C., and Bates, D.M. (2000) "Mixed-Effects Models in S and S-PLUS", Springer, esp. pp. 236, 243. ### See Also `[corClasses](corclasses)`, `[Initialize.corStruct](initialize.corstruct)`, `[summary.corStruct](summary.corstruct)` ### Examples ``` ## covariate is Time and grouping factor is Mare cs1 <- corCAR1(0.2, form = ~ Time | Mare) # Pinheiro and Bates, pp. 240, 243 fm1Ovar.lme <- lme(follicles ~ sin(2*pi*Time) + cos(2*pi*Time), data = Ovary, random = pdDiag(~sin(2*pi*Time))) fm4Ovar.lme <- update(fm1Ovar.lme, correlation = corCAR1(form = ~Time)) ``` r None `lme` Linear Mixed-Effects Models ---------------------------------- ### Description This generic function fits a linear mixed-effects model in the formulation described in Laird and Ware (1982) but allowing for nested random effects. The within-group errors are allowed to be correlated and/or have unequal variances. The methods `[lme.lmList](lme.lmlist)` and `[lme.groupedData](lme.groupeddata)` are documented separately. ### Usage ``` lme(fixed, data, random, correlation, weights, subset, method, na.action, control, contrasts = NULL, keep.data = TRUE) ## S3 method for class 'lme' update(object, fixed., ..., evaluate = TRUE) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `lme`, representing a fitted linear mixed-effects model. | | `fixed` | a two-sided linear formula object describing the fixed-effects part of the model, with the response on the left of a `~` operator and the terms, separated by `+` operators, on the right, an `"[lmList](lmlist)"` object, or a `"[groupedData](groupeddata)"` object. There is limited support for formulae such as `resp ~ 1` and `resp ~ 0`, and less prior to version 3.1-112. | | `fixed.` | Changes to the fixed-effects formula – see `[update.formula](../../stats/html/update.formula)` for details. | | `data` | an optional data frame containing the variables named in `fixed`, `random`, `correlation`, `weights`, and `subset`. By default the variables are taken from the environment from which `lme` is called. | | `random` | optionally, any of the following: (i) a one-sided formula of the form `~ x1 + ... + xn | g1/.../gm`, with `x1 + ... + xn` specifying the model for the random effects and `g1/.../gm` the grouping structure (`m` may be equal to 1, in which case no `/` is required). The random effects formula will be repeated for all levels of grouping, in the case of multiple levels of grouping; (ii) a list of one-sided formulas of the form `~ x1 + ... + xn | g`, with possibly different random effects models for each grouping level. The order of nesting will be assumed the same as the order of the elements in the list; (iii) a one-sided formula of the form `~ x1 + ... + xn`, or a `[pdMat](pdmat)` object with a formula (i.e. a non-`NULL` value for `formula(object)`), or a list of such formulas or `[pdMat](pdmat)` objects. In this case, the grouping structure formula will be derived from the data used to fit the linear mixed-effects model, which should inherit from class `"[groupedData](groupeddata)"`; (iv) a named list of formulas or `[pdMat](pdmat)` objects as in (iii), with the grouping factors as names. The order of nesting will be assumed the same as the order of the order of the elements in the list; (v) an `[reStruct](restruct)` object. See the documentation on `pdClasses` for a description of the available `[pdMat](pdmat)` classes. Defaults to a formula consisting of the right hand side of `fixed`. | | `correlation` | an optional `[corStruct](corclasses)` object describing the within-group correlation structure. See the documentation of `[corClasses](corclasses)` for a description of the available `corStruct` classes. Defaults to `NULL`, corresponding to no within-group correlations. | | `weights` | an optional `[varFunc](varfunc)` object or one-sided formula describing the within-group heteroscedasticity structure. If given as a formula, it is used as the argument to `[varFixed](varfixed)`, corresponding to fixed variance weights. See the documentation on `[varClasses](varclasses)` for a description of the available `[varFunc](varfunc)` classes. Defaults to `NULL`, corresponding to homoscedastic within-group errors. | | `subset` | an optional expression indicating the subset of the rows of `data` that should be used in the fit. This can be a logical vector, or a numeric vector indicating which observation numbers are to be included, or a character vector of the row names to be included. All observations are included by default. | | `method` | a character string. If `"REML"` the model is fit by maximizing the restricted log-likelihood. If `"ML"` the log-likelihood is maximized. Defaults to `"REML"`. | | `na.action` | a function that indicates what should happen when the data contain `NA`s. The default action (`[na.fail](../../stats/html/na.fail)`) causes `lme` to print an error message and terminate if there are any incomplete observations. | | `control` | a list of control values for the estimation algorithm to replace the default values returned by the function `[lmeControl](lmecontrol)`. Defaults to an empty list. | | `contrasts` | an optional list. See the `contrasts.arg` of `[model.matrix.default](../../stats/html/model.matrix)`. | | `keep.data` | logical: should the `data` argument (if supplied and a data frame) be saved as part of the model object? | | `...` | some methods for this generic require additional arguments. None are used in this method. | | `evaluate` | If `TRUE` evaluate the new call else return the call. | ### Value An object of class `"lme"` representing the linear mixed-effects model fit. Generic functions such as `print`, `plot` and `summary` have methods to show the results of the fit. See `[lmeObject](lmeobject)` for the components of the fit. The functions `[resid](../../stats/html/residuals)`, `[coef](../../stats/html/coef)`, `[fitted](../../stats/html/fitted.values)`, `<fixed.effects>`, and `<random.effects>` can be used to extract some of its components. ### Note The function does not do any scaling internally: the optimization will work best when the response is scaled so its variance is of the order of one. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References The computational methods follow the general framework of Lindstrom and Bates (1988). The model formulation is described in Laird and Ware (1982). The variance-covariance parametrizations are described in Pinheiro and Bates (1996). The different correlation structures available for the `correlation` argument are described in Box, Jenkins and Reinsel (1994), Littell *et al* (1996), and Venables and Ripley (2002). The use of variance functions for linear and nonlinear mixed effects models is presented in detail in Davidian and Giltinan (1995). Box, G.E.P., Jenkins, G.M., and Reinsel G.C. (1994) "Time Series Analysis: Forecasting and Control", 3rd Edition, Holden–Day. Davidian, M. and Giltinan, D.M. (1995) "Nonlinear Mixed Effects Models for Repeated Measurement Data", Chapman and Hall. Laird, N.M. and Ware, J.H. (1982) "Random-Effects Models for Longitudinal Data", Biometrics, 38, 963–974. Lindstrom, M.J. and Bates, D.M. (1988) "Newton-Raphson and EM Algorithms for Linear Mixed-Effects Models for Repeated-Measures Data", Journal of the American Statistical Association, 83, 1014–1022. Littell, R.C., Milliken, G.A., Stroup, W.W., and Wolfinger, R.D. (1996) "SAS Systems for Mixed Models", SAS Institute. Pinheiro, J.C. and Bates., D.M. (1996) "Unconstrained Parametrizations for Variance-Covariance Matrices", Statistics and Computing, 6, 289–296. Pinheiro, J.C., and Bates, D.M. (2000) "Mixed-Effects Models in S and S-PLUS", Springer. Venables, W.N. and Ripley, B.D. (2002) "Modern Applied Statistics with S", 4th Edition, Springer-Verlag. ### See Also `[corClasses](corclasses)`, `[lme.lmList](lme.lmlist)`, `[lme.groupedData](lme.groupeddata)`, `[lmeControl](lmecontrol)`, `[lmeObject](lmeobject)`, `[lmeStruct](lmestruct)`, `[lmList](lmlist)`, `[pdClasses](pdclasses)`, `<plot.lme>`, `<predict.lme>`, `<qqnorm.lme>`, `<residuals.lme>`, `[reStruct](restruct)`, `<simulate.lme>`, `<summary.lme>`, `[varClasses](varclasses)`, `[varFunc](varfunc)` ### Examples ``` fm1 <- lme(distance ~ age, data = Orthodont) # random is ~ age fm2 <- lme(distance ~ age + Sex, data = Orthodont, random = ~ 1) summary(fm1) summary(fm2) ``` r None `Fatigue` Cracks caused by metal fatigue ----------------------------------------- ### Description The `Fatigue` data frame has 262 rows and 3 columns. ### Format This data frame contains the following columns: Path an ordered factor with levels `1` < `2` < `3` < `4` < `5` < `6` < `7` < `8` < `9` < `10` < `11` < `12` < `13` < `14` < `15` < `16` < `17` < `18` < `19` < `20` < `21` giving the test path (or test unit) number. The order is in terms of increasing failure time or decreasing terminal crack length. cycles number of test cycles at which the measurement is made (millions of cycles). relLength relative crack length (dimensionless). ### Details These data are given in Lu and Meeker (1993) where they state “We obtained the data in Table 1 visually from figure 4.5.2 on page 242 of Bogdanoff and Kozin (1985).” The data represent the growth of cracks in metal for 21 test units. An initial notch of length 0.90 inches was made on each unit which then was subjected to several thousand test cycles. After every 10,000 test cycles the crack length was measured. Testing was stopped if the crack length exceeded 1.60 inches, defined as a failure, or at 120,000 cycles. ### Source Lu, C. Joséph , and Meeker, William Q. (1993), Using degradation measures to estimate a time-to-failure distribution, *Technometrics*, **35**, 161-174
programming_docs
r None `as.matrix.corStruct` Matrix of a corStruct Object --------------------------------------------------- ### Description This method function extracts the correlation matrix, or list of correlation matrices, associated with `object`. ### Usage ``` ## S3 method for class 'corStruct' as.matrix(x, ...) ``` ### Arguments | | | | --- | --- | | `x` | an object inheriting from class `"[corStruct](corclasses)"`, representing a correlation structure. | | `...` | further arguments passed from other methods. | ### Value If the correlation structure includes a grouping factor, the returned value will be a list with components given by the correlation matrices for each group. Otherwise, the returned value will be a matrix representing the correlation structure associated with `object`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Pinheiro, J. C. and Bates, D. M. (2000), *Mixed-Effects Models in S and S-PLUS*, Springer, New York. ### See Also `[corClasses](corclasses)`, `[corMatrix](cormatrix)` ### Examples ``` cst1 <- corAR1(form = ~1|Subject) cst1 <- Initialize(cst1, data = Orthodont) as.matrix(cst1) ``` r None `splitFormula` Split a Formula ------------------------------- ### Description Splits the right hand side of `form` into a list of subformulas according to the presence of `sep`. The left hand side of `form`, if present, will be ignored. The length of the returned list will be equal to the number of occurrences of `sep` in `form` plus one. ### Usage ``` splitFormula(form, sep) ``` ### Arguments | | | | --- | --- | | `form` | a `formula` object. | | `sep` | an optional character string specifying the separator to be used for splitting the formula. Defaults to `"/"`. | ### Value a list of formulas, corresponding to the split of `form` according to `sep`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[formula](../../stats/html/formula)` ### Examples ``` splitFormula(~ g1/g2/g3) ``` r None `logDet.reStruct` Extract reStruct Log-Determinants ---------------------------------------------------- ### Description Calculates, for each of the `pdMat` components of `object`, the logarithm of the determinant of a square-root factor. ### Usage ``` ## S3 method for class 'reStruct' logDet(object, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"[reStruct](restruct)"`, representing a random effects structure and consisting of a list of `pdMat` objects. | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value a vector with the log-determinants of square-root factors of the `pdMat` components of `object`. ### Author(s) José Pinheiro ### See Also `[reStruct](restruct)`, `[pdMat](pdmat)`, `[logDet](logdet)` ### Examples ``` rs1 <- reStruct(list(A = pdSymm(diag(1:3), form = ~Score), B = pdDiag(2 * diag(4), form = ~Educ))) logDet(rs1) ``` r None `Earthquake` Earthquake Intensity ---------------------------------- ### Description The `Earthquake` data frame has 182 rows and 5 columns. ### Format This data frame contains the following columns: Quake an ordered factor with levels `20` < `16` < `14` < `10` < `3` < `8` < `23` < `22` < `6` < `13` < `7` < `21` < `18` < `15` < `4` < `12` < `19` < `5` < `9` < `1` < `2` < `17` < `11` indicating the earthquake on which the measurements were made. Richter a numeric vector giving the intensity of the earthquake on the Richter scale. distance the distance from the seismological measuring station to the epicenter of the earthquake (km). soil a factor with levels `0` and `1` giving the soil condition at the measuring station, either soil or rock. accel maximum horizontal acceleration observed (g). ### Details Measurements recorded at available seismometer locations for 23 large earthquakes in western North America between 1940 and 1980. They were originally given in Joyner and Boore (1981); are mentioned in Brillinger (1987); and are analyzed in Davidian and Giltinan (1995). ### Source Pinheiro, J. C. and Bates, D. M. (2000), *Mixed-Effects Models in S and S-PLUS*, Springer, New York. (Appendix A.8) Davidian, M. and Giltinan, D. M. (1995), *Nonlinear Models for Repeated Measurement Data*, Chapman and Hall, London. Joyner and Boore (1981), Peak horizontal acceleration and velocity from strong-motion records including records from the 1979 Imperial Valley, California, earthquake, *Bulletin of the Seismological Society of America*, **71**, 2011-2038. Brillinger, D. (1987), Comment on a paper by C. R. Rao, *Statistical Science*, **2**, 448-450. r None `Matrix.reStruct` Assign reStruct Matrices ------------------------------------------- ### Description The individual matrices in `value` are assigned to each `pdMat` component of `object`, in the order they are listed. The new matrices must have the same dimensions as the matrices they are meant to replace. ### Usage ``` ## S3 replacement method for class 'reStruct' matrix(object) <- value ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"[reStruct](restruct)"`, representing a random effects structure and consisting of a list of `pdMat` objects. | | `value` | a matrix, or list of matrices, with the new values to be assigned to the matrices associated with the `pdMat` components of `object`. | ### Value an `reStruct` object similar to `object`, but with the coefficients of the individual `pdMat` components modified to produce the matrices listed in `value`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[reStruct](restruct)`, `[pdMat](pdmat)`, `"[matrix<-](matrix)"` ### Examples ``` rs1 <- reStruct(list(Dog = ~day, Side = ~1), data = Pixel) matrix(rs1) <- list(diag(2), 3) ``` r None `getResponse` Extract Response Variable from an Object ------------------------------------------------------- ### Description This function is generic; method functions can be written to handle specific classes of objects. Classes which already have methods for this function include `data.frame`, `gls`, `lme`, and `lmList`. ### Usage ``` getResponse(object, form) ``` ### Arguments | | | | --- | --- | | `object` | any object | | `form` | an optional two-sided formula. Defaults to `formula(object)`. | ### Value will depend on the method function used; see the appropriate documentation. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[getResponseFormula](getresponseformula)` ### Examples ``` getResponse(Orthodont) ``` r None `residuals.glsStruct` Calculate glsStruct Residuals ---------------------------------------------------- ### Description The residuals for the linear model represented by `object` are extracted. ### Usage ``` ## S3 method for class 'glsStruct' residuals(object, glsFit, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"[glsStruct](glsstruct)"`, representing a list of linear model components, such as `corStruct` and `"[varFunc](varfunc)"` objects. | | `glsFit` | an optional list with components `logLik` (log-likelihood), `beta` (coefficients), `sigma` (standard deviation for error term), `varBeta` (coefficients' covariance matrix), `fitted` (fitted values), and `residuals` (residuals). Defaults to `attr(object, "glsFit")`. | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value a vector with the residuals for the linear model represented by `object`. ### Note This method function is primarily used inside `gls` and `residuals.gls`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `<gls>`, `[glsStruct](glsstruct)`, `<residuals.gls>`, `[fitted.glsStruct](fitted.glsstruct)` r None `gapply` Apply a Function by Groups ------------------------------------ ### Description Applies the function to the distinct sets of rows of the data frame defined by `groups`. ### Usage ``` gapply(object, which, FUN, form, level, groups, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object to which the function will be applied - usually a `groupedData` object or a `data.frame`. Must inherit from class `"data.frame"`. | | `which` | an optional character or positive integer vector specifying which columns of `object` should be used with `FUN`. Defaults to all columns in `object`. | | `FUN` | function to apply to the distinct sets of rows of the data frame `object` defined by the values of `groups`. | | `form` | an optional one-sided formula that defines the groups. When this formula is given the right-hand side is evaluated in `object`, converted to a factor if necessary, and the unique levels are used to define the groups. Defaults to `formula(object)`. | | `level` | an optional positive integer giving the level of grouping to be used in an object with multiple nested grouping levels. Defaults to the highest or innermost level of grouping. | | `groups` | an optional factor that will be used to split the rows into groups. Defaults to `getGroups(object, form, level)`. | | `...` | optional additional arguments to the summary function `FUN`. Often it is helpful to specify `na.rm = TRUE`. | ### Value Returns a data frame with as many rows as there are levels in the `groups` argument. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Pinheiro, J.C., and Bates, D.M. (2000) "Mixed-Effects Models in S and S-PLUS", Springer, esp. sec. 3.4. ### See Also `<gsummary>` ### Examples ``` ## Find number of non-missing "conc" observations for each Subject gapply( Phenobarb, FUN = function(x) sum(!is.na(x$conc)) ) # Pinheiro and Bates, p. 127 table( gapply(Quinidine, "conc", function(x) sum(!is.na(x))) ) changeRecords <- gapply( Quinidine, FUN = function(frm) any(is.na(frm[["conc"]]) & is.na(frm[["dose"]])) ) ``` r None `intervals` Confidence Intervals on Coefficients ------------------------------------------------- ### Description Confidence intervals on the parameters associated with the model represented by `object` are obtained. This function is generic; method functions can be written to handle specific classes of objects. Classes which already have methods for this function include: `gls`, `lme`, and `lmList`. ### Usage ``` intervals(object, level, ...) ``` ### Arguments | | | | --- | --- | | `object` | a fitted model object from which parameter estimates can be extracted. | | `level` | an optional numeric value for the interval confidence level. Defaults to 0.95. | | `...` | some methods for the generic may require additional arguments. | ### Value will depend on the method function used; see the appropriate documentation. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Pinheiro, J.C., and Bates, D.M. (2000) "Mixed-Effects Models in S and S-PLUS", Springer. ### See Also `<intervals.lme>`, `[intervals.lmList](intervals.lmlist)`, `<intervals.gls>` ### Examples ``` ## see the method documentation ``` r None `getCovariateFormula` Extract Covariates Formula ------------------------------------------------- ### Description The right hand side of `formula(object)`, without any conditioning expressions (i.e. any expressions after a `|` operator) is returned as a one-sided formula. ### Usage ``` getCovariateFormula(object) ``` ### Arguments | | | | --- | --- | | `object` | any object from which a formula can be extracted. | ### Value a one-sided formula describing the covariates associated with `formula(object)`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[getCovariate](getcovariate)` ### Examples ``` getCovariateFormula(y ~ x | g) getCovariateFormula(y ~ x) ``` r None `Variogram.corRatio` Calculate Semi-variogram for a corRatio Object -------------------------------------------------------------------- ### Description This method function calculates the semi-variogram values corresponding to the Rational Quadratic correlation model, using the estimated coefficients corresponding to `object`, at the distances defined by `distance`. ### Usage ``` ## S3 method for class 'corRatio' Variogram(object, distance, sig2, length.out, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"[corRatio](corratio)"`, representing an Rational Quadratic spatial correlation structure. | | `distance` | an optional numeric vector with the distances at which the semi-variogram is to be calculated. Defaults to `NULL`, in which case a sequence of length `length.out` between the minimum and maximum values of `getCovariate(object)` is used. | | `sig2` | an optional numeric value representing the process variance. Defaults to `1`. | | `length.out` | an optional integer specifying the length of the sequence of distances to be used for calculating the semi-variogram, when `distance = NULL`. Defaults to `50`. | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value a data frame with columns `variog` and `dist` representing, respectively, the semi-variogram values and the corresponding distances. The returned value inherits from class `Variogram`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Cressie, N.A.C. (1993), "Statistics for Spatial Data", J. Wiley & Sons. ### See Also `[corRatio](corratio)`, `[plot.Variogram](plot.variogram)` `[Variogram](variogram)` ### Examples ``` cs1 <- corRatio(7, form = ~ Time | Rat) cs1 <- Initialize(cs1, BodyWeight) Variogram(cs1)[1:10,] ``` r None `getGroupsFormula` Extract Grouping Formula -------------------------------------------- ### Description The conditioning expression associated with `formula(object)` (i.e. the expression after the `|` operator) is returned either as a named list of one-sided formulas, or a single one-sided formula, depending on the value of `asList`. The components of the returned list are ordered from outermost to innermost level and are named after the grouping factor expression. ### Usage ``` getGroupsFormula(object, asList, sep) ``` ### Arguments | | | | --- | --- | | `object` | any object from which a formula can be extracted. | | `asList` | an optional logical value. If `TRUE` the returned value with be a list of formulas; else, if `FALSE` the returned value will be a one-sided formula. Defaults to `FALSE`. | | `sep` | character, the separator to use between group levels when multiple levels are collapsed. The default is `'/'`. | ### Value a one-sided formula, or a list of one-sided formulas, with the grouping structure associated with `formula(object)`. If no conditioning expression is present in `formula(object)` a `NULL` value is returned. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[getGroupsFormula.gls](getgroupsformula)`, `[getGroupsFormula.lmList](getgroupsformula)`, `[getGroupsFormula.lme](getgroupsformula)`, `[getGroupsFormula.reStruct](getgroupsformula)`, `[getGroups](getgroups)` ### Examples ``` getGroupsFormula(y ~ x | g1/g2) ``` r None `plot.lme` Plot an lme or nls object ------------------------------------- ### Description Diagnostic plots for the linear mixed-effects fit are obtained. The `form` argument gives considerable flexibility in the type of plot specification. A conditioning expression (on the right side of a `|` operator) always implies that different panels are used for each level of the conditioning factor, according to a Trellis display. If `form` is a one-sided formula, histograms of the variable on the right hand side of the formula, before a `|` operator, are displayed (the Trellis function `histogram` is used). If `form` is two-sided and both its left and right hand side variables are numeric, scatter plots are displayed (the Trellis function `xyplot` is used). Finally, if `form` is two-sided and its left had side variable is a factor, box-plots of the right hand side variable by the levels of the left hand side variable are displayed (the Trellis function `bwplot` is used). ### Usage ``` ## S3 method for class 'lme' plot(x, form, abline, id, idLabels, idResType, grid, ...) ## S3 method for class 'nls' plot(x, form, abline, id, idLabels, idResType, grid, ...) ``` ### Arguments | | | | --- | --- | | `x` | an object inheriting from class `"<lme>"`, representing a fitted linear mixed-effects model, or from `nls`, representing an fitted nonlinear least squares model. | | `form` | an optional formula specifying the desired type of plot. Any variable present in the original data frame used to obtain `x` can be referenced. In addition, `x` itself can be referenced in the formula using the symbol `"."`. Conditional expressions on the right of a `|` operator can be used to define separate panels in a Trellis display. Default is `resid(., type = "p") ~ fitted(.)` , corresponding to a plot of the standardized residuals versus fitted values, both evaluated at the innermost level of nesting. | | `abline` | an optional numeric value, or numeric vector of length two. If given as a single value, a horizontal line will be added to the plot at that coordinate; else, if given as a vector, its values are used as the intercept and slope for a line added to the plot. If missing, no lines are added to the plot. | | `id` | an optional numeric value, or one-sided formula. If given as a value, it is used as a significance level for a two-sided outlier test for the standardized, or normalized residuals. Observations with absolute standardized (normalized) residuals greater than the *1 - value/2* quantile of the standard normal distribution are identified in the plot using `idLabels`. If given as a one-sided formula, its right hand side must evaluate to a logical, integer, or character vector which is used to identify observations in the plot. If missing, no observations are identified. | | `idLabels` | an optional vector, or one-sided formula. If given as a vector, it is converted to character and used to label the observations identified according to `id`. If given as a one-sided formula, its right hand side must evaluate to a vector which is converted to character and used to label the identified observations. Default is the innermost grouping factor. | | `idResType` | an optional character string specifying the type of residuals to be used in identifying outliers, when `id` is a numeric value. If `"pearson"`, the standardized residuals (raw residuals divided by the corresponding standard errors) are used; else, if `"normalized"`, the normalized residuals (standardized residuals pre-multiplied by the inverse square-root factor of the estimated error correlation matrix) are used. Partial matching of arguments is used, so only the first character needs to be provided. Defaults to `"pearson"`. | | `grid` | an optional logical value indicating whether a grid should be added to plot. Default depends on the type of Trellis plot used: if `xyplot` defaults to `TRUE`, else defaults to `FALSE`. | | `...` | optional arguments passed to the Trellis plot function. | ### Value a diagnostic Trellis plot. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `<lme>`, `[xyplot](../../lattice/html/xyplot)`, `[bwplot](../../lattice/html/xyplot)`, `[histogram](../../lattice/html/histogram)` ### Examples ``` fm1 <- lme(distance ~ age, Orthodont, random = ~ age | Subject) # standardized residuals versus fitted values by gender plot(fm1, resid(., type = "p") ~ fitted(.) | Sex, abline = 0) # box-plots of residuals by Subject plot(fm1, Subject ~ resid(.)) # observed versus fitted values by Subject plot(fm1, distance ~ fitted(.) | Subject, abline = c(0,1)) ```
programming_docs
r None `fitted.lmeStruct` Calculate lmeStruct Fitted Values ----------------------------------------------------- ### Description The fitted values at level *i* are obtained by adding together the population fitted values (based only on the fixed effects estimates) and the estimated contributions of the random effects to the fitted values at grouping levels less or equal to *i*. The resulting values estimate the best linear unbiased predictions (BLUPs) at level *i*. ### Usage ``` ## S3 method for class 'lmeStruct' fitted(object, level, conLin, lmeFit, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"[lmeStruct](lmestruct)"`, representing a list of linear mixed-effects model components, such as `reStruct`, `corStruct`, and `varFunc` objects. | | `level` | an optional integer vector giving the level(s) of grouping to be used in extracting the fitted values from `object`. Level values increase from outermost to innermost grouping, with level zero corresponding to the population fitted values. Defaults to the highest or innermost level of grouping. | | `conLin` | an optional condensed linear model object, consisting of a list with components `"Xy"`, corresponding to a regression matrix (`X`) combined with a response vector (`y`), and `"logLik"`, corresponding to the log-likelihood of the underlying lme model. Defaults to `attr(object, "conLin")`. | | `lmeFit` | an optional list with components `beta` and `b` containing respectively the fixed effects estimates and the random effects estimates to be used to calculate the fitted values. Defaults to `attr(object, "lmeFit")`. | | `...` | some methods for this generic accept other optional arguments. | ### Value if a single level of grouping is specified in `level`, the returned value is a vector with the fitted values at the desired level; else, when multiple grouping levels are specified in `level`, the returned object is a matrix with columns given by the fitted values at different levels. ### Note This method function is generally only used inside `lme` and `fitted.lme`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `<lme>`, `<fitted.lme>`, `[residuals.lmeStruct](residuals.lmestruct)` r None `varClasses` Variance Function Classes --------------------------------------- ### Description Standard classes of variance function structures (`varFunc`) available in the `nlme` package. Covariates included in the variance function, denoted by variance covariates, may involve functions of the fitted model object, such as the fitted values and the residuals. Different coefficients may be assigned to the levels of a classification factor. ### Value Available standard classes: | | | | --- | --- | | `varExp` | exponential of a variance covariate. | | `varPower` | power of a variance covariate. | | `varConstPower` | constant plus power of a variance covariate. | | `varConstProp` | constant plus proportion of a variance covariate. | | `varIdent` | constant variance(s), generally used to allow different variances according to the levels of a classification factor. | | `varFixed` | fixed weights, determined by a variance covariate. | | `varComb` | combination of variance functions. | ### Note Users may define their own `varFunc` classes by specifying a `constructor` function and, at a minimum, methods for the functions `coef`, `coef<-`, and `initialize`. For examples of these functions, see the methods for class `varPower`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Pinheiro, J.C., and Bates, D.M. (2000) "Mixed-Effects Models in S and S-PLUS", Springer. ### See Also `[varComb](varcomb)`, `[varConstPower](varconstpower)`, `[varConstProp](varconstprop)`, `[varExp](varexp)`, `[varFixed](varfixed)`, `[varIdent](varident)`, `[varPower](varpower)`, `[summary.varFunc](summary.varfunc)` r None `pooledSD` Extract Pooled Standard Deviation --------------------------------------------- ### Description The pooled estimated standard deviation is obtained by adding together the residual sum of squares for each non-null element of `object`, dividing by the sum of the corresponding residual degrees-of-freedom, and taking the square-root. ### Usage ``` pooledSD(object) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `lmList`. | ### Value the pooled standard deviation for the non-null elements of `object`, with an attribute `df` with the number of degrees-of-freedom used in the estimation. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[lmList](lmlist)`, `[lm](../../stats/html/lm)` ### Examples ``` fm1 <- lmList(Orthodont) pooledSD(fm1) ``` r None `Gun` Methods for firing naval guns ------------------------------------ ### Description The `Gun` data frame has 36 rows and 4 columns. ### Format This data frame contains the following columns: rounds a numeric vector Method a factor with levels `M1` `M2` Team an ordered factor with levels `T1S` < `T3S` < `T2S` < `T1A` < `T2A` < `T3A` < `T1H` < `T3H` < `T2H` Physique an ordered factor with levels `Slight` < `Average` < `Heavy` ### Details Hicks (p.180, 1993) reports data from an experiment on methods for firing naval guns. Gunners of three different physiques (slight, average, and heavy) tested two firing methods. Both methods were tested twice by each of nine teams of three gunners with identical physique. The response was the number of rounds fired per minute. ### Source Hicks, C. R. (1993), *Fundamental Concepts in the Design of Experiments (4th ed)*, Harcourt Brace, New York. r None `residuals.gnlsStruct` Calculate gnlsStruct Residuals ------------------------------------------------------ ### Description The residuals for the nonlinear model represented by `object` are extracted. ### Usage ``` ## S3 method for class 'gnlsStruct' residuals(object, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"[gnlsStruct](gnlsstruct)"`, representing a list of model components, such as `corStruct` and `varFunc` objects, and attributes specifying the underlying nonlinear model and the response variable. | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value a vector with the residuals for the nonlinear model represented by `object`. ### Note This method function is primarily used inside `gnls` and `residuals.gnls`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `<gnls>`, `[residuals.gnls](residuals.gls)`, `[fitted.gnlsStruct](fitted.gnlsstruct)` r None `summary.pdMat` Summarize a pdMat Object ----------------------------------------- ### Description Attributes `structName` and `noCorrelation`, with the values of the corresponding arguments to the method function, are appended to `object` and its class is changed to `summary.pdMat`. ### Usage ``` ## S3 method for class 'pdMat' summary(object, structName, noCorrelation, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"[pdMat](pdmat)"`, representing a positive definite matrix. | | `structName` | an optional character string with a description of the `pdMat` class. Default depends on the method function: `"Blocked"` for `pdBlocked`, `"Compound Symmetry"` for `pdCompSymm`, `"Diagonal"` for `pdDiag`, `"Multiple of an Identity"` for `pdIdent`, `"General Positive-Definite, Natural Parametrization"` for `pdNatural`, `"General Positive-Definite"` for `pdSymm`, and `data.class(object)` for `pdMat`. | | `noCorrelation` | an optional logical value indicating whether correlations are to be printed in `print.summary.pdMat`. Default depends on the method function: `FALSE` for `pdDiag` and `pdIdent`, and `TRUE` for all other classes. | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value an object similar to `object`, with additional attributes `structName` and `noCorrelation`, inheriting from class `summary.pdMat`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[print.summary.pdMat](print.summary.pdmat)`, `[pdMat](pdmat)` ### Examples ``` summary(pdSymm(diag(4))) ``` r None `fixed.effects` Extract Fixed Effects -------------------------------------- ### Description This function is generic; method functions can be written to handle specific classes of objects. Classes which already have methods for this function include `lmList` and `lme`. ### Usage ``` fixed.effects(object, ...) fixef(object, ...) ``` ### Arguments | | | | --- | --- | | `object` | any fitted model object from which fixed effects estimates can be extracted. | | `...` | some methods for this generic function require additional arguments. | ### Value will depend on the method function used; see the appropriate documentation. ### References Pinheiro, J.C., and Bates, D.M. (2000) "Mixed-Effects Models in S and S-PLUS", Springer. ### See Also `[fixef.lmList](fixef.lmlist)` ### Examples ``` ## see the method function documentation ``` r None `varPower` Power Variance Function ----------------------------------- ### Description This function is a constructor for the `varPower` class, representing a power variance function structure. Letting *v* denote the variance covariate and *s2(v)* denote the variance function evaluated at *v*, the power variance function is defined as *s2(v) = |v|^(2\*t)*, where *t* is the variance function coefficient. When a grouping factor is present, a different *t* is used for each factor level. ### Usage ``` varPower(value, form, fixed) ``` ### Arguments | | | | --- | --- | | `value` | an optional numeric vector, or list of numeric values, with the variance function coefficients. `Value` must have length one, unless a grouping factor is specified in `form`. If `value` has length greater than one, it must have names which identify its elements to the levels of the grouping factor defined in `form`. If a grouping factor is present in `form` and `value` has length one, its value will be assigned to all grouping levels. Default is `numeric(0)`, which results in a vector of zeros of appropriate length being assigned to the coefficients when `object` is initialized (corresponding to constant variance equal to one). | | `form` | an optional one-sided formula of the form `~ v`, or `~ v | g`, specifying a variance covariate `v` and, optionally, a grouping factor `g` for the coefficients. The variance covariate must evaluate to a numeric vector and may involve expressions using `"."`, representing a fitted model object from which fitted values (`fitted(.)`) and residuals (`resid(.)`) can be extracted (this allows the variance covariate to be updated during the optimization of an object function). When a grouping factor is present in `form`, a different coefficient value is used for each of its levels. Several grouping variables may be simultaneously specified, separated by the `*` operator, like in `~ v | g1 * g2 * g3`. In this case, the levels of each grouping variable are pasted together and the resulting factor is used to group the observations. Defaults to `~ fitted(.)` representing a variance covariate given by the fitted values of a fitted model object and no grouping factor. | | `fixed` | an optional numeric vector, or list of numeric values, specifying the values at which some or all of the coefficients in the variance function should be fixed. If a grouping factor is specified in `form`, `fixed` must have names identifying which coefficients are to be fixed. Coefficients included in `fixed` are not allowed to vary during the optimization of an objective function. Defaults to `NULL`, corresponding to no fixed coefficients. | ### Value a `varPower` object representing a power variance function structure, also inheriting from class `varFunc`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Pinheiro, J.C., and Bates, D.M. (2000) "Mixed-Effects Models in S and S-PLUS", Springer. ### See Also `[varWeights.varFunc](varweights)`, `[coef.varPower](coef.varfunc)` ### Examples ``` vf1 <- varPower(0.2, form = ~age|Sex) ``` r None `corARMA` ARMA(p,q) Correlation Structure ------------------------------------------ ### Description This function is a constructor for the `corARMA` class, representing an autocorrelation-moving average correlation structure of order (p, q). Objects created using this constructor must later be initialized using the appropriate `Initialize` method. ### Usage ``` corARMA(value, form, p, q, fixed) ``` ### Arguments | | | | --- | --- | | `value` | a vector with the values of the autoregressive and moving average parameters, which must have length `p + q` and all elements between -1 and 1. Defaults to a vector of zeros, corresponding to uncorrelated observations. | | `form` | a one sided formula of the form `~ t`, or `~ t | g`, specifying a time covariate `t` and, optionally, a grouping factor `g`. A covariate for this correlation structure must be integer valued. When a grouping factor is present in `form`, the correlation structure is assumed to apply only to observations within the same grouping level; observations with different grouping levels are assumed to be uncorrelated. Defaults to `~ 1`, which corresponds to using the order of the observations in the data as a covariate, and no groups. | | `p, q` | non-negative integers specifying respectively the autoregressive order and the moving average order of the `ARMA` structure. Both default to 0. | | `fixed` | an optional logical value indicating whether the coefficients should be allowed to vary in the optimization, or kept fixed at their initial value. Defaults to `FALSE`, in which case the coefficients are allowed to vary. | ### Value an object of class `corARMA`, representing an autocorrelation-moving average correlation structure. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Box, G.E.P., Jenkins, G.M., and Reinsel G.C. (1994) "Time Series Analysis: Forecasting and Control", 3rd Edition, Holden-Day. Pinheiro, J.C., and Bates, D.M. (2000) "Mixed-Effects Models in S and S-PLUS", Springer, esp. pp. 236, 397. ### See Also `[corAR1](corar1)`, `[corClasses](corclasses)` `[Initialize.corStruct](initialize.corstruct)`, `[summary.corStruct](summary.corstruct)` ### Examples ``` ## ARMA(1,2) structure, with observation order as a covariate and ## Mare as grouping factor cs1 <- corARMA(c(0.2, 0.3, -0.1), form = ~ 1 | Mare, p = 1, q = 2) # Pinheiro and Bates, p. 237 cs1ARMA <- corARMA(0.4, form = ~ 1 | Subject, q = 1) cs1ARMA <- Initialize(cs1ARMA, data = Orthodont) corMatrix(cs1ARMA) cs2ARMA <- corARMA(c(0.8, 0.4), form = ~ 1 | Subject, p=1, q=1) cs2ARMA <- Initialize(cs2ARMA, data = Orthodont) corMatrix(cs2ARMA) # Pinheiro and Bates use in nlme: # from p. 240 needed on p. 396 fm1Ovar.lme <- lme(follicles ~ sin(2*pi*Time) + cos(2*pi*Time), data = Ovary, random = pdDiag(~sin(2*pi*Time))) fm5Ovar.lme <- update(fm1Ovar.lme, corr = corARMA(p = 1, q = 1)) # p. 396 fm1Ovar.nlme <- nlme(follicles~ A+B*sin(2*pi*w*Time)+C*cos(2*pi*w*Time), data=Ovary, fixed=A+B+C+w~1, random=pdDiag(A+B+w~1), start=c(fixef(fm5Ovar.lme), 1) ) # p. 397 fm3Ovar.nlme <- update(fm1Ovar.nlme, corr=corARMA(p=0, q=2) ) ``` r None `predict.gnls` Predictions from a gnls Object ---------------------------------------------- ### Description The predictions for the nonlinear model represented by `object` are obtained at the covariate values defined in `newdata`. ### Usage ``` ## S3 method for class 'gnls' predict(object, newdata, na.action, naPattern, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"<gnls>"`, representing a generalized nonlinear least squares fitted model. | | `newdata` | an optional data frame to be used for obtaining the predictions. All variables used in the nonlinear model must be present in the data frame. If missing, the fitted values are returned. | | `na.action` | a function that indicates what should happen when `newdata` contains `NA`s. The default action (`na.fail`) causes the function to print an error message and terminate if there are any incomplete observations. | | `naPattern` | an expression or formula object, specifying which returned values are to be regarded as missing. | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value a vector with the predicted values. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `<gnls>` ### Examples ``` fm1 <- gnls(weight ~ SSlogis(Time, Asym, xmid, scal), Soybean, weights = varPower()) newSoybean <- data.frame(Time = c(10,30,50,80,100)) predict(fm1, newSoybean) ``` r None `varWeights.lmeStruct` Variance Weights for lmeStruct Object ------------------------------------------------------------- ### Description If `object` includes a `varStruct` component, the inverse of the standard deviations of the variance function structure represented by the corresponding `varFunc` object are returned; else, a vector of ones of length equal to the number of observations in the data frame used to fit the associated linear mixed-effects model is returned. ### Usage ``` ## S3 method for class 'lmeStruct' varWeights(object) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"[lmeStruct](lmestruct)"`, representing a list of linear mixed-effects model components, such as `reStruct`, `corStruct`, and `varFunc` objects. | ### Value if `object` includes a `varStruct` component, a vector with the corresponding variance weights; else, or a vector of ones. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Pinheiro, J.C., and Bates, D.M. (2000) "Mixed-Effects Models in S and S-PLUS", Springer. ### See Also `[varWeights](varweights)` r None `ergoStool` Ergometrics experiment with stool types ---------------------------------------------------- ### Description The `ergoStool` data frame has 36 rows and 3 columns. ### Format This data frame contains the following columns: effort a numeric vector giving the effort (Borg scale) required to arise from a stool. Type a factor with levels `T1`, `T2`, `T3`, and `T4` giving the stool type. Subject an ordered factor giving a unique identifier for the subject in the experiment. ### Details Devore (2000) cites data from an article in *Ergometrics* (1993, pp. 519-535) on “The Effects of a Pneumatic Stool and a One-Legged Stool on Lower Limb Joint Load and Muscular Activity.” ### Source Pinheiro, J. C. and Bates, D. M. (2000), *Mixed-Effects Models in S and S-PLUS*, Springer, New York. (Appendix A.9) Devore, J. L. (2000), *Probability and Statistics for Engineering and the Sciences (5th ed)*, Duxbury, Boston, MA. ### Examples ``` fm1 <- lme(effort ~ Type, data = ergoStool, random = ~ 1 | Subject) anova( fm1 ) ``` r None `qqnorm.lme` Normal Plot of Residuals or Random Effects from an lme Object --------------------------------------------------------------------------- ### Description Diagnostic plots for assessing the normality of residuals and random effects in the linear mixed-effects fit are obtained. The `form` argument gives considerable flexibility in the type of plot specification. A conditioning expression (on the right side of a `|` operator) always implies that different panels are used for each level of the conditioning factor, according to a Trellis display. ### Usage ``` ## S3 method for class 'lme' qqnorm(y, form, abline, id, idLabels, grid, ...) ``` ### Arguments | | | | --- | --- | | `y` | an object inheriting from class `"<lme>"`, representing a fitted linear mixed-effects model or from class `"[lmList](lmlist)"`, representing a list of `lm` objects, or from class `"lm"`, representing a fitted linear model, or from class `"nls"`, representing a nonlinear least squares fitted model. | | `form` | an optional one-sided formula specifying the desired type of plot. Any variable present in the original data frame used to obtain `y` can be referenced. In addition, `y` itself can be referenced in the formula using the symbol `"."`. Conditional expressions on the right of a `|` operator can be used to define separate panels in a Trellis display. The expression on the right hand side of `form` and to the left of a `|` operator must evaluate to a residuals vector, or a random effects matrix. Default is `~ resid(., type = "p")`, corresponding to a normal plot of the standardized residuals evaluated at the innermost level of nesting. | | `abline` | an optional numeric value, or numeric vector of length two. If given as a single value, a horizontal line will be added to the plot at that coordinate; else, if given as a vector, its values are used as the intercept and slope for a line added to the plot. If missing, no lines are added to the plot. | | `id` | an optional numeric value, or one-sided formula. If given as a value, it is used as a significance level for a two-sided outlier test for the standardized residuals (random effects). Observations with absolute standardized residuals (random effects) greater than the *1 - value/2* quantile of the standard normal distribution are identified in the plot using `idLabels`. If given as a one-sided formula, its right hand side must evaluate to a logical, integer, or character vector which is used to identify observations in the plot. If missing, no observations are identified. | | `idLabels` | an optional vector, or one-sided formula. If given as a vector, it is converted to character and used to label the observations identified according to `id`. If given as a one-sided formula, its right hand side must evaluate to a vector which is converted to character and used to label the identified observations. Default is the innermost grouping factor. | | `grid` | an optional logical value indicating whether a grid should be added to plot. Default is `FALSE`. | | `...` | optional arguments passed to the Trellis plot function. | ### Value a diagnostic Trellis plot for assessing normality of residuals or random effects. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `<lme>`, `<plot.lme>` ### Examples ``` fm1 <- lme(distance ~ age, Orthodont, random = ~ age | Subject) ## normal plot of standardized residuals by gender qqnorm(fm1, ~ resid(., type = "p") | Sex, abline = c(0, 1)) ## normal plots of random effects qqnorm(fm1, ~ranef(.)) ```
programming_docs
r None `nlmeObject` Fitted nlme Object -------------------------------- ### Description An object returned by the `<nlme>` function, inheriting from class `"nlme"`, also inheriting from class `"lme"`, and representing a fitted nonlinear mixed-effects model. Objects of this class have methods for the generic functions `anova`, `coef`, `fitted`, `fixed.effects`, `formula`, `getGroups`, `getResponse`, `intervals`, `logLik`, `pairs`, `plot`, `predict`, `print`, `random.effects`, `residuals`, `summary`, and `update`. ### Value The following components must be included in a legitimate `"nlme"` object. | | | | --- | --- | | `apVar` | an approximate covariance matrix for the variance-covariance coefficients. If `apVar = FALSE` in the control values used in the call to `nlme`, this component is `NULL`. | | `call` | a list containing an image of the `nlme` call that produced the object. | | `coefficients` | a list with two components, `fixed` and `random`, where the first is a vector containing the estimated fixed effects and the second is a list of matrices with the estimated random effects for each level of grouping. For each matrix in the `random` list, the columns refer to the random effects and the rows to the groups. | | `contrasts` | a list with the contrasts used to represent factors in the fixed effects formula and/or random effects formula. This information is important for making predictions from a new data frame in which not all levels of the original factors are observed. If no factors are used in the nlme model, this component will be an empty list. | | `dims` | a list with basic dimensions used in the nlme fit, including the components `N` - the number of observations in the data, `Q` - the number of grouping levels, `qvec` - the number of random effects at each level from innermost to outermost (last two values are equal to zero and correspond to the fixed effects and the response), `ngrps` - the number of groups at each level from innermost to outermost (last two values are one and correspond to the fixed effects and the response), and `ncol` - the number of columns in the model matrix for each level of grouping from innermost to outermost (last two values are equal to the number of fixed effects and one). | | `fitted` | a data frame with the fitted values as columns. The leftmost column corresponds to the population fixed effects (corresponding to the fixed effects only) and successive columns from left to right correspond to increasing levels of grouping. | | `fixDF` | a list with components `X` and `terms` specifying the denominator degrees of freedom for, respectively, t-tests for the individual fixed effects and F-tests for the fixed-effects terms in the models. | | `groups` | a data frame with the grouping factors as columns. The grouping level increases from left to right. | | `logLik` | the (restricted) log-likelihood at convergence. | | `map` | a list with components `fmap`, `rmap`, `rmapRel`, and `bmap`, specifying various mappings for the fixed and random effects, used to generate predictions from the fitted object. | | `method` | the estimation method: either `"ML"` for maximum likelihood, or `"REML"` for restricted maximum likelihood. | | `modelStruct` | an object inheriting from class `nlmeStruct`, representing a list of mixed-effects model components, such as `reStruct`, `corStruct`, and `varFunc` objects. | | `numIter` | the number of iterations used in the iterative algorithm. | | `residuals` | a data frame with the residuals as columns. The leftmost column corresponds to the population residuals and successive columns from left to right correspond to increasing levels of grouping. | | `sigma` | the estimated within-group error standard deviation. | | `varFix` | an approximate covariance matrix of the fixed effects estimates. | ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `<nlme>`, `nlmeStruct` r None `recalc.varFunc` Recalculate for varFunc Object ------------------------------------------------ ### Description This method function pre-multiples the `"Xy"` component of `conLin` by a diagonal matrix with diagonal elements given by the weights corresponding to the variance structure represented by `object`e and adds the log-likelihood contribution of `object`, given by `logLik(object)`, to the `"logLik"` component of `conLin`. ### Usage ``` ## S3 method for class 'varFunc' recalc(object, conLin, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"[varFunc](varfunc)"`, representing a variance function structure. | | `conLin` | a condensed linear model object, consisting of a list with components `"Xy"`, corresponding to a regression matrix (`X`) combined with a response vector (`y`), and `"logLik"`, corresponding to the log-likelihood of the underlying model. | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value the recalculated condensed linear model object. ### Note This method function is only used inside model fitting functions, such as `lme` and `gls`, that allow heteroscedastic error terms. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `<recalc>`, `[varWeights](varweights)`, `[logLik.varFunc](loglik.varfunc)` r None `collapse` Collapse According to Groups ---------------------------------------- ### Description This function is generic; method functions can be written to handle specific classes of objects. Currently, only a `groupedData` method is available. ### Usage ``` collapse(object, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object to be collapsed, usually a data frame. | | `...` | some methods for the generic may require additional arguments. | ### Value will depend on the method function used; see the appropriate documentation. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[collapse.groupedData](collapse.groupeddata)` ### Examples ``` ## see the method function documentation ``` r None `Nitrendipene` Assay of nitrendipene ------------------------------------- ### Description The `Nitrendipene` data frame has 89 rows and 4 columns. ### Format This data frame contains the following columns: activity a numeric vector NIF a numeric vector Tissue an ordered factor with levels `2` < `1` < `3` < `4` log.NIF a numeric vector ### Source Bates, D. M. and Watts, D. G. (1988), *Nonlinear Regression Analysis and Its Applications*, Wiley, New York. r None `Names.pdMat` Names of a pdMat Object -------------------------------------- ### Description This method function returns the fist element of the `Dimnames` attribute of `object`, which contains the column names of the matrix represented by `object`. ### Usage ``` ## S3 method for class 'pdMat' Names(object, ...) ## S3 replacement method for class 'pdMat' Names(object, ...) <- value ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"[pdMat](pdmat)"`, representing a positive-definite matrix. | | `value` | a character vector with the replacement values for the column and row names of the matrix represented by `object`. It must have length equal to the dimension of the matrix represented by `object` and, if names have been previously assigned to `object`, it must correspond to a permutation of the original names. | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value if `object` has a `Dimnames` attribute then the first element of this attribute is returned; otherwise `NULL`. ### SIDE EFFECTS On the left side of an assignment, sets the `Dimnames` attribute of `object` to `list(value, value)`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[Names](names)`, `[Names.pdBlocked](names.pdblocked)` ### Examples ``` pd1 <- pdSymm(~age, data = Orthodont) Names(pd1) ``` r None `pairs.lme` Pairs Plot of an lme Object ---------------------------------------- ### Description Diagnostic plots for the linear mixed-effects fit are obtained. The `form` argument gives considerable flexibility in the type of plot specification. A conditioning expression (on the right side of a `|` operator) always implies that different panels are used for each level of the conditioning factor, according to a Trellis display. The expression on the right hand side of the formula, before a `|` operator, must evaluate to a data frame with at least two columns. If the data frame has two columns, a scatter plot of the two variables is displayed (the Trellis function `xyplot` is used). Otherwise, if more than two columns are present, a scatter plot matrix with pairwise scatter plots of the columns in the data frame is displayed (the Trellis function `splom` is used). ### Usage ``` ## S3 method for class 'lme' pairs(x, form, label, id, idLabels, grid, ...) ``` ### Arguments | | | | --- | --- | | `x` | an object inheriting from class `"<lme>"`, representing a fitted linear mixed-effects model. | | `form` | an optional one-sided formula specifying the desired type of plot. Any variable present in the original data frame used to obtain `x` can be referenced. In addition, `x` itself can be referenced in the formula using the symbol `"."`. Conditional expressions on the right of a `|` operator can be used to define separate panels in a Trellis display. The expression on the right hand side of `form`, and to the left of the `|` operator, must evaluate to a data frame with at least two columns. Default is `~ coef(.)` , corresponding to a pairs plot of the coefficients evaluated at the innermost level of nesting. | | `label` | an optional character vector of labels for the variables in the pairs plot. | | `id` | an optional numeric value, or one-sided formula. If given as a value, it is used as a significance level for an outlier test based on the Mahalanobis distances of the estimated random effects. Groups with random effects distances greater than the *1-value* percentile of the appropriate chi-square distribution are identified in the plot using `idLabels`. If given as a one-sided formula, its right hand side must evaluate to a logical, integer, or character vector which is used to identify points in the plot. If missing, no points are identified. | | `idLabels` | an optional vector, or one-sided formula. If given as a vector, it is converted to character and used to label the points identified according to `id`. If given as a one-sided formula, its right hand side must evaluate to a vector which is converted to character and used to label the identified points. Default is the innermost grouping factor. | | `grid` | an optional logical value indicating whether a grid should be added to plot. Default is `FALSE`. | | `...` | optional arguments passed to the Trellis plot function. | ### Value a diagnostic Trellis plot. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `<lme>`, `[pairs.compareFits](pairs.comparefits)`, `[pairs.lmList](pairs.lmlist)`, `[xyplot](../../lattice/html/xyplot)`, `[splom](../../lattice/html/splom)` ### Examples ``` fm1 <- lme(distance ~ age, Orthodont, random = ~ age | Subject) # scatter plot of coefficients by gender, identifying unusual subjects pairs(fm1, ~coef(., augFrame = TRUE) | Sex, id = 0.1, adj = -0.5) # scatter plot of estimated random effects : pairs(fm1, ~ranef(.)) ``` r None `getVarCov` Extract variance-covariance matrix ----------------------------------------------- ### Description Extract the variance-covariance matrix from a fitted model, such as a mixed-effects model. ### Usage ``` getVarCov(obj, ...) ## S3 method for class 'lme' getVarCov(obj, individuals, type = c("random.effects", "conditional", "marginal"), ...) ## S3 method for class 'gls' getVarCov(obj, individual = 1, ...) ``` ### Arguments | | | | --- | --- | | `obj` | A fitted model. Methods are available for models fit by `<lme>` and by `<gls>` | | `individuals` | For models fit by `<lme>` a vector of levels of the grouping factor can be specified for the conditional or marginal variance-covariance matrices. | | `individual` | For models fit by `<gls>` the only type of variance-covariance matrix provided is the marginal variance-covariance of the responses by group. The optional argument `individual` specifies the group of responses. | | `type` | For models fit by `<lme>` the `type` argument specifies the type of variance-covariance matrix, either `"random.effects"` for the random-effects variance-covariance (the default), or `"conditional"` for the conditional. variance-covariance of the responses or `"marginal"` for the the marginal variance-covariance of the responses. | | `...` | Optional arguments for some methods, as described above | ### Value A variance-covariance matrix or a list of variance-covariance matrices. ### Author(s) Mary Lindstrom [[email protected]](mailto:[email protected]) ### See Also `<lme>`, `<gls>` ### Examples ``` fm1 <- lme(distance ~ age, data = Orthodont, subset = Sex == "Female") getVarCov(fm1) getVarCov(fm1, individual = "F01", type = "marginal") getVarCov(fm1, type = "conditional") fm2 <- gls(follicles ~ sin(2*pi*Time) + cos(2*pi*Time), Ovary, correlation = corAR1(form = ~ 1 | Mare)) getVarCov(fm2) ``` r None `Tetracycline1` Pharmacokinetics of tetracycline ------------------------------------------------- ### Description The `Tetracycline1` data frame has 40 rows and 4 columns. ### Format This data frame contains the following columns: conc a numeric vector Time a numeric vector Subject an ordered factor with levels `5` < `3` < `2` < `4` < `1` Formulation a factor with levels `tetrachel` `tetracyn` ### Source Pinheiro, J. C. and Bates, D. M. (2000), *Mixed-Effects Models in S and S-PLUS*, Springer, New York. r None `Initialize.lmeStruct` Initialize an lmeStruct Object ------------------------------------------------------ ### Description The individual linear mixed-effects model components of the `lmeStruct` list are initialized. ### Usage ``` ## S3 method for class 'lmeStruct' Initialize(object, data, groups, conLin, control, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"[lmeStruct](lmestruct)"`, representing a list of linear mixed-effects model components, such as `reStruct`, `corStruct`, and `varFunc` objects. | | `data` | a data frame in which to evaluate the variables defined in `formula(object)`. | | `groups` | a data frame with the grouping factors corresponding to the lme model associated with `object` as columns, sorted from innermost to outermost grouping level. | | `conLin` | an optional condensed linear model object, consisting of a list with components `"Xy"`, corresponding to a regression matrix (`X`) combined with a response vector (`y`), and `"logLik"`, corresponding to the log-likelihood of the underlying lme model. Defaults to `attr(object, "conLin")`. | | `control` | an optional list with control parameters for the initialization and optimization algorithms used in `lme`. Defaults to `list(niterEM=20, gradHess=TRUE)`, implying that 20 EM iterations are to be used in the derivation of initial estimates for the coefficients of the `reStruct` component of `object` and, if possible, numerical gradient vectors and Hessian matrices for the log-likelihood function are to be used in the optimization algorithm. | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value an `lmeStruct` object similar to `object`, but with initialized model components. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `<lme>`, `[Initialize.reStruct](initialize.restruct)`, `[Initialize.corStruct](initialize.corstruct)`, `[Initialize.varFunc](initialize.varfunc)`, `[Initialize](initialize)` r None `Variogram.corLin` Calculate Semi-variogram for a corLin Object ---------------------------------------------------------------- ### Description This method function calculates the semi-variogram values corresponding to the Linear correlation model, using the estimated coefficients corresponding to `object`, at the distances defined by `distance`. ### Usage ``` ## S3 method for class 'corLin' Variogram(object, distance, sig2, length.out, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"[corLin](corlin)"`, representing an Linear spatial correlation structure. | | `distance` | an optional numeric vector with the distances at which the semi-variogram is to be calculated. Defaults to `NULL`, in which case a sequence of length `length.out` between the minimum and maximum values of `getCovariate(object)` is used. | | `sig2` | an optional numeric value representing the process variance. Defaults to `1`. | | `length.out` | an optional integer specifying the length of the sequence of distances to be used for calculating the semi-variogram, when `distance = NULL`. Defaults to `50`. | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value a data frame with columns `variog` and `dist` representing, respectively, the semi-variogram values and the corresponding distances. The returned value inherits from class `Variogram`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Cressie, N.A.C. (1993), "Statistics for Spatial Data", J. Wiley & Sons. ### See Also `[corLin](corlin)`, `[plot.Variogram](plot.variogram)`, `[Variogram](variogram)` ### Examples ``` cs1 <- corLin(15, form = ~ Time | Rat) cs1 <- Initialize(cs1, BodyWeight) Variogram(cs1)[1:10,] ``` r None `corMatrix` Extract Correlation Matrix --------------------------------------- ### Description This function is generic; method functions can be written to handle specific classes of objects. Classes which already have methods for this function include all `corStruct` classes. ### Usage ``` corMatrix(object, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object for which a correlation matrix can be extracted. | | `...` | some methods for this generic function require additional arguments. | ### Value will depend on the method function used; see the appropriate documentation. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[corMatrix.corStruct](cormatrix.corstruct)`, `[corMatrix.pdMat](cormatrix.pdmat)` ### Examples ``` ## see the method function documentation ``` r None `Orthodont` Growth curve data on an orthdontic measurement ----------------------------------------------------------- ### Description The `Orthodont` data frame has 108 rows and 4 columns of the change in an orthdontic measurement over time for several young subjects. ### Format This data frame contains the following columns: distance a numeric vector of distances from the pituitary to the pterygomaxillary fissure (mm). These distances are measured on x-ray images of the skull. age a numeric vector of ages of the subject (yr). Subject an ordered factor indicating the subject on which the measurement was made. The levels are labelled `M01` to `M16` for the males and `F01` to `F13` for the females. The ordering is by increasing average distance within sex. Sex a factor with levels `Male` and `Female` ### Details Investigators at the University of North Carolina Dental School followed the growth of 27 children (16 males, 11 females) from age 8 until age 14. Every two years they measured the distance between the pituitary and the pterygomaxillary fissure, two points that are easily identified on x-ray exposures of the side of the head. ### Source Pinheiro, J. C. and Bates, D. M. (2000), *Mixed-Effects Models in S and S-PLUS*, Springer, New York. (Appendix A.17) Potthoff, R. F. and Roy, S. N. (1964), “A generalized multivariate analysis of variance model useful especially for growth curve problems”, *Biometrika*, **51**, 313–326. ### Examples ``` formula(Orthodont) plot(Orthodont) ```
programming_docs
r None `Soybean` Growth of soybean plants ----------------------------------- ### Description The `Soybean` data frame has 412 rows and 5 columns. ### Format This data frame contains the following columns: Plot a factor giving a unique identifier for each plot. Variety a factor indicating the variety; Forrest (F) or Plant Introduction \#416937 (P). Year a factor indicating the year the plot was planted. Time a numeric vector giving the time the sample was taken (days after planting). weight a numeric vector giving the average leaf weight per plant (g). ### Details These data are described in Davidian and Giltinan (1995, 1.1.3, p.7) as “Data from an experiment to compare growth patterns of two genotypes of soybeans: Plant Introduction \#416937 (P), an experimental strain, and Forrest (F), a commercial variety.” ### Source Pinheiro, J. C. and Bates, D. M. (2000), *Mixed-Effects Models in S and S-PLUS*, Springer, New York. (Appendix A.27) Davidian, M. and Giltinan, D. M. (1995), *Nonlinear Models for Repeated Measurement Data*, Chapman and Hall, London. ### Examples ``` summary(fm1 <- nlsList(SSlogis, data = Soybean)) ``` r None `pdClasses` Positive-Definite Matrix Classes --------------------------------------------- ### Description Standard classes of positive-definite matrices (`pdMat`) structures available in the `nlme` package. ### Value Available standard classes: | | | | --- | --- | | `pdSymm` | general positive-definite matrix, with no additional structure | | `pdLogChol` | general positive-definite matrix, with no additional structure, using a log-Cholesky parameterization | | `pdDiag` | diagonal | | `pdIdent` | multiple of an identity | | `pdCompSymm` | compound symmetry structure (constant diagonal and constant off-diagonal elements) | | `pdBlocked` | block-diagonal matrix, with diagonal blocks of any "atomic" `pdMat` class | | `pdNatural` | general positive-definite matrix in natural parametrization (i.e. parametrized in terms of standard deviations and correlations). The underlying coefficients are not unrestricted, so this class should NOT be used for optimization. | ### Note Users may define their own `pdMat` classes by specifying a `constructor` function and, at a minimum, methods for the functions `pdConstruct`, `pdMatrix` and `coef`. For examples of these functions, see the methods for classes `pdSymm` and `pdDiag`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Pinheiro, J.C., and Bates, D.M. (2000) "Mixed-Effects Models in S and S-PLUS", Springer. ### See Also `[pdBlocked](pdblocked)`, `[pdCompSymm](pdcompsymm)`, `[pdDiag](pddiag)`, `[pdFactor](pdfactor)`, `[pdIdent](pdident)`, `[pdMat](pdmat)`, `[pdMatrix](pdmatrix)`, `[pdNatural](pdnatural)`, `[pdSymm](pdsymm)`, `[pdLogChol](pdlogchol)` r None `fitted.lmList` Extract lmList Fitted Values --------------------------------------------- ### Description The fitted values are extracted from each `lm` component of `object` and arranged into a list with as many components as `object`, or combined into a single vector. ### Usage ``` ## S3 method for class 'lmList' fitted(object, subset, asList, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"[lmList](lmlist)"`, representing a list of `lm` objects with a common model. | | `subset` | an optional character or integer vector naming the `lm` components of `object` from which the fitted values are to be extracted. Default is `NULL`, in which case all components are used. | | `asList` | an optional logical value. If `TRUE`, the returned object is a list with the fitted values split by groups; else the returned value is a vector. Defaults to `FALSE`. | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value a list with components given by the fitted values of each `lm` component of `object`, or a vector with the fitted values for all `lm` components of `object`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[lmList](lmlist)`, `[residuals.lmList](residuals.lmlist)` ### Examples ``` fm1 <- lmList(distance ~ age | Subject, Orthodont) fitted(fm1) ``` r None `plot.ranef.lmList` Plot a ranef.lmList Object ----------------------------------------------- ### Description If `form` is missing, or is given as a one-sided formula, a Trellis dot-plot of the random effects is generated, with a different panel for each random effect (coefficient). Rows in the dot-plot are determined by the `form` argument (if not missing) or by the row names of the random effects (coefficients). If a single factor is specified in `form`, its levels determine the dot-plot rows (with possibly multiple dots per row); otherwise, if `form` specifies a crossing of factors, the dot-plot rows are determined by all combinations of the levels of the individual factors in the formula. The Trellis function `dotplot` is used in this method function. If `form` is a two-sided formula, a Trellis display is generated, with a different panel for each variable listed in the right hand side of `form`. Scatter plots are generated for numeric variables and boxplots are generated for categorical (`factor` or `ordered`) variables. ### Usage ``` ## S3 method for class 'ranef.lmList' plot(x, form, grid, control, ...) ``` ### Arguments | | | | --- | --- | | `x` | an object inheriting from class `"[ranef.lmList](ranef.lmlist)"`, representing the estimated coefficients or estimated random effects for the `lmList` object from which it was produced. | | `form` | an optional formula specifying the desired type of plot. If given as a one-sided formula, a `dotplot` of the estimated random effects (coefficients) grouped according to all combinations of the levels of the factors named in `form` is returned. Single factors (`~g`) or crossed factors (`~g1*g2`) are allowed. If given as a two-sided formula, the left hand side must be a single random effects (coefficient) and the right hand side is formed by covariates in `x` separated by `+`. A Trellis display of the random effect (coefficient) versus the named covariates is returned in this case. Default is `NULL`, in which case the row names of the random effects (coefficients) are used. | | `grid` | an optional logical value indicating whether a grid should be added to plot. Only applies to plots associated with two-sided formulas in `form`. Default is `FALSE`. | | `control` | an optional list with control values for the plot, when `form` is given as a two-sided formula. The control values are referenced by name in the `control` list and only the ones to be modified from the default need to be specified. Available values include: `drawLine`, a logical value indicating whether a `loess` smoother should be added to the scatter plots and a line connecting the medians should be added to the boxplots (default is `TRUE`); `span.loess`, used as the `span` argument in the call to `panel.loess` (default is `2/3`); `degree.loess`, used as the `degree` argument in the call to `panel.loess` (default is `1`); `cex.axis`, the character expansion factor for the x-axis (default is `0.8`); `srt.axis`, the rotation factor for the x-axis (default is `0`); and `mgp.axis`, the margin parameters for the x-axis (default is `c(2, 0.5, 0)`). | | `...` | optional arguments passed to the Trellis `dotplot` function. | ### Value a Trellis plot of the estimated random-effects (coefficients) versus covariates, or groups. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[lmList](lmlist)`, `[dotplot](../../lattice/html/xyplot)` ### Examples ``` fm1 <- lmList(distance ~ age | Subject, Orthodont) plot(ranef(fm1)) fm1RE <- ranef(fm1, aug = TRUE) plot(fm1RE, form = ~ Sex) plot(fm1RE, form = age ~ Sex) ``` r None `coef.varFunc` varFunc Object Coefficients ------------------------------------------- ### Description This method function extracts the coefficients associated with the variance function structure represented by `object`. ### Usage ``` ## S3 method for class 'varFunc' coef(object, unconstrained, allCoef, ...) ## S3 replacement method for class 'varIdent' coef(object, ...) <- value ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"[varFunc](varfunc)"` representing a variance function structure. | | `unconstrained` | a logical value. If `TRUE` the coefficients are returned in unconstrained form (the same used in the optimization algorithm). If `FALSE` the coefficients are returned in "natural", generally constrained form. Defaults to `TRUE`. | | `allCoef` | a logical value. If `FALSE` only the coefficients which may vary during the optimization are returned. If `TRUE` all coefficients are returned. Defaults to `FALSE`. | | `value` | a vector with the replacement values for the coefficients associated with `object`. It must be have the same length of `coef{object}` and must be given in unconstrained form. `Object` must be initialized before new values can be assigned to its coefficients. | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value a vector with the coefficients corresponding to `object`. ### SIDE EFFECTS On the left side of an assignment, sets the values of the coefficients of `object` to `value`. ### Author(s) José Pinheiro and Douglas Bates ### See Also `[varFunc](varfunc)` ### Examples ``` vf1 <- varPower(1) coef(vf1) coef(vf1) <- 2 ``` r None `pdMatrix` Extract Matrix or Square-Root Factor from a pdMat Object -------------------------------------------------------------------- ### Description The positive-definite matrix represented by `object`, or a square-root factor of it is obtained. Letting *S* denote a positive-definite matrix, a square-root factor of *S* is any square matrix *L* such that *S = L'L*. This function extracts *S* or *L*. ### Usage ``` pdMatrix(object, factor) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `pdMat`, representing a positive definite matrix. | | `factor` | an optional logical value. If `TRUE`, a square-root factor of the positive-definite matrix represented by `object` is returned; else, if `FALSE`, the positive-definite matrix is returned. Defaults to `FALSE`. | ### Value if `fact` is `FALSE` the positive-definite matrix represented by `object` is returned; else a square-root of the positive-definite matrix is returned. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Pinheiro, J.C., and Bates, D.M. (2000) "Mixed-Effects Models in S and S-PLUS", Springer, esp. p. 162. ### See Also `[as.matrix.pdMat](as.matrix.pdmat)`, `[pdClasses](pdclasses)`, `[pdFactor](pdfactor)`, `[pdMat](pdmat)`, `[pdMatrix.reStruct](pdmatrix.restruct)`, `[corMatrix](cormatrix)` ### Examples ``` pd1 <- pdSymm(diag(1:4)) pdMatrix(pd1) ``` r None `pdLogChol` General Positive-Definite Matrix --------------------------------------------- ### Description This function is a constructor for the `pdLogChol` class, representing a general positive-definite matrix. If the matrix associated with `object` is of dimension *n*, it is represented by *n\*(n+1)/2* unrestricted parameters, using the log-Cholesky parametrization described in Pinheiro and Bates (1996). * When `value` is `numeric(0)`, an uninitialized `pdMat` object, a one-sided formula, or a character vector, `object` is returned as an *uninitialized* `pdLogChol` object (with just some of its attributes and its class defined) and needs to have its coefficients assigned later, generally using the `coef` or `matrix` replacement functions. * If `value` is an *initialized* `pdMat` object, `object` will be constructed from `as.matrix(value)`. * Finally, if `value` is a numeric vector, it is assumed to represent the unrestricted coefficients of the matrix-logarithm parametrization of the underlying positive-definite matrix. ### Usage ``` pdLogChol(value, form, nam, data) ``` ### Arguments | | | | --- | --- | | `value` | an optional initialization value, which can be any of the following: a `pdMat` object, a positive-definite matrix, a one-sided linear formula (with variables separated by `+`), a vector of character strings, or a numeric vector. Defaults to `numeric(0)`, corresponding to an uninitialized object. | | `form` | an optional one-sided linear formula specifying the row/column names for the matrix represented by `object`. Because factors may be present in `form`, the formula needs to be evaluated on a data frame to resolve the names it defines. This argument is ignored when `value` is a one-sided formula. Defaults to `NULL`. | | `nam` | an optional character vector specifying the row/column names for the matrix represented by object. It must have length equal to the dimension of the underlying positive-definite matrix and unreplicated elements. This argument is ignored when `value` is a character vector. Defaults to `NULL`. | | `data` | an optional data frame in which to evaluate the variables named in `value` and `form`. It is used to obtain the levels for `factors`, which affect the dimensions and the row/column names of the underlying matrix. If `NULL`, no attempt is made to obtain information on `factor`s appearing in the formulas. Defaults to the parent frame from which the function was called. | ### Details Internally, the `pdLogChol` representation of a symmetric positive definite matrix is a vector starting with the logarithms of the diagonal of the Choleski factorization of that matrix followed by its upper triangular portion. ### Value a `pdLogChol` object representing a general positive-definite matrix, also inheriting from class `pdMat`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Pinheiro, J.C. and Bates., D.M. (1996) Unconstrained Parametrizations for Variance-Covariance Matrices, *Statistics and Computing* **6**, 289–296. Pinheiro, J.C., and Bates, D.M. (2000) *Mixed-Effects Models in S and S-PLUS*, Springer. ### See Also `[as.matrix.pdMat](as.matrix.pdmat)`, `[coef.pdMat](coef.pdmat)`, `[pdClasses](pdclasses)`, `[matrix<-.pdMat](matrix.pdmat)` ### Examples ``` (pd1 <- pdLogChol(diag(1:3), nam = c("A","B","C"))) (pd4 <- pdLogChol(1:6)) (pd4c <- chol(pd4)) # -> upper-tri matrix with off-diagonals 4 5 6 pd4c[upper.tri(pd4c)] log(diag(pd4c)) # 1 2 3 ``` r None `IGF` Radioimmunoassay of IGF-I Protein ---------------------------------------- ### Description The `IGF` data frame has 237 rows and 3 columns. ### Format This data frame contains the following columns: Lot an ordered factor giving the radioactive tracer lot. age a numeric vector giving the age (in days) of the radioactive tracer. conc a numeric vector giving the estimated concentration of IGF-I protein (ng/ml) ### Details Davidian and Giltinan (1995) describe data obtained during quality control radioimmunoassays for ten different lots of radioactive tracer used to calibrate the Insulin-like Growth Factor (IGF-I) protein concentration measurements. ### Source Davidian, M. and Giltinan, D. M. (1995), *Nonlinear Models for Repeated Measurement Data*, Chapman and Hall, London. Pinheiro, J. C. and Bates, D. M. (2000), *Mixed-Effects Models in S and S-PLUS*, Springer, New York. (Appendix A.11) r None `formula.pdBlocked` Extract pdBlocked Formula ---------------------------------------------- ### Description The `formula` attributes of the `pdMat` elements of `x` are extracted and returned as a list, in case `asList=TRUE`, or converted to a single one-sided formula when `asList=FALSE`. If the `pdMat` elements do not have a `formula` attribute, a `NULL` value is returned. ### Usage ``` ## S3 method for class 'pdBlocked' formula(x, asList, ...) ``` ### Arguments | | | | --- | --- | | `x` | an object inheriting from class `"pdBlocked"`, representing a positive definite block diagonal matrix. | | `asList` | an optional logical value. If `TRUE`, a list with the formulas for the individual block diagonal elements of `x` is returned; else, if `FALSE`, a one-sided formula combining all individual formulas is returned. Defaults to `FALSE`. | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value a list of one-sided formulas, or a single one-sided formula, or `NULL`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[pdBlocked](pdblocked)`, `[pdMat](pdmat)` ### Examples ``` pd1 <- pdBlocked(list(~ age, ~ Sex - 1)) formula(pd1) formula(pd1, asList = TRUE) ``` r None `lme.groupedData` LME fit from groupedData Object -------------------------------------------------- ### Description The response variable and primary covariate in `formula(fixed)` are used to construct the fixed effects model formula. This formula and the `groupedData` object are passed as the `fixed` and `data` arguments to `lme.formula`, together with any other additional arguments in the function call. See the documentation on `lme.formula` for a description of that function. ### Usage ``` ## S3 method for class 'groupedData' lme(fixed, data, random, correlation, weights, subset, method, na.action, control, contrasts, keep.data = TRUE) ``` ### Arguments | | | | --- | --- | | `fixed` | a data frame inheriting from class `"[groupedData](groupeddata)"`. | | `data` | this argument is included for consistency with the generic function. It is ignored in this method function. | | `random` | optionally, any of the following: (i) a one-sided formula of the form `~x1+...+xn | g1/.../gm`, with `x1+...+xn` specifying the model for the random effects and `g1/.../gm` the grouping structure (`m` may be equal to 1, in which case no `/` is required). The random effects formula will be repeated for all levels of grouping, in the case of multiple levels of grouping; (ii) a list of one-sided formulas of the form `~x1+...+xn | g`, with possibly different random effects models for each grouping level. The order of nesting will be assumed the same as the order of the elements in the list; (iii) a one-sided formula of the form `~x1+...+xn`, or a `pdMat` object with a formula (i.e. a non-`NULL` value for `formula(object)`), or a list of such formulas or `pdMat` objects. In this case, the grouping structure formula will be derived from the data used to fit the linear mixed-effects model, which should inherit from class `groupedData`; (iv) a named list of formulas or `pdMat` objects as in (iii), with the grouping factors as names. The order of nesting will be assumed the same as the order of the order of the elements in the list; (v) an `reStruct` object. See the documentation on `pdClasses` for a description of the available `pdMat` classes. Defaults to a formula consisting of the right hand side of `fixed`. | | `correlation` | an optional `corStruct` object describing the within-group correlation structure. See the documentation of `corClasses` for a description of the available `corStruct` classes. Defaults to `NULL`, corresponding to no within-group correlations. | | `weights` | an optional `varFunc` object or one-sided formula describing the within-group heteroscedasticity structure. If given as a formula, it is used as the argument to `varFixed`, corresponding to fixed variance weights. See the documentation on `varClasses` for a description of the available `varFunc` classes. Defaults to `NULL`, corresponding to homoscedastic within-group errors. | | `subset` | an optional expression indicating the subset of the rows of `data` that should be used in the fit. This can be a logical vector, or a numeric vector indicating which observation numbers are to be included, or a character vector of the row names to be included. All observations are included by default. | | `method` | a character string. If `"REML"` the model is fit by maximizing the restricted log-likelihood. If `"ML"` the log-likelihood is maximized. Defaults to `"REML"`. | | `na.action` | a function that indicates what should happen when the data contain `NA`s. The default action (`na.fail`) causes `lme` to print an error message and terminate if there are any incomplete observations. | | `control` | a list of control values for the estimation algorithm to replace the default values returned by the function `lmeControl`. Defaults to an empty list. | | `contrasts` | an optional list. See the `contrasts.arg` of `model.matrix.default`. | | `keep.data` | logical: should the `data` argument (if supplied and a data frame) be saved as part of the model object? | ### Value an object of class `lme` representing the linear mixed-effects model fit. Generic functions such as `print`, `plot` and `summary` have methods to show the results of the fit. See `lmeObject` for the components of the fit. The functions `resid`, `coef`, `fitted`, `fixed.effects`, and `random.effects` can be used to extract some of its components. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References The computational methods follow on the general framework of Lindstrom, M.J. and Bates, D.M. (1988). The model formulation is described in Laird, N.M. and Ware, J.H. (1982). The variance-covariance parametrizations are described in Pinheiro, J.C. and Bates., D.M. (1996). The different correlation structures available for the `correlation` argument are described in Box, G.E.P., Jenkins, G.M., and Reinsel G.C. (1994), Littel, R.C., Milliken, G.A., Stroup, W.W., and Wolfinger, R.D. (1996), and Venables, W.N. and Ripley, B.D. (2002). The use of variance functions for linear and nonlinear mixed effects models is presented in detail in Davidian, M. and Giltinan, D.M. (1995). Box, G.E.P., Jenkins, G.M., and Reinsel G.C. (1994) "Time Series Analysis: Forecasting and Control", 3rd Edition, Holden-Day. Davidian, M. and Giltinan, D.M. (1995) "Nonlinear Mixed Effects Models for Repeated Measurement Data", Chapman and Hall. Laird, N.M. and Ware, J.H. (1982) "Random-Effects Models for Longitudinal Data", Biometrics, 38, 963-974. Lindstrom, M.J. and Bates, D.M. (1988) "Newton-Raphson and EM Algorithms for Linear Mixed-Effects Models for Repeated-Measures Data", Journal of the American Statistical Association, 83, 1014-1022. Littel, R.C., Milliken, G.A., Stroup, W.W., and Wolfinger, R.D. (1996) "SAS Systems for Mixed Models", SAS Institute. Pinheiro, J.C. and Bates., D.M. (1996) "Unconstrained Parametrizations for Variance-Covariance Matrices", Statistics and Computing, 6, 289-296. Pinheiro, J.C., and Bates, D.M. (2000) "Mixed-Effects Models in S and S-PLUS", Springer. Venables, W.N. and Ripley, B.D. (2002) "Modern Applied Statistics with S", 4th Edition, Springer-Verlag. ### See Also `<lme>`, `[groupedData](groupeddata)`, `[lmeObject](lmeobject)` ### Examples ``` fm1 <- lme(Orthodont) summary(fm1) ```
programming_docs
r None `Dim` Extract Dimensions from an Object ---------------------------------------- ### Description This function is generic; method functions can be written to handle specific classes of objects. Classes which already have methods for this function include: `"[corSpatial](corspatial)"`, `"[corStruct](corclasses)"`, `"pdCompSymm"`, `"pdDiag"`, `"pdIdent"`, `"pdMat"`, and `"pdSymm"`. ### Usage ``` Dim(object, ...) ``` ### Arguments | | | | --- | --- | | `object` | any object for which dimensions can be extracted. | | `...` | some methods for this generic function require additional arguments. | ### Value will depend on the method function used; see the appropriate documentation. ### Note If `dim` allowed more than one argument, there would be no need for this generic function. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[Dim.pdMat](dim.pdmat)`, `[Dim.corStruct](dim.corstruct)` ### Examples ``` ## see the method function documentation ``` r None `varConstProp` Constant Plus Proportion Variance Function ---------------------------------------------------------- ### Description This function is a constructor for the `varConstProp` class, representing a variance function structure corresponding to a two-component error model (additive and proportional error). Letting *v* denote the variance covariate and *s2(v)* denote the variance function evaluated at *v*, the two-component variance function is defined as *s2(v) = a^2 + b^2 \* v^2)*, where a is the additive component and b is the relative error component. In order to avoid overparameterisation of the model, it is recommended to use the possibility to fix sigma, preferably to a value of 1 (see examples). ### Usage ``` varConstProp(const, prop, form, fixed) ``` ### Arguments | | | | --- | --- | | `const, prop` | optional numeric vectors, or lists of numeric values, with, respectively, the coefficients for the constant and the proportional error terms. Both arguments must have length one, unless a grouping factor is specified in `form`. If either argument has length greater than one, it must have names which identify its elements to the levels of the grouping factor defined in `form`. If a grouping factor is present in `form` and the argument has length one, its value will be assigned to all grouping levels. Only positive values are allowed for `const`. Default is 0.1 for both `const` and `prop`. | | `form` | an optional one-sided formula of the form `~ v`, or `~ v | g`, specifying a variance covariate `v` and, optionally, a grouping factor `g` for the coefficients. The variance covariate must evaluate to a numeric vector and may involve expressions using `"."`, representing a fitted model object from which fitted values (`fitted(.)`) and residuals (`resid(.)`) can be extracted (this allows the variance covariate to be updated during the optimization of an object function). When a grouping factor is present in `form`, a different coefficient value is used for each of its levels. Several grouping variables may be simultaneously specified, separated by the `*` operator, as in `~ v | g1 * g2 * g3`. In this case, the levels of each grouping variable are pasted together and the resulting factor is used to group the observations. Defaults to `~ fitted(.)` representing a variance covariate given by the fitted values of a fitted model object and no grouping factor. | | `fixed` | an optional list with components `const` and/or `power`, consisting of numeric vectors, or lists of numeric values, specifying the values at which some or all of the coefficients in the variance function should be fixed. If a grouping factor is specified in `form`, the components of `fixed` must have names identifying which coefficients are to be fixed. Coefficients included in `fixed` are not allowed to vary during the optimization of an objective function. Defaults to `NULL`, corresponding to no fixed coefficients. | ### Value a `varConstProp` object representing a constant plus proportion variance function structure, also inheriting from class `varFunc`. ### Note The error model underlying this variance function structure can be understood to result from two uncorrelated sequences of standardized random variables (Lavielle(2015), p. 55) and has been proposed for use in analytical chemistry (Werner et al. (1978), Wilson et al. (2004)) and chemical degradation kinetics (Ranke and Meinecke (2019)). Note that the two-component error model proposed by Rocke and Lorenzato (1995) assumed a log-normal distribution of residuals at high absolute values, which is not compatible with the `[varFunc](varfunc)` structures in package nlme. ### Author(s) José Pinheiro and Douglas Bates (for `[varConstPower](varconstpower)`) and Johannes Ranke (adaptation to `varConstProp()`). ### References Lavielle, M. (2015) *Mixed Effects Models for the Population Approach: Models, Tasks, Methods and Tools*, Chapman and Hall/CRC. doi: [10.1201/b17203](https://doi.org/10.1201/b17203) Pinheiro, J.C., and Bates, D.M. (2000) *Mixed-Effects Models in S and S-PLUS*, Springer. doi: [10.1007/b98882](https://doi.org/10.1007/b98882) Ranke, J., and Meinecke, S. (2019) Error Models for the Kinetic Evaluation of Chemical Degradation Data. *Environments* **6**(12), 124 doi: [10.3390/environments6120124](https://doi.org/10.3390/environments6120124) Rocke, David M. and Lorenzato, Stefan (1995) A Two-Component Model for Measurement Error in Analytical Chemistry. *Technometrics* **37**(2), 176–184. doi: [10.1080/00401706.1995.10484302](https://doi.org/10.1080/00401706.1995.10484302) Werner, Mario, Brooks, Samuel H., and Knott, Lancaster B. (1978) Additive, Multiplicative, and Mixed Analytical Errors. *Clinical Chemistry* **24**(11), 1895–1898. doi: [10.1093/clinchem/24.11.1895](https://doi.org/10.1093/clinchem/24.11.1895) Wilson, M.D., Rocke, D.M., Durbin, B. and Kahn, H.D (2004) Detection Limits and Goodness-of-Fit Measures for the Two-Component Model of Chemical Analytical Error. *Analytica Chimica Acta* 2004, 509, 197–208 doi: [10.1016/j.aca.2003.12.047](https://doi.org/10.1016/j.aca.2003.12.047) ### See Also `[varClasses](varclasses)`, `[varWeights.varFunc](varweights)`, `[coef.varFunc](coef.varfunc)` ### Examples ``` # Generate some synthetic data using the two-component error model and use # different variance functions, also with fixed sigma in order to avoid # overparameterisation in the case of a constant term in the variance function times <- c(0, 1, 3, 7, 14, 28, 56, 120) pred <- 100 * exp(- 0.03 * times) sd_pred <- sqrt(3^2 + 0.07^2 * pred^2) n_replicates <- 2 set.seed(123456) syn_data <- data.frame( time = rep(times, each = n_replicates), value = rnorm(length(times) * n_replicates, rep(pred, each = n_replicates), rep(sd_pred, each = n_replicates))) syn_data$value <- ifelse(syn_data$value < 0, NA, syn_data$value) f_const <- gnls(value ~ SSasymp(time, 0, parent_0, lrc), data = syn_data, na.action = na.omit, start = list(parent_0 = 100, lrc = -3)) f_varPower <- gnls(value ~ SSasymp(time, 0, parent_0, lrc), data = syn_data, na.action = na.omit, start = list(parent_0 = 100, lrc = -3), weights = varPower()) f_varConstPower <- gnls(value ~ SSasymp(time, 0, parent_0, lrc), data = syn_data, na.action = na.omit, start = list(parent_0 = 100, lrc = -3), weights = varConstPower()) f_varConstPower_sf <- gnls(value ~ SSasymp(time, 0, parent_0, lrc), data = syn_data, na.action = na.omit, control = list(sigma = 1), start = list(parent_0 = 100, lrc = -3), weights = varConstPower()) f_varConstProp <- gnls(value ~ SSasymp(time, 0, parent_0, lrc), data = syn_data, na.action = na.omit, start = list(parent_0 = 100, lrc = -3), weights = varConstProp()) f_varConstProp_sf <- gnls(value ~ SSasymp(time, 0, parent_0, lrc), data = syn_data, na.action = na.omit, start = list(parent_0 = 100, lrc = -3), control = list(sigma = 1), weights = varConstProp()) AIC(f_const, f_varPower, f_varConstPower, f_varConstPower_sf, f_varConstProp, f_varConstProp_sf) # The error model parameters 3 and 0.07 are approximately recovered intervals(f_varConstProp_sf) ``` r None `Spruce` Growth of Spruce Trees -------------------------------- ### Description The `Spruce` data frame has 1027 rows and 4 columns. ### Format This data frame contains the following columns: Tree a factor giving a unique identifier for each tree. days a numeric vector giving the number of days since the beginning of the experiment. logSize a numeric vector giving the logarithm of an estimate of the volume of the tree trunk. plot a factor identifying the plot in which the tree was grown. ### Details Diggle, Liang, and Zeger (1994, Example 1.3, page 5) describe data on the growth of spruce trees that have been exposed to an ozone-rich atmosphere or to a normal atmosphere. ### Source Pinheiro, J. C. and Bates, D. M. (2000), *Mixed-Effects Models in S and S-PLUS*, Springer, New York. (Appendix A.28) Diggle, Peter J., Liang, Kung-Yee and Zeger, Scott L. (1994), *Analysis of longitudinal data*, Oxford University Press, Oxford. r None `logDet` Extract the Logarithm of the Determinant -------------------------------------------------- ### Description This function is generic; method functions can be written to handle specific classes of objects. Classes which already have methods for this function include: `corStruct`, several `pdMat` classes, and `reStruct`. ### Usage ``` logDet(object, ...) ``` ### Arguments | | | | --- | --- | | `object` | any object from which a matrix, or list of matrices, can be extracted | | `...` | some methods for this generic function require additional arguments. | ### Value will depend on the method function used; see the appropriate documentation. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[logLik](../../stats/html/loglik)`, `[logDet.corStruct](logdet.corstruct)`, `[logDet.pdMat](logdet.pdmat)`, `[logDet.reStruct](logdet.restruct)` ### Examples ``` ## see the method function documentation ``` r None `as.matrix.pdMat` Matrix of a pdMat Object ------------------------------------------- ### Description This method function extracts the positive-definite matrix represented by `x`. ### Usage ``` ## S3 method for class 'pdMat' as.matrix(x, ...) ``` ### Arguments | | | | --- | --- | | `x` | an object inheriting from class `"[pdMat](pdmat)"`, representing a positive-definite matrix. | | `...` | further arguments passed from other methods. | ### Value a matrix corresponding to the positive-definite matrix represented by `x`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Pinheiro, J. C. and Bates, D. M. (2000), *Mixed-Effects Models in S and S-PLUS*, Springer, New York. ### See Also `[pdMat](pdmat)`, `[corMatrix](cormatrix)` ### Examples ``` as.matrix(pdSymm(diag(4))) ``` r None `glsObject` Fitted gls Object ------------------------------ ### Description An object returned by the `<gls>` function, inheriting from class `"gls"` and representing a generalized least squares fitted linear model. Objects of this class have methods for the generic functions `anova`, `coef`, `fitted`, `formula`, `getGroups`, `getResponse`, `intervals`, `logLik`, `plot`, `predict`, `print`, `residuals`, `summary`, and `update`. ### Value The following components must be included in a legitimate `"gls"` object. | | | | --- | --- | | `apVar` | an approximate covariance matrix for the variance-covariance coefficients. If `apVar = FALSE` in the list of control values used in the call to `gls`, this component is equal to `NULL`. | | `call` | a list containing an image of the `gls` call that produced the object. | | `coefficients` | a vector with the estimated linear model coefficients. | | `contrasts` | a list with the contrasts used to represent factors in the model formula. This information is important for making predictions from a new data frame in which not all levels of the original factors are observed. If no factors are used in the model, this component will be an empty list. | | `dims` | a list with basic dimensions used in the model fit, including the components `N` - the number of observations in the data and `p` - the number of coefficients in the linear model. | | `fitted` | a vector with the fitted values.. | | `glsStruct` | an object inheriting from class `glsStruct`, representing a list of linear model components, such as `corStruct` and `varFunc` objects. | | `groups` | a vector with the correlation structure grouping factor, if any is present. | | `logLik` | the log-likelihood at convergence. | | `method` | the estimation method: either `"ML"` for maximum likelihood, or `"REML"` for restricted maximum likelihood. | | `numIter` | the number of iterations used in the iterative algorithm. | | `residuals` | a vector with the residuals. | | `sigma` | the estimated residual standard error. | | `varBeta` | an approximate covariance matrix of the coefficients estimates. | ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `<gls>`, `glsStruct` r None `Ovary` Counts of Ovarian Follicles ------------------------------------ ### Description The `Ovary` data frame has 308 rows and 3 columns. ### Format This data frame contains the following columns: Mare an ordered factor indicating the mare on which the measurement is made. Time time in the estrus cycle. The data were recorded daily from 3 days before ovulation until 3 days after the next ovulation. The measurement times for each mare are scaled so that the ovulations for each mare occur at times 0 and 1. follicles the number of ovarian follicles greater than 10 mm in diameter. ### Details Pierson and Ginther (1987) report on a study of the number of large ovarian follicles detected in different mares at several times in their estrus cycles. ### Source Pinheiro, J. C. and Bates, D. M. (2000), *Mixed-Effects Models in S and S-PLUS*, Springer, New York. (Appendix A.18) Pierson, R. A. and Ginther, O. J. (1987), Follicular population dynamics during the estrus cycle of the mare, *Animal Reproduction Science*, **14**, 219-231. r None `pdDiag` Diagonal Positive-Definite Matrix ------------------------------------------- ### Description This function is a constructor for the `pdDiag` class, representing a diagonal positive-definite matrix. If the matrix associated with `object` is of dimension *n*, it is represented by *n* unrestricted parameters, given by the logarithm of the square-root of the diagonal values. When `value` is `numeric(0)`, an uninitialized `pdMat` object, a one-sided formula, or a vector of character strings, `object` is returned as an uninitialized `pdDiag` object (with just some of its attributes and its class defined) and needs to have its coefficients assigned later, generally using the `coef` or `matrix` replacement functions. If `value` is an initialized `pdMat` object, `object` will be constructed from `as.matrix(value)`. Finally, if `value` is a numeric vector, it is assumed to represent the unrestricted coefficients of the underlying positive-definite matrix. ### Usage ``` pdDiag(value, form, nam, data) ``` ### Arguments | | | | --- | --- | | `value` | an optional initialization value, which can be any of the following: a `pdMat` object, a positive-definite matrix, a one-sided linear formula (with variables separated by `+`), a vector of character strings, or a numeric vector of length equal to the dimension of the underlying positive-definite matrix. Defaults to `numeric(0)`, corresponding to an uninitialized object. | | `form` | an optional one-sided linear formula specifying the row/column names for the matrix represented by `object`. Because factors may be present in `form`, the formula needs to be evaluated on a data.frame to resolve the names it defines. This argument is ignored when `value` is a one-sided formula. Defaults to `NULL`. | | `nam` | an optional vector of character strings specifying the row/column names for the matrix represented by object. It must have length equal to the dimension of the underlying positive-definite matrix and unreplicated elements. This argument is ignored when `value` is a vector of character strings. Defaults to `NULL`. | | `data` | an optional data frame in which to evaluate the variables named in `value` and `form`. It is used to obtain the levels for `factors`, which affect the dimensions and the row/column names of the underlying matrix. If `NULL`, no attempt is made to obtain information on `factors` appearing in the formulas. Defaults to the parent frame from which the function was called. | ### Value a `pdDiag` object representing a diagonal positive-definite matrix, also inheriting from class `pdMat`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Pinheiro, J.C., and Bates, D.M. (2000) "Mixed-Effects Models in S and S-PLUS", Springer. ### See Also `[as.matrix.pdMat](as.matrix.pdmat)`, `[coef.pdMat](coef.pdmat)`, `[pdClasses](pdclasses)`, `[matrix<-.pdMat](matrix.pdmat)` ### Examples ``` pd1 <- pdDiag(diag(1:3), nam = c("A","B","C")) pd1 ``` r None `asTable` Convert groupedData to a matrix ------------------------------------------ ### Description Create a tabular representation of the response in a balanced groupedData object. ### Usage ``` asTable(object) ``` ### Arguments | | | | --- | --- | | `object` | A balanced `groupedData` object | ### Details A balanced groupedData object can be represented as a matrix or table of response values corresponding to the values of a primary covariate for each level of a grouping factor. This function creates such a matrix representation of the data in `object`. ### Value A matrix. The data in the matrix are the values of the response. The columns correspond to the distinct values of the primary covariate and are labelled as such. The rows correspond to the distinct levels of the grouping factor and are labelled as such. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Pinheiro, J. C. and Bates, D. M. (2000), *Mixed-Effects Models in S and S-PLUS*, Springer, New York. ### See Also `[groupedData](groupeddata)`, `[isBalanced](isbalanced)`, `[balancedGrouped](balancedgrouped)` ### Examples ``` asTable(Orthodont) # Pinheiro and Bates, p. 109 ergoStool.mat <- asTable(ergoStool) ``` r None `getCovariate.varFunc` Extract varFunc Covariate ------------------------------------------------- ### Description This method function extracts the covariate(s) associated with the variance function represented by `object`, if any is present. ### Usage ``` ## S3 method for class 'varFunc' getCovariate(object, form, data) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `varFunc`, representing a variance function structure. | | `form` | an optional formula specifying the covariate to be evaluated in `object`. Defaults to `formula(object)`. | | `data` | some methods for this generic require a `data` object. Not used in this method. | ### Value if `object` has a `covariate` attribute, its value is returned; else `NULL` is returned. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[covariate<-.varFunc](covariate.varfunc)` ### Examples ``` vf1 <- varPower(1.1, form = ~age) covariate(vf1) <- Orthodont[["age"]] getCovariate(vf1) ```
programming_docs
r None `gnls` Fit Nonlinear Model Using Generalized Least Squares ----------------------------------------------------------- ### Description This function fits a nonlinear model using generalized least squares. The errors are allowed to be correlated and/or have unequal variances. ### Usage ``` gnls(model, data, params, start, correlation, weights, subset, na.action, naPattern, control, verbose) ``` ### Arguments | | | | --- | --- | | `model` | a two-sided formula object describing the model, with the response on the left of a `~` operator and a nonlinear expression involving parameters and covariates on the right. If `data` is given, all names used in the formula should be defined as parameters or variables in the data frame. | | `data` | an optional data frame containing the variables named in `model`, `correlation`, `weights`, `subset`, and `naPattern`. By default the variables are taken from the environment from which `gnls` is called. | | `params` | an optional two-sided linear formula of the form `p1+...+pn~x1+...+xm`, or list of two-sided formulas of the form `p1~x1+...+xm`, with possibly different models for each parameter. The `p1,...,pn` represent parameters included on the right hand side of `model` and `x1+...+xm` define a linear model for the parameters (when the left hand side of the formula contains several parameters, they are all assumed to follow the same linear model described by the right hand side expression). A `1` on the right hand side of the formula(s) indicates a single fixed effects for the corresponding parameter(s). By default, the parameters are obtained from the names of `start`. | | `start` | an optional named list, or numeric vector, with the initial values for the parameters in `model`. It can be omitted when a `selfStarting` function is used in `model`, in which case the starting estimates will be obtained from a single call to the `nls` function. | | `correlation` | an optional `corStruct` object describing the within-group correlation structure. See the documentation of `corClasses` for a description of the available `corStruct` classes. If a grouping variable is to be used, it must be specified in the `form` argument to the `corStruct` constructor. Defaults to `NULL`, corresponding to uncorrelated errors. | | `weights` | an optional `varFunc` object or one-sided formula describing the within-group heteroscedasticity structure. If given as a formula, it is used as the argument to `varFixed`, corresponding to fixed variance weights. See the documentation on `varClasses` for a description of the available `varFunc` classes. Defaults to `NULL`, corresponding to homoscedastic errors. | | `subset` | an optional expression indicating which subset of the rows of `data` should be used in the fit. This can be a logical vector, or a numeric vector indicating which observation numbers are to be included, or a character vector of the row names to be included. All observations are included by default. | | `na.action` | a function that indicates what should happen when the data contain `NA`s. The default action (`na.fail`) causes `gnls` to print an error message and terminate if there are any incomplete observations. | | `naPattern` | an expression or formula object, specifying which returned values are to be regarded as missing. | | `control` | a list of control values for the estimation algorithm to replace the default values returned by the function `gnlsControl`. Defaults to an empty list. | | `verbose` | an optional logical value. If `TRUE` information on the evolution of the iterative algorithm is printed. Default is `FALSE`. | ### Value an object of class `gnls`, also inheriting from class `gls`, representing the nonlinear model fit. Generic functions such as `print`, `plot` and `summary` have methods to show the results of the fit. See `gnlsObject` for the components of the fit. The functions `resid`, `coef`, and `fitted` can be used to extract some of its components. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References The different correlation structures available for the `correlation` argument are described in Box, G.E.P., Jenkins, G.M., and Reinsel G.C. (1994), Littel, R.C., Milliken, G.A., Stroup, W.W., and Wolfinger, R.D. (1996), and Venables, W.N. and Ripley, B.D. (2002). The use of variance functions for linear and nonlinear models is presented in detail in Carrol, R.J. and Rupert, D. (1988) and Davidian, M. and Giltinan, D.M. (1995). Box, G.E.P., Jenkins, G.M., and Reinsel G.C. (1994) "Time Series Analysis: Forecasting and Control", 3rd Edition, Holden-Day. Carrol, R.J. and Rupert, D. (1988) "Transformation and Weighting in Regression", Chapman and Hall. Davidian, M. and Giltinan, D.M. (1995) "Nonlinear Mixed Effects Models for Repeated Measurement Data", Chapman and Hall. Littel, R.C., Milliken, G.A., Stroup, W.W., and Wolfinger, R.D. (1996) "SAS Systems for Mixed Models", SAS Institute. Venables, W.N. and Ripley, B.D. (2002) "Modern Applied Statistics with S", 4th Edition, Springer-Verlag. Pinheiro, J.C., and Bates, D.M. (2000) "Mixed-Effects Models in S and S-PLUS", Springer. ### See Also `[corClasses](corclasses)`, `[gnlsControl](gnlscontrol)`, `[gnlsObject](gnlsobject)`, `[gnlsStruct](gnlsstruct)`, `<predict.gnls>`, `[varClasses](varclasses)`, `[varFunc](varfunc)` ### Examples ``` # variance increases with a power of the absolute fitted values fm1 <- gnls(weight ~ SSlogis(Time, Asym, xmid, scal), Soybean, weights = varPower()) summary(fm1) ``` r None `ranef.lme` Extract lme Random Effects --------------------------------------- ### Description The estimated random effects at level *i* are represented as a data frame with rows given by the different groups at that level and columns given by the random effects. If a single level of grouping is specified, the returned object is a data frame; else, the returned object is a list of such data frames. Optionally, the returned data frame(s) may be augmented with covariates summarized over groups. ### Usage ``` ## S3 method for class 'lme' ranef(object, augFrame, level, data, which, FUN, standard, omitGroupingFactor, subset, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"<lme>"`, representing a fitted linear mixed-effects model. | | `augFrame` | an optional logical value. If `TRUE`, the returned data frame is augmented with variables defined in `data`; else, if `FALSE`, only the coefficients are returned. Defaults to `FALSE`. | | `level` | an optional vector of positive integers giving the levels of grouping to be used in extracting the random effects from an object with multiple nested grouping levels. Defaults to all levels of grouping. | | `data` | an optional data frame with the variables to be used for augmenting the returned data frame when `augFrame = TRUE`. Defaults to the data frame used to fit `object`. | | `which` | an optional positive integer vector specifying which columns of `data` should be used in the augmentation of the returned data frame. Defaults to all columns in `data`. | | `FUN` | an optional summary function or a list of summary functions to be applied to group-varying variables, when collapsing `data` by groups. Group-invariant variables are always summarized by the unique value that they assume within that group. If `FUN` is a single function it will be applied to each non-invariant variable by group to produce the summary for that variable. If `FUN` is a list of functions, the names in the list should designate classes of variables in the frame such as `ordered`, `factor`, or `numeric`. The indicated function will be applied to any group-varying variables of that class. The default functions to be used are `mean` for numeric factors, and `Mode` for both `factor` and `ordered`. The `Mode` function, defined internally in `gsummary`, returns the modal or most popular value of the variable. It is different from the `mode` function that returns the S-language mode of the variable. | | `standard` | an optional logical value indicating whether the estimated random effects should be "standardized" (i.e. divided by the estimate of the standard deviation of that group of random effects). Defaults to `FALSE`. | | `omitGroupingFactor` | an optional logical value. When `TRUE` the grouping factor itself will be omitted from the group-wise summary of `data` but the levels of the grouping factor will continue to be used as the row names for the returned data frame. Defaults to `FALSE`. | | `subset` | an optional expression indicating for which rows the random effects should be extracted. | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value a data frame, or list of data frames, with the estimated random effects at the grouping level(s) specified in `level` and, optionally, other covariates summarized over groups. The returned object inherits from classes `random.effects.lme` and `data.frame`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Pinheiro, J.C., and Bates, D.M. (2000) "Mixed-Effects Models in S and S-PLUS", Springer, esp. pp. 100, 461. ### See Also `<coef.lme>`, `<gsummary>`, `<lme>`, `<plot.ranef.lme>`, `<random.effects>` ### Examples ``` fm1 <- lme(distance ~ age, Orthodont, random = ~ age | Subject) ranef(fm1) random.effects(fm1) # same as above random.effects(fm1, augFrame = TRUE) ``` r None `gnlsObject` Fitted gnls Object -------------------------------- ### Description An object returned by the `gnls` function, inheriting from class `gnls` and also from class `gls`, and representing a generalized nonlinear least squares fitted model. Objects of this class have methods for the generic functions `anova`, `coef`, `fitted`, `formula`, `getGroups`, `getResponse`, `intervals`, `logLik`, `plot`, `predict`, `print`, `residuals`, `summary`, and `update`. ### Value The following components must be included in a legitimate `gnls` object. | | | | --- | --- | | `apVar` | an approximate covariance matrix for the variance-covariance coefficients. If `apVar = FALSE` in the control values used in the call to `gnls`, this component is equal to `NULL`. | | `call` | a list containing an image of the `gnls` call that produced the object. | | `coefficients` | a vector with the estimated nonlinear model coefficients. | | `contrasts` | a list with the contrasts used to represent factors in the model formula. This information is important for making predictions from a new data frame in which not all levels of the original factors are observed. If no factors are used in the model, this component will be an empty list. | | `dims` | a list with basic dimensions used in the model fit, including the components `N` - the number of observations used in the fit and `p` - the number of coefficients in the nonlinear model. | | `fitted` | a vector with the fitted values. | | `modelStruct` | an object inheriting from class `gnlsStruct`, representing a list of model components, such as `corStruct` and `varFunc` objects. | | `groups` | a vector with the correlation structure grouping factor, if any is present. | | `logLik` | the log-likelihood at convergence. | | `numIter` | the number of iterations used in the iterative algorithm. | | `plist` | | | `pmap` | | | `residuals` | a vector with the residuals. | | `sigma` | the estimated residual standard error. | | `varBeta` | an approximate covariance matrix of the coefficients estimates. | ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `<gnls>`, `gnlsStruct` r None `LDEsysMat` Generate system matrix for LDEs -------------------------------------------- ### Description Generate the system matrix for the linear differential equations determined by a compartment model. ### Usage ``` LDEsysMat(pars, incidence) ``` ### Arguments | | | | --- | --- | | `pars` | a numeric vector of parameter values. | | `incidence` | an integer matrix with columns named `From`, `To`, and `Par`. Values in the `Par` column must be in the range 1 to `length(pars)`. Values in the `From` column must be between 1 and the number of compartments. Values in the `To` column must be between 0 and the number of compartments. | ### Details A compartment model describes material transfer between `k` in a system of `k` compartments to a linear system of differential equations. Given a description of the system and a vector of parameter values this function returns the system matrix. This function is intended for use in a general system for solving compartment models, as described in Bates and Watts (1988). ### Value A `k` by `k` numeric matrix. ### Author(s) Douglas Bates [[email protected]](mailto:[email protected]) ### References Bates, D. M. and Watts, D. G. (1988), *Nonlinear Regression Analysis and Its Applications*, Wiley, New York. ### Examples ``` # incidence matrix for a two compartment open system incidence <- matrix(c(1,1,2,2,2,1,3,2,0), ncol = 3, byrow = TRUE, dimnames = list(NULL, c("Par", "From", "To"))) incidence LDEsysMat(c(1.2, 0.3, 0.4), incidence) ``` r None `Pixel` X-ray pixel intensities over time ------------------------------------------ ### Description The `Pixel` data frame has 102 rows and 4 columns of data on the pixel intensities of CT scans of dogs over time ### Format This data frame contains the following columns: Dog a factor with levels `1` to `10` designating the dog on which the scan was made Side a factor with levels `L` and `R` designating the side of the dog being scanned day a numeric vector giving the day post injection of the contrast on which the scan was made pixel a numeric vector of pixel intensities ### Source Pinheiro, J. C. and Bates, D. M. (2000) *Mixed-effects Models in S and S-PLUS*, Springer. ### Examples ``` fm1 <- lme(pixel ~ day + I(day^2), data = Pixel, random = list(Dog = ~ day, Side = ~ 1)) summary(fm1) VarCorr(fm1) ``` r None `residuals.nlmeStruct` Calculate nlmeStruct Residuals ------------------------------------------------------ ### Description The residuals at level *i* are obtained by subtracting the fitted values at that level from the response vector. The fitted values at level *i* are obtained by adding together the contributions from the estimated fixed effects and the estimated random effects at levels less or equal to *i* and evaluating the model function at the resulting estimated parameters. ### Usage ``` ## S3 method for class 'nlmeStruct' residuals(object, level, conLin, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"[nlmeStruct](nlmestruct)"`, representing a list of mixed-effects model components, such as `reStruct`, `corStruct`, and `varFunc` objects. | | `level` | an optional integer vector giving the level(s) of grouping to be used in extracting the residuals from `object`. Level values increase from outermost to innermost grouping, with level zero corresponding to the population fitted values. Defaults to the highest or innermost level of grouping. | | `conLin` | an optional condensed linear model object, consisting of a list with components `"Xy"`, corresponding to a regression matrix (`X`) combined with a response vector (`y`), and `"logLik"`, corresponding to the log-likelihood of the underlying nlme model. Defaults to `attr(object, "conLin")`. | | `...` | optional arguments to the residuals generic. Not used. | ### Value if a single level of grouping is specified in `level`, the returned value is a vector with the residuals at the desired level; else, when multiple grouping levels are specified in `level`, the returned object is a matrix with columns given by the residuals at different levels. ### Note This method function is primarily used within the `nlme` function. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Bates, D.M. and Pinheiro, J.C. (1998) "Computational methods for multilevel models" available in PostScript or PDF formats at http://nlme.stat.wisc.edu ### See Also `<nlme>`, `[fitted.nlmeStruct](fitted.nlmestruct)` r None `residuals.lme` Extract lme Residuals -------------------------------------- ### Description The residuals at level *i* are obtained by subtracting the fitted levels at that level from the response vector (and dividing by the estimated within-group standard error, if `type="pearson"`). The fitted values at level *i* are obtained by adding together the population fitted values (based only on the fixed effects estimates) and the estimated contributions of the random effects to the fitted values at grouping levels less or equal to *i*. ### Usage ``` ## S3 method for class 'lme' residuals(object, level = Q, type = c("response", "pearson", "normalized"), asList = FALSE, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"<lme>"`, representing a fitted linear mixed-effects model. | | `level` | an optional integer vector giving the level(s) of grouping to be used in extracting the residuals from `object`. Level values increase from outermost to innermost grouping, with level zero corresponding to the population residuals. Defaults to the highest or innermost level of grouping. | | `type` | an optional character string specifying the type of residuals to be used. If `"response"`, as by default, the “raw” residuals (observed - fitted) are used; else, if `"pearson"`, the standardized residuals (raw residuals divided by the corresponding standard errors) are used; else, if `"normalized"`, the normalized residuals (standardized residuals pre-multiplied by the inverse square-root factor of the estimated error correlation matrix) are used. Partial matching of arguments is used, so only the first character needs to be provided. | | `asList` | an optional logical value. If `TRUE` and a single value is given in `level`, the returned object is a list with the residuals split by groups; else the returned value is either a vector or a data frame, according to the length of `level`. Defaults to `FALSE`. | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value if a single level of grouping is specified in `level`, the returned value is either a list with the residuals split by groups (`asList = TRUE`) or a vector with the residuals (`asList = FALSE`); else, when multiple grouping levels are specified in `level`, the returned object is a data frame with columns given by the residuals at different levels and the grouping factors. For a vector or data frame result the `[naresid](../../stats/html/nafns)` method is applied. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `<lme>`, `<fitted.lme>` ### Examples ``` fm1 <- lme(distance ~ age + Sex, data = Orthodont, random = ~ 1) head(residuals(fm1, level = 0:1)) summary(residuals(fm1) / residuals(fm1, type = "p")) # constant scaling factor 1.432 ``` r None `corSpatial` Spatial Correlation Structure ------------------------------------------- ### Description This function is a constructor for the `corSpatial` class, representing a spatial correlation structure. This class is "virtual", having four "real" classes, corresponding to specific spatial correlation structures, associated with it: `corExp`, `corGaus`, `corLin`, `corRatio`, and `corSpher`. The returned object will inherit from one of these "real" classes, determined by the `type` argument, and from the "virtual" `corSpatial` class. Objects created using this constructor must later be initialized using the appropriate `Initialize` method. ### Usage ``` corSpatial(value, form, nugget, type, metric, fixed) ``` ### Arguments | | | | --- | --- | | `value` | an optional vector with the parameter values in constrained form. If `nugget` is `FALSE`, `value` can have only one element, corresponding to the "range" of the spatial correlation structure, which must be greater than zero. If `nugget` is `TRUE`, meaning that a nugget effect is present, `value` can contain one or two elements, the first being the "range" and the second the "nugget effect" (one minus the correlation between two observations taken arbitrarily close together); the first must be greater than zero and the second must be between zero and one. Defaults to `numeric(0)`, which results in a range of 90% of the minimum distance and a nugget effect of 0.1 being assigned to the parameters when `object` is initialized. | | `form` | a one sided formula of the form `~ S1+...+Sp`, or `~ S1+...+Sp | g`, specifying spatial covariates `S1` through `Sp` and, optionally, a grouping factor `g`. When a grouping factor is present in `form`, the correlation structure is assumed to apply only to observations within the same grouping level; observations with different grouping levels are assumed to be uncorrelated. Defaults to `~ 1`, which corresponds to using the order of the observations in the data as a covariate, and no groups. | | `nugget` | an optional logical value indicating whether a nugget effect is present. Defaults to `FALSE`. | | `type` | an optional character string specifying the desired type of correlation structure. Available types include `"spherical"`, `"exponential"`, `"gaussian"`, `"linear"`, and `"rational"`. See the documentation on the functions `corSpher`, `corExp`, `corGaus`, `corLin`, and `corRatio` for a description of these correlation structures. Partial matching of arguments is used, so only the first character needs to be provided.Defaults to `"spherical"`. | | `metric` | an optional character string specifying the distance metric to be used. The currently available options are `"euclidean"` for the root sum-of-squares of distances; `"maximum"` for the maximum difference; and `"manhattan"` for the sum of the absolute differences. Partial matching of arguments is used, so only the first three characters need to be provided. Defaults to `"euclidean"`. | | `fixed` | an optional logical value indicating whether the coefficients should be allowed to vary in the optimization, or kept fixed at their initial value. Defaults to `FALSE`, in which case the coefficients are allowed to vary. | ### Value an object of class determined by the `type` argument and also inheriting from class `corSpatial`, representing a spatial correlation structure. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Cressie, N.A.C. (1993), "Statistics for Spatial Data", J. Wiley & Sons. Venables, W.N. and Ripley, B.D. (2002) "Modern Applied Statistics with S", 4th Edition, Springer-Verlag. Littel, Milliken, Stroup, and Wolfinger (1996) "SAS Systems for Mixed Models", SAS Institute. ### See Also `[corExp](corexp)`, `[corGaus](corgaus)`, `[corLin](corlin)`, `[corRatio](corratio)`, `[corSpher](corspher)`, `[Initialize.corStruct](initialize.corstruct)`, `[summary.corStruct](summary.corstruct)`, `[dist](../../stats/html/dist)` ### Examples ``` sp1 <- corSpatial(form = ~ x + y + z, type = "g", metric = "man") ```
programming_docs
r None `plot.ranef.lme` Plot a ranef.lme Object ----------------------------------------- ### Description Plots (class `"Trellis"` from package [lattice](https://CRAN.R-project.org/package=lattice)) of the random effects from linear mixed effects model, i.e., the result of `[ranef](random.effects)(<lme>(*))` (of class `"<ranef.lme>"`). ### Usage ``` ## S3 method for class 'ranef.lme' plot(x, form = NULL, omitFixed = TRUE, level = Q, grid = TRUE, control, xlab, ylab, strip, ...) ``` ### Arguments | | | | --- | --- | | `x` | an object inheriting from class `"<ranef.lme>"`, representing the estimated coefficients or estimated random effects for the `lme` object from which it was produced. | | `form` | an optional formula specifying the desired type of plot. * If given as a one-sided formula, a `[dotplot](../../lattice/html/xyplot)()` of the estimated random effects (coefficients) grouped according to all combinations of the levels of the factors named in `form` is returned. * If given as a two-sided formula (or by default, `NULL`), an `[xyplot](../../lattice/html/xyplot)()` Trellis display of the random effect (coefficient) versus the named covariates is returned. In `NULL` case the row names of the random effects (coefficients) are used (as covariates). See also ‘Details:’. | | `omitFixed` | an optional logical value indicating whether columns with values that are constant across groups should be omitted. Default is `TRUE`. | | `level` | an optional integer value giving the level of grouping to be used for `x`. Only used when `x` is a list with different components for each grouping level. Defaults to the highest or innermost level of grouping. | | `grid` | an optional logical value indicating whether a grid should be added to plot. Only applies to plots associated with two-sided formulas in `form`. Default is `TRUE`. | | `control` | an optional list with control values for the plot, when `form` is given as a two-sided formula. The control values are referenced by name in the `control` list and only the ones to be modified from the default need to be specified. Available values include: `drawLine`, a logical value indicating whether a `loess` smoother should be added to the scatter plots and a line connecting the medians should be added to the boxplots (default is `TRUE`); `span.loess`, used as the `span` argument in the call to `panel.loess` (default is `2/3`); `degree.loess`, used as the `degree` argument in the call to `panel.loess` (default is `1`); `cex.axis`, the character expansion factor for the x-axis (default is `0.8`); `srt.axis`, the rotation factor for the x-axis (default is `0`); and `mgp.axis`, the margin parameters for the x-axis (default is `c(2, 0.5, 0)`). | | `xlab, ylab` | axis labels, each with a sensible default. | | `strip` | a `[function](../../base/html/function)` or `FALSE`, see `[dotplot](../../lattice/html/xyplot)()` from package [lattice](https://CRAN.R-project.org/package=lattice). | | `...` | optional arguments passed to the Trellis `dotplot` function. | ### Details If `form` is missing, or is given as a one-sided formula, a Trellis dot-plot (via `[dotplot](../../lattice/html/xyplot)()` from pkg [lattice](https://CRAN.R-project.org/package=lattice)) of the random effects is generated, with a different panel for each random effect (coefficient). Rows in the dot-plot are determined by the `form` argument (if not missing) or by the row names of the random effects (coefficients). Single factors (`~g`) or crossed factors (`~g1*g2`) are allowed. For a single factor, its levels determine the dot-plot rows (with possibly multiple dots per row); otherwise, if `form` specifies a crossing of factors, the dot-plot rows are determined by all combinations of the levels of the individual factors in the formula. If `form` is a two-sided formula, the left hand side must be a single random effect (coefficient) and the right hand side is formed by covariates in `x` separated by `+`. An `[xyplot](../../lattice/html/xyplot)()` Trellis display is generated, with a different panel for each variable listed in the right hand side of `form`. Scatter plots are generated for numeric variables and boxplots are generated for categorical (`factor` or `ordered`) variables. ### Value a Trellis plot of the estimated random-effects (coefficients) versus covariates, or groups. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `<ranef.lme>`, `<lme>`, `[dotplot](../../lattice/html/xyplot)`. ### Examples ``` fm1 <- lme(distance ~ age, Orthodont, random = ~ age | Subject) plot(ranef(fm1)) fm1RE <- ranef(fm1, aug = TRUE) plot(fm1RE, form = ~ Sex) plot(fm1RE, form = age ~ Sex) # "connected" boxplots ``` r None `getGroups.gls` Extract gls Object Groups ------------------------------------------ ### Description If present, the grouping factor associated to the correlation structure for the linear model represented by `object` is extracted. ### Usage ``` ## S3 method for class 'gls' getGroups(object, form, level, data, sep) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `gls`, representing a generalized least squares fitted linear model. | | `form` | an optional formula with a conditioning expression on its right hand side (i.e. an expression involving the `|` operator). Defaults to `formula(object)`. Not used. | | `level` | a positive integer vector with the level(s) of grouping to be used when multiple nested levels of grouping are present. This argument is optional for most methods of this generic function and defaults to all levels of nesting. Not used. | | `data` | a data frame in which to interpret the variables named in `form`. Optional for most methods. Not used. | | `sep` | character, the separator to use between group levels when multiple levels are collapsed. The default is `'/'`. Not used. | ### Value if the linear model represented by `object` incorporates a correlation structure and the corresponding `corStruct` object has a grouping factor, a vector with the group values is returned; else, `NULL` is returned. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `<gls>`, `[corClasses](corclasses)` ### Examples ``` fm1 <- gls(follicles ~ sin(2*pi*Time) + cos(2*pi*Time), Ovary, correlation = corAR1(form = ~ 1 | Mare)) getGroups(fm1) ``` r None `isInitialized` Check if Object is Initialized ----------------------------------------------- ### Description Checks if `object` has been initialized (generally through a call to `Initialize`), by searching for components and attributes which are modified during initialization. ### Usage ``` isInitialized(object) ``` ### Arguments | | | | --- | --- | | `object` | any object requiring initialization. | ### Value a logical value indicating whether `object` has been initialized. ### Author(s) José Pinheiro and Douglas Bates ### See Also `[Initialize](initialize)` ### Examples ``` pd1 <- pdDiag(~age) isInitialized(pd1) ``` r None `Variogram.gls` Calculate Semi-variogram for Residuals from a gls Object ------------------------------------------------------------------------- ### Description This method function calculates the semi-variogram for the residuals from a `gls` fit. The semi-variogram values are calculated for pairs of residuals within the same group level, if a grouping factor is present. If `collapse` is different from `"none"`, the individual semi-variogram values are collapsed using either a robust estimator (`robust = TRUE`) defined in Cressie (1993), or the average of the values within the same distance interval. The semi-variogram is useful for modeling the error term correlation structure. ### Usage ``` ## S3 method for class 'gls' Variogram(object, distance, form, resType, data, na.action, maxDist, length.out, collapse, nint, breaks, robust, metric, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"<gls>"`, representing a generalized least squares fitted model. | | `distance` | an optional numeric vector with the distances between residual pairs. If a grouping variable is present, only the distances between residual pairs within the same group should be given. If missing, the distances are calculated based on the values of the arguments `form`, `data`, and `metric`, unless `object` includes a `corSpatial` element, in which case the associated covariate (obtained with the `getCovariate` method) is used. | | `form` | an optional one-sided formula specifying the covariate(s) to be used for calculating the distances between residual pairs and, optionally, a grouping factor for partitioning the residuals (which must appear to the right of a `|` operator in `form`). Default is `~1`, implying that the observation order within the groups is used to obtain the distances. | | `resType` | an optional character string specifying the type of residuals to be used. If `"response"`, the "raw" residuals (observed - fitted) are used; else, if `"pearson"`, the standardized residuals (raw residuals divided by the corresponding standard errors) are used; else, if `"normalized"`, the normalized residuals (standardized residuals pre-multiplied by the inverse square-root factor of the estimated error correlation matrix) are used. Partial matching of arguments is used, so only the first character needs to be provided. Defaults to `"pearson"`. | | `data` | an optional data frame in which to interpret the variables in `form`. By default, the same data used to fit `object` is used. | | `na.action` | a function that indicates what should happen when the data contain `NA`s. The default action (`na.fail`) causes an error message to be printed and the function to terminate, if there are any incomplete observations. | | `maxDist` | an optional numeric value for the maximum distance used for calculating the semi-variogram between two residuals. By default all residual pairs are included. | | `length.out` | an optional integer value. When `object` includes a `corSpatial` element, its semi-variogram values are calculated and this argument is used as the `length.out` argument to the corresponding `Variogram` method. Defaults to `50`. | | `collapse` | an optional character string specifying the type of collapsing to be applied to the individual semi-variogram values. If equal to `"quantiles"`, the semi-variogram values are split according to quantiles of the distance distribution, with equal number of observations per group, with possibly varying distance interval lengths. Else, if `"fixed"`, the semi-variogram values are divided according to distance intervals of equal lengths, with possibly different number of observations per interval. Else, if `"none"`, no collapsing is used and the individual semi-variogram values are returned. Defaults to `"quantiles"`. | | `nint` | an optional integer with the number of intervals to be used when collapsing the semi-variogram values. Defaults to `20`. | | `robust` | an optional logical value specifying if a robust semi-variogram estimator should be used when collapsing the individual values. If `TRUE` the robust estimator is used. Defaults to `FALSE`. | | `breaks` | an optional numeric vector with the breakpoints for the distance intervals to be used in collapsing the semi-variogram values. If not missing, the option specified in `collapse` is ignored. | | `metric` | an optional character string specifying the distance metric to be used. The currently available options are `"euclidean"` for the root sum-of-squares of distances; `"maximum"` for the maximum difference; and `"manhattan"` for the sum of the absolute differences. Partial matching of arguments is used, so only the first three characters need to be provided. Defaults to `"euclidean"`. | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value a data frame with columns `variog` and `dist` representing, respectively, the semi-variogram values and the corresponding distances. If the semi-variogram values are collapsed, an extra column, `n.pairs`, with the number of residual pairs used in each semi-variogram calculation, is included in the returned data frame. If `object` includes a `corSpatial` element, a data frame with its corresponding semi-variogram is included in the returned value, as an attribute `"modelVariog"`. The returned value inherits from class `Variogram`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Cressie, N.A.C. (1993), "Statistics for Spatial Data", J. Wiley & Sons. ### See Also `<gls>`, `[Variogram](variogram)`, `[Variogram.default](variogram.default)`, `[Variogram.lme](variogram.lme)`, `[plot.Variogram](plot.variogram)` ### Examples ``` fm1 <- gls(weight ~ Time * Diet, BodyWeight) Vm1 <- Variogram(fm1, form = ~ Time | Rat) print(head(Vm1), digits = 3) ``` r None `varWeights` Extract Variance Function Weights ----------------------------------------------- ### Description The inverse of the standard deviations corresponding to the variance function structure represented by `object` are returned. ### Usage ``` varWeights(object) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `varFunc`, representing a variance function structure. | ### Value if `object` has a `weights` attribute, its value is returned; else `NULL` is returned. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Pinheiro, J.C., and Bates, D.M. (2000) "Mixed-Effects Models in S and S-PLUS", Springer. ### See Also `[logLik.varFunc](loglik.varfunc)`, `[varWeights](varweights)` ### Examples ``` vf1 <- varPower(form=~age) vf1 <- Initialize(vf1, Orthodont) coef(vf1) <- 0.3 varWeights(vf1)[1:10] ``` r None `pdCompSymm` Positive-Definite Matrix with Compound Symmetry Structure ----------------------------------------------------------------------- ### Description This function is a constructor for the `pdCompSymm` class, representing a positive-definite matrix with compound symmetry structure (constant diagonal and constant off-diagonal elements). The underlying matrix is represented by 2 unrestricted parameters. When `value` is `numeric(0)`, an unitialized `pdMat` object, a one-sided formula, or a vector of character strings, `object` is returned as an uninitialized `pdCompSymm` object (with just some of its attributes and its class defined) and needs to have its coefficients assigned later, generally using the `coef` or `matrix` replacement functions. If `value` is an initialized `pdMat` object, `object` will be constructed from `as.matrix(value)`. Finally, if `value` is a numeric vector of length 2, it is assumed to represent the unrestricted coefficients of the underlying positive-definite matrix. ### Usage ``` pdCompSymm(value, form, nam, data) ``` ### Arguments | | | | --- | --- | | `value` | an optional initialization value, which can be any of the following: a `pdMat` object, a positive-definite matrix, a one-sided linear formula (with variables separated by `+`), a vector of character strings, or a numeric vector of length 2. Defaults to `numeric(0)`, corresponding to an uninitialized object. | | `form` | an optional one-sided linear formula specifying the row/column names for the matrix represented by `object`. Because factors may be present in `form`, the formula needs to be evaluated on a data.frame to resolve the names it defines. This argument is ignored when `value` is a one-sided formula. Defaults to `NULL`. | | `nam` | an optional vector of character strings specifying the row/column names for the matrix represented by object. It must have length equal to the dimension of the underlying positive-definite matrix and unreplicated elements. This argument is ignored when `value` is a vector of character strings. Defaults to `NULL`. | | `data` | an optional data frame in which to evaluate the variables named in `value` and `form`. It is used to obtain the levels for `factors`, which affect the dimensions and the row/column names of the underlying matrix. If `NULL`, no attempt is made to obtain information on `factors` appearing in the formulas. Defaults to the parent frame from which the function was called. | ### Value a `pdCompSymm` object representing a positive-definite matrix with compound symmetry structure, also inheriting from class `pdMat`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Pinheiro, J.C., and Bates, D.M. (2000) "Mixed-Effects Models in S and S-PLUS", Springer, esp. p. 161. ### See Also `[as.matrix.pdMat](as.matrix.pdmat)`, `[coef.pdMat](coef.pdmat)`, `[matrix<-.pdMat](matrix.pdmat)`, `[pdClasses](pdclasses)` ### Examples ``` pd1 <- pdCompSymm(diag(3) + 1, nam = c("A","B","C")) pd1 ``` r None `getResponseFormula` Extract Formula Specifying Response Variable ------------------------------------------------------------------ ### Description The left hand side of `formula{object}` is returned as a one-sided formula. ### Usage ``` getResponseFormula(object) ``` ### Arguments | | | | --- | --- | | `object` | any object from which a formula can be extracted. | ### Value a one-sided formula with the response variable associated with `formula{object}`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[getResponse](getresponse)` ### Examples ``` getResponseFormula(y ~ x | g) ``` r None `Variogram.corExp` Calculate Semi-variogram for a corExp Object ---------------------------------------------------------------- ### Description This method function calculates the semi-variogram values corresponding to the Exponential correlation model, using the estimated coefficients corresponding to `object`, at the distances defined by `distance`. ### Usage ``` ## S3 method for class 'corExp' Variogram(object, distance, sig2, length.out, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"[corExp](corexp)"`, representing an exponential spatial correlation structure. | | `distance` | an optional numeric vector with the distances at which the semi-variogram is to be calculated. Defaults to `NULL`, in which case a sequence of length `length.out` between the minimum and maximum values of `getCovariate(object)` is used. | | `sig2` | an optional numeric value representing the process variance. Defaults to `1`. | | `length.out` | an optional integer specifying the length of the sequence of distances to be used for calculating the semi-variogram, when `distance = NULL`. Defaults to `50`. | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value a data frame with columns `variog` and `dist` representing, respectively, the semi-variogram values and the corresponding distances. The returned value inherits from class `Variogram`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Cressie, N.A.C. (1993), "Statistics for Spatial Data", J. Wiley & Sons. ### See Also `[corExp](corexp)`, `[plot.Variogram](plot.variogram)`, `[Variogram](variogram)` ### Examples ``` stopifnot(require("stats", quietly = TRUE)) cs1 <- corExp(3, form = ~ Time | Rat) cs1 <- Initialize(cs1, BodyWeight) Variogram(cs1)[1:10,] ``` r None `Glucose` Glucose levels over time ----------------------------------- ### Description The `Glucose` data frame has 378 rows and 4 columns. ### Format This data frame contains the following columns: Subject an ordered factor with levels `6` < `2` < `3` < `5` < `1` < `4` Time a numeric vector conc a numeric vector of glucose levels Meal an ordered factor with levels `2am` < `6am` < `10am` < `2pm` < `6pm` < `10pm` ### Source Hand, D. and Crowder, M. (1996), *Practical Longitudinal Data Analysis*, Chapman and Hall, London.
programming_docs
r None `Extract.pdMat` Subscript a pdMat Object ----------------------------------------- ### Description This method function extracts sub-matrices from the positive-definite matrix represented by `x`. ### Usage ``` ## S3 method for class 'pdMat' x[i, j, drop = TRUE] ## S3 replacement method for class 'pdMat' x[i, j] <- value ``` ### Arguments | | | | --- | --- | | `x` | an object inheriting from class `"[pdMat](pdmat)"` representing a positive-definite matrix. | | `i, j` | optional subscripts applying respectively to the rows and columns of the positive-definite matrix represented by `object`. When `i` (`j`) is omitted, all rows (columns) are extracted. | | `drop` | a logical value. If `TRUE`, single rows or columns are converted to vectors. If `FALSE` the returned value retains its matrix representation. | | `value` | a vector, or matrix, with the replacement values for the relevant piece of the matrix represented by `x`. | ### Value if `i` and `j` are identical, the returned value will be `pdMat` object with the same class as `x`. Otherwise, the returned value will be a matrix. In the case a single row (or column) is selected, the returned value may be converted to a vector, according to the rules above. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[[](../../base/html/extract)`, `[pdMat](pdmat)` ### Examples ``` pd1 <- pdSymm(diag(3)) pd1[1, , drop = FALSE] pd1[1:2, 1:2] <- 3 * diag(2) ``` r None `fitted.nlmeStruct` Calculate nlmeStruct Fitted Values ------------------------------------------------------- ### Description The fitted values at level *i* are obtained by adding together the contributions from the estimated fixed effects and the estimated random effects at levels less or equal to *i* and evaluating the model function at the resulting estimated parameters. The resulting values estimate the predictions at level *i*. ### Usage ``` ## S3 method for class 'nlmeStruct' fitted(object, level, conLin, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"[nlmeStruct](nlmestruct)"`, representing a list of mixed-effects model components, such as `reStruct`, `corStruct`, and `varFunc` objects, plus attributes specifying the underlying nonlinear model and the response variable. | | `level` | an optional integer vector giving the level(s) of grouping to be used in extracting the fitted values from `object`. Level values increase from outermost to innermost grouping, with level zero corresponding to the population fitted values. Defaults to the highest or innermost level of grouping. | | `conLin` | an optional condensed linear model object, consisting of a list with components `"Xy"`, corresponding to a regression matrix (`X`) combined with a response vector (`y`), and `"logLik"`, corresponding to the log-likelihood of the underlying nlme model. Defaults to `attr(object, "conLin")`. | | `...` | additional arguments that could be given to this method. None are used. | ### Value if a single level of grouping is specified in `level`, the returned value is a vector with the fitted values at the desired level; else, when multiple grouping levels are specified in `level`, the returned object is a matrix with columns given by the fitted values at different levels. ### Note This method function is generally only used inside `nlme` and `fitted.nlme`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Bates, D.M. and Pinheiro, J.C. (1998) "Computational methods for multilevel models" available in PostScript or PDF formats at http://nlme.stat.wisc.edu/pub/NLME/ ### See Also `<nlme>`, `[residuals.nlmeStruct](residuals.nlmestruct)` r None `update.varFunc` Update varFunc Object --------------------------------------- ### Description If the `formula(object)` includes a `"."` term, representing a fitted object, the variance covariate needs to be updated upon completion of an optimization cycle (in which the variance function weights are kept fixed). This method function allows a reevaluation of the variance covariate using the current fitted object and, optionally, other variables in the original data. ### Usage ``` ## S3 method for class 'varFunc' update(object, data, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"[varFunc](varfunc)"`, representing a variance function structure. | | `data` | a list with a component named `"."` with the current version of the fitted object (from which fitted values, coefficients, and residuals can be extracted) and, if necessary, other variables used to evaluate the variance covariate(s). | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value if `formula(object)` includes a `"."` term, an `varFunc` object similar to `object`, but with the variance covariate reevaluated at the current fitted object value; else `object` is returned unchanged. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[needUpdate](needupdate)`, `[covariate<-.varFunc](covariate.varfunc)` r None `getGroups.varFunc` Extract varFunc Groups ------------------------------------------- ### Description This method function extracts the grouping factor associated with the variance function represented by `object`, if any is present. ### Usage ``` ## S3 method for class 'varFunc' getGroups(object, form, level, data, sep) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `varFunc`, representing a variance function structure. | | `form` | an optional formula with a conditioning expression on its right hand side (i.e. an expression involving the `|` operator). Defaults to `formula(object)`. Not used. | | `level` | a positive integer vector with the level(s) of grouping to be used when multiple nested levels of grouping are present. This argument is optional for most methods of this generic function and defaults to all levels of nesting. Not used. | | `data` | a data frame in which to interpret the variables named in `form`. Optional for most methods. Not used. | | `sep` | character, the separator to use between group levels when multiple levels are collapsed. The default is `'/'`. Not used. | ### Value if `object` has a `groups` attribute, its value is returned; else `NULL` is returned. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### Examples ``` vf1 <- varPower(form = ~ age | Sex) vf1 <- Initialize(vf1, Orthodont) getGroups(vf1) ``` r None `pdFactor` Square-Root Factor of a Positive-Definite Matrix ------------------------------------------------------------ ### Description A square-root factor of the positive-definite matrix represented by `object` is obtained. Letting *S* denote a positive-definite matrix, a square-root factor of *S* is any square matrix *L* such that *S = L'L*. This function extracts *L*. ### Usage ``` pdFactor(object) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `pdMat`, representing a positive definite matrix, which must have been initialized (i.e. `length(coef(object)) > 0`). | ### Value a vector with a square-root factor of the positive-definite matrix associated with `object` stacked column-wise. ### Note This function is used intensively in optimization algorithms and its value is returned as a vector for efficiency reasons. The `pdMatrix` function can be used to obtain square-root factors in matrix form. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Pinheiro, J.C., and Bates, D.M. (2000) "Mixed-Effects Models in S and S-PLUS", Springer. ### See Also `[pdMatrix](pdmatrix)` ### Examples ``` pd1 <- pdCompSymm(4 * diag(3) + 1) pdFactor(pd1) ``` r None `pdBlocked` Positive-Definite Block Diagonal Matrix ---------------------------------------------------- ### Description This function is a constructor for the `pdBlocked` class, representing a positive-definite block-diagonal matrix. Each block-diagonal element of the underlying matrix is itself a positive-definite matrix and is represented internally as an individual `pdMat` object. When `value` is `numeric(0)`, a list of uninitialized `pdMat` objects, a list of one-sided formulas, or a list of vectors of character strings, `object` is returned as an uninitialized `pdBlocked` object (with just some of its attributes and its class defined) and needs to have its coefficients assigned later, generally using the `coef` or `matrix` replacement functions. If `value` is a list of initialized `pdMat` objects, `object` will be constructed from the list obtained by applying `as.matrix` to each of the `pdMat` elements of `value`. Finally, if `value` is a list of numeric vectors, they are assumed to represent the unrestricted coefficients of the block-diagonal elements of the underlying positive-definite matrix. ### Usage ``` pdBlocked(value, form, nam, data, pdClass) ``` ### Arguments | | | | --- | --- | | `value` | an optional list with elements to be used as the `value` argument to other `pdMat` constructors. These include: `pdMat` objects, positive-definite matrices, one-sided linear formulas, vectors of character strings, or numeric vectors. All elements in the list must be similar (e.g. all one-sided formulas, or all numeric vectors). Defaults to `numeric(0)`, corresponding to an uninitialized object. | | `form` | an optional list of one-sided linear formulas specifying the row/column names for the block-diagonal elements of the matrix represented by `object`. Because factors may be present in `form`, the formulas needs to be evaluated on a data.frame to resolve the names they define. This argument is ignored when `value` is a list of one-sided formulas. Defaults to `NULL`. | | `nam` | an optional list of vector of character strings specifying the row/column names for the block-diagonal elements of the matrix represented by object. Each of its components must have length equal to the dimension of the corresponding block-diagonal element and unreplicated elements. This argument is ignored when `value` is a list of vector of character strings. Defaults to `NULL`. | | `data` | an optional data frame in which to evaluate the variables named in `value` and `form`. It is used to obtain the levels for `factors`, which affect the dimensions and the row/column names of the underlying matrix. If `NULL`, no attempt is made to obtain information on any `factors` appearing in the formulas. Defaults to the parent frame from which the function was called. | | `pdClass` | an optional vector of character strings naming the `pdMat` classes to be assigned to the individual blocks in the underlying matrix. If a single class is specified, it is used for all block-diagonal elements. This argument will only be used when `value` is missing, or its elements are not `pdMat` objects. Defaults to `"pdSymm"`. | ### Value a `pdBlocked` object representing a positive-definite block-diagonal matrix, also inheriting from class `pdMat`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Pinheiro, J.C., and Bates, D.M. (2000) "Mixed-Effects Models in S and S-PLUS", Springer, esp. p. 162. ### See Also `[as.matrix.pdMat](as.matrix.pdmat)`, `[coef.pdMat](coef.pdmat)`, `[pdClasses](pdclasses)`, `[matrix<-.pdMat](matrix.pdmat)` ### Examples ``` pd1 <- pdBlocked(list(diag(1:2), diag(c(0.1, 0.2, 0.3))), nam = list(c("A","B"), c("a1", "a2", "a3"))) pd1 ``` r None `gnlsControl` Control Values for gnls Fit ------------------------------------------ ### Description The values supplied in the function call replace the defaults and a list with all possible arguments is returned. The returned list is used as the `control` argument to the `gnls` function. ### Usage ``` gnlsControl(maxIter = 50, nlsMaxIter = 7, msMaxIter = 50, minScale = 0.001, tolerance = 1e-6, nlsTol = 0.001, msTol = 1e-7, returnObject = FALSE, msVerbose = FALSE, apVar = TRUE, .relStep =, opt = c("nlminb", "optim"), optimMethod = "BFGS", minAbsParApVar = 0.05, sigma = NULL) ``` ### Arguments | | | | --- | --- | | `maxIter` | maximum number of iterations for the `gnls` optimization algorithm. Default is 50. | | `nlsMaxIter` | maximum number of iterations for the `nls` optimization step *inside* the `gnls` optimization. Default is 7. | | `msMaxIter` | maximum number of iterations for the `ms` optimization step inside the `gnls` optimization. Default is 50. | | `minScale` | minimum factor by which to shrink the default step size in an attempt to decrease the sum of squares in the `nls` step. Default 0.001. | | `tolerance` | tolerance for the convergence criterion in the `gnls` algorithm. Default is 1e-6. | | `nlsTol` | tolerance for the convergence criterion in `nls` step. Default is 1e-3. | | `msTol` | tolerance for the convergence criterion of the first outer iteration when `optim` is used. Default is 1e-7. | | `returnObject` | a logical value indicating whether the fitted object should be returned with a `[warning](../../base/html/warning)` (instead of an error via `[stop](../../base/html/stop)()`) when the maximum number of iterations is reached without convergence of the algorithm. | | `msVerbose` | a logical value passed as the `trace` argument to the optimizer chosen by `opt`; see documentation on that. Default is `FALSE`. | | `apVar` | a logical value indicating whether the approximate covariance matrix of the variance-covariance parameters should be calculated. Default is `TRUE`. | | `.relStep` | relative step for numerical derivatives calculations. Default is `.Machine$double.eps^(1/3)` (about 6e-6). | | `opt` | the optimizer to be used, either `"[nlminb](../../stats/html/nlminb)"` (the current default) or `"[optim](../../stats/html/optim)"` (the previous default). | | `optimMethod` | character - the optimization method to be used with the `[optim](../../stats/html/optim)` optimizer. The default is `"BFGS"`. An alternative is `"L-BFGS-B"`. | | `minAbsParApVar` | numeric value - minimum absolute parameter value in the approximate variance calculation. The default is `0.05`. | | `sigma` | optionally a positive number to fix the residual error at. If `NULL`, as by default, or `0`, sigma is estimated. | ### Value a list with components for each of the possible arguments. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]); the `sigma` option: Siem Heisterkamp and Bert van Willigen. ### See Also `<gnls>` ### Examples ``` # decrease the maximum number iterations in the ms call and # request that information on the evolution of the ms iterations be printed gnlsControl(msMaxIter = 20, msVerbose = TRUE) ``` r None `augPred` Augmented Predictions -------------------------------- ### Description Predicted values are obtained at the specified values of `primary`. If `object` has a grouping structure (i.e. `getGroups(object)` is not `NULL`), predicted values are obtained for each group. If `level` has more than one element, predictions are obtained for each level of the `max(level)` grouping factor. If other covariates besides `primary` are used in the prediction model, their average (numeric covariates) or most frequent value (categorical covariates) are used to obtain the predicted values. The original observations are also included in the returned object. ### Usage ``` augPred(object, primary, minimum, maximum, length.out, ...) ## S3 method for class 'lme' augPred(object, primary = NULL, minimum = min(primary), maximum = max(primary), length.out = 51, level = Q, ...) ``` ### Arguments | | | | --- | --- | | `object` | a fitted model object from which predictions can be extracted, using a `predict` method. | | `primary` | an optional one-sided formula specifying the primary covariate to be used to generate the augmented predictions. By default, if a covariate can be extracted from the data used to generate `object` (using `getCovariate`), it will be used as `primary`. | | `minimum` | an optional lower limit for the primary covariate. Defaults to `min(primary)`. | | `maximum` | an optional upper limit for the primary covariate. Defaults to `max(primary)`. | | `length.out` | an optional integer with the number of primary covariate values at which to evaluate the predictions. Defaults to 51. | | `level` | an optional integer vector specifying the desired prediction levels. Levels increase from outermost to innermost grouping, with level 0 representing the population (fixed effects) predictions. Defaults to the innermost level. | | `...` | some methods for the generic may require additional arguments. | ### Value a data frame with four columns representing, respectively, the values of the primary covariate, the groups (if `object` does not have a grouping structure, all elements will be `1`), the predicted or observed values, and the type of value in the third column: `original` for the observed values and `predicted` (single or no grouping factor) or `predict.groupVar` (multiple levels of grouping), with `groupVar` replaced by the actual grouping variable name (`fixed` is used for population predictions). The returned object inherits from class `"augPred"`. ### Note This function is generic; method functions can be written to handle specific classes of objects. Classes which already have methods for this function include: `gls`, `lme`, and `lmList`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Pinheiro, J. C. and Bates, D. M. (2000), *Mixed-Effects Models in S and S-PLUS*, Springer, New York. ### See Also `[plot.augPred](plot.augpred)`, `[getGroups](getgroups)`, `[predict](../../stats/html/predict)` ### Examples ``` fm1 <- lme(Orthodont, random = ~1) augPred(fm1, length.out = 2, level = c(0,1)) ``` r None `pdConstruct.pdBlocked` Construct pdBlocked Objects ---------------------------------------------------- ### Description This function give an alternative constructor for the `pdBlocked` class, representing a positive-definite block-diagonal matrix. Each block-diagonal element of the underlying matrix is itself a positive-definite matrix and is represented internally as an individual `pdMat` object. When `value` is `numeric(0)`, a list of uninitialized `pdMat` objects, a list of one-sided formulas, or a list of vectors of character strings, `object` is returned as an uninitialized `pdBlocked` object (with just some of its attributes and its class defined) and needs to have its coefficients assigned later, generally using the `coef` or `matrix` replacement functions. If `value` is a list of initialized `pdMat` objects, `object` will be constructed from the list obtained by applying `as.matrix` to each of the `pdMat` elements of `value`. Finally, if `value` is a list of numeric vectors, they are assumed to represent the unrestricted coefficients of the block-diagonal elements of the underlying positive-definite matrix. ### Usage ``` ## S3 method for class 'pdBlocked' pdConstruct(object, value, form, nam, data, pdClass, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"pdBlocked"`, representing a positive definite block-diagonal matrix. | | `value` | an optional list with elements to be used as the `value` argument to other `pdMat` constructors. These include: `pdMat` objects, positive-definite matrices, one-sided linear formulas, vectors of character strings, or numeric vectors. All elements in the list must be similar (e.g. all one-sided formulas, or all numeric vectors). Defaults to `numeric(0)`, corresponding to an uninitialized object. | | `form` | an optional list of one-sided linear formula specifying the row/column names for the block-diagonal elements of the matrix represented by `object`. Because factors may be present in `form`, the formulas needs to be evaluated on a data.frame to resolve the names they defines. This argument is ignored when `value` is a list of one-sided formulas. Defaults to `NULL`. | | `nam` | an optional list of vector of character strings specifying the row/column names for the block-diagonal elements of the matrix represented by object. Each of its components must have length equal to the dimension of the corresponding block-diagonal element and unreplicated elements. This argument is ignored when `value` is a list of vector of character strings. Defaults to `NULL`. | | `data` | an optional data frame in which to evaluate the variables named in `value` and `form`. It is used to obtain the levels for `factors`, which affect the dimensions and the row/column names of the underlying matrix. If `NULL`, no attempt is made to obtain information on `factors` appearing in the formulas. Defaults to the parent frame from which the function was called. | | `pdClass` | an optional vector of character strings naming the `pdMat` classes to be assigned to the individual blocks in the underlying matrix. If a single class is specified, it is used for all block-diagonal elements. This argument will only be used when `value` is missing, or its elements are not `pdMat` objects. Defaults to `"pdSymm"`. | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value a `pdBlocked` object representing a positive-definite block-diagonal matrix, also inheriting from class `pdMat`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Pinheiro, J.C., and Bates, D.M. (2000) "Mixed-Effects Models in S and S-PLUS", Springer. ### See Also `[as.matrix.pdMat](as.matrix.pdmat)`, `[coef.pdMat](coef.pdmat)`, `[pdBlocked](pdblocked)`, `[pdClasses](pdclasses)`, `[pdConstruct](pdconstruct)`, `[matrix<-.pdMat](matrix.pdmat)` ### Examples ``` pd1 <- pdBlocked(list(c("A","B"), c("a1", "a2", "a3"))) pdConstruct(pd1, list(diag(1:2), diag(c(0.1, 0.2, 0.3)))) ```
programming_docs
r None `glsControl` Control Values for gls Fit ---------------------------------------- ### Description The values supplied in the function call replace the defaults and a list with all possible arguments is returned. The returned list is used as the `control` argument to the `gls` function. ### Usage ``` glsControl(maxIter, msMaxIter, tolerance, msTol, msVerbose, singular.ok, returnObject = FALSE, apVar, .relStep, opt = c("nlminb", "optim"), optimMethod, minAbsParApVar, natural, sigma = NULL) ``` ### Arguments | | | | --- | --- | | `maxIter` | maximum number of iterations for the `gls` optimization algorithm. Default is 50. | | `msMaxIter` | maximum number of iterations for the optimization step inside the `gls` optimization. Default is 50. | | `tolerance` | tolerance for the convergence criterion in the `gls` algorithm. Default is 1e-6. | | `msTol` | tolerance for the convergence criterion of the first outer iteration when `optim` is used. Default is 1e-7. | | `msVerbose` | a logical value passed as the `trace` argument to `ms` (see documentation on that function). Default is `FALSE`. | | `singular.ok` | a logical value indicating whether non-estimable coefficients (resulting from linear dependencies among the columns of the regression matrix) should be allowed. Default is `FALSE`. | | `returnObject` | a logical value indicating whether the fitted object should be returned when the maximum number of iterations is reached without convergence of the algorithm. Default is `FALSE`. | | `apVar` | a logical value indicating whether the approximate covariance matrix of the variance-covariance parameters should be calculated. Default is `TRUE`. | | `.relStep` | relative step for numerical derivatives calculations. Default is `.Machine$double.eps^(1/3)`. | | `opt` | the optimizer to be used, either `"[nlminb](../../stats/html/nlminb)"` (the current default) or `"[optim](../../stats/html/optim)"` (the previous default). | | `optimMethod` | character - the optimization method to be used with the `[optim](../../stats/html/optim)` optimizer. The default is `"BFGS"`. An alternative is `"L-BFGS-B"`. | | `minAbsParApVar` | numeric value - minimum absolute parameter value in the approximate variance calculation. The default is `0.05`. | | `natural` | logical. Should the natural parameterization be used for the approximate variance calculations? Default is `TRUE`. | | `sigma` | optionally a positive number to fix the residual error at. If `NULL`, as by default, or `0`, sigma is estimated. | ### Value a list with components for each of the possible arguments. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]); the `sigma` option: Siem Heisterkamp and Bert van Willigen. ### See Also `<gls>` ### Examples ``` # decrease the maximum number iterations in the optimization call and # request that information on the evolution of the ms iterations be printed glsControl(msMaxIter = 20, msVerbose = TRUE) ``` r None `getCovariate.data.frame` Extract Data Frame Covariate ------------------------------------------------------- ### Description The right hand side of `form`, stripped of any conditioning expression (i.e. an expression following a `|` operator), is evaluated in `object`. ### Usage ``` ## S3 method for class 'data.frame' getCovariate(object, form, data) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `data.frame`. | | `form` | an optional formula specifying the covariate to be evaluated in `object`. Defaults to `formula(object)`. | | `data` | some methods for this generic require a separate data frame. Not used in this method. | ### Value the value of the right hand side of `form`, stripped of any conditional expression, evaluated in `object`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[getCovariateFormula](getcovariateformula)` ### Examples ``` getCovariate(Orthodont) ``` r None `coef.reStruct` reStruct Object Coefficients --------------------------------------------- ### Description This method function extracts the coefficients associated with the positive-definite matrix represented by `object`. ### Usage ``` ## S3 method for class 'reStruct' coef(object, unconstrained, ...) ## S3 replacement method for class 'reStruct' coef(object, ...) <- value ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"[reStruct](restruct)"`, representing a random effects structure and consisting of a list of `pdMat` objects. | | `unconstrained` | a logical value. If `TRUE` the coefficients are returned in unconstrained form (the same used in the optimization algorithm). If `FALSE` the coefficients are returned in "natural", possibly constrained, form. Defaults to `TRUE`. | | `value` | a vector with the replacement values for the coefficients associated with `object`. It must be a vector with the same length of `coef(object)` and must be given in unconstrained form. | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value a vector with the coefficients corresponding to `object`. ### SIDE EFFECTS On the left side of an assignment, sets the values of the coefficients of `object` to `value`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[coef.pdMat](coef.pdmat)`, `[reStruct](restruct)`, `[pdMat](pdmat)` ### Examples ``` rs1 <- reStruct(list(A = pdSymm(diag(1:3), form = ~Score), B = pdDiag(2 * diag(4), form = ~Educ))) coef(rs1) ``` r None `Wafer` Modeling of Analog MOS Circuits ---------------------------------------- ### Description The `Wafer` data frame has 400 rows and 4 columns. ### Format This data frame contains the following columns: Wafer a factor with levels `1` `2` `3` `4` `5` `6` `7` `8` `9` `10` Site a factor with levels `1` `2` `3` `4` `5` `6` `7` `8` voltage a numeric vector current a numeric vector ### Source Pinheiro, J. C. and Bates, D. M. (2000), *Mixed-Effects Models in S and S-PLUS*, Springer, New York. r None `collapse.groupedData` Collapse a groupedData Object ----------------------------------------------------- ### Description If `object` has a single grouping factor, it is returned unchanged. Else, it is summarized by the values of the `displayLevel` grouping factor (or the combination of its values and the values of the covariate indicated in `preserve`, if any is present). The collapsed data is used to produce a new `groupedData` object, with grouping factor given by the `displayLevel` factor. ### Usage ``` ## S3 method for class 'groupedData' collapse(object, collapseLevel, displayLevel, outer, inner, preserve, FUN, subset, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `groupedData`, generally with multiple grouping factors. | | `collapseLevel` | an optional positive integer or character string indicating the grouping level to use when collapsing the data. Level values increase from outermost to innermost grouping. Default is the highest or innermost level of grouping. | | `displayLevel` | an optional positive integer or character string indicating the grouping level to use as the grouping factor for the collapsed data. Default is `collapseLevel`. | | `outer` | an optional logical value or one-sided formula, indicating covariates that are outer to the `displayLevel` grouping factor. If equal to `TRUE`, the `displayLevel` element `attr(object, "outer")` is used to indicate the outer covariates. An outer covariate is invariant within the sets of rows defined by the grouping factor. Ordering of the groups is done in such a way as to preserve adjacency of groups with the same value of the outer variables. Defaults to `NULL`, meaning that no outer covariates are to be used. | | `inner` | an optional logical value or one-sided formula, indicating a covariate that is inner to the `displayLevel` grouping factor. If equal to `TRUE`, `attr(object, "outer")` is used to indicate the inner covariate. An inner covariate can change within the sets of rows defined by the grouping factor. Defaults to `NULL`, meaning that no inner covariate is present. | | `preserve` | an optional one-sided formula indicating a covariate whose levels should be preserved when collapsing the data according to the `collapseLevel` grouping factor. The collapsing factor is obtained by pasting together the levels of the `collapseLevel` grouping factor and the values of the covariate to be preserved. Default is `NULL`, meaning that no covariates need to be preserved. | | `FUN` | an optional summary function or a list of summary functions to be used for collapsing the data. The function or functions are applied only to variables in `object` that vary within the groups defined by `collapseLevel`. Invariant variables are always summarized by group using the unique value that they assume within that group. If `FUN` is a single function it will be applied to each non-invariant variable by group to produce the summary for that variable. If `FUN` is a list of functions, the names in the list should designate classes of variables in the data such as `ordered`, `factor`, or `numeric`. The indicated function will be applied to any non-invariant variables of that class. The default functions to be used are `mean` for numeric factors, and `Mode` for both `factor` and `ordered`. The `Mode` function, defined internally in `gsummary`, returns the modal or most popular value of the variable. It is different from the `mode` function that returns the S-language mode of the variable. | | `subset` | an optional named list. Names can be either positive integers representing grouping levels, or names of grouping factors. Each element in the list is a vector indicating the levels of the corresponding grouping factor to be preserved in the collapsed data. Default is `NULL`, meaning that all levels are used. | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value a `groupedData` object with a single grouping factor given by the `displayLevel` grouping factor, resulting from collapsing `object` over the levels of the `collapseLevel` grouping factor. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[groupedData](groupeddata)`, `[plot.nmGroupedData](plot.nmgroupeddata)` ### Examples ``` # collapsing by Dog collapse(Pixel, collapse = 1) # same as collapse(Pixel, collapse = "Dog") ``` r None `Variogram.lme` Calculate Semi-variogram for Residuals from an lme Object -------------------------------------------------------------------------- ### Description This method function calculates the semi-variogram for the within-group residuals from an `lme` fit. The semi-variogram values are calculated for pairs of residuals within the same group. If `collapse` is different from `"none"`, the individual semi-variogram values are collapsed using either a robust estimator (`robust = TRUE`) defined in Cressie (1993), or the average of the values within the same distance interval. The semi-variogram is useful for modeling the error term correlation structure. ### Usage ``` ## S3 method for class 'lme' Variogram(object, distance, form, resType, data, na.action, maxDist, length.out, collapse, nint, breaks, robust, metric, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"<lme>"`, representing a fitted linear mixed-effects model. | | `distance` | an optional numeric vector with the distances between residual pairs. If a grouping variable is present, only the distances between residual pairs within the same group should be given. If missing, the distances are calculated based on the values of the arguments `form`, `data`, and `metric`, unless `object` includes a `corSpatial` element, in which case the associated covariate (obtained with the `getCovariate` method) is used. | | `form` | an optional one-sided formula specifying the covariate(s) to be used for calculating the distances between residual pairs and, optionally, a grouping factor for partitioning the residuals (which must appear to the right of a `|` operator in `form`). Default is `~1`, implying that the observation order within the groups is used to obtain the distances. | | `resType` | an optional character string specifying the type of residuals to be used. If `"response"`, the "raw" residuals (observed - fitted) are used; else, if `"pearson"`, the standardized residuals (raw residuals divided by the corresponding standard errors) are used; else, if `"normalized"`, the normalized residuals (standardized residuals pre-multiplied by the inverse square-root factor of the estimated error correlation matrix) are used. Partial matching of arguments is used, so only the first character needs to be provided. Defaults to `"pearson"`. | | `data` | an optional data frame in which to interpret the variables in `form`. By default, the same data used to fit `object` is used. | | `na.action` | a function that indicates what should happen when the data contain `NA`s. The default action (`na.fail`) causes an error message to be printed and the function to terminate, if there are any incomplete observations. | | `maxDist` | an optional numeric value for the maximum distance used for calculating the semi-variogram between two residuals. By default all residual pairs are included. | | `length.out` | an optional integer value. When `object` includes a `corSpatial` element, its semi-variogram values are calculated and this argument is used as the `length.out` argument to the corresponding `Variogram` method. Defaults to `50`. | | `collapse` | an optional character string specifying the type of collapsing to be applied to the individual semi-variogram values. If equal to `"quantiles"`, the semi-variogram values are split according to quantiles of the distance distribution, with equal number of observations per group, with possibly varying distance interval lengths. Else, if `"fixed"`, the semi-variogram values are divided according to distance intervals of equal lengths, with possibly different number of observations per interval. Else, if `"none"`, no collapsing is used and the individual semi-variogram values are returned. Defaults to `"quantiles"`. | | `nint` | an optional integer with the number of intervals to be used when collapsing the semi-variogram values. Defaults to `20`. | | `robust` | an optional logical value specifying if a robust semi-variogram estimator should be used when collapsing the individual values. If `TRUE` the robust estimator is used. Defaults to `FALSE`. | | `breaks` | an optional numeric vector with the breakpoints for the distance intervals to be used in collapsing the semi-variogram values. If not missing, the option specified in `collapse` is ignored. | | `metric` | an optional character string specifying the distance metric to be used. The currently available options are `"euclidean"` for the root sum-of-squares of distances; `"maximum"` for the maximum difference; and `"manhattan"` for the sum of the absolute differences. Partial matching of arguments is used, so only the first three characters need to be provided. Defaults to `"euclidean"`. | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value a data frame with columns `variog` and `dist` representing, respectively, the semi-variogram values and the corresponding distances. If the semi-variogram values are collapsed, an extra column, `n.pairs`, with the number of residual pairs used in each semi-variogram calculation, is included in the returned data frame. If `object` includes a `corSpatial` element, a data frame with its corresponding semi-variogram is included in the returned value, as an attribute `"modelVariog"`. The returned value inherits from class `Variogram`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Cressie, N.A.C. (1993), "Statistics for Spatial Data", J. Wiley & Sons. ### See Also `<lme>`, `[Variogram](variogram)`, `[Variogram.default](variogram.default)`, `[Variogram.gls](variogram.gls)`, `[plot.Variogram](plot.variogram)` ### Examples ``` fm1 <- lme(weight ~ Time * Diet, data=BodyWeight, ~ Time | Rat) Variogram(fm1, form = ~ Time | Rat, nint = 10, robust = TRUE) ``` r None `Wheat2` Wheat Yield Trials ---------------------------- ### Description The `Wheat2` data frame has 224 rows and 5 columns. ### Format This data frame contains the following columns: Block an ordered factor with levels `4` < `2` < `3` < `1` variety a factor with levels `ARAPAHOE` `BRULE` `BUCKSKIN` `CENTURA` `CENTURK78` `CHEYENNE` `CODY` `COLT` `GAGE` `HOMESTEAD` `KS831374` `LANCER` `LANCOTA` `NE83404` `NE83406` `NE83407` `NE83432` `NE83498` `NE83T12` `NE84557` `NE85556` `NE85623` `NE86482` `NE86501` `NE86503` `NE86507` `NE86509` `NE86527` `NE86582` `NE86606` `NE86607` `NE86T666` `NE87403` `NE87408` `NE87409` `NE87446` `NE87451` `NE87457` `NE87463` `NE87499` `NE87512` `NE87513` `NE87522` `NE87612` `NE87613` `NE87615` `NE87619` `NE87627` `NORKAN` `REDLAND` `ROUGHRIDER` `SCOUT66` `SIOUXLAND` `TAM107` `TAM200` `VONA` yield a numeric vector latitude a numeric vector longitude a numeric vector ### Source Pinheiro, J. C. and Bates, D. M. (2000), *Mixed-Effects Models in S and S-PLUS*, Springer, New York. r None `Matrix.pdMat` Assign Matrix to a pdMat or pdBlocked Object ------------------------------------------------------------ ### Description The positive-definite matrix represented by `object` is replaced by `value`. If the original matrix had row and/or column names, the corresponding names for `value` can either be `NULL`, or a permutation of the original names. ### Usage ``` ## S3 replacement method for class 'pdMat' matrix(object) <- value ## S3 replacement method for class 'pdBlocked' matrix(object) <- value ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"[pdMat](pdmat)"`, representing a positive definite matrix. | | `value` | a matrix with the new values to be assigned to the positive-definite matrix represented by `object`. Must have the same dimensions as `as.matrix(object)`. | ### Value a `pdMat` or `pdBlocked` object similar to `object`, but with its coefficients modified to produce the matrix in `value`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[pdMat](pdmat)`, `"[matrix<-](matrix)"` ### Examples ``` class(pd1 <- pdSymm(diag(3))) # "pdSymm" "pdMat" matrix(pd1) <- diag(1:3) pd1 ``` r None `lmList.groupedData` lmList Fit from a groupedData Object ---------------------------------------------------------- ### Description The response variable and primary covariate in `formula(object)` are used to construct the linear model formula. This formula and the `groupedData` object are passed as the `object` and `data` arguments to `lmList.formula`, together with any other additional arguments in the function call. See the documentation on `lmList.formula` for a description of that function. ### Usage ``` ## S3 method for class 'groupedData' lmList(object, data, level, subset, na.action = na.fail, pool = TRUE, warn.lm = TRUE) ``` ### Arguments | | | | --- | --- | | `object` | a data frame inheriting from class `"[groupedData](groupeddata)"`. | | `data` | this argument is included for consistency with the generic function. It is ignored in this method function. | | `level` | an optional integer specifying the level of grouping to be used when multiple nested levels of grouping are present. | | `subset` | an optional expression indicating which subset of the rows of `data` should be used in the fit. This can be a logical vector, or a numeric vector indicating which observation numbers are to be included, or a character vector of the row names to be included. All observations are included by default. | | `na.action` | a function that indicates what should happen when the data contain `NA`s. The default action (`na.fail`) causes `lmList` to print an error message and terminate if there are any incomplete observations. | | `pool, warn.lm` | optional `[logical](../../base/html/logical)`s, see `[lmList](lmlist)`. | ### Value a list of `lm` objects with as many components as the number of groups defined by the grouping factor. Generic functions such as `coef`, `fixed.effects`, `lme`, `pairs`, `plot`, `predict`, `random.effects`, `summary`, and `update` have methods that can be applied to an `lmList` object. ### See Also `[groupedData](groupeddata)`, `[lm](../../stats/html/lm)`, `[lme.lmList](lme.lmlist)`, `[lmList](lmlist)`, `[lmList.formula](lmlist)` ### Examples ``` fm1 <- lmList(Orthodont) summary(fm1) ```
programming_docs
r None `Oxboys` Heights of Boys in Oxford ----------------------------------- ### Description The `Oxboys` data frame has 234 rows and 4 columns. ### Format This data frame contains the following columns: Subject an ordered factor giving a unique identifier for each boy in the experiment age a numeric vector giving the standardized age (dimensionless) height a numeric vector giving the height of the boy (cm) Occasion an ordered factor - the result of converting `age` from a continuous variable to a count so these slightly unbalanced data can be analyzed as balanced. ### Details These data are described in Goldstein (1987) as data on the height of a selection of boys from Oxford, England versus a standardized age. ### Source Pinheiro, J. C. and Bates, D. M. (2000), *Mixed-Effects Models in S and S-PLUS*, Springer, New York. (Appendix A.19) r None `plot.lmList` Plot an lmList Object ------------------------------------ ### Description Diagnostic plots for the linear model fits corresponding to the `x` components are obtained. The `form` argument gives considerable flexibility in the type of plot specification. A conditioning expression (on the right side of a `|` operator) always implies that different panels are used for each level of the conditioning factor, according to a Trellis display. If `form` is a one-sided formula, histograms of the variable on the right hand side of the formula, before a `|` operator, are displayed (the Trellis function `histogram` is used). If `form` is two-sided and both its left and right hand side variables are numeric, scatter plots are displayed (the Trellis function `xyplot` is used). Finally, if `form` is two-sided and its left had side variable is a factor, box-plots of the right hand side variable by the levels of the left hand side variable are displayed (the Trellis function `bwplot` is used). ### Usage ``` ## S3 method for class 'lmList' plot(x, form, abline, id, idLabels, grid, ...) ``` ### Arguments | | | | --- | --- | | `x` | an object inheriting from class `"[lmList](lmlist)"`, representing a list of `lm` objects with a common model. | | `form` | an optional formula specifying the desired type of plot. Any variable present in the original data frame used to obtain `x` can be referenced. In addition, `x` itself can be referenced in the formula using the symbol `"."`. Conditional expressions on the right of a `|` operator can be used to define separate panels in a Trellis display. Default is `resid(., type = "pool") ~ fitted(.)` , corresponding to a plot of the standardized residuals (using a pooled estimate for the residual standard error) versus fitted values. | | `abline` | an optional numeric value, or numeric vector of length two. If given as a single value, a horizontal line will be added to the plot at that coordinate; else, if given as a vector, its values are used as the intercept and slope for a line added to the plot. If missing, no lines are added to the plot. | | `id` | an optional numeric value, or one-sided formula. If given as a value, it is used as a significance level for a two-sided outlier test for the standardized residuals. Observations with absolute standardized residuals greater than the *1 - value/2* quantile of the standard normal distribution are identified in the plot using `idLabels`. If given as a one-sided formula, its right hand side must evaluate to a logical, integer, or character vector which is used to identify observations in the plot. If missing, no observations are identified. | | `idLabels` | an optional vector, or one-sided formula. If given as a vector, it is converted to character and used to label the observations identified according to `id`. If given as a one-sided formula, its right hand side must evaluate to a vector which is converted to character and used to label the identified observations. Default is `getGroups(x)`. | | `grid` | an optional logical value indicating whether a grid should be added to plot. Default depends on the type of Trellis plot used: if `xyplot` defaults to `TRUE`, else defaults to `FALSE`. | | `...` | optional arguments passed to the Trellis plot function. | ### Value a diagnostic Trellis plot. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[lmList](lmlist)`,`[predict.lm](../../stats/html/predict.lm)`, `[xyplot](../../lattice/html/xyplot)`, `[bwplot](../../lattice/html/xyplot)`, `[histogram](../../lattice/html/histogram)` ### Examples ``` fm1 <- lmList(distance ~ age | Subject, Orthodont) # standardized residuals versus fitted values by gender plot(fm1, resid(., type = "pool") ~ fitted(.) | Sex, abline = 0, id = 0.05) # box-plots of residuals by Subject plot(fm1, Subject ~ resid(.)) # observed versus fitted values by Subject plot(fm1, distance ~ fitted(.) | Subject, abline = c(0,1)) ``` r None `getGroups.lme` Extract lme Object Groups ------------------------------------------ ### Description The grouping factors corresponding to the linear mixed-effects model represented by `object` are extracted. If more than one level is indicated in `level`, the corresponding grouping factors are combined into a data frame; else the selected grouping factor is returned as a vector. ### Usage ``` ## S3 method for class 'lme' getGroups(object, form, level, data, sep) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `lme`, representing a fitted linear mixed-effects model. | | `form` | this argument is included to make the method function compatible with the generic and is ignored in this method. | | `level` | an optional integer vector giving the level(s) of grouping to be extracted from `object`. Defaults to the highest or innermost level of grouping. | | `data` | unused | | `sep` | character, the separator to use between group levels when multiple levels are collapsed. The default is `'/'`. | ### Value either a data frame with columns given by the grouping factors indicated in `level`, or, when a single level is requested, a factor representing the selected grouping factor. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `<lme>` ### Examples ``` fm1 <- lme(pixel ~ day + day^2, Pixel, random = list(Dog = ~day, Side = ~1)) getGroups(fm1, level = 1:2) ``` r None `varExp` Exponential Variance Function --------------------------------------- ### Description This function is a constructor for the `varExp` class, representing an exponential variance function structure. Letting *v* denote the variance covariate and *s2(v)* denote the variance function evaluated at *v*, the exponential variance function is defined as *s2(v) = exp(2\* t \* v)*, where *t* is the variance function coefficient. When a grouping factor is present, a different *t* is used for each factor level. ### Usage ``` varExp(value, form, fixed) ``` ### Arguments | | | | --- | --- | | `value` | an optional numeric vector, or list of numeric values, with the variance function coefficients. `Value` must have length one, unless a grouping factor is specified in `form`. If `value` has length greater than one, it must have names which identify its elements to the levels of the grouping factor defined in `form`. If a grouping factor is present in `form` and `value` has length one, its value will be assigned to all grouping levels. Default is `numeric(0)`, which results in a vector of zeros of appropriate length being assigned to the coefficients when `object` is initialized (corresponding to constant variance equal to one). | | `form` | an optional one-sided formula of the form `~ v`, or `~ v | g`, specifying a variance covariate `v` and, optionally, a grouping factor `g` for the coefficients. The variance covariate must evaluate to a numeric vector and may involve expressions using `"."`, representing a fitted model object from which fitted values (`fitted(.)`) and residuals (`resid(.)`) can be extracted (this allows the variance covariate to be updated during the optimization of an object function). When a grouping factor is present in `form`, a different coefficient value is used for each of its levels. Several grouping variables may be simultaneously specified, separated by the `*` operator, like in `~ v | g1 * g2 * g3`. In this case, the levels of each grouping variable are pasted together and the resulting factor is used to group the observations. Defaults to `~ fitted(.)` representing a variance covariate given by the fitted values of a fitted model object and no grouping factor. | | `fixed` | an optional numeric vector, or list of numeric values, specifying the values at which some or all of the coefficients in the variance function should be fixed. If a grouping factor is specified in `form`, `fixed` must have names identifying which coefficients are to be fixed. Coefficients included in `fixed` are not allowed to vary during the optimization of an objective function. Defaults to `NULL`, corresponding to no fixed coefficients. | ### Value a `varExp` object representing an exponential variance function structure, also inheriting from class `varFunc`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Pinheiro, J.C., and Bates, D.M. (2000) "Mixed-Effects Models in S and S-PLUS", Springer. ### See Also `[varClasses](varclasses)`, `[varWeights.varFunc](varweights)`, `[coef.varExp](coef.varfunc)` ### Examples ``` vf1 <- varExp(0.2, form = ~age|Sex) ``` r None `Phenobarb` Phenobarbitol Kinetics ----------------------------------- ### Description The `Phenobarb` data frame has 744 rows and 7 columns. ### Format This data frame contains the following columns: Subject an ordered factor identifying the infant. Wt a numeric vector giving the birth weight of the infant (kg). Apgar an ordered factor giving the 5-minute Apgar score for the infant. This is an indication of health of the newborn infant. ApgarInd a factor indicating whether the 5-minute Apgar score is `< 5` or `>= 5`. time a numeric vector giving the time when the sample is drawn or drug administered (hr). dose a numeric vector giving the dose of drug administered (*μ*g/kg). conc a numeric vector giving the phenobarbital concentration in the serum (*μ*g/L). ### Details Data from a pharmacokinetics study of phenobarbital in neonatal infants. During the first few days of life the infants receive multiple doses of phenobarbital for prevention of seizures. At irregular intervals blood samples are drawn and serum phenobarbital concentrations are determined. The data were originally given in Grasela and Donn(1985) and are analyzed in Boeckmann, Sheiner and Beal (1994), in Davidian and Giltinan (1995), and in Littell et al. (1996). ### Source Pinheiro, J. C. and Bates, D. M. (2000), *Mixed-Effects Models in S and S-PLUS*, Springer, New York. (Appendix A.23) Davidian, M. and Giltinan, D. M. (1995), *Nonlinear Models for Repeated Measurement Data*, Chapman and Hall, London. (section 6.6) Grasela and Donn (1985), Neonatal population pharmacokinetics of phenobarbital derived from routine clinical data, *Developmental Pharmacology and Therapeutics*, **8**, 374-383. Boeckmann, A. J., Sheiner, L. B., and Beal, S. L. (1994), *NONMEM Users Guide: Part V*, University of California, San Francisco. Littell, R. C., Milliken, G. A., Stroup, W. W. and Wolfinger, R. D. (1996), *SAS System for Mixed Models*, SAS Institute, Cary, NC. r None `asOneFormula` Combine Formulas of a Set of Objects ---------------------------------------------------- ### Description The names of all variables used in the formulas extracted from the objects defined in `...` are converted into a single linear formula, with the variables names separated by `+`. ### Usage ``` asOneFormula(..., omit) ``` ### Arguments | | | | --- | --- | | `...` | objects, or lists of objects, from which a formula can be extracted. | | `omit` | an optional character vector with the names of variables to be omitted from the returned formula. Defaults to c(".", "pi"). | ### Value a one-sided linear formula with all variables named in the formulas extracted from the objects in `...`, except the ones listed in `omit`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[formula](../../stats/html/formula)`, `[all.vars](../../base/html/allnames)` ### Examples ``` asOneFormula(y ~ x + z | g, list(~ w, ~ t * sin(2 * pi))) ``` r None `getData.lmList` Extract lmList Object Data -------------------------------------------- ### Description If present in the calling sequence used to produce `object`, the data frame used to fit the model is obtained. ### Usage ``` ## S3 method for class 'lmList' getData(object) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `lmList`, representing a list of `lm` objects with a common model. | ### Value if a `data` argument is present in the calling sequence that produced `object`, the corresponding data frame (with `na.action` and `subset` applied to it, if also present in the call that produced `object`) is returned; else, `NULL` is returned. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[lmList](lmlist)`, `[getData](getdata)` ### Examples ``` fm1 <- lmList(distance ~ age | Subject, Orthodont) getData(fm1) ``` r None `print.summary.pdMat` Print a summary.pdMat Object --------------------------------------------------- ### Description The standard deviations and correlations associated with the positive-definite matrix represented by `object` (considered as a variance-covariance matrix) are printed, together with the formula and the grouping level associated `object`, if any are present. ### Usage ``` ## S3 method for class 'summary.pdMat' print(x, sigma, rdig, Level, resid, ...) ``` ### Arguments | | | | --- | --- | | `x` | an object inheriting from class `"[summary.pdMat](summary.pdmat)"`, generally resulting from applying `[summary](../../base/html/summary)` to an object inheriting from class `"[pdMat](pdmat)"`. | | `sigma` | an optional numeric value used as a multiplier for the square-root factor of the positive-definite matrix represented by `object` (usually the estimated within-group standard deviation from a mixed-effects model). Defaults to 1. | | `rdig` | an optional integer value with the number of significant digits to be used in printing correlations. Defaults to 3. | | `Level` | an optional character string with a description of the grouping level associated with `object` (generally corresponding to levels of grouping in a mixed-effects model). Defaults to NULL. | | `resid` | an optional logical value. If `TRUE` an extra row with the `"residual"` standard deviation given in `sigma` will be included in the output. Defaults to `FALSE`. | | `...` | optional arguments passed to `print.default`; see the documentation on that method function. | ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[summary.pdMat](summary.pdmat)`,`[pdMat](pdmat)` ### Examples ``` pd1 <- pdCompSymm(3 * diag(2) + 1, form = ~age + age^2, data = Orthodont) print(summary(pd1), sigma = 1.2, resid = TRUE) ``` r None `corGaus` Gaussian Correlation Structure ----------------------------------------- ### Description This function is a constructor for the `corGaus` class, representing a Gaussian spatial correlation structure. Letting *d* denote the range and *n* denote the nugget effect, the correlation between two observations a distance *r* apart is *exp(-(r/d)^2)* when no nugget effect is present and *(1-n)\*exp(-(r/d)^2)* when a nugget effect is assumed. Objects created using this constructor must later be initialized using the appropriate ' `Initialize` method. ### Usage ``` corGaus(value, form, nugget, metric, fixed) ``` ### Arguments | | | | --- | --- | | `value` | an optional vector with the parameter values in constrained form. If `nugget` is `FALSE`, `value` can have only one element, corresponding to the "range" of the Gaussian correlation structure, which must be greater than zero. If `nugget` is `TRUE`, meaning that a nugget effect is present, `value` can contain one or two elements, the first being the "range" and the second the "nugget effect" (one minus the correlation between two observations taken arbitrarily close together); the first must be greater than zero and the second must be between zero and one. Defaults to `numeric(0)`, which results in a range of 90% of the minimum distance and a nugget effect of 0.1 being assigned to the parameters when `object` is initialized. | | `form` | a one sided formula of the form `~ S1+...+Sp`, or `~ S1+...+Sp | g`, specifying spatial covariates `S1` through `Sp` and, optionally, a grouping factor `g`. When a grouping factor is present in `form`, the correlation structure is assumed to apply only to observations within the same grouping level; observations with different grouping levels are assumed to be uncorrelated. Defaults to `~ 1`, which corresponds to using the order of the observations in the data as a covariate, and no groups. | | `nugget` | an optional logical value indicating whether a nugget effect is present. Defaults to `FALSE`. | | `metric` | an optional character string specifying the distance metric to be used. The currently available options are `"euclidean"` for the root sum-of-squares of distances; `"maximum"` for the maximum difference; and `"manhattan"` for the sum of the absolute differences. Partial matching of arguments is used, so only the first three characters need to be provided. Defaults to `"euclidean"`. | | `fixed` | an optional logical value indicating whether the coefficients should be allowed to vary in the optimization, or kept fixed at their initial value. Defaults to `FALSE`, in which case the coefficients are allowed to vary. | ### Value an object of class `corGaus`, also inheriting from class `corSpatial`, representing a Gaussian spatial correlation structure. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Cressie, N.A.C. (1993), "Statistics for Spatial Data", J. Wiley & Sons. Venables, W.N. and Ripley, B.D. (2002) "Modern Applied Statistics with S", 4th Edition, Springer-Verlag. Littel, Milliken, Stroup, and Wolfinger (1996) "SAS Systems for Mixed Models", SAS Institute. Pinheiro, J.C., and Bates, D.M. (2000) "Mixed-Effects Models in S and S-PLUS", Springer. ### See Also `[Initialize.corStruct](initialize.corstruct)`, `[summary.corStruct](summary.corstruct)`, `[dist](../../stats/html/dist)` ### Examples ``` sp1 <- corGaus(form = ~ x + y + z) # example lme(..., corGaus ...) # Pinheiro and Bates, pp. 222-249 fm1BW.lme <- lme(weight ~ Time * Diet, BodyWeight, random = ~ Time) # p. 223 fm2BW.lme <- update(fm1BW.lme, weights = varPower()) # p 246 fm3BW.lme <- update(fm2BW.lme, correlation = corExp(form = ~ Time)) # p. 249 fm8BW.lme <- update(fm3BW.lme, correlation = corGaus(form = ~ Time)) ``` r None `residuals.gls` Extract gls Residuals -------------------------------------- ### Description The residuals for the linear model represented by `object` are extracted. ### Usage ``` ## S3 method for class 'gls' residuals(object, type, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"<gls>"`, representing a generalized least squares fitted linear model, or from class `gnls`, representing a generalized nonlinear least squares fitted linear model. | | `type` | an optional character string specifying the type of residuals to be used. If `"response"`, the "raw" residuals (observed - fitted) are used; else, if `"pearson"`, the standardized residuals (raw residuals divided by the corresponding standard errors) are used; else, if `"normalized"`, the normalized residuals (standardized residuals pre-multiplied by the inverse square-root factor of the estimated error correlation matrix) are used. Partial matching of arguments is used, so only the first character needs to be provided. Defaults to `"response"`. | | `...` | some methods for this generic function require additional arguments. None are used in this method. | ### Value a vector with the residuals for the linear model represented by `object`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `<gls>` ### Examples ``` fm1 <- gls(follicles ~ sin(2*pi*Time) + cos(2*pi*Time), Ovary, correlation = corAR1(form = ~ 1 | Mare)) residuals(fm1) ```
programming_docs
r None `corSymm` General Correlation Structure ---------------------------------------- ### Description This function is a constructor for the `corSymm` class, representing a general correlation structure. The internal representation of this structure, in terms of unconstrained parameters, uses the spherical parametrization defined in Pinheiro and Bates (1996). Objects created using this constructor must later be initialized using the appropriate `Initialize` method. ### Usage ``` corSymm(value, form, fixed) ``` ### Arguments | | | | --- | --- | | `value` | an optional vector with the parameter values. Default is `numeric(0)`, which results in a vector of zeros of appropriate dimension being assigned to the parameters when `object` is initialized (corresponding to an identity correlation structure). | | `form` | a one sided formula of the form `~ t`, or `~ t | g`, specifying a time covariate `t` and, optionally, a grouping factor `g`. A covariate for this correlation structure must be integer valued. When a grouping factor is present in `form`, the correlation structure is assumed to apply only to observations within the same grouping level; observations with different grouping levels are assumed to be uncorrelated. Defaults to `~ 1`, which corresponds to using the order of the observations in the data as a covariate, and no groups. | | `fixed` | an optional logical value indicating whether the coefficients should be allowed to vary in the optimization, or kept fixed at their initial value. Defaults to `FALSE`, in which case the coefficients are allowed to vary. | ### Value an object of class `corSymm` representing a general correlation structure. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Pinheiro, J.C. and Bates., D.M. (1996) "Unconstrained Parametrizations for Variance-Covariance Matrices", Statistics and Computing, 6, 289-296. Pinheiro, J.C., and Bates, D.M. (2000) "Mixed-Effects Models in S and S-PLUS", Springer. ### See Also `[Initialize.corSymm](initialize.corstruct)`, `[summary.corSymm](summary.corstruct)` ### Examples ``` ## covariate is observation order and grouping factor is Subject cs1 <- corSymm(form = ~ 1 | Subject) # Pinheiro and Bates, p. 225 cs1CompSymm <- corCompSymm(value = 0.3, form = ~ 1 | Subject) cs1CompSymm <- Initialize(cs1CompSymm, data = Orthodont) corMatrix(cs1CompSymm) # Pinheiro and Bates, p. 226 cs1Symm <- corSymm(value = c(0.2, 0.1, -0.1, 0, 0.2, 0), form = ~ 1 | Subject) cs1Symm <- Initialize(cs1Symm, data = Orthodont) corMatrix(cs1Symm) # example gls(..., corSpher ...) # Pinheiro and Bates, pp. 261, 263 fm1Wheat2 <- gls(yield ~ variety - 1, Wheat2) # p. 262 fm2Wheat2 <- update(fm1Wheat2, corr = corSpher(c(28, 0.2), form = ~ latitude + longitude, nugget = TRUE)) # example gls(..., corSymm ... ) # Pinheiro and Bates, p. 251 fm1Orth.gls <- gls(distance ~ Sex * I(age - 11), Orthodont, correlation = corSymm(form = ~ 1 | Subject), weights = varIdent(form = ~ 1 | age)) ``` r None `getCovariate.corStruct` Extract corStruct Object Covariate ------------------------------------------------------------ ### Description This method function extracts the covariate(s) associated with `object`. ### Usage ``` ## S3 method for class 'corStruct' getCovariate(object, form, data) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `corStruct` representing a correlation structure. | | `form` | this argument is included to make the method function compatible with the generic. It will be assigned the value of `formula(object)` and should not be modified. | | `data` | an optional data frame in which to evaluate the variables defined in `form`, in case `object` is not initialized and the covariate needs to be evaluated. | ### Value when the correlation structure does not include a grouping factor, the returned value will be a vector or a matrix with the covariate(s) associated with `object`. If a grouping factor is present, the returned value will be a list of vectors or matrices with the covariate(s) corresponding to each grouping level. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Pinheiro, J.C., and Bates, D.M. (2000) "Mixed-Effects Models in S and S-PLUS", Springer. ### See Also `[getCovariate](getcovariate)` ### Examples ``` cs1 <- corAR1(form = ~ 1 | Subject) getCovariate(cs1, data = Orthodont) ``` r None `recalc` Recalculate Condensed Linear Model Object --------------------------------------------------- ### Description This function is generic; method functions can be written to handle specific classes of objects. Classes which already have methods for this function include: `corStruct`, `modelStruct`, `reStruct`, and `varFunc`. ### Usage ``` recalc(object, conLin, ...) ``` ### Arguments | | | | --- | --- | | `object` | any object which induces a recalculation of the condensed linear model object `conLin`. | | `conLin` | a condensed linear model object, consisting of a list with components `"Xy"`, corresponding to a regression matrix (`X`) combined with a response vector (`y`), and `"logLik"`, corresponding to the log-likelihood of the underlying model. | | `...` | some methods for this generic can take additional arguments. | ### Value the recalculated condensed linear model object. ### Note This function is only used inside model fitting functions, such as `lme` and `gls`, that require recalculation of a condensed linear model object. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[recalc.corStruct](recalc.corstruct)`, `[recalc.modelStruct](recalc.modelstruct)`, `[recalc.reStruct](recalc.restruct)`, `[recalc.varFunc](recalc.varfunc)` ### Examples ``` ## see the method function documentation ``` r None `Machines` Productivity Scores for Machines and Workers -------------------------------------------------------- ### Description The `Machines` data frame has 54 rows and 3 columns. ### Format This data frame contains the following columns: Worker an ordered factor giving the unique identifier for the worker. Machine a factor with levels `A`, `B`, and `C` identifying the machine brand. score a productivity score. ### Details Data on an experiment to compare three brands of machines used in an industrial process are presented in Milliken and Johnson (p. 285, 1992). Six workers were chosen randomly among the employees of a factory to operate each machine three times. The response is an overall productivity score taking into account the number and quality of components produced. ### Source Pinheiro, J. C. and Bates, D. M. (2000), *Mixed-Effects Models in S and S-PLUS*, Springer, New York. (Appendix A.14) Milliken, G. A. and Johnson, D. E. (1992), *Analysis of Messy Data, Volume I: Designed Experiments*, Chapman and Hall, London. r None `varComb` Combination of Variance Functions -------------------------------------------- ### Description This function is a constructor for the `varComb` class, representing a combination of variance functions. The corresponding variance function is equal to the product of the variance functions of the `varFunc` objects listed in `...`. ### Usage ``` varComb(...) ``` ### Arguments | | | | --- | --- | | `...` | objects inheriting from class `varFunc` representing variance function structures. | ### Value a `varComb` object representing a combination of variance functions, also inheriting from class `varFunc`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Pinheiro, J.C., and Bates, D.M. (2000) "Mixed-Effects Models in S and S-PLUS", Springer. ### See Also `[varClasses](varclasses)`, `[varWeights.varComb](varweights)`, `[coef.varComb](coef.varfunc)` ### Examples ``` vf1 <- varComb(varIdent(form = ~1|Sex), varPower()) ``` r None `Alfalfa` Split-Plot Experiment on Varieties of Alfalfa -------------------------------------------------------- ### Description The `Alfalfa` data frame has 72 rows and 4 columns. ### Format This data frame contains the following columns: Variety a factor with levels `Cossack`, `Ladak`, and `Ranger` Date a factor with levels `None` `S1` `S20` `O7` Block a factor with levels `1` `2` `3` `4` `5` `6` Yield a numeric vector ### Details These data are described in Snedecor and Cochran (1980) as an example of a split-plot design. The treatment structure used in the experiment was a 3*\times*4 full factorial, with three varieties of alfalfa and four dates of third cutting in 1943. The experimental units were arranged into six blocks, each subdivided into four plots. The varieties of alfalfa (*Cossac*, *Ladak*, and *Ranger*) were assigned randomly to the blocks and the dates of third cutting (*None*, *S1*—September 1, *S20*—September 20, and *O7*—October 7) were randomly assigned to the plots. All four dates were used on each block. ### Source Pinheiro, J. C. and Bates, D. M. (2000), *Mixed-Effects Models in S and S-PLUS*, Springer, New York. (Appendix A.1) Snedecor, G. W. and Cochran, W. G. (1980), *Statistical Methods (7th ed)*, Iowa State University Press, Ames, IA r None `logLik.glsStruct` Log-Likelihood of a glsStruct Object -------------------------------------------------------- ### Description `Pars` is used to update the coefficients of the model components of `object` and the individual (restricted) log-likelihood contributions of each component are added together. The type of log-likelihood (restricted or not) is determined by the `settings` attribute of `object`. ### Usage ``` ## S3 method for class 'glsStruct' logLik(object, Pars, conLin, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"[glsStruct](glsstruct)"`, representing a list of linear model components, such as `corStruct` and `"[varFunc](varfunc)"` objects. | | `Pars` | the parameter values at which the (restricted) log-likelihood is to be evaluated. | | `conLin` | an optional condensed linear model object, consisting of a list with components `"Xy"`, corresponding to a regression matrix (`X`) combined with a response vector (`y`), and `"logLik"`, corresponding to the log-likelihood of the underlying linear model. Defaults to `attr(object, "conLin")`. | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value the (restricted) log-likelihood for the linear model described by `object`, evaluated at `Pars`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `<gls>`, `[glsStruct](glsstruct)`, `[logLik.lme](loglik.lme)` r None `getGroups.data.frame` Extract Groups from a Data Frame -------------------------------------------------------- ### Description Each variable named in the expression after the `|` operator on the right hand side of `form` is evaluated in `object`. If more than one variable is indicated in `level` they are combined into a data frame; else the selected variable is returned as a vector. When multiple grouping levels are defined in `form` and `level > 1`, the levels of the returned factor are obtained by pasting together the levels of the grouping factors of level greater or equal to `level`, to ensure their uniqueness. ### Usage ``` ## S3 method for class 'data.frame' getGroups(object, form, level, data, sep) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `data.frame`. | | `form` | an optional formula with a conditioning expression on its right hand side (i.e. an expression involving the `|` operator). Defaults to `formula(object)`. | | `level` | a positive integer vector with the level(s) of grouping to be used when multiple nested levels of grouping are present. Defaults to all levels of nesting. | | `data` | unused | | `sep` | character, the separator to use between group levels when multiple levels are collapsed. The default is `'/'`. | ### Value either a data frame with columns given by the grouping factors indicated in `level`, from outer to inner, or, when a single level is requested, a factor representing the selected grouping factor. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Pinheiro, J.C., and Bates, D.M. (2000) "Mixed-Effects Models in S and S-PLUS", Springer, esp. pp. 100, 461. ### See Also `[getGroupsFormula](getgroupsformula)` ### Examples ``` getGroups(Pixel) getGroups(Pixel, level = 2) ``` r None `simulate.lme` Simulate Results from lme Models ------------------------------------------------ ### Description The model `object` is fit to the data. Using the fitted values of the parameters, `nsim` new data vectors from this model are simulated. Both `object` and `m2` are fit by maximum likelihood (ML) and/or by restricted maximum likelihood (REML) to each of the simulated data vectors. ### Usage ``` ## S3 method for class 'lme' simulate(object, nsim = 1, seed = , m2, method = c("REML", "ML"), niterEM = c(40, 200), useGen, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"<lme>"`, representing a fitted linear mixed-effects model, or a list containing an `lme` model specification. If given as a list, it should contain components `fixed`, `data`, and `random` with values suitable for a call to `<lme>`. This argument defines the null model. | | `m2` | an `"<lme>"` object or a list, like `object` containing a second lme model specification. This argument defines the alternative model. If given as a list, only those parts of the specification that change between model `object` and `m2` need to be specified. | | `seed` | an optional integer that is passed to `set.seed`. Defaults to a random integer. | | `method` | an optional character array. If it includes `"REML"` the models are fit by maximizing the restricted log-likelihood. If it includes `"ML"` the log-likelihood is maximized. Defaults to `c("REML", "ML")`, in which case both methods are used. | | `nsim` | an optional positive integer specifying the number of simulations to perform. Defaults to `1`. **This has changed. Previously the default was 1000.** | | `niterEM` | an optional integer vector of length 2 giving the number of iterations of the EM algorithm to apply when fitting the `object` and `m2` to each simulated set of data. Defaults to `c(40,200)`. | | `useGen` | an optional logical value. If `TRUE`, numerical derivatives are used to obtain the gradient and the Hessian of the log-likelihood in the optimization algorithm in the `ms` function. If `FALSE`, the default algorithm in `ms` for functions that do not incorporate gradient and Hessian attributes is used. Default depends on the `"[pdMat](pdmat)"` classes used in `object` and `m2`: if both are standard classes (see `[pdClasses](pdclasses)`) then defaults to `TRUE`, otherwise defaults to `FALSE`. | | `...` | optional additional arguments. None are used. | ### Value an object of class `simulate.lme` with components `null` and `alt`. Each of these has components `ML` and/or `REML` which are matrices. An attribute called `Random.seed` contains the seed that was used for the random number generator. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Pinheiro, J.C., and Bates, D.M. (2000) *Mixed-Effects Models in S and S-PLUS*, Springer. ### See Also `<lme>`, `[set.seed](../../base/html/random)` ### Examples ``` orthSim <- simulate.lme(list(fixed = distance ~ age, data = Orthodont, random = ~ 1 | Subject), nsim = 200, m2 = list(random = ~ age | Subject)) ``` r None `plot.compareFits` Plot a compareFits Object --------------------------------------------- ### Description A Trellis `dotplot` of the values being compared, with different rows per group, is generated, with a different panel for each coefficient. Different symbols (colors) are used for each object being compared. ### Usage ``` ## S3 method for class 'compareFits' plot(x, subset, key, mark, ...) ``` ### Arguments | | | | --- | --- | | `x` | an object of class `"[compareFits](comparefits)"`. | | `subset` | an optional logical or integer vector specifying which rows of `x` should be used in the plots. If missing, all rows are used. | | `key` | an optional logical value, or list. If `TRUE`, a legend is included at the top of the plot indicating which symbols (colors) correspond to which objects being compared. If `FALSE`, no legend is included. If given as a list, `key` is passed down as an argument to the `trellis` function generating the plots (`dotplot`). Defaults to `TRUE`. | | `mark` | an optional numeric vector, of length equal to the number of coefficients being compared, indicating where vertical lines should be drawn in the plots. If missing, no lines are drawn. | | `...` | optional arguments passed down to the `trellis` function generating the plots. | ### Value A Trellis `dotplot` of the values being compared, with rows determined by the groups and panels by the coefficients. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[compareFits](comparefits)`, `[pairs.compareFits](pairs.comparefits)`, `[dotplot](../../lattice/html/xyplot)` ### Examples ``` example(compareFits) # cF12 <- compareFits(coef(lmList(Orthodont)), .. lme(*)) plot(cF12) ``` r None `coef.lmList` Extract lmList Coefficients ------------------------------------------ ### Description The coefficients of each `lm` object in the `object` list are extracted and organized into a data frame, with rows corresponding to the `lm` components and columns corresponding to the coefficients. Optionally, the returned data frame may be augmented with covariates summarized over the groups associated with the `lm` components. ### Usage ``` ## S3 method for class 'lmList' coef(object, augFrame, data, which, FUN, omitGroupingFactor, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"[lmList](lmlist)"`, representing a list of `lm` objects with a common model. | | `augFrame` | an optional logical value. If `TRUE`, the returned data frame is augmented with variables defined in the data frame used to produce `object`; else, if `FALSE`, only the coefficients are returned. Defaults to `FALSE`. | | `data` | an optional data frame with the variables to be used for augmenting the returned data frame when `augFrame = TRUE`. Defaults to the data frame used to fit `object`. | | `which` | an optional positive integer or character vector specifying which columns of the data frame used to produce `object` should be used in the augmentation of the returned data frame. Defaults to all variables in the data. | | `FUN` | an optional summary function or a list of summary functions to be applied to group-varying variables, when collapsing the data by groups. Group-invariant variables are always summarized by the unique value that they assume within that group. If `FUN` is a single function it will be applied to each non-invariant variable by group to produce the summary for that variable. If `FUN` is a list of functions, the names in the list should designate classes of variables in the frame such as `ordered`, `factor`, or `numeric`. The indicated function will be applied to any group-varying variables of that class. The default functions to be used are `mean` for numeric factors, and `Mode` for both `factor` and `ordered`. The `Mode` function, defined internally in `gsummary`, returns the modal or most popular value of the variable. It is different from the `mode` function that returns the S-language mode of the variable. | | `omitGroupingFactor` | an optional logical value. When `TRUE` the grouping factor itself will be omitted from the group-wise summary of `data` but the levels of the grouping factor will continue to be used as the row names for the returned data frame. Defaults to `FALSE`. | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value a data frame inheriting from class `"coef.lmList"` with the estimated coefficients for each `"lm"` component of `object` and, optionally, other covariates summarized over the groups corresponding to the `"lm"` components. The returned object also inherits from classes `"ranef.lmList"` and `"data.frame"`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Pinheiro, J. C. and Bates, D. M. (2000), *Mixed-Effects Models in S and S-PLUS*, Springer, New York, esp. pp. 457-458. ### See Also `[lmList](lmlist)`, `[fixed.effects.lmList](fixef.lmlist)`, `[ranef.lmList](ranef.lmlist)`, `[plot.ranef.lmList](plot.ranef.lmlist)`, `<gsummary>` ### Examples ``` fm1 <- lmList(distance ~ age|Subject, data = Orthodont) coef(fm1) coef(fm1, augFrame = TRUE) ```
programming_docs
r None `pdMat` Positive-Definite Matrix --------------------------------- ### Description This function gives an alternative way of constructing an object inheriting from the `pdMat` class named in `pdClass`, or from `data.class(object)` if `object` inherits from `pdMat`, and is mostly used internally in other functions. See the documentation on the principal constructor function, generally with the same name as the `pdMat` class of object. ### Usage ``` pdMat(value, form, nam, data, pdClass) ``` ### Arguments | | | | --- | --- | | `value` | an optional initialization value, which can be any of the following: a `pdMat` object, a positive-definite matrix, a one-sided linear formula (with variables separated by `+`), a vector of character strings, or a numeric vector. Defaults to `numeric(0)`, corresponding to an uninitialized object. | | `form` | an optional one-sided linear formula specifying the row/column names for the matrix represented by `object`. Because factors may be present in `form`, the formula needs to be evaluated on a data.frame to resolve the names it defines. This argument is ignored when `value` is a one-sided formula. Defaults to `NULL`. | | `nam` | an optional vector of character strings specifying the row/column names for the matrix represented by object. It must have length equal to the dimension of the underlying positive-definite matrix and unreplicated elements. This argument is ignored when `value` is a vector of character strings. Defaults to `NULL`. | | `data` | an optional data frame in which to evaluate the variables named in `value` and `form`. It is used to obtain the levels for `factors`, which affect the dimensions and the row/column names of the underlying matrix. If `NULL`, no attempt is made to obtain information on `factors` appearing in the formulas. Defaults to the parent frame from which the function was called. | | `pdClass` | an optional character string naming the `pdMat` class to be assigned to the returned object. This argument will only be used when `value` is not a `pdMat` object. Defaults to `"pdSymm"`. | ### Value a `pdMat` object representing a positive-definite matrix, inheriting from the class named in `pdClass`, or from `class(object)`, if `object` inherits from `pdMat`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Pinheiro, J.C., and Bates, D.M. (2000) "Mixed-Effects Models in S and S-PLUS", Springer. ### See Also `[pdClasses](pdclasses)`, `[pdCompSymm](pdcompsymm)`, `[pdDiag](pddiag)`, `[pdIdent](pdident)`, `[pdNatural](pdnatural)`, `[pdSymm](pdsymm)`, `[reStruct](restruct)`, `[solve.pdMat](solve.pdmat)`, `[summary.pdMat](summary.pdmat)` ### Examples ``` pd1 <- pdMat(diag(1:4), pdClass = "pdDiag") pd1 ``` r None `corRatio` Rational Quadratic Correlation Structure ---------------------------------------------------- ### Description This function is a constructor for the `corRatio` class, representing a rational quadratic spatial correlation structure. Letting *d* denote the range and *n* denote the nugget effect, the correlation between two observations a distance *r* apart is *1/(1+(r/d)^2)* when no nugget effect is present and *(1-n)/(1+(r/d)^2)* when a nugget effect is assumed. Objects created using this constructor need to be later initialized using the appropriate `Initialize` method. ### Usage ``` corRatio(value, form, nugget, metric, fixed) ``` ### Arguments | | | | --- | --- | | `value` | an optional vector with the parameter values in constrained form. If `nugget` is `FALSE`, `value` can have only one element, corresponding to the "range" of the rational quadratic correlation structure, which must be greater than zero. If `nugget` is `TRUE`, meaning that a nugget effect is present, `value` can contain one or two elements, the first being the "range" and the second the "nugget effect" (one minus the correlation between two observations taken arbitrarily close together); the first must be greater than zero and the second must be between zero and one. Defaults to `numeric(0)`, which results in a range of 90% of the minimum distance and a nugget effect of 0.1 being assigned to the parameters when `object` is initialized. | | `form` | a one sided formula of the form `~ S1+...+Sp`, or `~ S1+...+Sp | g`, specifying spatial covariates `S1` through `Sp` and, optionally, a grouping factor `g`. When a grouping factor is present in `form`, the correlation structure is assumed to apply only to observations within the same grouping level; observations with different grouping levels are assumed to be uncorrelated. Defaults to `~ 1`, which corresponds to using the order of the observations in the data as a covariate, and no groups. | | `nugget` | an optional logical value indicating whether a nugget effect is present. Defaults to `FALSE`. | | `metric` | an optional character string specifying the distance metric to be used. The currently available options are `"euclidean"` for the root sum-of-squares of distances; `"maximum"` for the maximum difference; and `"manhattan"` for the sum of the absolute differences. Partial matching of arguments is used, so only the first three characters need to be provided. Defaults to `"euclidean"`. | | `fixed` | an optional logical value indicating whether the coefficients should be allowed to vary in the optimization, or kept fixed at their initial value. Defaults to `FALSE`, in which case the coefficients are allowed to vary. | ### Value an object of class `corRatio`, also inheriting from class `corSpatial`, representing a rational quadratic spatial correlation structure. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Cressie, N.A.C. (1993), "Statistics for Spatial Data", J. Wiley & Sons. Venables, W.N. and Ripley, B.D. (2002) "Modern Applied Statistics with S", 4th Edition, Springer-Verlag. Littel, Milliken, Stroup, and Wolfinger (1996) "SAS Systems for Mixed Models", SAS Institute. Pinheiro, J.C., and Bates, D.M. (2000) "Mixed-Effects Models in S and S-PLUS", Springer. ### See Also `[Initialize.corStruct](initialize.corstruct)`, `[summary.corStruct](summary.corstruct)`, `[dist](../../stats/html/dist)` ### Examples ``` sp1 <- corRatio(form = ~ x + y + z) # example lme(..., corRatio ...) # Pinheiro and Bates, pp. 222-249 fm1BW.lme <- lme(weight ~ Time * Diet, BodyWeight, random = ~ Time) # p. 223 fm2BW.lme <- update(fm1BW.lme, weights = varPower()) # p 246 fm3BW.lme <- update(fm2BW.lme, correlation = corExp(form = ~ Time)) # p. 249 fm5BW.lme <- update(fm3BW.lme, correlation = corRatio(form = ~ Time)) # example gls(..., corRatio ...) # Pinheiro and Bates, pp. 261, 263 fm1Wheat2 <- gls(yield ~ variety - 1, Wheat2) # p. 263 fm3Wheat2 <- update(fm1Wheat2, corr = corRatio(c(12.5, 0.2), form = ~ latitude + longitude, nugget = TRUE)) ``` r None `plot.gls` Plot a gls Object ----------------------------- ### Description Diagnostic plots for the linear model fit are obtained. The `form` argument gives considerable flexibility in the type of plot specification. A conditioning expression (on the right side of a `|` operator) always implies that different panels are used for each level of the conditioning factor, according to a Trellis display. If `form` is a one-sided formula, histograms of the variable on the right hand side of the formula, before a `|` operator, are displayed (the Trellis function `histogram` is used). If `form` is two-sided and both its left and right hand side variables are numeric, scatter plots are displayed (the Trellis function `xyplot` is used). Finally, if `form` is two-sided and its left had side variable is a factor, box-plots of the right hand side variable by the levels of the left hand side variable are displayed (the Trellis function `bwplot` is used). ### Usage ``` ## S3 method for class 'gls' plot(x, form, abline, id, idLabels, idResType, grid, ...) ``` ### Arguments | | | | --- | --- | | `x` | an object inheriting from class `"<gls>"`, representing a generalized least squares fitted linear model. | | `form` | an optional formula specifying the desired type of plot. Any variable present in the original data frame used to obtain `x` can be referenced. In addition, `x` itself can be referenced in the formula using the symbol `"."`. Conditional expressions on the right of a `|` operator can be used to define separate panels in a Trellis display. Default is `resid(., type = "p") ~ fitted(.)` , corresponding to a plot of the standardized residuals versus fitted values, both evaluated at the innermost level of nesting. | | `abline` | an optional numeric value, or numeric vector of length two. If given as a single value, a horizontal line will be added to the plot at that coordinate; else, if given as a vector, its values are used as the intercept and slope for a line added to the plot. If missing, no lines are added to the plot. | | `id` | an optional numeric value, or one-sided formula. If given as a value, it is used as a significance level for a two-sided outlier test for the standardized residuals. Observations with absolute standardized residuals greater than the *1 - value/2* quantile of the standard normal distribution are identified in the plot using `idLabels`. If given as a one-sided formula, its right hand side must evaluate to a logical, integer, or character vector which is used to identify observations in the plot. If missing, no observations are identified. | | `idLabels` | an optional vector, or one-sided formula. If given as a vector, it is converted to character mode and used to label the observations identified according to `id`. If given as a one-sided formula, its right hand side must evaluate to a vector which is converted to character mode and used to label the identified observations. Default is the innermost grouping factor. | | `idResType` | an optional character string specifying the type of residuals to be used in identifying outliers, when `id` is a numeric value. If `"pearson"`, the standardized residuals (raw residuals divided by the corresponding standard errors) are used; else, if `"normalized"`, the normalized residuals (standardized residuals pre-multiplied by the inverse square-root factor of the estimated error correlation matrix) are used. Partial matching of arguments is used, so only the first character needs to be provided. Defaults to `"pearson"`. | | `grid` | an optional logical value indicating whether a grid should be added to plot. Default depends on the type of Trellis plot used: if `xyplot` defaults to `TRUE`, else defaults to `FALSE`. | | `...` | optional arguments passed to the Trellis plot function. | ### Value a diagnostic Trellis plot. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `<gls>`, `[xyplot](../../lattice/html/xyplot)`, `[bwplot](../../lattice/html/xyplot)`, `[histogram](../../lattice/html/histogram)` ### Examples ``` fm1 <- gls(follicles ~ sin(2*pi*Time) + cos(2*pi*Time), Ovary, correlation = corAR1(form = ~ 1 | Mare)) # standardized residuals versus fitted values by Mare plot(fm1, resid(., type = "p") ~ fitted(.) | Mare, abline = 0) # box-plots of residuals by Mare plot(fm1, Mare ~ resid(.)) # observed versus fitted values by Mare plot(fm1, follicles ~ fitted(.) | Mare, abline = c(0,1)) ``` r None `Dim.corSpatial` Dimensions of a corSpatial Object --------------------------------------------------- ### Description if `groups` is missing, it returns the `Dim` attribute of `object`; otherwise, calculates the dimensions associated with the grouping factor. ### Usage ``` ## S3 method for class 'corSpatial' Dim(object, groups, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"[corSpatial](corspatial)"`, representing a spatial correlation structure. | | `groups` | an optional factor defining the grouping of the observations; observations within a group are correlated and observations in different groups are uncorrelated. | | `...` | further arguments to be passed to or from methods. | ### Value a list with components: | | | | --- | --- | | `N` | length of `groups` | | `M` | number of groups | | `spClass` | an integer representing the spatial correlation class; 0 = user defined class, 1 = `corSpher`, 2 = `corExp`, 3 = `corGaus`, 4 = `corLin` | | `sumLenSq` | sum of the squares of the number of observations per group | | `len` | an integer vector with the number of observations per group | | `start` | an integer vector with the starting position for the distance vectors in each group, beginning from zero | ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[Dim](dim)`, `[Dim.corStruct](dim.corstruct)` ### Examples ``` Dim(corGaus(), getGroups(Orthodont)) cs1ARMA <- corARMA(0.4, form = ~ 1 | Subject, q = 1) cs1ARMA <- Initialize(cs1ARMA, data = Orthodont) Dim(cs1ARMA) ``` r None `pdFactor.reStruct` Extract Square-Root Factor from Components of an reStruct Object ------------------------------------------------------------------------------------- ### Description This method function extracts square-root factors of the positive-definite matrices corresponding to the `pdMat` elements of `object`. ### Usage ``` ## S3 method for class 'reStruct' pdFactor(object) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"[reStruct](restruct)"`, representing a random effects structure and consisting of a list of `pdMat` objects. | ### Value a vector with square-root factors of the positive-definite matrices corresponding to the elements of `object` stacked column-wise. ### Note This function is used intensively in optimization algorithms and its value is returned as a vector for efficiency reasons. The `pdMatrix` function can be used to obtain square-root factors in matrix form. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Pinheiro, J.C., and Bates, D.M. (2000) "Mixed-Effects Models in S and S-PLUS", Springer. ### See Also `[pdFactor](pdfactor)`, `[pdMatrix.reStruct](pdmatrix.restruct)`, `[pdFactor.pdMat](pdfactor)` ### Examples ``` rs1 <- reStruct(pdSymm(diag(3), ~age+Sex, data = Orthodont)) pdFactor(rs1) ``` r None `logLik.gnlsStruct` Log-Likelihood of a gnlsStruct Object ---------------------------------------------------------- ### Description `Pars` is used to update the coefficients of the model components of `object` and the individual log-likelihood contributions of each component are added together. ### Usage ``` ## S3 method for class 'gnlsStruct' logLik(object, Pars, conLin, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `gnlsStruct`, representing a list of model components, such as `corStruct` and `varFunc` objects, and attributes specifying the underlying nonlinear model and the response variable. | | `Pars` | the parameter values at which the log-likelihood is to be evaluated. | | `conLin` | an optional condensed linear model object, consisting of a list with components `"Xy"`, corresponding to a regression matrix (`X`) combined with a response vector (`y`), and `"logLik"`, corresponding to the log-likelihood of the underlying nonlinear model. Defaults to `attr(object, "conLin")`. | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value the log-likelihood for the linear model described by `object`, evaluated at `Pars`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `<gnls>`, `[gnlsStruct](gnlsstruct)`, `[logLik.gnls](loglik.gnls)` r None `Meat` Tenderness of meat -------------------------- ### Description The `Meat` data frame has 30 rows and 4 columns. ### Format This data frame contains the following columns: Storage an ordered factor specifying the storage treatment - 1 (0 days), 2 (1 day), 3 (2 days), 4 (4 days), 5 (9 days), and 6 (18 days) score a numeric vector giving the tenderness score of beef roast. Block an ordered factor identifying the muscle from which the roast was extracted with levels `II` < `V` < `I` < `III` < `IV` Pair an ordered factor giving the unique identifier for each pair of beef roasts with levels `II-1` < ... < `IV-1` ### Details Cochran and Cox (section 11.51, 1957) describe data from an experiment conducted at Iowa State College (Paul, 1943) to compare the effects of length of cold storage on the tenderness of beef roasts. Six storage periods ranging from 0 to 18 days were used. Thirty roasts were scored by four judges on a scale from 0 to 10, with the score increasing with tenderness. The response was the sum of all four scores. Left and right roasts from the same animal were grouped into pairs, which were further grouped into five blocks, according to the muscle from which they were extracted. Different storage periods were applied to each roast within a pair according to a balanced incomplete block design. ### Source Cochran, W. G. and Cox, G. M. (1957), *Experimental Designs*, Wiley, New York. r None `Names.reStruct` Names of an reStruct Object --------------------------------------------- ### Description This method function extracts the column names of each of the positive-definite matrices represented the `pdMat` elements of `object`. ### Usage ``` ## S3 method for class 'reStruct' Names(object, ...) ## S3 replacement method for class 'reStruct' Names(object, ...) <- value ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"[reStruct](restruct)"`, representing a random effects structure and consisting of a list of `pdMat` objects. | | `value` | a list of character vectors with the replacement values for the names of the individual `pdMat` objects that form `object`. It must have the same length as `object`. | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value a list containing the column names of each of the positive-definite matrices represented by the `pdMat` elements of `object`. ### SIDE EFFECTS On the left side of an assignment, sets the `Names` of the `pdMat` elements of `object` to the corresponding element of `value`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[reStruct](restruct)`, `[pdMat](pdmat)`, `[Names.pdMat](names.pdmat)` ### Examples ``` rs1 <- reStruct(list(Dog = ~day, Side = ~1), data = Pixel) Names(rs1) ``` r None `MathAchieve` Mathematics achievement scores --------------------------------------------- ### Description The `MathAchieve` data frame has 7185 rows and 6 columns. ### Format This data frame contains the following columns: School an ordered factor identifying the school that the student attends Minority a factor with levels `No` `Yes` indicating if the student is a member of a minority racial group. Sex a factor with levels `Male` `Female` SES a numeric vector of socio-economic status. MathAch a numeric vector of mathematics achievement scores. MEANSES a numeric vector of the mean SES for the school. ### Details Each row in this data frame contains the data for one student. ### Examples ``` summary(MathAchieve) ``` r None `Glucose2` Glucose Levels Following Alcohol Ingestion ------------------------------------------------------ ### Description The `Glucose2` data frame has 196 rows and 4 columns. ### Format This data frame contains the following columns: Subject a factor with levels `1` to `7` identifying the subject whose glucose level is measured. Date a factor with levels `1` `2` indicating the occasion in which the experiment was conducted. Time a numeric vector giving the time since alcohol ingestion (in min/10). glucose a numeric vector giving the blood glucose level (in mg/dl). ### Details Hand and Crowder (Table A.14, pp. 180-181, 1996) describe data on the blood glucose levels measured at 14 time points over 5 hours for 7 volunteers who took alcohol at time 0. The same experiment was repeated on a second date with the same subjects but with a dietary additive used for all subjects. ### Source Pinheiro, J. C. and Bates, D. M. (2000), *Mixed-Effects Models in S and S-PLUS*, Springer, New York. (Appendix A.10) Hand, D. and Crowder, M. (1996), *Practical Longitudinal Data Analysis*, Chapman and Hall, London.
programming_docs
r None `corMatrix.reStruct` Extract Correlation Matrix from Components of an reStruct Object -------------------------------------------------------------------------------------- ### Description This method function extracts the correlation matrices corresponding to the `pdMat` elements of `object`. ### Usage ``` ## S3 method for class 'reStruct' corMatrix(object, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"[reStruct](restruct)"`, representing a random effects structure and consisting of a list of `pdMat` objects. | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value a list with components given by the correlation matrices corresponding to the elements of `object`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[as.matrix.reStruct](as.matrix.restruct)`, `[corMatrix](cormatrix)`, `[reStruct](restruct)`, `[pdMat](pdmat)` ### Examples ``` rs1 <- reStruct(pdSymm(diag(3), ~age+Sex, data = Orthodont)) corMatrix(rs1) ``` r None `Muscle` Contraction of heart muscle sections ---------------------------------------------- ### Description The `Muscle` data frame has 60 rows and 3 columns. ### Format This data frame contains the following columns: Strip an ordered factor indicating the strip of muscle being measured. conc a numeric vector giving the concentration of CaCl2 length a numeric vector giving the shortening of the heart muscle strip. ### Details Baumann and Waldvogel (1963) describe data on the shortening of heart muscle strips dipped in a *CaCl\_2* solution. The muscle strips are taken from the left auricle of a rat's heart. ### Source Baumann, F. and Waldvogel, F. (1963), La restitution pastsystolique de la contraction de l'oreillette gauche du rat. Effets de divers ions et de l'acetylcholine, *Helvetica Physiologica Acta*, **21**. r None `as.matrix.reStruct` Matrices of an reStruct Object ---------------------------------------------------- ### Description This method function extracts the positive-definite matrices corresponding to the `pdMat` elements of `object`. ### Usage ``` ## S3 method for class 'reStruct' as.matrix(x, ...) ``` ### Arguments | | | | --- | --- | | `x` | an object inheriting from class `"[reStruct](restruct)"`, representing a random effects structure and consisting of a list of `pdMat` objects. | | `...` | further arguments passed from other methods. | ### Value a list with components given by the positive-definite matrices corresponding to the elements of `object`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Pinheiro, J. C. and Bates, D. M. (2000), *Mixed-Effects Models in S and S-PLUS*, Springer, New York. ### See Also `[as.matrix.pdMat](as.matrix.pdmat)`, `[reStruct](restruct)`, `[pdMat](pdmat)` ### Examples ``` rs1 <- reStruct(pdSymm(diag(3), ~age+Sex, data = Orthodont)) as.matrix(rs1) ``` r None `pdNatural` General Positive-Definite Matrix in Natural Parametrization ------------------------------------------------------------------------ ### Description This function is a constructor for the `pdNatural` class, representing a general positive-definite matrix, using a natural parametrization . If the matrix associated with `object` is of dimension *n*, it is represented by *n\*(n+1)/2* parameters. Letting *S(i,j)* denote the *ij*-th element of the underlying positive definite matrix and *r(i,j) = S(i,j)/sqrt(S(i,i)S(j,j)), i not equal to j* denote the associated "correlations", the "natural" parameters are given by *sqrt(Sii), i=1,..,n* and *log((1+r(i,j))/(1-r(i,j))), i not equal to j*. Note that all natural parameters are individually unrestricted, but not jointly unrestricted (meaning that not all unrestricted vectors would give positive-definite matrices). Therefore, this parametrization should NOT be used for optimization. It is mostly used for deriving approximate confidence intervals on parameters following the optimization of an objective function. When `value` is `numeric(0)`, an uninitialized `pdMat` object, a one-sided formula, or a vector of character strings, `object` is returned as an uninitialized `pdSymm` object (with just some of its attributes and its class defined) and needs to have its coefficients assigned later, generally using the `coef` or `matrix` replacement functions. If `value` is an initialized `pdMat` object, `object` will be constructed from `as.matrix(value)`. Finally, if `value` is a numeric vector, it is assumed to represent the natural parameters of the underlying positive-definite matrix. ### Usage ``` pdNatural(value, form, nam, data) ``` ### Arguments | | | | --- | --- | | `value` | an optional initialization value, which can be any of the following: a `pdMat` object, a positive-definite matrix, a one-sided linear formula (with variables separated by `+`), a vector of character strings, or a numeric vector. Defaults to `numeric(0)`, corresponding to an uninitialized object. | | `form` | an optional one-sided linear formula specifying the row/column names for the matrix represented by `object`. Because factors may be present in `form`, the formula needs to be evaluated on a data.frame to resolve the names it defines. This argument is ignored when `value` is a one-sided formula. Defaults to `NULL`. | | `nam` | an optional vector of character strings specifying the row/column names for the matrix represented by object. It must have length equal to the dimension of the underlying positive-definite matrix and unreplicated elements. This argument is ignored when `value` is a vector of character strings. Defaults to `NULL`. | | `data` | an optional data frame in which to evaluate the variables named in `value` and `form`. It is used to obtain the levels for `factors`, which affect the dimensions and the row/column names of the underlying matrix. If `NULL`, no attempt is made to obtain information on `factors` appearing in the formulas. Defaults to the parent frame from which the function was called. | ### Value a `pdNatural` object representing a general positive-definite matrix in natural parametrization, also inheriting from class `pdMat`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Pinheiro, J.C., and Bates, D.M. (2000) "Mixed-Effects Models in S and S-PLUS", Springer, esp. p. 162. ### See Also `[as.matrix.pdMat](as.matrix.pdmat)`, `[coef.pdMat](coef.pdmat)`, `[pdClasses](pdclasses)`, `[matrix<-.pdMat](matrix.pdmat)` ### Examples ``` pdNatural(diag(1:3)) ``` r None `lmeStruct` Linear Mixed-Effects Structure ------------------------------------------- ### Description A linear mixed-effects structure is a list of model components representing different sets of parameters in the linear mixed-effects model. An `lmeStruct` list must contain at least a `reStruct` object, but may also contain `corStruct` and `varFunc` objects. `NULL` arguments are not included in the `lmeStruct` list. ### Usage ``` lmeStruct(reStruct, corStruct, varStruct) ``` ### Arguments | | | | --- | --- | | `reStruct` | a `reStruct` representing a random effects structure. | | `corStruct` | an optional `corStruct` object, representing a correlation structure. Default is `NULL`. | | `varStruct` | an optional `varFunc` object, representing a variance function structure. Default is `NULL`. | ### Value a list of model components determining the parameters to be estimated for the associated linear mixed-effects model. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[corClasses](corclasses)`, `<lme>`, `[residuals.lmeStruct](residuals.lmestruct)`, `[reStruct](restruct)`, `[varFunc](varfunc)` ### Examples ``` lms1 <- lmeStruct(reStruct(~age), corAR1(), varPower()) ``` r None `logLik.corStruct` Extract corStruct Log-Likelihood ---------------------------------------------------- ### Description This method function extracts the component of a Gaussian log-likelihood associated with the correlation structure, which is equal to the negative of the logarithm of the determinant (or sum of the logarithms of the determinants) of the matrix (or matrices) represented by `object`. ### Usage ``` ## S3 method for class 'corStruct' logLik(object, data, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"[corStruct](corclasses)"`, representing a correlation structure. | | `data` | this argument is included to make this method function compatible with other `logLik` methods and will be ignored. | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value the negative of the logarithm of the determinant (or sum of the logarithms of the determinants) of the correlation matrix (or matrices) represented by `object`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[logDet.corStruct](logdet.corstruct)`, `[logLik.lme](loglik.lme)`, ### Examples ``` cs1 <- corAR1(0.2) cs1 <- Initialize(cs1, data = Orthodont) logLik(cs1) ``` r None `ACF` Autocorrelation Function ------------------------------- ### Description This function is generic; method functions can be written to handle specific classes of objects. Classes which already have methods for this function include: `gls` and `lme`. ### Usage ``` ACF(object, maxLag, ...) ``` ### Arguments | | | | --- | --- | | `object` | any object from which an autocorrelation function can be obtained. Generally an object resulting from a model fit, from which residuals can be extracted. | | `maxLag` | maximum lag for which the autocorrelation should be calculated. | | `...` | some methods for this generic require additional arguments. | ### Value will depend on the method function used; see the appropriate documentation. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Box, G.E.P., Jenkins, G.M., and Reinsel G.C. (1994) "Time Series Analysis: Forecasting and Control", 3rd Edition, Holden-Day. Pinheiro, J.C., and Bates, D.M. (2000) "Mixed-Effects Models in S and S-PLUS", Springer. ### See Also `[ACF.gls](acf.gls)`, `[ACF.lme](acf.lme)`, `[plot.ACF](plot.acf)` ### Examples ``` ## see the method function documentation ``` r None `varFixed` Fixed Variance Function ----------------------------------- ### Description This function is a constructor for the `varFixed` class, representing a variance function with fixed variances. Letting *v* denote the variance covariate defined in `value`, the variance function *s2(v)* for this class is *s2(v)=|v|*. The variance covariate *v* is evaluated once at initialization and remains fixed thereafter. No coefficients are required to represent this variance function. ### Usage ``` varFixed(value) ``` ### Arguments | | | | --- | --- | | `value` | a one-sided formula of the form `~ v` specifying a variance covariate `v`. Grouping factors are ignored. | ### Value a `varFixed` object representing a fixed variance function structure, also inheriting from class `varFunc`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Pinheiro, J.C., and Bates, D.M. (2000) "Mixed-Effects Models in S and S-PLUS", Springer. ### See Also `[varClasses](varclasses)`, `[varWeights.varFunc](varweights)`, `[varFunc](varfunc)` ### Examples ``` vf1 <- varFixed(~age) ``` r None `fitted.gnlsStruct` Calculate gnlsStruct Fitted Values ------------------------------------------------------- ### Description The fitted values for the nonlinear model represented by `object` are extracted. ### Usage ``` ## S3 method for class 'gnlsStruct' fitted(object, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object inheriting from class `"[gnlsStruct](gnlsstruct)"`, representing a list of model components, such as `corStruct` and `varFunc` objects, and attributes specifying the underlying nonlinear model and the response variable. | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value a vector with the fitted values for the nonlinear model represented by `object`. ### Note This method function is generally only used inside `gnls` and `fitted.gnls`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `<gnls>`, `[residuals.gnlsStruct](residuals.gnlsstruct)` r None `gsummary` Summarize by Groups ------------------------------- ### Description Provide a summary of the variables in a data frame by groups of rows. This is most useful with a `groupedData` object to examine the variables by group. ### Usage ``` gsummary(object, FUN, omitGroupingFactor, form, level, groups, invariantsOnly, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object to be summarized - usually a `groupedData` object or a `data.frame`. | | `FUN` | an optional summary function or a list of summary functions to be applied to each variable in the frame. The function or functions are applied only to variables in `object` that vary within the groups defined by `groups`. Invariant variables are always summarized by group using the unique value that they assume within that group. If `FUN` is a single function it will be applied to each non-invariant variable by group to produce the summary for that variable. If `FUN` is a list of functions, the names in the list should designate classes of variables in the frame such as `ordered`, `factor`, or `numeric`. The indicated function will be applied to any non-invariant variables of that class. The default functions to be used are `mean` for numeric factors, and `Mode` for both `factor` and `ordered`. The `Mode` function, defined internally in `gsummary`, returns the modal or most popular value of the variable. It is different from the `mode` function that returns the S-language mode of the variable. | | `omitGroupingFactor` | an optional logical value. When `TRUE` the grouping factor itself will be omitted from the group-wise summary but the levels of the grouping factor will continue to be used as the row names for the data frame that is produced by the summary. Defaults to `FALSE`. | | `form` | an optional one-sided formula that defines the groups. When this formula is given, the right-hand side is evaluated in `object`, converted to a factor if necessary, and the unique levels are used to define the groups. Defaults to `formula(object)`. | | `level` | an optional positive integer giving the level of grouping to be used in an object with multiple nested grouping levels. Defaults to the highest or innermost level of grouping. | | `groups` | an optional factor that will be used to split the rows into groups. Defaults to `getGroups(object, form, level)`. | | `invariantsOnly` | an optional logical value. When `TRUE` only those covariates that are invariant within each group will be summarized. The summary value for the group is always the unique value taken on by that covariate within the group. The columns in the summary are of the same class as the corresponding columns in `object`. By definition, the grouping factor itself must be an invariant. When combined with `omitGroupingFactor = TRUE`, this option can be used to discover is there are invariant covariates in the data frame. Defaults to `FALSE`. | | `...` | optional additional arguments to the summary functions that are invoked on the variables by group. Often it is helpful to specify `na.rm = TRUE`. | ### Value A `data.frame` with one row for each level of the grouping factor. The number of columns is at most the number of columns in `object`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Pinheiro, J.C., and Bates, D.M. (2000) "Mixed-Effects Models in S and S-PLUS", Springer. ### See Also `[summary](../../base/html/summary)`, `[groupedData](groupeddata)`, `[getGroups](getgroups)` ### Examples ``` gsummary(Orthodont) # default summary by Subject ## gsummary with invariantsOnly = TRUE and omitGroupingFactor = TRUE ## determines whether there are covariates like Sex that are invariant ## within the repeated observations on the same Subject. gsummary(Orthodont, inv = TRUE, omit = TRUE) ``` r None `corFactor` Factor of a Correlation Matrix ------------------------------------------- ### Description This function is generic; method functions can be written to handle specific classes of objects. Classes which already have methods for this function include all `corStruct` classes. ### Usage ``` corFactor(object, ...) ``` ### Arguments | | | | --- | --- | | `object` | an object from which a correlation matrix can be extracted. | | `...` | some methods for this generic function require additional arguments. | ### Value will depend on the method function used; see the appropriate documentation. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[corFactor.corStruct](corfactor.corstruct)`, `[recalc.corStruct](recalc.corstruct)` ### Examples ``` ## see the method function documentation ``` r None `getGroups` Extract Grouping Factors from an Object ---------------------------------------------------- ### Description This function is generic; method functions can be written to handle specific classes of objects. Classes which already have methods for this function include `corStruct`, `data.frame`, `gls`, `lme`, `lmList`, and `varFunc`. ### Usage ``` getGroups(object, form, level, data, sep) ``` ### Arguments | | | | --- | --- | | `object` | any object | | `form` | an optional formula with a conditioning expression on its right hand side (i.e. an expression involving the `|` operator). Defaults to `formula(object)`. | | `level` | a positive integer vector with the level(s) of grouping to be used when multiple nested levels of grouping are present. This argument is optional for most methods of this generic function and defaults to all levels of nesting. | | `data` | a data frame in which to interpret the variables named in `form`. Optional for most methods. | | `sep` | character, the separator to use between group levels when multiple levels are collapsed. The default is `'/'`. | ### Value will depend on the method function used; see the appropriate documentation. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Pinheiro, J.C., and Bates, D.M. (2000) "Mixed-Effects Models in S and S-PLUS", Springer, esp. pp. 100, 461. ### See Also `[getGroupsFormula](getgroupsformula)`, `[getGroups.data.frame](getgroups.data.frame)`, `[getGroups.gls](getgroups.gls)`, `[getGroups.lmList](getgroups.lmlist)`, `[getGroups.lme](getgroups.lme)` ### Examples ``` ## see the method function documentation ``` r None `Variogram.default` Calculate Semi-variogram --------------------------------------------- ### Description This method function calculates the semi-variogram for an arbitrary vector `object`, according to the distances in `distance`. For each pair of elements *x,y* in `object`, the corresponding semi-variogram is *(x-y)^2/2*. The semi-variogram is useful for identifying and modeling spatial correlation structures in observations with constant expectation and constant variance. ### Usage ``` ## Default S3 method: Variogram(object, distance, ...) ``` ### Arguments | | | | --- | --- | | `object` | a numeric vector with the values to be used for calculating the semi-variogram, usually a residual vector from a fitted model. | | `distance` | a numeric vector with the pairwise distances corresponding to the elements of `object`. The order of the elements in `distance` must correspond to the pairs `(1,2), (1,3), ..., (n-1,n)`, with `n` representing the length of `object`, and must have length `n(n-1)/2`. | | `...` | some methods for this generic require additional arguments. None are used in this method. | ### Value a data frame with columns `variog` and `dist` representing, respectively, the semi-variogram values and the corresponding distances. The returned value inherits from class `Variogram`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Cressie, N.A.C. (1993), "Statistics for Spatial Data", J. Wiley & Sons. ### See Also `[Variogram](variogram)`, `[Variogram.gls](variogram.gls)`, `[Variogram.lme](variogram.lme)`, `[plot.Variogram](plot.variogram)` ### Examples ``` fm1 <- lm(follicles ~ sin(2 * pi * Time) + cos(2 * pi * Time), Ovary, subset = Mare == 1) Variogram(resid(fm1), dist(1:29))[1:10,] ```
programming_docs
r None `varConstPower` Constant Plus Power Variance Function ------------------------------------------------------ ### Description This function is a constructor for the `varConstPower` class, representing a constant plus power variance function structure. Letting *v* denote the variance covariate and *s2(v)* denote the variance function evaluated at *v*, the constant plus power variance function is defined as *s2(v) = (t1 + |v|^t2)^2*, where *t1, t2* are the variance function coefficients. When a grouping factor is present, different *t1, t2* are used for each factor level. ### Usage ``` varConstPower(const, power, form, fixed) ``` ### Arguments | | | | --- | --- | | `const, power` | optional numeric vectors, or lists of numeric values, with, respectively, the coefficients for the constant and the power terms. Both arguments must have length one, unless a grouping factor is specified in `form`. If either argument has length greater than one, it must have names which identify its elements to the levels of the grouping factor defined in `form`. If a grouping factor is present in `form` and the argument has length one, its value will be assigned to all grouping levels. Only positive values are allowed for `const`. Default is `numeric(0)`, which results in a vector of zeros of appropriate length being assigned to the coefficients when `object` is initialized (corresponding to constant variance equal to one). | | `form` | an optional one-sided formula of the form `~ v`, or `~ v | g`, specifying a variance covariate `v` and, optionally, a grouping factor `g` for the coefficients. The variance covariate must evaluate to a numeric vector and may involve expressions using `"."`, representing a fitted model object from which fitted values (`fitted(.)`) and residuals (`resid(.)`) can be extracted (this allows the variance covariate to be updated during the optimization of an object function). When a grouping factor is present in `form`, a different coefficient value is used for each of its levels. Several grouping variables may be simultaneously specified, separated by the `*` operator, as in `~ v | g1 * g2 * g3`. In this case, the levels of each grouping variable are pasted together and the resulting factor is used to group the observations. Defaults to `~ fitted(.)` representing a variance covariate given by the fitted values of a fitted model object and no grouping factor. | | `fixed` | an optional list with components `const` and/or `power`, consisting of numeric vectors, or lists of numeric values, specifying the values at which some or all of the coefficients in the variance function should be fixed. If a grouping factor is specified in `form`, the components of `fixed` must have names identifying which coefficients are to be fixed. Coefficients included in `fixed` are not allowed to vary during the optimization of an objective function. Defaults to `NULL`, corresponding to no fixed coefficients. | ### Value a `varConstPower` object representing a constant plus power variance function structure, also inheriting from class `varFunc`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### References Pinheiro, J.C., and Bates, D.M. (2000) "Mixed-Effects Models in S and S-PLUS", Springer. ### See Also `[varClasses](varclasses)`, `[varWeights.varFunc](varweights)`, `[coef.varConstPower](coef.varfunc)` ### Examples ``` vf1 <- varConstPower(1.2, 0.2, form = ~age|Sex) ``` r None `qqnorm.gls` Normal Plot of Residuals from a gls Object -------------------------------------------------------- ### Description Diagnostic plots for assessing the normality of residuals the generalized least squares fit are obtained. The `form` argument gives considerable flexibility in the type of plot specification. A conditioning expression (on the right side of a `|` operator) always implies that different panels are used for each level of the conditioning factor, according to a Trellis display. ### Usage ``` ## S3 method for class 'gls' qqnorm(y, form, abline, id, idLabels, grid, ...) ``` ### Arguments | | | | --- | --- | | `y` | an object inheriting from class `"<gls>"`, representing a generalized least squares fitted model. | | `form` | an optional one-sided formula specifying the desired type of plot. Any variable present in the original data frame used to obtain `y` can be referenced. In addition, `y` itself can be referenced in the formula using the symbol `"."`. Conditional expressions on the right of a `|` operator can be used to define separate panels in a Trellis display. The expression on the right hand side of `form` and to the left of a `|` operator must evaluate to a residuals vector. Default is `~ resid(., type = "p")`, corresponding to a normal plot of the standardized residuals. | | `abline` | an optional numeric value, or numeric vector of length two. If given as a single value, a horizontal line will be added to the plot at that coordinate; else, if given as a vector, its values are used as the intercept and slope for a line added to the plot. If missing, no lines are added to the plot. | | `id` | an optional numeric value, or one-sided formula. If given as a value, it is used as a significance level for a two-sided outlier test for the standardized residuals (random effects). Observations with absolute standardized residuals (random effects) greater than the *1 - value/2* quantile of the standard normal distribution are identified in the plot using `idLabels`. If given as a one-sided formula, its right hand side must evaluate to a logical, integer, or character vector which is used to identify observations in the plot. If missing, no observations are identified. | | `idLabels` | an optional vector, or one-sided formula. If given as a vector, it is converted to character and used to label the observations identified according to `id`. If given as a one-sided formula, its right hand side must evaluate to a vector which is converted to character and used to label the identified observations. Default is the innermost grouping factor. | | `grid` | an optional logical value indicating whether a grid should be added to plot. Default depends on the type of Trellis plot used: if `xyplot` defaults to `TRUE`, else defaults to `FALSE`. | | `...` | optional arguments passed to the Trellis plot function. | ### Value a diagnostic Trellis plot for assessing normality of residuals. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `<gls>`, `<plot.gls>` ### Examples ``` fm1 <- gls(follicles ~ sin(2*pi*Time) + cos(2*pi*Time), Ovary, correlation = corAR1(form = ~ 1 | Mare)) qqnorm(fm1, abline = c(0,1)) ``` r None `compareFits` Compare Fitted Objects ------------------------------------- ### Description The columns in `object1` and `object2` are put together in matrices which allow direct comparison of the individual elements for each object. Missing columns in either object are replaced by `NA`s. ### Usage ``` compareFits(object1, object2, which) ``` ### Arguments | | | | --- | --- | | `object1,object2` | data frames, or matrices, with the same row names, but possibly different column names. These will usually correspond to coefficients from fitted objects with a grouping structure (e.g. `lme` and `lmList` objects). | | `which` | an optional integer or character vector indicating which columns in `object1` and `object2` are to be used in the returned object. Defaults to all columns. | ### Value a three-dimensional array, with the third dimension given by the number of unique column names in either `object1` or `object2`. To each column name there corresponds a matrix with as many rows as the rows in `object1` and two columns, corresponding to `object1` and `object2`. The returned object inherits from class `compareFits`. ### Author(s) José Pinheiro and Douglas Bates [[email protected]](mailto:[email protected]) ### See Also `[plot.compareFits](plot.comparefits)`, `[pairs.compareFits](pairs.comparefits)`, `[comparePred](comparepred)`, `[coef](../../stats/html/coef)`, `<random.effects>` ### Examples ``` fm1 <- lmList(Orthodont) fm2 <- lme(fm1) (cF12 <- compareFits(coef(fm1), coef(fm2))) ``` r None `splines-package` Regression Spline Functions and Classes ---------------------------------------------------------- ### Description Regression spline functions and classes. ### Details This package provides functions for working with regression splines using the B-spline basis, `<bs>`, and the natural cubic spline basis, `<ns>`. For a complete list of functions, use `library(help = "splines")`. ### Author(s) Douglas M. Bates [[email protected]](mailto:[email protected]) and William N. Venables [[email protected]](mailto:[email protected]) Maintainer: R Core Team [[email protected]](mailto:[email protected]) r None `periodicSpline` Create a Periodic Interpolation Spline -------------------------------------------------------- ### Description Create a periodic interpolation spline, either from `x` and `y` vectors, or from a formula/data.frame combination. ### Usage ``` periodicSpline(obj1, obj2, knots, period = 2*pi, ord = 4L) ``` ### Arguments | | | | --- | --- | | `obj1` | either a numeric vector of `x` values or a formula. | | `obj2` | if `obj1` is numeric this should be a numeric vector of the same length. If `obj1` is a formula this can be an optional data frame in which to evaluate the names in the formula. | | `knots` | optional numeric vector of knot positions. | | `period` | positive numeric value giving the period for the periodic spline. Defaults to `2 * pi`. | | `ord` | integer giving the order of the spline, at least 2. Defaults to 4. See `[splineOrder](splineorder)` for a definition of the order of a spline. | ### Value An object that inherits from class `spline`. The object can be in the B-spline representation, in which case it will be a `pbSpline` object, or in the piecewise polynomial representation (a `ppolySpline` object). ### Author(s) Douglas Bates and Bill Venables ### See Also `[splineKnots](splineknots)`, `[interpSpline](interpspline)` ### Examples ``` require(graphics); require(stats) xx <- seq( -pi, pi, length.out = 16 )[-1] yy <- sin( xx ) frm <- data.frame( xx, yy ) pispl <- periodicSpline( xx, yy, period = 2 * pi) pispl pispl2 <- periodicSpline( yy ~ xx, frm, period = 2 * pi ) stopifnot(all.equal(pispl, pispl2)) # pispl and pispl2 are the same plot( pispl ) # displays over one period points( yy ~ xx, col = "brown") plot( predict( pispl, seq(-3*pi, 3*pi, length.out = 101) ), type = "l" ) ``` r None `backSpline` Monotone Inverse Spline ------------------------------------- ### Description Create a monotone inverse of a monotone natural spline. ### Usage ``` backSpline(object) ``` ### Arguments | | | | --- | --- | | `object` | an object that inherits from class `nbSpline` or `npolySpline`. That is, the object must represent a natural interpolation spline but it can be either in the B-spline representation or the piecewise polynomial one. The spline is checked to see if it represents a monotone function. | ### Value An object of class `polySpline` that contains the piecewise polynomial representation of a function that has the appropriate values and derivatives at the knot positions to be an inverse of the spline represented by `object`. Technically this object is not a spline because the second derivative is not constrained to be continuous at the knot positions. However, it is often a much better approximation to the inverse than fitting an interpolation spline to the y/x pairs. ### Author(s) Douglas Bates and Bill Venables ### See Also `[interpSpline](interpspline)` ### Examples ``` require(graphics) ispl <- interpSpline( women$height, women$weight ) bspl <- backSpline( ispl ) plot( bspl ) # plots over the range of the knots points( women$weight, women$height ) ``` r None `splineKnots` Knot Vector from a Spline ---------------------------------------- ### Description Return the knot vector corresponding to a spline object. ### Usage ``` splineKnots(object) ``` ### Arguments | | | | --- | --- | | `object` | an object that inherits from class `"spline"`. | ### Value A non-decreasing numeric vector of knot positions. ### Author(s) Douglas Bates and Bill Venables ### Examples ``` ispl <- interpSpline( weight ~ height, women ) splineKnots( ispl ) ``` r None `polySpline` Piecewise Polynomial Spline Representation -------------------------------------------------------- ### Description Create the piecewise polynomial representation of a spline object. ### Usage ``` polySpline(object, ...) as.polySpline(object, ...) ``` ### Arguments | | | | --- | --- | | `object` | An object that inherits from class `spline`. | | `...` | Optional additional arguments. At present no additional arguments are used. | ### Value An object that inherits from class `polySpline`. This is the piecewise polynomial representation of a univariate spline function. It is defined by a set of distinct numeric values called knots. The spline function is a polynomial function between each successive pair of knots. At each interior knot the polynomial segments on each side are constrained to have the same value of the function and some of its derivatives. ### Author(s) Douglas Bates and Bill Venables ### See Also `[interpSpline](interpspline)`, `[periodicSpline](periodicspline)`, `[splineKnots](splineknots)`, `[splineOrder](splineorder)` ### Examples ``` require(graphics) ispl <- polySpline(interpSpline( weight ~ height, women, bSpline = TRUE)) ## IGNORE_RDIFF_BEGIN print( ispl ) # print the piecewise polynomial representation ## IGNORE_RDIFF_END plot( ispl ) # plots over the range of the knots points( women$height, women$weight ) ``` r None `interpSpline` Create an Interpolation Spline ---------------------------------------------- ### Description Create an interpolation spline, either from `x` and `y` vectors (`default` method), or from a `formula` / `data.frame` combination (`formula` method). ### Usage ``` interpSpline(obj1, obj2, bSpline = FALSE, period = NULL, ord = 4L, na.action = na.fail, sparse = FALSE) ``` ### Arguments | | | | --- | --- | | `obj1` | either a numeric vector of `x` values or a formula. | | `obj2` | if `obj1` is numeric this should be a numeric vector of the same length. If `obj1` is a formula this can be an optional data frame in which to evaluate the names in the formula. | | `bSpline` | if `TRUE` the b-spline representation is returned, otherwise the piecewise polynomial representation is returned. Defaults to `FALSE`. | | `period` | an optional positive numeric value giving a period for a periodic interpolation spline. | | `ord` | an integer specifying the spline *order*, the number of coefficients per interval. *ord = d+1* where *d* is the *degree* polynomial degree. Currently, only cubic splines (`ord = 4`) are implemented. | | `na.action` | a optional function which indicates what should happen when the data contain `NA`s. The default action (`na.omit`) is to omit any incomplete observations. The alternative action `na.fail` causes `interpSpline` to print an error message and terminate if there are any incomplete observations. | | `sparse` | logical passed to the underlying `[splineDesign](splinedesign)`. If true, saves memory and is faster when there are more than a few hundred points. | ### Value An object that inherits from (S3) class `spline`. The object can be in the B-spline representation, in which case it will be of class `nbSpline` for natural B-spline, or in the piecewise polynomial representation, in which case it will be of class `npolySpline`. ### Author(s) Douglas Bates and Bill Venables ### See Also `[splineKnots](splineknots)`, `[splineOrder](splineorder)`, `[periodicSpline](periodicspline)`. ### Examples ``` require(graphics); require(stats) ispl <- interpSpline( women$height, women$weight ) ispl2 <- interpSpline( weight ~ height, women ) # ispl and ispl2 should be the same plot( predict( ispl, seq( 55, 75, length.out = 51 ) ), type = "l" ) points( women$height, women$weight ) plot( ispl ) # plots over the range of the knots points( women$height, women$weight ) splineKnots( ispl ) ``` r None `bs` B-Spline Basis for Polynomial Splines ------------------------------------------- ### Description Generate the B-spline basis matrix for a polynomial spline. ### Usage ``` bs(x, df = NULL, knots = NULL, degree = 3, intercept = FALSE, Boundary.knots = range(x)) ``` ### Arguments | | | | --- | --- | | `x` | the predictor variable. Missing values are allowed. | | `df` | degrees of freedom; one can specify `df` rather than `knots`; `bs()` then chooses `df-degree` (minus one if there is an intercept) knots at suitable quantiles of `x` (which will ignore missing values). The default, `NULL`, takes the number of inner knots as `length(knots)`. If that is zero as per default, that corresponds to `df = degree - intercept`. | | `knots` | the *internal* breakpoints that define the spline. The default is `NULL`, which results in a basis for ordinary polynomial regression. Typical values are the mean or median for one knot, quantiles for more knots. See also `Boundary.knots`. | | `degree` | degree of the piecewise polynomial—default is `3` for cubic splines. | | `intercept` | if `TRUE`, an intercept is included in the basis; default is `FALSE`. | | `Boundary.knots` | boundary points at which to anchor the B-spline basis (default the range of the non-`[NA](../../base/html/na)` data). If both `knots` and `Boundary.knots` are supplied, the basis parameters do not depend on `x`. Data can extend beyond `Boundary.knots`. | ### Details `bs` is based on the function `[splineDesign](splinedesign)`. It generates a basis matrix for representing the family of piecewise polynomials with the specified interior knots and degree, evaluated at the values of `x`. A primary use is in modeling formulas to directly specify a piecewise polynomial term in a model. When `Boundary.knots` are set *inside* `range(x)`, `bs()` now uses a ‘pivot’ inside the respective boundary knot which is important for derivative evaluation. In **R** versions *<=* 3.2.2, the boundary knot itself had been used as pivot, which lead to somewhat wrong extrapolations. ### Value A matrix of dimension `c(length(x), df)`, where either `df` was supplied or if `knots` were supplied, `df = length(knots) + degree` plus one if there is an intercept. Attributes are returned that correspond to the arguments to `bs`, and explicitly give the `knots`, `Boundary.knots` etc for use by `predict.bs()`. ### Author(s) Douglas Bates and Bill Venables. Tweaks by R Core, and a patch fixing extrapolation “outside” `Boundary.knots` by Trevor Hastie. ### References Hastie, T. J. (1992) Generalized additive models. Chapter 7 of *Statistical Models in S* eds J. M. Chambers and T. J. Hastie, Wadsworth & Brooks/Cole. ### See Also `<ns>`, `[poly](../../stats/html/poly)`, `[smooth.spline](../../stats/html/smooth.spline)`, `<predict.bs>`, `[SafePrediction](../../stats/html/makepredictcall)` ### Examples ``` require(stats); require(graphics) bs(women$height, df = 5) summary(fm1 <- lm(weight ~ bs(height, df = 5), data = women)) ## example of safe prediction plot(women, xlab = "Height (in)", ylab = "Weight (lb)") ht <- seq(57, 73, length.out = 200) lines(ht, predict(fm1, data.frame(height = ht))) ``` r None `predict.bSpline` Evaluate a Spline at New Values of x ------------------------------------------------------- ### Description The `predict` methods for the classes that inherit from the virtual classes `bSpline` and `polySpline` are used to evaluate the spline or its derivatives. The `plot` method for a spline object first evaluates `predict` with the `x` argument missing, then plots the resulting `xyVector` with `type = "l"`. ### Usage ``` ## S3 method for class 'bSpline' predict(object, x, nseg = 50, deriv = 0, ...) ## S3 method for class 'nbSpline' predict(object, x, nseg = 50, deriv = 0, ...) ## S3 method for class 'pbSpline' predict(object, x, nseg = 50, deriv = 0, ...) ## S3 method for class 'npolySpline' predict(object, x, nseg = 50, deriv = 0, ...) ## S3 method for class 'ppolySpline' predict(object, x, nseg = 50, deriv = 0, ...) ``` ### Arguments | | | | --- | --- | | `object` | An object that inherits from the `bSpline` or the `polySpline` class. | | `x` | A numeric vector of `x` values at which to evaluate the spline. If this argument is missing a suitable set of `x` values is generated as a sequence of `nseq` segments spanning the range of the knots. | | `nseg` | A positive integer giving the number of segments in a set of equally-spaced `x` values spanning the range of the knots in `object`. This value is only used if `x` is missing. | | `deriv` | An integer between 0 and `splineOrder(object) - 1` specifying the derivative to evaluate. | | `...` | further arguments passed to or from other methods. | ### Value an `xyVector` with components | | | | --- | --- | | `x` | the supplied or inferred numeric vector of `x` values | | `y` | the value of the spline (or its `deriv`'th derivative) at the `x` vector | ### Author(s) Douglas Bates and Bill Venables ### See Also `[xyVector](xyvector)`, `[interpSpline](interpspline)`, `[periodicSpline](periodicspline)` ### Examples ``` require(graphics); require(stats) ispl <- interpSpline( weight ~ height, women ) opar <- par(mfrow = c(2, 2), las = 1) plot(predict(ispl, nseg = 201), # plots over the range of the knots main = "Original data with interpolating spline", type = "l", xlab = "height", ylab = "weight") points(women$height, women$weight, col = 4) plot(predict(ispl, nseg = 201, deriv = 1), main = "First derivative of interpolating spline", type = "l", xlab = "height", ylab = "weight") plot(predict(ispl, nseg = 201, deriv = 2), main = "Second derivative of interpolating spline", type = "l", xlab = "height", ylab = "weight") plot(predict(ispl, nseg = 401, deriv = 3), main = "Third derivative of interpolating spline", type = "l", xlab = "height", ylab = "weight") par(opar) ```
programming_docs
r None `splineDesign` Design Matrix for B-splines ------------------------------------------- ### Description Evaluate the design matrix for the B-splines defined by `knots` at the values in `x`. ### Usage ``` splineDesign(knots, x, ord = 4, derivs, outer.ok = FALSE, sparse = FALSE) spline.des (knots, x, ord = 4, derivs, outer.ok = FALSE, sparse = FALSE) ``` ### Arguments | | | | --- | --- | | `knots` | a numeric vector of knot positions (which will be sorted increasingly if needed). | | `x` | a numeric vector of values at which to evaluate the B-spline functions or derivatives. Unless `outer.ok` is true, the values in `x` must be between the “inner” knots `knots[ord]` and `knots[ length(knots) - (ord-1)]`. | | `ord` | a positive integer giving the order of the spline function. This is the number of coefficients in each piecewise polynomial segment, thus a cubic spline has order 4. Defaults to 4. | | `derivs` | an integer vector with values between `0` and `ord - 1`, conceptually recycled to the length of `x`. The derivative of the given order is evaluated at the `x` positions. Defaults to zero (or a vector of zeroes of the same length as `x`). | | `outer.ok` | logical indicating if `x` should be allowed outside the *inner* knots, see the `x` argument. | | `sparse` | logical indicating if the result should inherit from class `"[sparseMatrix](../../matrix/html/sparsematrix-class)"` (from package [Matrix](https://CRAN.R-project.org/package=Matrix)). | ### Value A matrix with `length(x)` rows and `length(knots) - ord` columns. The i'th row of the matrix contains the coefficients of the B-splines (or the indicated derivative of the B-splines) defined by the `knot` vector and evaluated at the i'th value of `x`. Each B-spline is defined by a set of `ord` successive knots so the total number of B-splines is `length(knots) - ord`. ### Note The older `spline.des` function takes the same arguments but returns a list with several components including `knots`, `ord`, `derivs`, and `design`. The `design` component is the same as the value of the `splineDesign` function. ### Author(s) Douglas Bates and Bill Venables ### Examples ``` require(graphics) splineDesign(knots = 1:10, x = 4:7) splineDesign(knots = 1:10, x = 4:7, derivs = 1) ## visualize band structure Matrix::drop0(zapsmall(6*splineDesign(knots = 1:40, x = 4:37, sparse = TRUE))) knots <- c(1,1.8,3:5,6.5,7,8.1,9.2,10) # 10 => 10-4 = 6 Basis splines x <- seq(min(knots)-1, max(knots)+1, length.out = 501) bb <- splineDesign(knots, x = x, outer.ok = TRUE) plot(range(x), c(0,1), type = "n", xlab = "x", ylab = "", main = "B-splines - sum to 1 inside inner knots") mtext(expression(B[j](x) *" and "* sum(B[j](x), j == 1, 6)), adj = 0) abline(v = knots, lty = 3, col = "light gray") abline(v = knots[c(4,length(knots)-3)], lty = 3, col = "gray10") lines(x, rowSums(bb), col = "gray", lwd = 2) matlines(x, bb, ylim = c(0,1), lty = 1) ``` r None `asVector` Coerce an Object to a Vector ---------------------------------------- ### Description This is a generic function. Methods for this function coerce objects of given classes to vectors. ### Usage ``` asVector(object) ``` ### Arguments | | | | --- | --- | | `object` | An object. | ### Details Methods for vector coercion in new classes must be created for the `asVector` generic instead of `as.vector`. The `as.vector` function is internal and not easily extended. Currently the only class with an `asVector` method is the `xyVector` class. ### Value a vector ### Author(s) Douglas Bates and Bill Venables ### See Also `[xyVector](xyvector)` ### Examples ``` require(stats) ispl <- interpSpline( weight ~ height, women ) pred <- predict(ispl) class(pred) utils::str(pred) asVector(pred) ``` r None `ns` Generate a Basis Matrix for Natural Cubic Splines ------------------------------------------------------- ### Description Generate the B-spline basis matrix for a natural cubic spline. ### Usage ``` ns(x, df = NULL, knots = NULL, intercept = FALSE, Boundary.knots = range(x)) ``` ### Arguments | | | | --- | --- | | `x` | the predictor variable. Missing values are allowed. | | `df` | degrees of freedom. One can supply `df` rather than knots; `ns()` then chooses `df - 1 - intercept` knots at suitably chosen quantiles of `x` (which will ignore missing values). The default, `df = NULL`, sets the number of inner knots as `length(knots)`. | | `knots` | breakpoints that define the spline. The default is no knots; together with the natural boundary conditions this results in a basis for linear regression on `x`. Typical values are the mean or median for one knot, quantiles for more knots. See also `Boundary.knots`. | | `intercept` | if `TRUE`, an intercept is included in the basis; default is `FALSE`. | | `Boundary.knots` | boundary points at which to impose the natural boundary conditions and anchor the B-spline basis (default the range of the data). If both `knots` and `Boundary.knots` are supplied, the basis parameters do not depend on `x`. Data can extend beyond `Boundary.knots` | ### Details `ns` is based on the function `[splineDesign](splinedesign)`. It generates a basis matrix for representing the family of piecewise-cubic splines with the specified sequence of interior knots, and the natural boundary conditions. These enforce the constraint that the function is linear beyond the boundary knots, which can either be supplied or default to the extremes of the data. A primary use is in modeling formula to directly specify a natural spline term in a model: see the examples. ### Value A matrix of dimension `length(x) * df` where either `df` was supplied or if `knots` were supplied, `df = length(knots) + 1 + intercept`. Attributes are returned that correspond to the arguments to `ns`, and explicitly give the `knots`, `Boundary.knots` etc for use by `predict.ns()`. ### References Hastie, T. J. (1992) Generalized additive models. Chapter 7 of *Statistical Models in S* eds J. M. Chambers and T. J. Hastie, Wadsworth & Brooks/Cole. ### See Also `<bs>`, `[predict.ns](predict.bs)`, `[SafePrediction](../../stats/html/makepredictcall)` ### Examples ``` require(stats); require(graphics) ns(women$height, df = 5) summary(fm1 <- lm(weight ~ ns(height, df = 5), data = women)) ## To see what knots were selected attr(terms(fm1), "predvars") ## example of safe prediction plot(women, xlab = "Height (in)", ylab = "Weight (lb)") ht <- seq(57, 73, length.out = 200) ; nD <- data.frame(height = ht) lines(ht, p1 <- predict(fm1, nD)) stopifnot(all.equal(p1, predict(update(fm1, . ~ splines::ns(height, df=5)), nD))) # not true in R < 3.5.0 ``` r None `xyVector` Construct an xyVector Object ---------------------------------------- ### Description Create an object to represent a set of x-y pairs. The resulting object can be treated as a matrix or as a data frame or as a vector. When treated as a vector it reduces to the `y` component only. The result of functions such as `predict.spline` is returned as an `xyVector` object so the x-values used to generate the y-positions are retained, say for purposes of generating plots. ### Usage ``` xyVector(x, y) ``` ### Arguments | | | | --- | --- | | `x` | a numeric vector | | `y` | a numeric vector of the same length as `x` | ### Value An object of class `xyVector` with components | | | | --- | --- | | `x` | a numeric vector | | `y` | a numeric vector of the same length as `x` | ### Author(s) Douglas Bates and Bill Venables ### Examples ``` require(stats); require(graphics) ispl <- interpSpline( weight ~ height, women ) weights <- predict( ispl, seq( 55, 75, length.out = 51 )) class( weights ) plot( weights, type = "l", xlab = "height", ylab = "weight" ) points( women$height, women$weight ) weights ``` r None `predict.bs` Evaluate a Spline Basis ------------------------------------- ### Description Evaluate a predefined spline basis at given values. ### Usage ``` ## S3 method for class 'bs' predict(object, newx, ...) ## S3 method for class 'ns' predict(object, newx, ...) ``` ### Arguments | | | | --- | --- | | `object` | the result of a call to `<bs>` or `<ns>` having attributes describing `knots`, `degree`, etc. | | `newx` | the `x` values at which evaluations are required. | | `...` | Optional additional arguments. At present no additional arguments are used. | ### Value An object just like `object`, except evaluated at the new values of `x`. These are methods for the generic function `[predict](../../stats/html/predict)` for objects inheriting from classes `"bs"` or `"ns"`. See `[predict](../../stats/html/predict)` for the general behavior of this function. ### See Also `<bs>`, `<ns>`, `[poly](../../stats/html/poly)`. ### Examples ``` require(stats) basis <- ns(women$height, df = 5) newX <- seq(58, 72, length.out = 51) # evaluate the basis at the new data predict(basis, newX) ``` r None `splineOrder` Determine the Order of a Spline ---------------------------------------------- ### Description Return the order of a spline object. ### Usage ``` splineOrder(object) ``` ### Arguments | | | | --- | --- | | `object` | An object that inherits from class `"spline"`. | ### Details The order of a spline is the number of coefficients in each piece of the piecewise polynomial representation. Thus a cubic spline has order 4. ### Value A positive integer. ### Author(s) Douglas Bates and Bill Venables ### See Also `[splineKnots](splineknots)`, `[interpSpline](interpspline)`, `[periodicSpline](periodicspline)` ### Examples ``` splineOrder( interpSpline( weight ~ height, women ) ) ``` r None `adjustcolor` Adjust Colors in One or More Directions Conveniently. -------------------------------------------------------------------- ### Description Adjust or modify a vector of colors by “turning knobs” on one or more coordinates in *(r,g,b,α)* space, typically by up or down scaling them. ### Usage ``` adjustcolor(col, alpha.f = 1, red.f = 1, green.f = 1, blue.f = 1, offset = c(0, 0, 0, 0), transform = diag(c(red.f, green.f, blue.f, alpha.f))) ``` ### Arguments | | | | --- | --- | | `col` | vector of colors, in any format that col2rgb() accepts | | `alpha.f` | factor modifying the opacity alpha; typically in [0,1] | | `red.f, green.f, blue.f` | factors modifying the “red-”, “green-” or “blue-”ness of the colors, respectively. | | `offset` | | | `transform` | | ### Value a color vector of the same length as `col`, effectively the result of `<rgb>()`. ### See Also `<rgb>`, `<col2rgb>`. For more sophisticated color constructions: `[convertColor](convertcolor)` ### Examples ``` ## Illustrative examples : opal <- palette("default") stopifnot(identical(adjustcolor(1:8, 0.75), adjustcolor(palette(), 0.75))) cbind(palette(), adjustcolor(1:8, 0.75)) ## alpha = 1/2 * previous alpha --> opaque colors x <- palette(adjustcolor(palette(), 0.5)) sines <- outer(1:20, 1:4, function(x, y) sin(x / 20 * pi * y)) matplot(sines, type = "b", pch = 21:23, col = 2:5, bg = 2:5, main = "Using an 'opaque ('translucent') color palette") x. <- adjustcolor(x, offset = c(0.5, 0.5, 0.5, 0), # <- "more white" transform = diag(c(.7, .7, .7, 0.6))) cbind(x, x.) op <- par(bg = adjustcolor("goldenrod", offset = -rep(.4, 4)), xpd = NA) plot(0:9, 0:9, type = "n", axes = FALSE, xlab = "", ylab = "", main = "adjustcolor() -> translucent") text(1:8, labels = paste0(x,"++"), col = x., cex = 8) par(op) ## and (M <- cbind( rbind( matrix(1/3, 3, 3), 0), c(0, 0, 0, 1))) adjustcolor(x, transform = M) ## revert to previous palette: active palette(opal) ``` r None `rgb2hsv` RGB to HSV Conversion -------------------------------- ### Description `rgb2hsv` transforms colors from RGB space (red/green/blue) into HSV space (hue/saturation/value). ### Usage ``` rgb2hsv(r, g = NULL, b = NULL, maxColorValue = 255) ``` ### Arguments | | | | --- | --- | | `r` | vector of ‘red’ values in *[0, M]*, (*M =* `maxColorValue`) or 3-row rgb matrix. | | `g` | vector of ‘green’ values, or `[NULL](../../base/html/null)` when `r` is a matrix. | | `b` | vector of ‘blue’ values, or `[NULL](../../base/html/null)` when `r` is a matrix. | | `maxColorValue` | number giving the maximum of the RGB color values range. The default `255` corresponds to the typical `0:255` RGB coding as in `<col2rgb>()`. | ### Details Value (brightness) gives the amount of light in the color. Hue describes the dominant wavelength. Saturation is the amount of Hue mixed into the color. An HSV colorspace is relative to an RGB colorspace, which in **R** is sRGB, which has an implicit gamma correction. ### Value A matrix with a column for each color. The three rows of the matrix indicate hue, saturation and value and are named `"h"`, `"s"`, and `"v"` accordingly. ### Author(s) **R** interface by Wolfram Fischer [[email protected]](mailto:[email protected]); C code mainly by Nicholas Lewin-Koh [[email protected]](mailto:[email protected]). ### See Also `<hsv>`, `<col2rgb>`, `<rgb>`. ### Examples ``` ## These (saturated, bright ones) only differ by hue (rc <- col2rgb(c("red", "yellow","green","cyan", "blue", "magenta"))) (hc <- rgb2hsv(rc)) 6 * hc["h",] # the hues are equispaced (rgb3 <- floor(256 * matrix(stats::runif(3*12), 3, 12))) (hsv3 <- rgb2hsv(rgb3)) ## Consistency : stopifnot(rgb3 == col2rgb(hsv(h = hsv3[1,], s = hsv3[2,], v = hsv3[3,])), all.equal(hsv3, rgb2hsv(rgb3/255, maxColorValue = 1))) ## A (simplified) pure R version -- originally by Wolfram Fischer -- ## showing the exact algorithm: rgb2hsvR <- function(rgb, gamma = 1, maxColorValue = 255) { if(!is.numeric(rgb)) stop("rgb matrix must be numeric") d <- dim(rgb) if(d[1] != 3) stop("rgb matrix must have 3 rows") n <- d[2] if(n == 0) return(cbind(c(h = 1, s = 1, v = 1))[,0]) rgb <- rgb/maxColorValue if(gamma != 1) rgb <- rgb ^ (1/gamma) ## get the max and min v <- apply( rgb, 2, max) s <- apply( rgb, 2, min) D <- v - s # range ## set hue to zero for undefined values (gray has no hue) h <- numeric(n) notgray <- ( s != v ) ## blue hue idx <- (v == rgb[3,] & notgray ) if (any (idx)) h[idx] <- 2/3 + 1/6 * (rgb[1,idx] - rgb[2,idx]) / D[idx] ## green hue idx <- (v == rgb[2,] & notgray ) if (any (idx)) h[idx] <- 1/3 + 1/6 * (rgb[3,idx] - rgb[1,idx]) / D[idx] ## red hue idx <- (v == rgb[1,] & notgray ) if (any (idx)) h[idx] <- 1/6 * (rgb[2,idx] - rgb[3,idx]) / D[idx] ## correct for negative red idx <- (h < 0) h[idx] <- 1+h[idx] ## set the saturation s[! notgray] <- 0; s[notgray] <- 1 - s[notgray] / v[notgray] rbind( h = h, s = s, v = v ) } ## confirm the equivalence: all.equal(rgb2hsv (rgb3), rgb2hsvR(rgb3), tolerance = 1e-14) # TRUE ``` r None `recordGraphics` Record Graphics Operations -------------------------------------------- ### Description Records arbitrary code on the graphics engine display list. Useful for encapsulating calculations with graphical output that depends on the calculations. Intended *only* for expert use. ### Usage ``` recordGraphics(expr, list, env) ``` ### Arguments | | | | --- | --- | | `expr` | object of mode `[expression](../../base/html/expression)` or `call` or an unevaluated expression. | | `list` | a list defining the environment in which `expr` is to be evaluated. | | `env` | an `[environment](../../base/html/environment)` specifying where **R** looks for objects not found in `list`. | ### Details The code in `expr` is evaluated in an environment constructed from `list`, with `env` as the parent of that environment. All three arguments are saved on the graphics engine display list so that on a device resize or copying between devices, the original evaluation environment can be recreated and the code can be re-evaluated to reproduce the graphical output. ### Value The value from evaluating `expr`. ### Warning This function is not intended for general use. Incorrect or improper use of this function could lead to unintended and/or undesirable results. An example of acceptable use is querying the current state of a graphics device or graphics system setting and then calling a graphics function. An example of improper use would be calling the `assign` function to performing assignments in the global environment. ### See Also `[eval](../../base/html/eval)` ### Examples ``` require(graphics) plot(1:10) # This rectangle remains 1inch wide when the device is resized recordGraphics( { rect(4, 2, 4 + diff(par("usr")[1:2])/par("pin")[1], 3) }, list(), getNamespace("graphics")) ``` r None `nclass` Compute the Number of Classes for a Histogram ------------------------------------------------------- ### Description Compute the number of classes for a histogram. ### Usage ``` nclass.Sturges(x) nclass.scott(x) nclass.FD(x) ``` ### Arguments | | | | --- | --- | | `x` | a data vector. | ### Details `nclass.Sturges` uses Sturges' formula, implicitly basing bin sizes on the range of the data. `nclass.scott` uses Scott's choice for a normal distribution based on the estimate of the standard error, unless that is zero where it returns `1`. `nclass.FD` uses the Freedman-Diaconis choice based on the inter-quartile range (`[IQR](../../stats/html/iqr)(signif(x, 5))`) unless that's zero where it uses increasingly more extreme symmetric quantiles up to c(1,511)/512 and if that difference is still zero, reverts to using Scott's choice. ### Value The suggested number of classes. ### References Venables, W. N. and Ripley, B. D. (2002) *Modern Applied Statistics with S-PLUS.* Springer, page 112. Freedman, D. and Diaconis, P. (1981). On the histogram as a density estimator: *L\_2* theory. *Zeitschrift für Wahrscheinlichkeitstheorie und verwandte Gebiete*, **57**, 453–476. doi: [10.1007/BF01025868](https://doi.org/10.1007/BF01025868). Scott, D. W. (1979). On optimal and data-based histograms. *Biometrika*, **66**, 605–610. doi: [10.2307/2335182](https://doi.org/10.2307/2335182). Scott, D. W. (1992) *Multivariate Density Estimation. Theory, Practice, and Visualization*. Wiley. Sturges, H. A. (1926). The choice of a class interval. *Journal of the American Statistical Association*, **21**, 65–66. doi: [10.1080/01621459.1926.10502161](https://doi.org/10.1080/01621459.1926.10502161). ### See Also `[hist](../../graphics/html/hist)` and `[truehist](../../mass/html/truehist)` (package [MASS](https://CRAN.R-project.org/package=MASS)); `[dpih](../../kernsmooth/html/dpih)` (package [KernSmooth](https://CRAN.R-project.org/package=KernSmooth)) for a plugin bandwidth proposed by Wand(1995). ### Examples ``` set.seed(1) x <- stats::rnorm(1111) nclass.Sturges(x) ## Compare them: NC <- function(x) c(Sturges = nclass.Sturges(x), Scott = nclass.scott(x), FD = nclass.FD(x)) NC(x) onePt <- rep(1, 11) NC(onePt) # no longer gives NaN ``` r None `colors` Color Names --------------------- ### Description Returns the built-in color names which **R** knows about. ### Usage ``` colors (distinct = FALSE) colours(distinct = FALSE) ``` ### Arguments | | | | --- | --- | | `distinct` | logical indicating if the colors returned should all be distinct; e.g., `"snow"` and `"snow1"` are effectively the same point in the *(0:255)^3* RGB space. | ### Details These color names can be used with a `col=` specification in graphics functions. An even wider variety of colors can be created with primitives `rgb`, `hsv` and `hcl`, or the derived `rainbow`, `heat.colors`, etc. `"transparent"` is not a color and so not listed, but it is accepted as a color specification. ### Value A character vector containing all the built-in color names. ### See Also `<palette>` for setting the ‘palette’ of colors for `par(col=`*<num>*`)`; `<rgb>`, `<hsv>`, `<hcl>`, `<gray>`; `[rainbow](palettes)` for a nice example; and `[heat.colors](palettes)`, `[topo.colors](palettes)` for images. `<col2rgb>` for translating to RGB numbers and extended examples. ### Examples ``` cl <- colors() length(cl); cl[1:20] length(cl. <- colors(TRUE)) ## only 502 of the 657 named ones ## ----------- Show all named colors and more: demo("colors") ## ----------- ```
programming_docs
r None `x11Fonts` X11 Fonts --------------------- ### Description These functions handle the translation of a device-independent R graphics font family name to an X11 font description on Unix-alike platforms. ### Usage ``` X11Font(font) X11Fonts(...) ``` ### Arguments | | | | --- | --- | | `font` | a character string containing an X11 font description. | | `...` | either character strings naming mappings to display, or new (named) mappings to define. | ### Details These functions apply only to an `[X11](x11)` device with `type = "Xlib"` – `X11(type = "cairo")` uses a different mechanism to select fonts. Such a device is created with a default font (see the documentation for `[X11](x11)`), but it is also possible to specify a font family when drawing to the device (for example, see the documentation for `"family"` in `[par](../../graphics/html/par)` and for `"fontfamily"` in `[gpar](../../grid/html/gpar)` in the grid package). The font family sent to the device is a simple string name, which must be mapped to something more specific to X11 fonts. A list of mappings is maintained and can be modified by the user. The `X11Fonts` function can be used to list existing mappings and to define new mappings. The `X11Font` function can be used to create a new mapping. Default mappings are provided for three device-independent font family names: `"sans"` for a sans-serif font, `"serif"` for a serif font and `"mono"` for a monospaced font. Further mappings are provided for `"Helvetica"` (the device default), `"Times"`, `"CyrHelvetica"`, `"CyrTimes"` (versions of these fonts with Cyrillic support, at least on Linux), `"Arial"` (on some platforms including macOS and Solaris) and `"Mincho"` (a CJK font). ### Note Available only when `[capabilities](../../base/html/capabilities)()[["X11"]]` is true. ### See Also `[X11](x11)` ### Examples ``` ## IGNORE_RDIFF_BEGIN if(capabilities()[["X11"]]) withAutoprint({ X11Fonts() X11Fonts("mono") utopia <- X11Font("-*-utopia-*-*-*-*-*-*-*-*-*-*-*-*") X11Fonts(utopia = utopia) }) ## IGNORE_RDIFF_END ``` r None `gray` Gray Level Specification -------------------------------- ### Description Create a vector of colors from a vector of gray levels. ### Usage ``` gray(level, alpha) grey(level, alpha) ``` ### Arguments | | | | --- | --- | | `level` | a vector of desired gray levels between `0` and `1`; zero indicates `"black"` and one indicates `"white"`. | | `alpha` | the opacity, if specified. | ### Details The values returned by `gray` can be used with a `col=` specification in graphics functions or in `[par](../../graphics/html/par)`. `grey` is an alias for `gray`. ### Value A vector of colors of the same length as `level`. ### See Also `[rainbow](palettes)`, `<hsv>`, `<hcl>`, `<rgb>`. ### Examples ``` gray(0:8 / 8) ``` r None `hsv` HSV Color Specification ------------------------------ ### Description Create a vector of colors from vectors specifying hue, saturation and value. ### Usage ``` hsv(h = 1, s = 1, v = 1, alpha) ``` ### Arguments | | | | --- | --- | | `h,s,v` | numeric vectors of values in the range `[0, 1]` for ‘hue’, ‘saturation’ and ‘value’ to be combined to form a vector of colors. Values in shorter arguments are recycled. | | `alpha` | numeric vector of values in the range `[0, 1]` for alpha transparency channel (0 means transparent and 1 means opaque). | ### Details Semi-transparent colors (`0 < alpha < 1`) are supported only on some devices: see `<rgb>`. ### Value This function creates a vector of colors corresponding to the given values in HSV space. The values returned by `hsv` can be used with a `col=` specification in graphics functions or in `par`. ### See Also `<hcl>` for a perceptually based version of `hsv()`, `<rgb>` and `<rgb2hsv>` for RGB to HSV conversion; `[rainbow](palettes)`, `<gray>`. ### Examples ``` require(graphics) hsv(.5,.5,.5) ## Red tones: n <- 20; y <- -sin(3*pi*((1:n)-1/2)/n) op <- par(mar = rep(1.5, 4)) plot(y, axes = FALSE, frame.plot = TRUE, xlab = "", ylab = "", pch = 21, cex = 30, bg = rainbow(n, start = .85, end = .1), main = "Red tones") par(op) ``` r None `extendrange` Extend a Numerical Range by a Small Percentage ------------------------------------------------------------- ### Description Extends a numerical range by a small percentage, i.e., fraction, *on both sides*. ### Usage ``` extendrange(x, r = range(x, na.rm = TRUE), f = 0.05) ``` ### Arguments | | | | --- | --- | | `x` | numeric vector; not used if `r` is specified. | | `r` | numeric vector of length 2; defaults to the `[range](../../base/html/range)` of `x`. | | `f` | positive number(s) specifying the fraction by which the range should be extended. If longer than one, `f[1]` is used on the left, and `f[2]` on the right. | ### Value A numeric vector of length 2, `r + c(-f1,f2) * diff(r)`, where f1 is `f[1]` and f2 is `f[2]` or `f` if it is of length one. ### See Also `[range](../../base/html/range)`; `[pretty](../../base/html/pretty)` which can be considered a sophisticated extension of `extendrange`. ### Examples ``` x <- 1:5 (r <- range(x)) # 1 5 extendrange(x) # 0.8 5.2 extendrange(x, f= 0.01) # 0.96 5.04 ## extend more to the right: extendrange(x, f=c(.01,.03)) # 0.96 5.12 ## Use 'r' if you have it already: stopifnot(identical(extendrange(r = r), extendrange(x))) ``` r None `cairo` Cairographics-based SVG, PDF and PostScript Graphics Devices --------------------------------------------------------------------- ### Description Graphics devices for SVG, PDF and PostScript graphics files using the cairo graphics API. ### Usage ``` svg(filename = if(onefile) "Rplots.svg" else "Rplot%03d.svg", width = 7, height = 7, pointsize = 12, onefile = FALSE, family = "sans", bg = "white", antialias = c("default", "none", "gray", "subpixel"), symbolfamily) cairo_pdf(filename = if(onefile) "Rplots.pdf" else "Rplot%03d.pdf", width = 7, height = 7, pointsize = 12, onefile = FALSE, family = "sans", bg = "white", antialias = c("default", "none", "gray", "subpixel"), fallback_resolution = 300, symbolfamily) cairo_ps(filename = if(onefile) "Rplots.ps" else "Rplot%03d.ps", width = 7, height = 7, pointsize = 12, onefile = FALSE, family = "sans", bg = "white", antialias = c("default", "none", "gray", "subpixel"), fallback_resolution = 300, symbolfamily) ``` ### Arguments | | | | --- | --- | | `filename` | the name of the output file. The page number is substituted if a C integer format is included in the character string, as in the default. (The result must be less than `PATH_MAX` characters long, and may be truncated if not. See `<postscript>` for further details.) Tilde expansion is performed where supported by the platform. | | `width` | the width of the device in inches. | | `height` | the height of the device in inches. | | `pointsize` | the default pointsize of plotted text (in big points). | | `onefile` | should all plots appear in one file or in separate files? | | `family` | one of the device-independent font families, `"sans"`, `"serif"` and `"mono"`, or a character string specify a font family to be searched for in a system-dependent way. On unix-alikes (incl.\ Mac), see the ‘Cairo fonts’ section in the help for `[X11](x11)`. | | `bg` | the initial background colour: can be overridden by setting par("bg"). | | `antialias` | string, the type of anti-aliasing (if any) to be used; defaults to `"default"`. | | `fallback_resolution` | numeric: the resolution in dpi used when falling back to bitmap output. Prior to **R** 3.3.0 this depended on the cairo implementation but was commonly 300. | | `symbolfamily` | a length-one character string that specifies the font family to be used as the "symbol" font (e.g., for <plotmath> output). | ### Details SVG (Scalar Vector Graphics) is a W3C standard for vector graphics. See <https://www.w3.org/Graphics/SVG/>. The output from `svg` is SVG version 1.1 for `onefile = FALSE` (the default), otherwise SVG 1.2. (Few SVG viewers are capable of displaying multi-page SVG files.) Note that unlike `<postscript>` and `<pdf>`, `cairo_pdf` and `cairo_ps` sometimes record *bitmaps* and not vector graphics. On the other hand, they can (on suitable platforms) include a much wider range of UTF-8 glyphs, and embed the fonts used. The output produced by `cairo_ps(onefile = FALSE)` will be encapsulated postscript on a platform with cairo >= 1.6. **R** can be compiled without support for any of these devices: this will be reported if you attempt to use them on a system where they are not supported. They all require cairo version 1.2 or later. If you plot more than one page on one of these devices and do not include something like `%d` for the sequence number in `file` (or set `onefile = TRUE`) the file will contain the last page plotted. There is full support of semi-transparency, but using this is one of the things liable to trigger bitmap output (and will always do so for `cairo_ps`). ### Value A plot device is opened: nothing is returned to the **R** interpreter. ### Anti-aliasing Anti-aliasing is applied to both graphics and fonts. It is generally preferable for lines and text, but can lead to undesirable effects for fills, e.g. for `[image](../../graphics/html/image)` plots, and so is never used for fills. `antialias = "default"` is in principle platform-dependent, but seems most often equivalent to `antialias = "gray"`. ### Conventions This section describes the implementation of the conventions for graphics devices set out in the ‘R Internals’ manual. * The default device size is in pixels (`svg`) or inches. * Font sizes are in big points. * The default font family is Helvetica. * Line widths are multiples of 1/96 inch. * Circle radii have a minimum of 1/72 inch. * Colours are interpreted by the viewing application. ### Warning Support for all these devices are optional, so in packages they should be used conditionally after checking `[capabilities](../../base/html/capabilities)("cairo")`. ### Note In principle these devices are independent of X11 (as is seen by their presence on Windows). But on a Unix-alike the cairo libraries may be distributed as part of the X11 system and hence that (for example, on `x86_64` macOS, XQuartz) may need to be installed. ### See Also `[Devices](devices)`, `[dev.print](dev2)`, `<pdf>`, `<postscript>` `[capabilities](../../base/html/capabilities)` to see if cairo is supported. r None `quartz` macOS Quartz Device ----------------------------- ### Description `quartz` starts a graphics device driver for the macOS system. It supports plotting both to the screen (the default) and to various graphics file formats. ### Usage ``` quartz(title, width, height, pointsize, family, antialias, type, file = NULL, bg, canvas, dpi) quartz.options(..., reset = FALSE) quartz.save(file, type = "png", device = dev.cur(), dpi = 100, ...) ``` ### Arguments | | | | --- | --- | | `title` | title for the Quartz window (applies to on-screen output only), default `"Quartz %d"`. A C-style format for an integer will be substituted by the device number (see the `file` argument to `<postscript>` for further details). | | `width` | the width of the plotting area in inches. Default `7`. | | `height` | the height of the plotting area in inches. Default `7`. | | `pointsize` | the default pointsize to be used. Default `12`. | | `family` | this is the family name of the font that will be used by the device. Default `"Arial"`. This will be the base name of a font as shown in Font Book. | | `antialias` | whether to use antialiasing. Default `TRUE`. | | `type` | the type of output to use. See ‘Details’ for more information. Default `"native"`. | | `file` | an optional target for the graphics device. The default, `NULL`, selects a default name where one is needed. See ‘Details’ for more information. | | `bg` | the initial background colour to use for the device. Default `"transparent"`. An opaque colour such as `"white"` will normally be required on off-screen types that support transparency such as `"png"` and `"tiff"`. | | `canvas` | canvas colour to use for an on-screen device. Default `"white"`, and will be forced to be an opaque colour. | | `dpi` | resolution of the output. The default (`NA_real_`) for an on-screen display defaults to the resolution of the main screen, and to 72 dpi otherwise. See ‘Details’. | | `...` | Any of the arguments to `quartz` except `file`. | | `reset` | logical: should the defaults be reset to their defaults? | | `device` | device number to copy from. | ### Details The defaults for all but one of the arguments of `quartz` are set by `quartz.options`: the ‘Arguments’ section gives the ‘factory-fresh’ defaults. The Quartz graphics device supports a variety of output types. On-screen output types are `""` or `"native"` or `"Cocoa"`. Off-screen output types produce output files and utilize the `file` argument. `type = "pdf"` gives PDF output. The following bitmap formats may be supported (depending on the OS version): `"png"`, `"jpeg"`, `"jpg"`, `"jpeg2000"`, `"tif"`, `"tiff"`, `"gif"`, `"psd"` (Adobe Photoshop), `"bmp"` (Windows bitmap), `"sgi"` and `"pict"`. The `file` argument is used for off-screen drawing. The actual file is only created when the device is closed (e.g., using `dev.off()`). For the bitmap devices, the page number is substituted if a C integer format is included in the character string, e.g. `Rplot%03d.png`. (The result must be less than `PATH_MAX` characters long, and may be truncated if not. See `<postscript>` for further details.) If a `file` argument is not supplied, the default is `Rplots.pdf` or `Rplot%03d.type`. Tilde expansion (see `[path.expand](../../base/html/path.expand)`) is done. If a device-independent **R** graphics font family is specified (e.g., via `par(family =)` in the graphics package), the Quartz device makes use of the Quartz font database (see `quartzFonts`) to convert the R graphics font family to a Quartz-specific font family description. The default conversions are (MonoType TrueType versions of) `Helvetica` for `sans`, `Times-Roman` for `serif` and `Courier` for `mono`. On-screen devices are launched with a semi-transparent canvas. Once a new plot is created, the canvas is first painted with the `canvas` colour and then the current background colour (which can be transparent or semi-transparent). Off-screen devices have no canvas colour, and so start with a transparent background where possible (e.g., `type = "png"` and `type = "tiff"`) – otherwise it appears that a solid white canvas is assumed in the Quartz code. PNG and TIFF files are saved with a dark grey matte which will show up in some viewers, including `Preview`. `title` can be used for on-screen output. It must be a single character string with an optional integer printf-style format that will be substituted by the device number. It is also optionally used (without a format) to give a title to a PDF file. Calling `quartz()` sets `[.Device](../../base/html/dev)` to `"quartz"` for on-screen devices and to `"quartz_off_screen"` otherwise. The font family chosen needs to cover the characters to be used: characters not in the font are rendered as empty oblongs. For non-Western-European languages something other than the default of `"Arial"` is likely to be needed—one choice for Chinese is `"MingLiU"`. `quartz.save` is a modified version of `[dev.copy2pdf](dev2)` to copy the plot from the current screen device to a `quartz` device, by default to a PNG file. ### Conventions This section describes the implementation of the conventions for graphics devices set out in the ‘R Internals’ manual. * The default device size is 7 inches square. * Font sizes are in big points. * The default font family is Arial. * Line widths are a multiple of 1/96 inch with no minimum set by **R**. * Circle radii are real-valued with no minimum set by **R**. * Colours are specified as sRGB. ### Note For a long time the default font family was documented as `"Helvetica"` after it had been changed to `"Arial"` to work around a deficiency in macOS 10.4. It may be changed back in future. A fairly common Mac problem is no text appearing on plots due to corrupted or duplicated fonts on your system. You may be able to confirm this by using another font family, e.g. `family = "serif"`. Open the `Font Book` application (in `Applications`) and check the fonts that you are using. ### See Also `[quartzFonts](quartzfonts)`, `[Devices](devices)`. `<png>` for way to access the bitmap types of this device via **R**'s standard bitmap devices. ### Examples ``` ## Not run: ## Only on a Mac, ## put something like this is your .Rprofile to customize the defaults setHook(packageEvent("grDevices", "onLoad"), function(...) grDevices::quartz.options(width = 8, height = 6, pointsize = 10)) ## End(Not run) ``` r None `devAskNewPage` Prompt before New Page --------------------------------------- ### Description This function can be used to control (for the current device) whether the user is prompted before starting a new page of output. ### Usage ``` devAskNewPage(ask = NULL) ``` ### Arguments | | | | --- | --- | | `ask` | `NULL` or a logical value. If `TRUE`, the user will in future be prompted before a new page of output is started. | ### Details If the current device is the null device, this will open a graphics device. The default argument just returns the current setting and does not change it. The default value when a device is opened is taken from the setting of `[options](../../base/html/options)("device.ask.default")`. The precise circumstances when the user will be asked to confirm a new page depend on the graphics subsystem. Obviously this needs to be an interactive session. In addition ‘recording’ needs to be in operation, so only when the display list is enabled (see `[dev.control](dev2)`) which it usually is only on a screen device. ### Value The current prompt setting *before* any new setting is applied. Invisibly if `ask` is logical. ### See Also `[plot.new](../../graphics/html/frame)`, `[grid.newpage](../../grid/html/grid.newpage)` r None `embedFonts` Embed Fonts in PostScript and PDF ----------------------------------------------- ### Description Runs Ghostscript to process a PDF or PostScript file and embed all fonts in the file. ### Usage ``` embedFonts(file, format, outfile = file, fontpaths = character(), options = character()) ``` ### Arguments | | | | --- | --- | | `file` | a character string giving the name of the original file. | | `format` | the format for the new file (with fonts embedded) given as the name of a ghostscript output device. If not specified, it is guessed from the suffix of `file`. | | `outfile` | the name of the new file (with fonts embedded). | | `fontpaths` | a character vector giving directories that Ghostscript will search for fonts. | | `options` | a character vector containing further options to Ghostscript. | ### Details This function is not necessary if you just use the standard default fonts for PostScript and PDF output. If you use a special font, this function is useful for embedding that font in your PostScript or PDF document so that it can be shared with others without them having to install your special font (provided the font licence allows this). If the special font is not installed for Ghostscript, you will need to tell Ghostscript where the font is, using something like `options="-sFONTPATH=path/to/font"`. You will need `ghostscript`: the full path to the executable can be set by the environment variable R\_GSCMD. If this is unset, a GhostScript executable will be looked for by name on your path: on a Unix alike `"gs"` is used, and on Windows the setting of the environment variable GSC is used, otherwise commands `"gswi64c.exe"` then `"gswin32c.exe"` are tried. The `format` is by default `"ps2write"`, when the original file has a `.ps` or `.eps` suffix, or `"pdfwrite"` when the original file has a `.pdf` suffix. For versions of Ghostscript before 9.10, `format = "pswrite"` or `format = "epswrite"` can be used: as from 9.14 `format = "eps2write"` is also available. If an invalid device is given, the error message will list the available devices. Note that Ghostscript may do font substitution, so the font embedded may differ from that specified in the original file. Some other options which can be useful (see your Ghostscript documentation) are -dMaxSubsetPct=100, -dSubsetFonts=true and -dEmbedAllFonts=true. ### Value The shell command used to invoke Ghostscript is returned invisibly. This may be useful for debugging purposes as you can run the command by hand in a shell to look for problems. ### See Also `[postscriptFonts](postscriptfonts)`, `[Devices](devices)`. Paul Murrell and Brian Ripley (2006). “Non-standard fonts in PostScript and PDF graphics.” *R News*, **6**(2), 41–47. <https://www.r-project.org/doc/Rnews/Rnews_2006-2.pdf>.
programming_docs
r None `Devices` List of Graphical Devices ------------------------------------ ### Description The following graphics devices are currently available: `<windows>`: On Windows only, the graphics device for Windows (on screen, to printer and to Windows metafile). `<pdf>`: Write PDF graphics commands to a file `<postscript>`: Writes PostScript graphics commands to a file `<xfig>`: Device for XFIG graphics file format `[bitmap](dev2bitmap)`: bitmap pseudo-device via `Ghostscript` (if available). `<pictex>`: Writes TeX/PicTeX graphics commands to a file (of historical interest only) The following devices will be functional if **R** was compiled to use them (they exist but will return with a warning on other systems): `[cairo\_pdf](cairo)`, `cairo_ps`: PDF and PostScript devices based on cairo graphics. `[svg](cairo)`: SVG device based on cairo graphics `<png>`: PNG bitmap device `[jpeg](png)`: JPEG bitmap device `[bmp](png)`: BMP bitmap device `[tiff](png)`: TIFF bitmap device On Unix-alikes (incl. Mac) only: `[X11](x11)`: The graphics device for the X11 windowing system `<quartz>`: The graphics device for the macOS native Quartz 2d graphics system. (This is only functional on macOS where it can be used from the `R.app` GUI and from the command line: but it will display on the local screen even for a remote session.) ### Details If no device is open, calling any high-level graphics function will cause a device to be opened. Which device is determined by `[options](../../base/html/options)("device")` which is initially set as the most appropriate for each platform: a screen device for most interactive use and `<pdf>` (or the setting of R\_DEFAULT\_DEVICE) otherwise. The exception is interactive use under Unix if no screen device is known to be available, when `pdf()` is used. It is possible for an **R** package (or an **R** front-end such as RStudio) to provide further graphics devices and several packages on CRAN do so. These include other devices outputting SVG and PGF/TiKZ (TeX-based graphics, see <http://pgf.sourceforge.net/>). ### See Also The individual help files for further information on any of the devices listed here; on Windows: `<windows.options>`, on a Unix-alike: `[X11](x11).options`, `[quartz.options](quartz)`, `<ps.options>` and `<pdf.options>` for how to customize devices. `<dev.interactive>`, `[dev.cur](dev)`, `[dev.print](dev2)`, `[graphics.off](dev)`, `[image](../../graphics/html/image)`, `<dev2bitmap>`. On Unix-alikes only: `[capabilities](../../base/html/capabilities)` to see if `[X11](x11)`, `[jpeg](png)`, `<png>`, `[tiff](png)`, `<quartz>` and the cairo-based devices are available. ### Examples ``` ## Not run: ## open the default screen device on this platform if no device is ## open if(dev.cur() == 1) dev.new() ## End(Not run) ``` r None `axisTicks` Compute Pretty Axis Tick Scales -------------------------------------------- ### Description Compute pretty axis scales and tick mark locations, the same way as traditional **R** graphics do it. This is interesting particularly for log scale axes. ### Usage ``` axisTicks(usr, log, axp = NULL, nint = 5) .axisPars(usr, log = FALSE, nintLog = 5) ``` ### Arguments | | | | --- | --- | | `usr` | numeric vector of length 2, with `c(min, max)` axis extents. | | `log` | logical indicating if a log scale is (thought to be) in use. | | `axp` | numeric vector of length 3, `c(mi, ma, n.)`, with identical meaning to `[par](../../graphics/html/par)("?axp")` (where `?` is `x` or `y`), namely “pretty” axis extents, and an integer *code* `n.`. | | `nint, nintLog` | positive integer value indicating (*approximately*) the desired number of intervals. `nintLog` is used **only** for the case `log = TRUE`. | ### Details `axisTicks(usr, *)` calls `.axisPars(usr, ..)` to set `axp` when that is missing or `NULL`. Apart from that, `[axisTicks](axisticks)()` just calls the C function `CreateAtVector()` in ‘<Rsrc>/src/main/plot.c’ which is also called by the base graphics package function `[axis](../../graphics/html/axis)(side, *)` when its argument `at` is not specified. Since **R** 4.1.0, the underlying C `CreateAtVector()` has been tuned to provide a considerably more balanced (symmetric) set of tick locations. ### Value `axisTicks()` returns a numeric vector of potential axis tick locations, of length approximately `nint+1`. `.axisPars()` returns a `[list](../../base/html/list)` with components | | | | --- | --- | | `axp` | numeric vector of length 2, `c(min., max.)`, of pretty axis extents. | | `n` | integer (code), with the same meaning as `[par](../../graphics/html/par)("?axp")[3]`. | ### See Also `[axTicks](../../graphics/html/axticks)`, `[axis](../../graphics/html/axis)`, and `[par](../../graphics/html/par)` all from the graphics package. ### Examples ``` ##--- Demonstrating correspondence between graphics' ##--- axis() and the graphics-engine agnostic axisTicks() : require("graphics") plot(10*(0:10)); (pu <- par("usr")) aX <- function(side, at, ...) axis(side, at = at, labels = FALSE, lwd.ticks = 2, col.ticks = 2, tck = 0.05, ...) aX(1, print(xa <- axisTicks(pu[1:2], log = FALSE))) # x axis aX(2, print(ya <- axisTicks(pu[3:4], log = FALSE))) # y axis axisTicks(pu[3:4], log = FALSE, nint = 10) plot(10*(0:10), log = "y"); (pu <- par("usr")) aX(2, print(ya <- axisTicks(pu[3:4], log = TRUE))) # y axis plot(2^(0:9), log = "y"); (pu <- par("usr")) aX(2, print(ya <- axisTicks(pu[3:4], log = TRUE))) # y axis ``` r None `hcl` HCL Color Specification ------------------------------ ### Description Create a vector of colors from vectors specifying hue, chroma and luminance. ### Usage ``` hcl(h = 0, c = 35, l = 85, alpha, fixup = TRUE) ``` ### Arguments | | | | --- | --- | | `h` | The hue of the color specified as an angle in the range [0,360]. 0 yields red, 120 yields green 240 yields blue, etc. | | `c` | The chroma of the color. The upper bound for chroma depends on hue and luminance. | | `l` | A value in the range [0,100] giving the luminance of the colour. For a given combination of hue and chroma, only a subset of this range is possible. | | `alpha` | numeric vector of values in the range `[0,1]` for alpha transparency channel (0 means transparent and 1 means opaque). | | `fixup` | a logical value which indicates whether the resulting RGB values should be corrected to ensure that a real color results. if `fixup` is `FALSE` RGB components lying outside the range [0,1] will result in an `NA` value. | ### Details This function corresponds to polar coordinates in the CIE-LUV color space. Steps of equal size in this space correspond to approximately equal perceptual changes in color. Thus, `hcl` can be thought of as a perceptually based version of `<hsv>`. The function is primarily intended as a way of computing colors for filling areas in plots where area corresponds to a numerical value (pie charts, bar charts, mosaic plots, histograms, etc). Choosing colors which have equal chroma and luminance provides a way of minimising the irradiation illusion which would otherwise produce a misleading impression of how large the areas are. The default values of chroma and luminance make it possible to generate a full range of hues and have a relatively pleasant pastel appearance. The RGB values produced by this function correspond to the sRGB color space used on most PC computer displays. There are other packages which provide more general color space facilities. Semi-transparent colors (`0 < alpha < 1`) are supported only on some devices: see `<rgb>`. ### Value A vector of character strings which can be used as color specifications by **R** graphics functions. Missing or infinite values of any of `h`, `c`, `l` result in `NA`: such values of `alpha` are taken as `1` (opaque). ### Note At present there is no guarantee that the colours rendered by R graphics devices will correspond to their sRGB description. It is planned to adopt sRGB as the standard R color description in future. ### Author(s) Ross Ihaka ### References Ihaka, R. (2003). Colour for Presentation Graphics, Proceedings of the 3rd International Workshop on Distributed Statistical Computing (DSC 2003), March 20-22, 2003, Technische Universität Wien, Vienna, Austria. <http://www.ci.tuwien.ac.at/Conferences/DSC-2003/>. ### See Also `<hsv>`, `<rgb>`. ### Examples ``` require(graphics) # The Foley and Van Dam PhD Data. csd <- matrix(c( 4,2,4,6, 4,3,1,4, 4,7,7,1, 0,7,3,2, 4,5,3,2, 5,4,2,2, 3,1,3,0, 4,4,6,7, 1,10,8,7, 1,5,3,2, 1,5,2,1, 4,1,4,3, 0,3,0,6, 2,1,5,5), nrow = 4) csphd <- function(colors) barplot(csd, col = colors, ylim = c(0,30), names.arg = 72:85, xlab = "Year", ylab = "Students", legend.text = c("Winter", "Spring", "Summer", "Fall"), main = "Computer Science PhD Graduates", las = 1) # The Original (Metaphorical) Colors (Ouch!) csphd(c("blue", "green", "yellow", "orange")) # A Color Tetrad (Maximal Color Differences) csphd(hcl(h = c(30, 120, 210, 300))) # Same, but lighter and less colorful # Turn off automatic correction to make sure # that we have defined real colors. csphd(hcl(h = c(30, 120, 210, 300), c = 20, l = 90, fixup = FALSE)) # Analogous Colors # Good for those with red/green color confusion csphd(hcl(h = seq(60, 240, by = 60))) # Metaphorical Colors csphd(hcl(h = seq(210, 60, length.out = 4))) # Cool Colors csphd(hcl(h = seq(120, 0, length.out = 4) + 150)) # Warm Colors csphd(hcl(h = seq(120, 0, length.out = 4) - 30)) # Single Color hist(stats::rnorm(1000), col = hcl(240)) ## Exploring the hcl() color space {in its mapping to R's sRGB colors}: demo(hclColors) ``` r None `cm` Unit Transformation ------------------------- ### Description Translates from inches to cm (centimeters). ### Usage ``` cm(x) ``` ### Arguments | | | | --- | --- | | `x` | numeric vector | ### Examples ``` cm(1) # = 2.54 ## Translate *from* cm *to* inches: 10 / cm(1) # -> 10cm are 3.937 inches ``` r None `savePlot` Save Cairo X11 Plot to File --------------------------------------- ### Description Save the current page of a cairo `[X11](x11)()` device to a file. ### Usage ``` savePlot(filename = paste0("Rplot.", type), type = c("png", "jpeg", "tiff", "bmp"), device = dev.cur()) ``` ### Arguments | | | | --- | --- | | `filename` | filename to save to. | | `type` | file type. | | `device` | the device to save from. | ### Details Only cairo-based `X11` devices are supported. This works by copying the image surface to a file. For PNG will always be a 24-bit per pixel PNG ‘DirectClass’ file, for JPEG the quality is 75% and for TIFF there is no compression. For devices with buffering this copies the buffer's image surface, so works even if `[dev.hold](dev.flush)` has been called. The plot is saved after rendering onto the canvas (default opaque white), so for the default `bg = "transparent"` the effective background colour is the canvas colour. ### Value Invisible `NULL`. ### Note There is a similar function of the same name but more types for `windows` devices on Windows: that has an additional argument `restoreConsole` which is only supported on Windows. ### See Also `[recordPlot](recordplot)()` which is device independent. Further, `[X11](x11)`, `[dev.copy](dev2)`, `[dev.print](dev2)` r None `bringToTop` Assign Focus to a Window -------------------------------------- ### Description `bringToTop` brings the specified screen device's window to the front of the window stack (and gives it focus). With first argument `-1` it brings the console to the top. If `stay = TRUE`, the window is designated as a topmost window, i.e. it will stay on top of any regular window. `stay` may only be used when Rgui is run in SDI mode. This corresponds to the “Stay on top” popup menu item in Rgui. ### Usage ``` bringToTop(which = dev.cur(), stay = FALSE) ``` ### Arguments | | | | --- | --- | | `which` | a device number, or `-1`. | | `stay` | whether to make the window stay on top. | ### See Also `[msgWindow](msgwindow)`, `<windows>` r None `as.raster` Create a Raster Object ----------------------------------- ### Description Functions to create a raster object (representing a bitmap image) and coerce other objects to a raster object. ### Usage ``` is.raster(x) as.raster(x, ...) ## S3 method for class 'matrix' as.raster(x, max = 1, ...) ## S3 method for class 'array' as.raster(x, max = 1, ...) ## S3 method for class 'logical' as.raster(x, max = 1, ...) ## S3 method for class 'numeric' as.raster(x, max = 1, ...) ## S3 method for class 'character' as.raster(x, max = 1, ...) ## S3 method for class 'raw' as.raster(x, max = 255L, ...) ``` ### Arguments | | | | --- | --- | | `x` | any **R** object. | | `max` | number giving the maximum of the color values range. | | `...` | further arguments passed to or from other methods. | ### Details An object of class `"raster"` is a matrix of colour values as given by `<rgb>` representing a bitmap image. It is not expected that the user will need to call these functions directly; functions to render bitmap images in graphics packages will make use of the `as.raster()` function to generate a raster object from their input. The `as.raster()` function is (S3) generic so methods can be written to convert other **R** objects to a raster object. The default implementation for numeric matrices interprets scalar values on black-to-white scale. Raster objects can be subsetted like a matrix and it is possible to assign to a subset of a raster object. There is a method for converting a raster object to a `[matrix](../../base/html/matrix)` (of colour strings). Raster objects can be compared for equality or inequality (with each other or with a colour string). There is a `[is.na](../../base/html/na)` method which returns a logical matrix of the same dimensions as the raster object. Note that `NA` values are interpreted as the fully transparent colour by some (but not all) graphics devices. ### Value For `as.raster()`, a raster object. For `is.raster()`, a logical indicating whether `x` is a raster object. ### Note Raster images are internally represented row-first, which can cause confusion when trying to manipulate a raster object. The recommended approach is to coerce a raster to a matrix, perform the manipulation, then convert back to a raster. ### Examples ``` # A red gradient as.raster(matrix(hcl(0, 80, seq(50, 80, 10)), nrow = 4, ncol = 5)) # Vectors are 1-column matrices ... # character vectors are color names ... as.raster(hcl(0, 80, seq(50, 80, 10))) # numeric vectors are greyscale ... as.raster(1:5, max = 5) # logical vectors are black and white ... as.raster(1:10 %% 2 == 0) # ... unless nrow/ncol are supplied ... as.raster(1:10 %% 2 == 0, nrow = 1) # Matrix can also be logical or numeric (or raw) ... as.raster(matrix(c(TRUE, FALSE), nrow = 3, ncol = 2)) as.raster(matrix(1:3/4, nrow = 3, ncol = 4)) # An array can be 3-plane numeric (R, G, B planes) ... as.raster(array(c(0:1, rep(0.5, 4)), c(2, 1, 3))) # ... or 4-plane numeric (R, G, B, A planes) as.raster(array(c(0:1, rep(0.5, 6)), c(2, 1, 4))) # subsetting r <- as.raster(matrix(colors()[1:100], ncol = 10)) r[, 2] r[2:4, 2:5] # assigning to subset r[2:4, 2:5] <- "white" # comparison r == "white" ``` r None `check.options` Set Options with Consistency Checks ---------------------------------------------------- ### Description Utility function for setting options with some consistency checks. The `[attributes](../../base/html/attributes)` of the new settings in `new` are checked for consistency with the *model* (often default) list in `name.opt`. ### Usage ``` check.options(new, name.opt, reset = FALSE, assign.opt = FALSE, envir = .GlobalEnv, check.attributes = c("mode", "length"), override.check = FALSE) ``` ### Arguments | | | | --- | --- | | `new` | a *named* list | | `name.opt` | character with the name of **R** object containing the default list. | | `reset` | logical; if `TRUE`, reset the options from `name.opt`. If there is more than one **R** object with name `name.opt`, remove the first one in the `[search](../../base/html/search)()` path. | | `assign.opt` | logical; if `TRUE`, assign the ... | | `envir` | the `[environment](../../base/html/environment)` used for `[get](../../base/html/get)` and `[assign](../../base/html/assign)`. | | `check.attributes` | character containing the attributes which `check.options` should check. | | `override.check` | logical vector of length `length(new)` (or 1 which entails recycling). For those `new[i]` where `override.check[i] == TRUE`, the checks are overridden and the changes made anyway. | ### Value A list of components with the same names as the one called `name.opt`. The values of the components are changed from the `new` list, as long as these pass the checks (when these are not overridden according to `override.check`). ### Note Option `"names"` is exempt from all the checks or warnings, as in the application it can be `NULL` or a variable-length character vector. ### Author(s) Martin Maechler ### See Also `<ps.options>` and `<pdf.options>`, which use `check.options`. ### Examples ``` (L1 <- list(a = 1:3, b = pi, ch = "CH")) check.options(list(a = 0:2), name.opt = "L1") check.options(NULL, reset = TRUE, name.opt = "L1") ``` r None `xy.coords` Extracting Plotting Structures ------------------------------------------- ### Description `xy.coords` is used by many functions to obtain x and y coordinates for plotting. The use of this common mechanism across all relevant **R** functions produces a measure of consistency. ### Usage ``` xy.coords(x, y = NULL, xlab = NULL, ylab = NULL, log = NULL, recycle = FALSE, setLab = TRUE) ``` ### Arguments | | | | --- | --- | | `x, y` | the x and y coordinates of a set of points. Alternatively, a single argument `x` can be provided. | | `xlab, ylab` | names for the x and y variables to be extracted. | | `log` | character, `"x"`, `"y"` or both, as for `[plot](../../graphics/html/plot.default)`. Sets negative values to `[NA](../../base/html/na)` and gives a warning. | | `recycle` | logical; if `TRUE`, recycle (`[rep](../../base/html/rep)`) the shorter of `x` or `y` if their lengths differ. | | `setLab` | logical indicating if the resulting `xlab` and `ylab` should be constructed from the “kind” of `(x,y)`; otherwise, the arguments `xlab` and `ylab` are used. | ### Details An attempt is made to interpret the arguments `x` and `y` in a way suitable for bivariate plotting (or other bivariate procedures). If `y` is `NULL` and `x` is a formula: of the form `yvar ~ xvar`. `xvar` and `yvar` are used as x and y variables. list: containing components `x` and `y`, these are used to define plotting coordinates. time series: the x values are taken to be `[time](../../stats/html/time)(x)` and the y values to be the time series. matrix or `[data.frame](../../base/html/data.frame)` with two or more columns: the first is assumed to contain the x values and the second the y values. *Note* that is also true if `x` has columns named `"x"` and `"y"`; these names will be irrelevant here. In any other case, the `x` argument is coerced to a vector and returned as **y** component where the resulting `x` is just the index vector `1:n`. In this case, the resulting `xlab` component is set to `"Index"` (if `setLab` is true as by default). If `x` (after transformation as above) inherits from class `"POSIXt"` it is coerced to class `"POSIXct"`. ### Value A list with the components | | | | --- | --- | | `x` | numeric (i.e., `"double"`) vector of abscissa values. | | `y` | numeric vector of the same length as `x`. | | `xlab` | `character(1)` or `NULL`, the ‘label’ of `x`. | | `ylab` | `character(1)` or `NULL`, the ‘label’ of `y`. | ### See Also `[plot.default](../../graphics/html/plot.default)`, `[lines](../../graphics/html/lines)`, `[points](../../graphics/html/points)` and `[lowess](../../stats/html/lowess)` are examples of functions which use this mechanism. ### Examples ``` ff <- stats::fft(1:9) xy.coords(ff) xy.coords(ff, xlab = "fft") # labels "Re(fft)", "Im(fft)" with(cars, xy.coords(dist ~ speed, NULL)$xlab ) # = "speed" xy.coords(1:3, 1:2, recycle = TRUE) # otherwise error "lengths differ" xy.coords(-2:10, log = "y") ##> xlab: "Index" \\ warning: 3 y values <= 0 omitted .. ```
programming_docs