在这个模块之中仅包含有最基本的数据操作函数
base
01 Syntax
02 Methods
| Name | Overloads | Summary |
|---|---|---|
| isTRUE | 1 | Logical Operators isTRUE(x) is the same as { is.logical(x) && length(x) == 1 && !is.na(x) && x }; isFALSE() is defined analogously. |
| isFALSE | 1 | Logical Operators isTRUE(x) is the same as { is.logical(x) && length(x) == 1 && !is.na(x) && x }; isFALSE() is defined analogously. |
| numeric | 1 | Numeric Vectors Creates or coerces objects of type "numeric". |
| raws | 1 | Create the raw bytes vector |
| argumentList | 1 | Argument List of a Function Displays the argument names and corresponding default values of a (non-primitive or primitive) function. |
| commandArgs | 1 | commandArgs: Extract Command Line Arguments Provides access to a copy of the command line arguments supplied when this R session was invoked. |
| range | 1 | Range of Values range returns a vector containing the minimum and maximum of all the given arguments. |
| seq | 1 | Sequence Generation Generate regular sequences. |
| date | 1 | System Date and Time |
| c | 1 | Combine Values into a Vector or List This is a generic function which combines its arguments. |
| ifelse | 1 | Conditional Element Selection ifelse returns a value with the same shape as test which is filled with elements selected from either yes or no depending on whether the elemen… |
| Robj_dimension | 1 | Dimensions of an Object Retrieve or set the dimension of an object. |
| rep | 1 | Replicate Elements of Vectors and Lists rep replicates the values in x. |
| rep_int | 1 | |
| rep_len | 1 | |
| rbind | 1 | Combine R Objects by Rows or Columns Take a sequence of vector, matrix or data-frame arguments and combine by columns or rows, respectively. |
| cbind | 1 | Combine R Objects by Rows or Columns Take a sequence of vector, matrix or data-frame arguments and combine by columns or rows, respectively. |
| rowwise | 1 | dataframe to rows |
| t | 1 | matrix transpose Given a matrix or data.frame x, t returns the transpose of x. |
| allocate | 1 | create an empty vector with specific count of null value filled |
| unitOfT | 1 | Function to Create a Unit Object get or set unit to a given vector. |
| __invisible | 1 | Change the Print Mode to Invisible Return a (temporarily) invisible copy of an object. |
| neg | 1 | A function to make the numeric value negative |
| append | 1 | Vector Merging Add elements to a vector. |
| objectAddInvoke | 1 | implements append via the add method |
| Rdataframe | 1 | Data Frames The function data.frame() creates data frames, tightly coupled collections of variables which share many of the properties of matrices and of lists, used as the… |
| checkDimensionsAgree | 1 | Utils function for check for dataframe object construction |
| nrow | 1 | The Number of Rows/Columns of an Array nrow and ncol return the number of rows or columns present in x. |
| ncol | 1 | The Number of Rows/Columns of an Array nrow and ncol return the number of rows or columns present in x. |
| Rlist | 1 | Lists – Generic and Dotted Pairs Functions to construct, coerce and check for both kinds of R# lists. |
| summary | 1 | Object Summaries summary is a generic function used to produce result summaries of the results of various model fitting functions. |
| isEmpty | 1 | This function returns a logical value to determine that the given object is empty or not? |
| isNull | 1 | The Null Object NULL represents the null object in R: it is a reserved word. |
| isDataframe | 1 | Coerce to a Data Frame Functions to check if an object is a data frame, or coerce it if possible. |
| isList | 1 | Lists – Generic and Dotted Pairs Functions to construct, coerce and check for both kinds of R lists. |
| isFunction | 1 | Is an Object of Type (Primitive) Function? Checks whether its argument is a (primitive) function. |
| isRVector | 1 | ‘is.vector’ returns ‘TRUE’ if ‘x’ is a vector of the specified mode having no attributes _other than names_. |
| is_array | 1 | Check of the given object is clr array or not |
| as_array | 1 | cast any R object collection as a generic type clr array |
| isNA | 1 | ‘Not Available’ / Missing Values NA is a logical constant of length 1 which contains a missing value indicator. |
| sink | 1 | Send R Output to a File sink diverts R output to a connection (and stops such diversions). |
| sink_number | 1 | sink.number() reports how many diversions are in use. |
| length | 1 | Length of an Object Get or set the length of vectors (including lists) and factors, and of any other R object for which a method has been defined. |
| source | 1 | Run the external R# script. |
| getOption | 1 | Options Settings Allow the user to set and examine a variety of global options which affect the way in which R computes and displays its results. |
| options | 1 | Options Settings Allow the user to set and examine a variety of global options which affect the way in which R computes and displays its results. |
| options_flush | 1 | save the options configuration data to file |
| names | 1 | The Names of an Object Functions to get or set the names of an object. |
| makeNames | 1 | Make Syntactically Valid Names Make syntactically valid names out of character vectors. |
| uniqueNames | 1 | Make Character Strings Unique Makes the elements of a character vector unique by appending sequence numbers to duplicates. |
| rownames | 1 | Row and Column Names Retrieve or set the row or column names of a matrix-like object. |
| colnames | 1 | Row and Column Names Retrieve or set the row or column names of a matrix-like object. |
| stop | 1 | Stop Function Execution stop stops execution of the current expression and executes an error action. |
| warning | 1 | Warning Messages Generates a warning message that corresponds to its argument(s) and (optionally) the expression or function from which it was called. |
| warnings | 1 | Print Warning Messages warnings and its print method print the variable last.warning in a pleasing form. |
| sQuote | 1 | Quote Text Single or double quote text by combining with appropriate single or double left and right quotation marks. |
| dQuote | 1 | Quote Text Single or double quote text by combining with appropriate single or double left and right quotation marks. |
| println_message | 1 | Diagnostic Messages Generate a diagnostic message from its arguments. |
| cat | 1 | Concatenate and Print Outputs the objects, concatenating the representations. |
| str | 1 | Compactly Display the Structure of an Arbitrary R# Object Compactly display the internal structure of an R object, a diagnostic function and an alternative to summary (and to… |
| 1 | Print Values print prints its argument and returns it invisibly (via invisible(x)). | |
| factors | 1 | The function factor is used to encode a vector as a factor (the terms ‘category’ and ‘enumerated type’ are also used for factors). |
| autoDispose | 1 | |
| requireNamespace | 1 | Loading and Unloading Name Spaces Functions to load and unload name spaces. |
| library | 1 | Loading/Attaching and Listing of Packages library and require load and attach add-on packages. |
| attachPackageFile | 1 | attact a given zip archive file as package |
| on_exit | 1 | Function Exit Code on.exit records the expression given as its argument as needing to be executed when the current function exits (either naturally or as the result of an erro… |
| load | 1 | Reload Saved Datasets Reload datasets written with the function save. |
| save | 1 | Save R Objects writes an external representation of R objects to the specified file. |
| saveRDS | 1 | Serialization Interface for Single Objects Functions to write a single R object to a file, and to restore it. |
| readRDS | 1 | Serialization Interface for Single Objects Functions to write a single R object to a file, and to restore it. |
| saveImage | 1 | Save R Objects save.image() is just a short-cut for ‘save my current workspace’, i.e., save(list = ls(all.names = TRUE), file = ".RData", envir = .GlobalEnv). |
| logical | 1 | |
| character | 1 | |
| ints | 1 | |
| year | 1 | |
| replace | 1 | |
| join_data | 1 | |
| Sys_time | 1 |
03 Members
Object)Logical Operators
isTRUE(x) is the same as { is.logical(x) && length(x) == 1 && !is.na(x) && x }; isFALSE() is defined analogously. Consequently, if(isTRUE(cond)) may be preferable to if(cond) because of NAs.
In earlier R versions, isTRUE <- function(x) identical(x, TRUE), had the drawback to be false e.g., for x <- c(val = TRUE).
| Name | Type | Description |
|---|---|---|
x | Object | - |
TRUE
isTRUE(TRUE);
FALSE
isTRUE("TRUE");
FALSE
isTRUE(FALSE);
FALSE
isTRUE([TRUE TRUE]);
Object)Logical Operators
isTRUE(x) is the same as { is.logical(x) && length(x) == 1 && !is.na(x) && x }; isFALSE() is defined analogously. Consequently, if(isTRUE(cond)) may be preferable to if(cond) because of NAs.
In earlier R versions, isTRUE <- function(x) identical(x, TRUE), had the drawback to be false e.g., for x <- c(val = TRUE).
| Name | Type | Description |
|---|---|---|
x | Object | - |
Int32, Environment)Numeric Vectors
Creates or coerces objects of type "numeric". is.numeric is a more general test of an object being interpretable as numbers.
numeric is identical to double. It creates a double-precision vector of the specified length with each element equal to 0.
| Name | Type | Description |
|---|---|---|
length | Int32 | A non-negative integer specifying the desired length. Double values will be coerced to integer: supplying an argument of length other than one is an error. |
env | Environment | - |
Int32, Environment)Create the raw bytes vector
| Name | Type | Description |
|---|---|---|
length | Int32 | - |
env | Environment | - |
A vector of the raw bytes data if the given length greater than zero or a .net clr MemoryStream object that could be used for the file write connection if used the default length value: zero.
Object, Environment)Argument List of a Function
Displays the argument names and corresponding default values of a (non-primitive or primitive) function.
This function is mainly used interactively to print the argument list of a function. For programming, consider using formals instead.
| Name | Type | Description |
|---|---|---|
name | Object | a function (a primitive or a closure, i.e., “non-primitive”). If name is a character string then the function with that name is found and used. |
- For a closure, a closure with identical formal argument list but an empty (NULL) body.
- For a primitive (function), a closure with the documented usage And NULL body. Note that some primitives do Not make use of named arguments And match by position rather than name.
- NULL in case of a non-function.
Boolean, String)commandArgs: Extract Command Line Arguments
Provides access to a copy of the command line arguments supplied when this R session was invoked.
These arguments are captured before the standard R command line processing takes place. This means that they are the unmodified values. This is especially useful with the --args command-line flag to R, as all of the command line after that flag is skipped.
| Name | Type | Description |
|---|---|---|
trailingOnly | Boolean | logical. Should only arguments after --args be returned? |
parse_args | String | parse the arguments value? a character vector of the parse mode:
|
A character vector containing the name of the executable and the user-supplied command line arguments. The first element is the name of the executable by which R was invoked. The exact form of this element is platform dependent: it may be the fully qualified name, or simply the last component (or basename) of the application, or for an embedded R it can be anything the programmer supplied.
if trailingOnly = TRUE, a character vector Of those arguments (If any) supplied after --args.
Range of Values
range returns a vector containing the minimum and maximum of all the given arguments.
range is a generic function: methods can be defined for it directly or via the Summary group generic. For this to work properly, the arguments ... should be unnamed, and dispatch is on the first argument.
If na.rm Is False, NA And NaN values In any Of the arguments will cause NA values To be returned, otherwise NA values are ignored. If finite Is True, the minimum And maximum Of all finite values Is computed, i.e., finite = True includes na.rm = True.
A special situation occurs When there Is no (after omission Of NAs) nonempty argument left, see min.
| Name | Type | Description |
|---|---|---|
x | Object | any numeric or character objects. |
na_rm | Object | logical, indicating if NA's should be omitted. |
finite | Boolean | logical, indicating if all non-finite elements should be omitted. |
[2] 1 6
range(1:6);
Sequence Generation
Generate regular sequences. seq is a standard generic with a default method. seq.int is a primitive which can be much faster but has a few restrictions. seq_along and seq_len are very fast primitives for two common cases.
Numerical inputs should all be finite (that is, not infinite, NaN or NA). The interpretation Of the unnamed arguments Of seq And seq.int Is Not standard, And it Is recommended always To name the arguments When programming.
seq Is generic, And only the default method Is described here. Note that it dispatches on the class of the first argument irrespective of argument names. This can have unintended consequences if it Is called with just one argument intending this to be taken as along.with it Is much better to use seq_along in that case.
seq.int Is an internal generic which dispatches on methods for "seq" based on the class of the first supplied argument (before argument matching).
Typical usages are
- seq(from, to)
- seq(from, to, by= )
- seq(from, to, length.out= )
- seq(along.with= )
- seq(from)
- seq(length.out= )
The first form generates the sequence from, from+/-1, ..., To (identical To from:to).
The second form generates from, from+by, ..., up To the sequence value less than Or equal To To. Specifying To - from And by Of opposite signs Is an Error. Note that the computed final value can go just beyond To To allow For rounding Error, but Is truncated To To. ('Just beyond’ is by up to 1e-10 times abs(from - to).)
The third generates a sequence Of length.out equally spaced values from from To To. (length.out Is usually abbreviated To length Or len, And seq_len Is much faster.)
The fourth form generates the Integer sequence 1, 2, ..., length(along.With). (along.With Is usually abbreviated To along, And seq_along Is much faster.)
The fifth form generates the sequence 1, 2, ..., length(from) (As If argument along.With had been specified), unless the argument Is numeric Of length 1 When it Is interpreted As 1:from (even for seq(0) for compatibility with S). Using either seq_along Or seq_len Is much preferred (unless strict S compatibility Is essential).
The final form generates the Integer sequence 1, 2, ..., length.out unless length.out = 0, When it generates Integer(0).
Very small sequences (With from - To Of the order Of 10^{-14} times the larger Of the ends) will Return from.
For seq(only), up To two Of from, To And by can be supplied As complex values provided length.out Or along.With Is specified. More generally, the Default method Of seq will handle classed objects With methods For the Math, Ops And Summary group generics.
seq.int, seq_along And seq_len are primitive.
| Name | Type | Description |
|---|---|---|
from | Object | the starting And (maximal) End values Of the sequence. Of length 1 unless just from Is supplied As an unnamed argument. |
[to] | Object | the starting And (maximal) End values Of the sequence. Of length 1 unless just from Is supplied As an unnamed argument. |
by | Double | number: increment of the sequence. |
seq(1, 5);
is equals to
1:5;
seq(1, 5, by = 0.1);
is equals to
1:5 step 0.1;
String(), String, Boolean)System Date and Time
the given number string will not be treated as unix timestamp if the format string has been specific.
| Name | Type | Description |
|---|---|---|
str | String() | this parameter also can accept the unix timestamp. |
format | String | specific the date string parser format, example as |
Returns a character string of the current system date and time.
Object, Environment)Combine Values into a Vector or List
This is a generic function which combines its arguments. The Default method combines its arguments To form a vector. All arguments are coerced To a common type which Is the type Of the returned value, And all attributes except names are removed.
| Name | Type | Description |
|---|---|---|
values | Object | objects to be concatenated. |
env | Environment | - |
NULL or an expression or a vector of an appropriate mode. (With no arguments the value is NULL.)
for the vector literal, use the syntax of [] literal is better:
use c() function
c(1,2,3,4,5,6);
is equals to the vector literal syntax
[1 2 3 4 5 6];
create string vector
c("a","b","c","d");
create logical vector
c(TRUE, TRUE, FALSE);
Conditional Element Selection
ifelse returns a value with the same shape as test which is filled with elements selected from either yes or no depending on whether the element of test is TRUE or FALSE.
If yes or no are too short, their elements are recycled. yes will be evaluated if and only if any element of test is true, and analogously for no.
Missing values In test give missing values In the result.
| Name | Type | Description |
|---|---|---|
test | Object | an object which can be coerced to logical mode. |
yes | Object | return values for true elements of test. |
no | Object | return values for false elements of test. |
A vector of the same length and attributes (including dimensions and "class") as test and data values from the values of yes or no. The mode of the answer will be coerced from logical to accommodate first any values taken from yes and then any values taken from no.
Object, Environment)Dimensions of an Object
Retrieve or set the dimension of an object.
The functions dim and dim<- are internal generic primitive functions. Dim has a method For data.frames, which returns the lengths Of the row.names attribute Of x And Of x (As the numbers Of rows And columns respectively).
| Name | Type | Description |
|---|---|---|
x | Object | an R Object, For example a matrix, array Or data frame. |
For the default method, either NULL or a numeric vector, which is coerced to integer (by truncation).
For an array (and hence in particular, for a matrix) dim retrieves the dim attribute of the object. It is NULL or a vector of mode integer.
The replacement method changes the "dim" attribute (provided the New value Is compatible) And removes any "dimnames" And "names" attributes.
Replicate Elements of Vectors and Lists
rep replicates the values in x. It is a generic function, and the (internal) default method is described here.
| Name | Type | Description |
|---|---|---|
x | Object | a vector (of any mode including a list) or a factor or (for rep only) a POSIXct or POSIXlt or Date object; or an S4 object containing such an object. |
each | Nullable(Of Int32) | non-negative integer. Each element of x is repeated each times. Other inputs will be coerced to an integer or double vector and the first element taken. Treated as 1 if NA or invalid. |
times | Nullable(Of Int32) | an integer-valued vector giving the (non-negative) number of times to repeat each element if of length length(x), or to repeat the whole vector if of length 1. Negative or NA values are an error. A double vector is accepted, other inputs being coerced to an integer or double vector. |
| Name | Type | Description |
|---|---|---|
x | Object | - |
times | Int32 | an integer-valued vector giving the (non-negative) number of times to repeat each element if of length length(x), or to repeat the whole vector if of length 1. Negative or NA values are an error. A double vector is accepted, other inputs being coerced to an integer or double vector. |
env | Environment | - |
| Name | Type | Description |
|---|---|---|
x | Object | - |
length_out | Int32 | non-negative integer. The desired length of the output vector. Other inputs will be coerced to a double vector and the first element taken. Ignored if NA or invalid. |
env | Environment | - |
Combine R Objects by Rows or Columns
Take a sequence of vector, matrix or data-frame arguments and combine by columns or rows, respectively. These are generic functions with methods for other R classes.
| Name | Type | Description |
|---|---|---|
d | dataframe | should be a dataframe object |
row | Object | should be another dataframe object, or a vector for combine a row or a tuple list for combine as a row. |
env | Boolean | - |
safe | Environment | Merge the dataframe safely? |
Combine R Objects by Rows or Columns
Take a sequence of vector, matrix or data-frame arguments and combine by columns or rows, respectively. These are generic functions with methods for other R classes.
| Name | Type | Description |
|---|---|---|
x | list | (generalized) vectors Or matrices. These can be given as named arguments. Other R objects may be coerced as appropriate, Or S4 methods may be used: see sections 'Details’ and ‘Value’. (For the "data.frame" method of cbind these can be further arguments to data.frame such as stringsAsFactors.) |
strict | Boolean | this option affects the column merge speed. When this option is set to TRUE, then cbind function will check the row order at first and then do row re-ordering for column appends. When this option is set to FALSE, then the cbind function will merge the dataframe directly without any row order checking. So you must ensure that the row order is keeps the same when doing non-strict cbind invoke. |
env | Object | - |
dataframe to rows
| Name | Type | Description |
|---|---|---|
x | dataframe | - |
matrix transpose
Given a matrix or data.frame x, t returns the transpose of x.
This is a generic function for which methods can be written. The description here applies to the default and "data.frame" methods.
A data frame Is first coerced To a matrix: see as.matrix. When x Is a vector, it Is treated as a column, i.e., the result Is a 1-row matrix.
| Name | Type | Description |
|---|---|---|
x | dataframe | a matrix Or data frame, typically. |
A matrix, with dim and dimnames constructed appropriately from those of x, and other attributes except names copied across.
Int32)create an empty vector with specific count of null value filled
| Name | Type | Description |
|---|---|---|
size | Int32 | - |
Function to Create a Unit Object
get or set unit to a given vector. This function creates a unit object — a vector of unit values. A unit value is typically just a single numeric value with an associated unit.
Unit objects allow the user to specify locations and dimensions in a large number of different coordinate systems. All drawing occurs relative to a viewport and the units specifies what coordinate system to use within that viewport.
Possible units (coordinate systems) are:
"npc" Normalised Parent Coordinates (the default). The origin of the viewport is (0, 0) and the viewport has a width and height of 1 unit. For example, (0.5, 0.5) is the centre of the viewport.
"cm" Centimetres.
"inches" Inches. 1 in = 2.54 cm.
"mm" Millimetres. 10 mm = 1 cm.
"points" Points. 72.27 pt = 1 in.
"picas" Picas. 1 pc = 12 pt.
"bigpts" Big Points. 72 bp = 1 in.
"dida" Dida. 1157 dd = 1238 pt.
"cicero" Cicero. 1 cc = 12 dd.
"scaledpts" Scaled Points. 65536 sp = 1 pt.
"lines" Lines of text. Locations and dimensions are in terms of multiples of the default text size of the viewport (as specified by the viewport's fontsize and lineheight).
"char" Multiples of nominal font height of the viewport (as specified by the viewport's fontsize).
"native" Locations and dimensions are relative to the viewport's xscale and yscale.
"snpc" Square Normalised Parent Coordinates. Same as Normalised Parent Coordinates, except gives the same answer for horizontal and vertical locations/dimensions. It uses the lesser of npc-width and npc-height. This is useful for making things which are a proportion of the viewport, but have to be square (or have a fixed aspect ratio).
"strwidth" Multiples of the width of the string specified in the data argument. The font size is determined by the pointsize of the viewport.
"strheight" Multiples of the height of the string specified in the data argument. The font size is determined by the pointsize of the viewport.
"grobwidth" Multiples of the width of the grob specified in the data argument.
"grobheight" Multiples of the height of the grob specified in the data argument.
A number of variations are also allowed for the most common units. For example, it is possible to use "in" or "inch" instead of "inches" and "centimetre" or "centimeter" instead of "cm".
A special units value of "null" is also allowed, but only makes sense when used in specifying widths of columns or heights of rows in grid layouts (see grid.layout).
The data argument must be a list when the unit.length() is greater than 1. For example,
unit(rep(1, 3), c("npc", "strwidth", "inches"),
data = list(NULL, "my string", NULL))
It is possible to subset unit objects in the normal way and to perform subassignment (see the examples), but a special function unit.c is provided for combining unit objects.
Certain arithmetic and summary operations are defined for unit objects. In particular, it is possible to add and subtract unit objects (e.g., unit(1, "npc") - unit(1, "inches")), and to specify the minimum or maximum of a list of unit objects (e.g., min(unit(0.5, "npc"), unit(1, "inches"))).
There is a format method for units, which should respond to the arguments for the default format method, e.g., digits to control the number of significant digits printed for numeric values.
The is.unit() function is a convenience for checking whether x inherits from the "unit" class.
| Name | Type | Description |
|---|---|---|
x | Object | A numeric vector. For is.unit, any R object. |
units | Object | A character vector specifying the units for the corresponding numeric values. |
data | Object | This argument is used to supply extra information for special unit types. |
a numeric vector data that tagged with the given specific unit value, or returns the units name of the given vector data if the units parameter has not been assigned.
Object)Change the Print Mode to Invisible
Return a (temporarily) invisible copy of an object.
| Name | Type | Description |
|---|---|---|
x | Object | an arbitrary R object. |
This function can be useful when it is desired to have functions return values which can be assigned, but which do not print when they are not assigned.
Object)A function to make the numeric value negative
| Name | Type | Description |
|---|---|---|
o | Object | - |
Vector Merging
Add elements to a vector.
for append one tuple list into another tuple list, element value may be overrides if there is duplicated name between the two list. join function could be used for union the element value.
| Name | Type | Description |
|---|---|---|
x | Object | the vector the values are to be appended to. |
values | Object | to be included in the modified vector. |
env | Environment | - |
A vector containing the values in x with the elements of values appended after the specified element of x.
let a = list(a = 1, b = 2); let b = list(a = 333, c = 5);
str(append(a,b));
tuple key a in list a has been overrided by the
tuple key a from the list b
List of 3
$ a : int 333
$ b : int 2
$ c : int 5
str(join(a, b));
tuple value of a will be union in join function
List of 3
$ a : int [1:2] 1 333
$ b : int 2
$ c : int 5
implements append via the add method
| Name | Type | Description |
|---|---|---|
env | Environment | - |
x | Object | - |
values | Object | - |
Object, Environment)Data Frames
The function data.frame() creates data frames, tightly coupled collections of variables which share many of the properties of matrices and of lists, used as the fundamental data structure by most of R's modeling software.
| Name | Type | Description |
|---|---|---|
columns | Object | these arguments are of either the form value or |
env | Environment | - |
A data frame, a matrix-like structure whose columns may be of differing types (numeric, logical, factor and character and so on).
How the names Of the data frame are created Is complex, And the rest Of this paragraph Is only the basic story. If the arguments are all named And simple objects (Not lists, matrices Of data frames) Then the argument names give the column names. For an unnamed simple argument, a deparsed version Of the argument Is used As the name (With an enclosing I(...) removed). For a named matrix/list/dataframe argument With more than one named column, the names Of the columns are the name Of the argument followed by a dot And the column name inside the argument: If the argument Is unnamed, the argument's column names are used. For a named or unnamed matrix/list/data frame argument that contains a single column, the column name in the result is the column name in the argument. Finally, the names are adjusted to be unique and syntactically valid unless check.names = FALSE.
Object, Environment)Utils function for check for dataframe object construction
| Name | Type | Description |
|---|---|---|
columns | Object | - |
env | Environment | - |
false means the data has some column fields that do not matched with others to create a valid dataframe object
Object, Environment)The Number of Rows/Columns of an Array
nrow and ncol return the number of rows or columns present in x.
| Name | Type | Description |
|---|---|---|
x | Object | a vector, array, data frame, or NULL. |
env | Environment | - |
an integer of length 1 or NULL, the latter only for ncol and nrow.
Object, Environment)The Number of Rows/Columns of an Array
nrow and ncol return the number of rows or columns present in x.
| Name | Type | Description |
|---|---|---|
x | Object | a vector, array, data frame, or NULL. |
env | Environment | - |
an integer of length 1 or NULL, the latter only for ncol and nrow.
Object, Environment)Lists – Generic and Dotted Pairs
Functions to construct, coerce and check for both kinds of R# lists.
Almost all lists in R internally are Generic Vectors, whereas traditional dotted pair lists (as in LISP) remain available but rarely seen by users (except as formals of functions).
The arguments to list or pairlist are of the form value or tag = value. The functions return a list or dotted pair list composed of its arguments with each value either tagged or untagged, depending on how the argument was specified.
alist handles its arguments as if they described function arguments. So the values are not evaluated, and tagged arguments with no value are allowed whereas list simply ignores them. alist is most often used in conjunction with formals.
as.list attempts to coerce its argument to a list. For functions, this returns the concatenation of the list of formal arguments and the function body. For expressions, the list of constituent elements is returned. as.list is generic, and as the default method calls as.vector(mode = "list") for a non-list, methods for as.vector may be invoked. as.list turns a factor into a list of one-element factors, keeping names. Other attributes may be dropped unless the argument already is a list or expression. (This is inconsistent with functions such as as.character which always drop attributes, and is for efficiency since lists can be expensive to copy.)
is.list returns TRUE if and only if its argument is a list or a pairlist of length > 0. is.pairlist returns TRUE if and only if the argument is a pairlist (or NULL which is a pairlist, see below).
The "environment" method for as.list copies the name-value pairs (for names not beginning with a dot) from an environment to a named list. The user can request that all named objects are copied. Unless sorted = TRUE, the list is in no particular order (the order depends on the order of creation of objects and whether the environment is hashed). No enclosing environments are searched. (Objects copied are duplicated so this can be an expensive operation.) Note that there is an inverse operation, the as.environment() method for list objects.
An empty pairlist, pairlist() is the same as NULL. This is different from list(): some but not all operations will promote an empty pairlist to an empty list.
as.pairlist is implemented as as.vector(x, "pairlist"), and hence will dispatch methods for the generic function as.vector. Lists are copied element-by-element into a pairlist and the names of the list used as tags for the pairlist: the return value for other types of argument is undocumented.
list, is.list and is.pairlist are primitive functions.
| Name | Type | Description |
|---|---|---|
slots | Object | objects, possibly named. |
envir | Environment | - |
Object Summaries
summary is a generic function used to produce result summaries of the results of various model fitting functions. The function invokes particular methods which depend on the class of the first argument.
| Name | Type | Description |
|---|---|---|
object | Object | an object for which a summary is desired. |
Object)This function returns a logical value to determine that the given object is empty or not?
| Name | Type | Description |
|---|---|---|
x | Object | an object for which test for empty is desired. |
The Null Object
NULL represents the null object in R: it is a reserved word. NULL is often returned by expressions and functions whose value is undefined.
is.null is a primitive function.
NULL can be indexed (see Extract) in just about any syntactically legal way: whether it makes sense or not, the result is always NULL. Objects with value NULL can be changed by replacement operators and will be coerced to the type of the right-hand side.
NULL Is also used as the empty pairlist: see the examples. Because pairlists are often promoted To lists, you may encounter NULL being promoted To an empty list.
Objects with value NULL cannot have attributes as there Is only one null object attempts to assign them are either an error (attr) Or promote the object to an empty list with attribute(s) (attributes And structure).
| Name | Type | Description |
|---|---|---|
x | Object | an object to be tested or coerced. |
els | Boolean | does function test for the elements inside x, not the given object x? |
is.null returns TRUE if its argument's value is NULL and FALSE otherwise.
Object)Coerce to a Data Frame
Functions to check if an object is a data frame, or coerce it if possible.
| Name | Type | Description |
|---|---|---|
x | Object | any R object. |
is.data.frame returns TRUE if its argument is a data frame (that is, has "data.frame" amongst its classes) and FALSE otherwise.
Object)Lists – Generic and Dotted Pairs
Functions to construct, coerce and check for both kinds of R lists.
| Name | Type | Description |
|---|---|---|
x | Object | object to be coerced or tested. |
is.list returns TRUE if and only if its argument is a list or a pairlist of length > 0. is.pairlist returns TRUE if and only if the argument is a pairlist or NULL (see below).
Object)Is an Object of Type (Primitive) Function?
Checks whether its argument is a (primitive) function.
is.primitive(x) tests if x is a primitive function, i.e, if typeof(x) is either "builtin" or "special".
| Name | Type | Description |
|---|---|---|
x | Object | an R object. |
TRUE if x is a (primitive) function, and FALSE otherwise.
Object, Object)‘is.vector’ returns ‘TRUE’ if ‘x’ is a vector of the specified mode having no attributes other than names. It returns 'FALSE’ otherwise.
The atomic modes are ‘"logical"’, ‘"integer"’, ‘"numeric"’ (synonym '"double"’), ‘"complex"’, ‘"character"’ and ‘"raw"’.
If 'mode = "any"’, ‘is.vector’ may return ‘TRUE’ for the atomic modes, 'list’ and ‘expression’. For any ‘mode’, it will return 'FALSE’ if ‘x’ has any attributes except names. (This is incompatible with S.) On the other hand, 'as.vector’ removes all attributes including names For results Of atomic mode (but Not those of mode '"list"’ nor ‘"expression"’).
Note that factors are not vectors; 'is.vector’ returns ‘FALSE’ And 'as.vector’ converts a factor to a character vector for ‘mode = "any"'.
| Name | Type | Description |
|---|---|---|
x | Object | an R object. |
mode | Object | character string naming an atomic mode or ‘"list"’ or '"expression"’ or (except for ‘vector’) ‘"any"’. Currently, 'is.vector()’ allows any type (see ‘typeof’) for ‘mode’, and when mode Is Not '"any"’, ‘is.vector(x, mode)’ is almost the same as 'typeof(x) == mode’. |
Object)Check of the given object is clr array or not
| Name | Type | Description |
|---|---|---|
x | Object | - |
Object)cast any R object collection as a generic type clr array
| Name | Type | Description |
|---|---|---|
x | Object | - |
Object, Environment)‘Not Available’ / Missing Values
NA is a logical constant of length 1 which contains a missing value indicator. NA can be coerced to any other vector type except raw. There are also constants NA_integer_, NA_real_, NA_complex_ and NA_character_ of the other atomic vector types which support missing values: all of these are reserved words in the R language.
The generic Function Is.na indicates which elements are missing. The generic Function Is.na<- sets elements To NA.
| Name | Type | Description |
|---|---|---|
x | Object | an R object to be tested: the default method for is.na and anyNA handle atomic vectors, lists, pairlists, and NULL. |
env | Environment | - |
The default method for is.na applied to an atomic vector returns a logical vector of the same length as its argument x, containing TRUE for those elements marked NA or, for numeric or complex vectors, NaN, and FALSE otherwise. (A complex value is regarded as NA if either its real or imaginary part is NA or NaN.) dim, dimnames and names attributes are copied to the result.
The Default methods also work For lists And pairlists
For Is.na, elementwise the result Is false unless that element Is a length-one atomic vector And the single element of that vector Is regarded as NA Or NaN (note that any Is.na method for the class of the element Is ignored).
anyNA(recursive = FALSE) works the same way as Is.na; anyNA(recursive = TRUE) applies anyNA (with method dispatch) to each element.
The data frame method For Is.na returns a logical matrix With the same dimensions As the data frame, And With dimnames taken from the row And column names Of the data frame.
anyNA(NULL) Is false; Is.na(NULL) Is logical(0) (no longer warning since R version 3.5.0).
Send R Output to a File
sink diverts R output to a connection (and stops such diversions).
sink diverts R output to a connection (and must be used again to finish such a diversion, see below!). If file is a character string, a file connection with that name will be established for the duration of the diversion.
Normal R output (To connection stdout) Is diverted by the Default type = "output". Only prompts And (most) messages Continue To appear On the console. Messages sent To stderr() (including those from message, warning And Stop) can be diverted by sink(type = "message") (see below).
sink() Or sink(file = NULL) ends the last diversion (of the specified type). There Is a stack of diversions for normal output, so output reverts to the previous diversion (if there was one). The stack Is of up to 21 connections (20 diversions).
If file Is a connection it will be opened If necessary (In "wt" mode) And closed once it Is removed from the stack Of diversions.
split = TRUE only splits R output (via Rvprintf) And the default output from writeLines: it does Not split all output that might be sent To stdout().
Sink-ing the messages stream should be done only with great care. For that stream file must be an already open connection, And there Is no stack of connections.
If file Is a character String, the file will be opened Using the current encoding. If you want a different encoding (e.g., To represent strings which have been stored In UTF-8), use a file connection — but some ways To produce R output will already have converted such strings To the current encoding.
| Name | Type | Description |
|---|---|---|
file | String | a writable connection Or a character String naming the file To write To, Or NULL To Stop sink-ing. |
append | Boolean | logical. If TRUE, output will be appended to file; otherwise, it will overwrite the contents of file. |
split | Boolean | logical: if TRUE, output will be sent to the new sink and to the current output stream, like the Unix program |
sink returns NULL.
Object, Environment)sink.number() reports how many diversions are in use.
| Name | Type | Description |
|---|---|---|
type | Object | - |
Object, Int32)Length of an Object
Get or set the length of vectors (including lists) and factors, and of any other R object for which a method has been defined.
| Name | Type | Description |
|---|---|---|
x | Object | an R object. For replacement, a vector or factor. |
newSize | Int32 | a non-negative integer or double (which will be rounded down). |
The default method for length currently returns a non-negative integer of length 1, except for vectors of more than 2^31 - 1 elements, when it returns a double.
For vectors(including lists) And factors the length Is the number of elements. For an environment it Is the number of objects in the environment, And NULL has length 0. For expressions And pairlists (including language objects And dotlists) it Is the length of the pairlist chain. All other objects (including functions) have length one: note that For functions this differs from S.
The replacement form removes all the attributes Of x except its names, which are adjusted (And If necessary extended by "").
Run the external R# script. Read R Code from a File, a Connection or Expressions
causes R to accept its input from the named file or URL or connection or expressions directly. Input is read and parsed from that file until the end of the file is reached, then the parsed expressions are evaluated sequentially in the chosen environment.
| Name | Type | Description |
|---|---|---|
path | String | a connection Or a character String giving the pathname Of the file Or URL To read from. "" indicates the connection |
envir | Object | - |
The value of special last variable or the value returns by the return keyword.
Options Settings
Allow the user to set and examine a variety of global options which affect the way in which R computes and displays its results.
Invoking options() with no arguments returns a list with the current values of the options. Note that not all options listed below are set initially. To access the value of a single option, one should use, e.g., getOption("width") rather than options("width") which is a list of length one.
| Name | Type | Description |
|---|---|---|
x | String | a character string holding an option name. |
default | String | if the specified option is not set in the options list, this value is returned. This facilitates retrieving an option and checking whether it is set and setting it separately if not. |
envir | Environment | - |
For getOption, the current value set for option x, or default (which defaults to NULL) if the option is unset.
Object, Environment)Options Settings
Allow the user to set and examine a variety of global options which affect the way in which R computes and displays its results.
Options used in base R
- add.smooth: typically logical, defaulting to TRUE. Could also be set to an
integer for specifying how many (simulated) smooths should be added. This is currently only used by plot.lm.
- askYesNo: a function (typically set by a front-end) to ask the user binary
response functions in a consistent way, or a vector of strings used by askYesNo to use as default responses for such questions.
browserNLdisabled: logical: whether newline is disabled as a synonym for "n" in the browser.
checkPackageLicense: logical, not set by default. If true, loadNamespace asks a user to accept any non-standard license at first load of the package.
check.bounds: logical, defaulting to FALSE. If true, a warning is produced whenever a vector (atomic or list) is extended, by something like x <- 1:3; x[5] <- 6.
CBoundsCheck: logical, controlling whether .C and .Fortran make copies to check for array over-runs on the atomic vector arguments.
Initially set from value of the environment variable R_C_BOUNDS_CHECK (set to yes to enable).
conflicts.policy: character string or list controlling handling of conflicts found in calls to library or require. See library for details.
continue: a non-empty string setting the prompt used for lines which continue over one line.
defaultPackages: the packages that are attached by default when R starts up. Initially set from value of the environment variable R_DEFAULT_PACKAGES, or if that is unset to c("datasets", "utils", "grDevices", "graphics", "stats", "methods"). (Set R_DEFAULT_PACKAGES to NULL or a comma-separated list of package names.) It will not work to set this in a ‘.Rprofile’ file, as its value is consulted before that file is read.
deparse.cutoff: integer value controlling the printing of language constructs which are deparsed. Default 60.
deparse.max.lines: controls the number of lines used when deparsing in traceback, browser, and upon entry to a function whose debugging flag is set. Initially unset, and only used if set to a positive integer.
digits: controls the number of significant (see signif) digits to print when printing numeric values. It is a suggestion only. Valid values are 1...22 with default
- See the note in print.default about values greater than 15.
digits.secs: controls the maximum number of digits to print when formatting time values in seconds. Valid values are 0...6 with default 0. See strftime.
download.file.extra: Extra command-line argument(s) for non-default methods: see download.file.
download.file.method: Method to be used for download.file. Currently download methods "internal", "wininet" (Windows only), "libcurl", "wget" and "curl" are available. If not set, method = "auto" is chosen: see download.file.
echo: logical. Only used in non-interactive mode, when it controls whether input is echoed. Command-line option --slave sets this to FALSE, but otherwise it starts the session as TRUE.
encoding: The name of an encoding, default "native.enc". See connections.
error: either a function or an expression governing the handling of non-catastrophic errors such as those generated by stop as well as by signals and internally detected errors. If the option is a function, a call to that function, with no arguments, is generated as the expression. By default the option is not set: see stop for the behaviour in that case. The functions dump.frames and recover provide alternatives that allow post-mortem debugging. Note that these need to specified as e.g. options(error = utils::recover) in startup files such as ‘.Rprofile’.
expressions: sets a limit on the number of nested expressions that will be evaluated. Valid values are 25...500000 with default 5000. If you increase it, you may also want to start R with a larger protection stack; see --max-ppsize in Memory. Note too that you may cause a segfault from overflow of the C stack, and on OSes where it is possible you may want to increase that. Once the limit is reached an error is thrown. The current number under evaluation can be found by calling Cstack_info.
interrupt: a function taking no arguments to be called on a user interrupt if the interrupt condition is not otherwise handled.
keep.parse.data: When internally storing source code (keep.source is TRUE), also store parse data. Parse data can then be retrieved with getParseData() and used e.g. for spell checking of string constants or syntax highlighting. The value has effect only when internally storing source code (see keep.source). The default is TRUE.
keep.parse.data.pkgs: As for keep.parse.data, used only when packages are installed. Defaults to FALSE unless the environment variable R_KEEP_PKG_PARSE_DATA is set to yes. The space overhead of parse data can be substantial even after compression and it causes performance overhead when loading packages.
keep.source: When TRUE, the source code for functions (newly defined or loaded) is stored internally allowing comments to be kept in the right places. Retrieve the source by printing or using deparse(fn, control = "useSource").
The default is interactive(), i.e., TRUE for interactive use.
keep.source.pkgs: As for keep.source, used only when packages are installed. Defaults to FALSE unless the environment variable R_KEEP_PKG_SOURCE is set to yes.
matprod: a string selecting the implementation of the matrix products %*%, crossprod, and tcrossprod for double and complex vectors:
"internal" uses an unoptimized 3-loop algorithm which correctly propagates NaN and Inf values and is consistent in precision with other summation algorithms inside R like sum or colSums (which now means that it uses a long double accumulator for summation if available and enabled, see capabilities).
"default" uses BLAS to speed up computation, but to ensure correct propagation of NaN and Inf values it uses an unoptimized 3-loop algorithm for inputs that may contain NaN or Inf values. When deemed beneficial for performance, "default" may call the 3-loop algorithm unconditionally, i.e., without checking the input for NaN/Inf values. The 3-loop algorithm uses (only) a double accumulator for summation, which is consistent with the reference BLAS implementation.
"blas" uses BLAS unconditionally without any checks and should be used with extreme caution. BLAS libraries do not propagate NaN or Inf values correctly and for inputs with NaN/Inf values the results may be undefined.
"default.simd" is experimental and will likely be removed in future versions of R. It provides the same behavior as "default", but the check whether the input contains NaN/Inf values is faster on some SIMD hardware. On older systems it will run correctly, but may be much slower than "default".
max.print: integer, defaulting to 99999. print or show methods can make use of this option, to limit the amount of information that is printed, to something in the order of (and typically slightly less than) max.print entries.
OutDec: character string containing a single character. The preferred character to be used as the decimal point in output conversions, that is in printing, plotting, format and as.character but not when deparsing nor by sprintf nor formatC (which are sometimes used prior to printing.)
pager: the command used for displaying text files by file.show, details depending on the platform:
On a unix-alike defaults to ‘R_HOME/bin/pager’, which is a shell script running the command-line specified by the environment variable PAGER whose default is set at configuration, usually to less.
On Windows defaults to "internal", which uses a pager similar to the GUI console. Another possibility is "console" to use the console itself.
Can be a character string or an R function, in which case it needs to accept the arguments (files, header, title, delete.file) corresponding to the first four arguments of file.show.
papersize: the default paper format used by postscript; set by environment variable R_PAPERSIZE when R is started: if that is unset or invalid it defaults platform dependently
on a unix-alike to a value derived from the locale category LC_PAPER, or if that is unavailable to a default set when R was built.
on Windows to "a4", or "letter" in US and Canadian locales.
PCRE_limit_recursion: Logical: should grep(perl = TRUE) and similar limit the maximal recursion allowed when matching? PCRE can be built not to use a recursion stack (see pcre_config, but it is by default with a recursion limit of 10000000 which potentially needs a very large C stack: see the discussion at http://www.pcre.org/original/doc/html/pcrestack.html. If true, the limit is reduced using R's estimate of the C stack size available (if known), otherwise 10000. If NA, the limit is imposed only if any input string has 1000 or more bytes.
PCRE_study: Logical or integer: should grep(perl = TRUE) and similar ‘study’ the patterns? Either logical or a numerical threshold for the minimum number of strings to be matched for the pattern to be studied (the default is 10)). Missing values and negative numbers are treated as false.
PCRE_use_JIT: Logical: should grep(perl = TRUE), strsplit(perl = TRUE) and similar make use of PCRE's Just-In-Time compiler for studied patterns, if available? Missing values are treated as false.
pdfviewer: default PDF viewer. The default is set from the environment variable R_PDFVIEWER, the default value of which
on a unix-alike is set when R is configured, and
on Windows is the full path to open.exe, a utility supplied with R.
printcmd: the command used by postscript for printing; set by environment variable R_PRINTCMD when R is started. This should be a command that expects either input to be piped to ‘stdin’ or to be given a single filename argument. Usually set to "lpr" on a Unix-alike.
prompt: a non-empty string to be used for R's prompt; should usually end in a blank (" ").
rl_word_breaks: (Unix only:) Used for the readline-based terminal interface. Default value " \t\n\"\\'`><=%;,|&{()}".
This is the set of characters use to break the input line into tokens for object- and file-name completion. Those who do not use spaces around operators may prefer " \t\n\"\\'`><=+-*%;,|&{()}"
save.defaults, save.image.defaults: see save.
scipen: integer. A penalty to be applied when deciding to print numeric values in fixed or exponential notation. Positive values bias towards fixed and negative towards scientific notation: fixed notation will be preferred unless it is more than scipen digits wider.
setWidthOnResize: a logical. If set and TRUE, R run in a terminal using a recent readline library will set the width option when the terminal is resized.
showWarnCalls, showErrorCalls: a logical. Should warning and error messages show a summary of the call stack? By default error calls are shown in non-interactive sessions.
showNCalls: integer. Controls how long the sequence of calls must be (in bytes) before ellipses are used. Defaults to 40 and should be at least 30 and no more than 500.
show.error.locations: Should source locations of errors be printed? If set to TRUE or "top", the source location that is highest on the stack (the most recent call) will be printed. "bottom" will print the location of the earliest call found on the stack.
Integer values can select other entries. The value 0 corresponds to "top" and positive values count down the stack from there. The value -1 corresponds to "bottom" and negative values count up from there.
show.error.messages: a logical. Should error messages be printed? Intended for use with try or a user-installed error handler.
stringsAsFactors: The default setting for arguments of data.frame and read.table.
texi2dvi: used by functions texi2dvi and texi2pdf in package tools.
unix-alike only: Set at startup from the environment variable R_TEXI2DVICMD, which defaults first to the value of environment variable TEXI2DVI, and then to a value set when R was installed (the full path to a texi2dvi script if one was found). If necessary, that environment variable can be set to "emulation".
timeout: integer. The timeout for some Internet operations, in seconds. Default 60 seconds. See download.file and connections.
topLevelEnvironment: see topenv and sys.source.
url.method: character string: the default method for url. Normally unset, which is equivalent to "default", which is "internal" except on Windows.
useFancyQuotes: controls the use of directional quotes in sQuote, dQuote and in rendering text help (see Rd2txt in package tools). Can be TRUE, FALSE, "TeX" or "UTF-8".
verbose: logical. Should R report extra information on progress? Set to TRUE by the command-line option --verbose.
warn: sets the handling of warning messages. If warn is negative all warnings are ignored. If warn is zero (the default) warnings are stored until the top–level function returns. If 10 or fewer warnings were signalled they will be printed otherwise a message saying how many were signalled. An object called last.warning is created and can be printed through the function warnings. If warn is one, warnings are printed as they occur. If warn is two (or larger, coercible to integer), all warnings are turned into errors.
warnPartialMatchArgs: logical. If true, warns if partial matching is used in argument matching.
warnPartialMatchAttr: logical. If true, warns if partial matching is used in extracting attributes via attr.
warnPartialMatchDollar: logical. If true, warns if partial matching is used for extraction by $.
warning.expression: an R code expression to be called if a warning is generated, replacing the standard message. If non-null it is called irrespective of the value of option warn.
warning.length: sets the truncation limit for error and warning messages. A non-negative integer, with allowed values 100...8170, default 1000.
nwarnings: the limit for the number of warnings kept when warn = 0, default 50. This will discard messages if called whilst they are being collected. If you increase this limit, be aware that the current implementation pre-allocates the equivalent of a named list for them, i.e., do not increase it to more than say a million.
width: controls the maximum number of columns on a line used in printing vectors, matrices and arrays, and when filling by cat.
Columns are normally the same as characters except in East Asian languages.
You may want to change this if you re-size the window that R is running in. Valid values are 10...10000 with default normally 80. (The limits on valid values are in file ‘Print.h’ and can be changed by re-compiling R.) Some R consoles automatically change the value when they are resized.
See the examples on Startup for one way to set this automatically from the terminal width when R is started.
The ‘factory-fresh’ default settings of some of these options are
| options | default value | |
|---|---|---|
| add.smooth | TRUE | |
| check.bounds | FALSE | |
| continue | "+ " | |
| digits | 7 | |
| echo | TRUE | |
| encoding | "native.enc" | |
| error | NULL | |
| expressions | 5000 | |
| keep.source | interactive() | |
| keep.source.pkgs | FALSE | |
| max.print | 99999 | |
| OutDec | "." | |
| prompt | "> " | |
| scipen | 0 | |
| show.error.messages | TRUE | |
| timeout | 60 | |
| verbose | FALSE | |
| warn | 0 | |
| warning.length | 1000 | |
| width | 80 |
Others are set from environment variables or are platform-dependent.
| Name | Type | Description |
|---|---|---|
opts | Object | any options can be defined, using name = value. However, only the ones below are used in base R. Options can also be passed by giving a Single unnamed argument which Is a named list. |
envir | Environment | - |
For options(), a list of all set options sorted by name. For options(name), a list of length one containing the set value, or NULL if it is unset. For uses setting one or more options, a list with the previous values of the options changed (returned invisibly).
save the options configuration data to file
| Name | Type | Description |
|---|---|---|
env | Environment | - |
The Names of an Object
Functions to get or set the names of an object.
| Name | Type | Description |
|---|---|---|
object | Object | an R object. |
namelist | Object | a character vector of up to the same length as |
envir | Environment | - |
For names, NULL or a character vector of the same length as x. (NULL is given if the object has no names, including for objects of types which cannot have names.) For an environment, the length is the number of objects in the environment but the order of the names is arbitrary.
For names<-, the updated object. (Note that the value of names(x) <- value Is that of the assignment, value, Not the return value from the left-hand side.)
x = list(1,2,3,4,5,6) print(names(x));
NULL
names(x) = ["a", "b", "c", "d", "e", "f"]; print(names(x));
[1] "a" "b" "c" "d" "e" "f"
Object, Boolean, Boolean)Make Syntactically Valid Names
Make syntactically valid names out of character vectors.
A syntactically valid name consists of letters, numbers and the dot or underline characters and starts with a letter or the dot not followed by a number. Names such as ".2way" are not valid, and neither are the reserved words.
The definition Of a letter depends On the current locale, but only ASCII digits are considered To be digits.
The character "X" Is prepended If necessary. All invalid characters are translated To ".". A missing value Is translated To "NA". Names which match R keywords have a dot appended To them. Duplicated values are altered by make.unique.
| Name | Type | Description |
|---|---|---|
names | Object | character vector To be coerced To syntactically valid names. This Is coerced To character If necessary. |
unique | Boolean | logical; if TRUE, the resulting elements are unique. This may be desired for, e.g., column names. |
allow_ | Boolean | logical. For compatibility with R prior to 1.9.0. |
A character vector of same length as names with each changed to a syntactically valid name, in the current locale's encoding.
Object, String)Make Character Strings Unique
Makes the elements of a character vector unique by appending sequence numbers to duplicates.
The algorithm used by make.unique has the property that make.unique(c(A, B)) == make.unique(c(make.unique(A), B)). In other words, you can append one string at a time to a vector, making it unique each time, And get the same result as applying make.unique to all of the strings at once. If character vector A Is already unique, Then make.unique(c(A, B)) preserves A.
| Name | Type | Description |
|---|---|---|
names | Object | a character vector. |
sep | String | a character string used to separate a duplicate name from its sequence number. |
A character vector of same length as names with duplicates changed, in the current locale's encoding.
make.unique(c("a", "a", "a")) make.unique(c(make.unique(c("a", "a")), "a"))
make.unique(c("a", "a", "a.2", "a")) make.unique(c(make.unique(c("a", "a")), "a.2", "a"))
Now show a bit where this Is used :
trace(make.unique)
Applied in data.frame() constructions:
(d1 <- data.frame(x = 1, x = 2, x = 3)) # direct d2 <- data.frame(data.frame(x = 1, x = 2), x = 3) # pairwise stopifnot(identical(d1, d2), colnames(d1) == c("x", "x.1", "x.2")) untrace(make.unique)
Row and Column Names
Retrieve or set the row or column names of a matrix-like object.
The extractor functions try to do something sensible for any matrix-like object x. If the object has dimnames the first component is used as the row names, and the second component (if any) is used for the column names. For a data frame, rownames and colnames eventually call row.names and names respectively, but the latter are preferred.
If do.NULL Is FALSE, a character vector (of length NROW(x) Or NCOL(x)) Is returned in any case, prepending prefix to simple numbers, if there are no dimnames Or the corresponding component of the dimnames Is NULL.
The replacement methods For arrays/matrices coerce vector And factor values Of value To character, but Do Not dispatch methods For As.character.
For a data frame, value for rownames should be a character vector of non-duplicated And non-missing names (this Is enforced), And for colnames a character vector of (preferably) unique syntactically-valid names. In both cases, value will be coerced by as.character, And setting colnames will convert the row names To character.
| Name | Type | Description |
|---|---|---|
[object] | Object | a matrix-like R object, with at least two dimensions for colnames. |
namelist | Object | a valid value for that component of |
envir | Environment | - |
Row and Column Names
Retrieve or set the row or column names of a matrix-like object.
The extractor functions try to do something sensible for any matrix-like object x. If the object has dimnames the first component is used as the row names, and the second component (if any) is used for the column names. For a data frame, rownames and colnames eventually call row.names and names respectively, but the latter are preferred.
If do.NULL Is FALSE, a character vector (of length NROW(x) Or NCOL(x)) Is returned in any case, prepending prefix to simple numbers, if there are no dimnames Or the corresponding component of the dimnames Is NULL.
The replacement methods For arrays/matrices coerce vector And factor values Of value To character, but Do Not dispatch methods For As.character.
For a data frame, value for rownames should be a character vector of non-duplicated And non-missing names (this Is enforced), And for colnames a character vector of (preferably) unique syntactically-valid names. In both cases, value will be coerced by as.character, And setting colnames will convert the row names To character.
| Name | Type | Description |
|---|---|---|
x | Object | a matrix-like R object, with at least two dimensions for colnames. |
namelist | Object | a valid value for that component of |
envir | Environment | - |
Object, Environment)Stop Function Execution
stop stops execution of the current expression and executes an error action.
The error action is controlled by error handlers established within the executing code and by the current default error handler set by options(error=). The error is first signaled as if using signalCondition(). If there are no handlers or if all handlers return, then the error message is printed (if options("show.error.messages") is true) and the default error handler is used. The default behaviour (the NULL error-handler) in interactive use is to return to the top level prompt or the top level browser, and in non-interactive use to (effectively) call q("no", status = 1, runLast = FALSE). The default handler stores the error message in a buffer; it can be retrieved by geterrmessage(). It also stores a trace of the call stack that can be retrieved by traceback().
Errors will be truncated To getOption("warning.length") characters, Default 1000.
If a condition Object Is supplied it should be the only argument, And further arguments will be ignored, With a warning.
| Name | Type | Description |
|---|---|---|
message | Object |
|
envir | Environment | - |
Warning Messages
Generates a warning message that corresponds to its argument(s) and (optionally) the expression or function from which it was called.
Create a new wraning message in current environment frame
| Name | Type | Description |
|---|---|---|
message | Object | zero Or more objects which can be coerced to character (And which are pasted together with no separator) Or a single condition object. |
immediate_ | Boolean | logical, indicating if the warning should be output immediately, even if getOption("warn") <= 0. NB: this is not respected for condition objects. |
envir | Environment | - |
The warning message as character string, invisibly.
Boolean, GlobalEnvironment)Print Warning Messages
warnings and its print method print the variable last.warning in a pleasing form.
| Name | Type | Description |
|---|---|---|
all | Boolean | - |
env | GlobalEnvironment | - |
String, Object)Quote Text
Single or double quote text by combining with appropriate single or double left and right quotation marks.
| Name | Type | Description |
|---|---|---|
x | String | an R object, to be coerced to a character vector. |
q | Object | the kind of quotes to be used, see ‘Details’. |
String, Object)Quote Text
Single or double quote text by combining with appropriate single or double left and right quotation marks.
| Name | Type | Description |
|---|---|---|
x | String | an R object, to be coerced to a character vector. |
q | Object | the kind of quotes to be used, see ‘Details’. |
Diagnostic Messages
Generate a diagnostic message from its arguments.
| Name | Type | Description |
|---|---|---|
x | list | zero or more objects which can be coerced to character (and which are pasted together with no separator) or (for message only) a single condition object. |
Concatenate and Print
Outputs the objects, concatenating the representations. cat performs much less conversion than print.
| Name | Type | Description |
|---|---|---|
x | Object | R objects (see ‘Details’ for the types of objects allowed). |
file | Object | A connection, or a character string naming the file to print to. If "" (the default), cat prints to the standard output connection, the console unless redirected by |
sep | String | a character vector of strings to append after each element. |
Compactly Display the Structure of an Arbitrary R# Object
Compactly display the internal structure of an R object, a diagnostic function and an alternative to summary (and to some extent, 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 for (non-primitive) function objects.
strOptions() Is a convenience function for setting options(str = .), see the examples.
| Name | Type | Description |
|---|---|---|
object | Object | any R object about which you want to have some information. |
list_len | Int32 | numeric; maximum number of list elements to display within a level. |
Print Values
print prints its argument and returns it invisibly (via invisible(x)). It is a generic function which means that new printing methods can be easily added for new classes.
| Name | Type | Description |
|---|---|---|
x | Object | an object used to select a method. |
args | list | quotelogical, indicating whether Or Not strings (characters) should be printed with surrounding quotes. colorcharacter, set the color of this message to print on the console by using the asni escape sequence. this option only supports on the string vector message max.printinteger, the max number of elements to print. this parameter value will overrides the max.print options from the options function. syntax.highlightlogical, indicates that show the R# runtime expression object code with syntax highlights? default is TRUE. max.widthinteger, the max character number for display in a cell when apply for print of the dataframe contents. default config is max 200 character in a cell. if the cell string char length is greater then this threshold then the display string will be truncated. selectcharacter, a character vector for select the columns for display when do print of a dataframe object. |
env | Environment | - |
String(), Object, Object, Object, Boolean, Nullable(Of Int32))The function factor is used to encode a vector as a factor (the terms ‘category’ and ‘enumerated type’ are also used for factors). If argument ordered is TRUE, the factor levels are assumed to be ordered. For compatibility with S there is also a function ordered.
The type of the vector x is not restricted; it only must have an as.character method and be sortable (by order). Ordered factors differ from factors only In their Class, but methods And the model-fitting functions treat the two classes quite differently. The encoding Of the vector happens As follows. First all the values In exclude are removed from levels. If x[i] equals levels[j], Then the i-th element Of the result Is j. If no match Is found For x[i] In levels (which will happen For excluded values) Then the i-th element Of the result Is Set To NA. Normally the 'levels’ used as an attribute of the result are the reduced set of levels after removing those in exclude, but this can be altered by supplying labels. This should either be a set of new labels for the levels, or a character string, in which case the levels are that character string with a sequence number appended. factor(x, exclude = NULL) applied to a factor without NAs Is a no-operation unless there are unused levels in that case, a factor with the reduced level set Is returned. If exclude Is used, since R version 3.4.0, excluding non-existing character levels Is equivalent to excluding nothing, And when exclude Is a character vector, that Is applied to the levels of x. Alternatively, exclude can be factor with the same level set as x And will exclude the levels present in exclude. The codes Of a factor may contain NA. For a numeric x, Set exclude = NULL To make NA an extra level (prints As <NA>); by Default, this Is the last level. If NA Is a level, the way To Set a code To be missing (As opposed To the code Of the missing level) Is To use Is.na On the left-hand-side Of an assignment (As In Is.na(f)[i] <- True; indexing inside Is.na does Not work). Under those circumstances missing values are currently printed As <NA>, i.e., identical To entries Of level NA. Is.factor Is generic: you can write methods To handle specific classes Of objects, see InternalMethods. Where levels Is Not supplied, unique Is called. Since factors typically have quite a small number Of levels, For large vectors x it Is helpful To supply nmax As an upper bound On the number Of unique values. When using c to combine a (possibly ordered) factor with other objects, if all objects are (possibly ordered) factors, the result will be a factor with levels the union of the level sets of the elements, in the order the levels occur in the level sets of the elements (which means that if all the elements have the same level set, that Is the level set of the result), equivalent to how unlist operates on a list of factor objects.
| Name | Type | Description |
|---|---|---|
x | String() | a vector of data, usually taking a small number of distinct values. |
levels | Object | an optional vector of the unique values (as character strings) that x might have taken. The default is the unique set of values taken by as.character(x), sorted into increasing order of x. Note that this set can be specified as smaller than sort(unique(x)). |
labels | Object | either an optional character vector of labels for the levels (in the same order as levels after removing those in exclude), or a character string of length 1. Duplicated values in labels can be used to map different values of x to the same factor level. |
exclude | Object | a vector Of values To be excluded When forming the Set Of levels. This may be factor With the same level Set As x Or should be a character. |
ordered | Boolean | logical flag To determine If the levels should be regarded As ordered (In the order given). |
nmax | Nullable(Of Int32) | an upper bound on the number of levels; see ‘Details’. |
a vector with elements data encoded as factor. factor returns an object of class "factor" which has a set of integer codes the length of x with a "levels" attribute of mode character and unique (!anyDuplicated(.)) entries. If argument ordered is true (or ordered() is used) the result has class c("ordered", "factor"). Undocumentedly for a long time, factor(x) loses all attributes(x) but "names", and resets "levels" and "class".
Applying factor to an ordered or unordered factor returns a factor (of the same type) with just the levels which occur: see also [.factor for a more transparent way to achieve this.
| Name | Type | Description |
|---|---|---|
x | Object |
|
dispose | Object | the dispose handler, for type of parameter x is |
env | Environment | - |
Loading and Unloading Name Spaces
Functions to load and unload name spaces.
requireNamespace is a wrapper for loadNamespace analogous to require that returns a logical value.
| Name | Type | Description |
|---|---|---|
package | String | String naming the package/name space To load. |
quietly | Boolean | - |
env | Environment | - |
requireNamespace returns TRUE if it succeeds or FALSE.
Loading/Attaching and Listing of Packages
library and require load and attach add-on packages.
library(package) and require(package) both load the namespace of the package with name package and attach it on the search list. require is designed for use inside other functions; it returns FALSE and gives a warning (rather than an error as library() does by default) if the package does not exist. Both functions check and update the list of currently attached packages and do not reload a namespace which is already loaded. (If you want to reload such a package, call detach(unload = TRUE) or unloadNamespace first.) If you want to load a package without attaching it on the search list, see requireNamespace.
To suppress messages during the loading of packages use suppressPackageStartupMessages: this will suppress all messages from R itself but Not necessarily all those from package authors.
If library Is called With no package Or help argument, it lists all available packages In the libraries specified by Lib.loc, And returns the corresponding information In an Object Of Class "libraryIQR". (The Structure Of this Class may change In future versions.) Use .packages(all = True) To obtain just the names Of all available packages, And installed.packages() For even more information.
library(help = somename) computes basic information about the package somename, And returns this in an object of class "packageInfo". (The structure of this class may change in future versions.) When used with the default value (NULL) for lib.loc, the attached packages are searched before the libraries.
| Name | Type | Description |
|---|---|---|
package | String | the name Of a package, given As a name Or literal character String, Or a character String, depending On whether character.only Is False (Default) Or True. |
env | Boolean | - |
Normally library returns (invisibly) the list of attached packages, but TRUE or FALSE if logical.return is TRUE. When called as library() it returns an object of class "libraryIQR", and for library(help=), one of class "packageInfo".
require returns(invisibly) a logical indicating whether the required package Is available.
attact a given zip archive file as package
| Name | Type | Description |
|---|---|---|
R | RInterpreter | - |
zip | String | the file path to the zip package |
Function Exit Code
on.exit records the expression given as its argument as needing to be executed when the current function exits (either naturally or as the result of an error). This is useful for resetting graphical parameters or performing other cleanup actions.
If no expression Is provided, i.e., the Call Is on.exit(), Then the current on.exit code Is removed.
The expr argument passed to on.exit is recorded without evaluation. If it is not subsequently removed/replaced by another on.exit call in the same function, it is evaluated in the evaluation frame of the function when it exits (including during standard error handling). Thus any functions or variables in the expression will be looked for in the function and its environment at the time of exit: to capture the current value in expr use substitute or similar.
If multiple On.Exit expressions are Set Using add = True Then all expressions will be run even If one signals an Error.
This Is a 'special’ primitive function: it only evaluates the arguments add and after.
| Name | Type | Description |
|---|---|---|
expr | Expression | an expression to be executed. |
add | Boolean | if TRUE, add expr to be executed after any previously set expressions (or before if after is FALSE); otherwise (the default) expr will overwrite any previously set expressions. |
after | Boolean | if add is TRUE and after is FALSE, then expr will be added on top of the expressions that were already registered. The resulting last in first out order is useful for freeing or closing resources in reverse order. |
Invisible NULL.
Reload Saved Datasets
Reload datasets written with the function save.
load can load R objects saved in the current or any earlier format. It can read a compressed file (see save) directly from a file or from a suitable connection (including a call to url).
A Not-open connection will be opened in mode "rb" And closed after use. Any connection other than a gzfile Or gzcon connection will be wrapped in gzcon to allow compressed saves to be handled: note that this leaves the connection In an altered state (In particular, binary-only), And that it needs To be closed explicitly (it will Not be garbage-collected).
Only R objects saved In the current format (used since R 1.4.0) can be read from a connection. If no input Is available On a connection a warning will be given, but any input Not In the current format will result In a Error.
Loading from an earlier version will give a warning about the 'magic number’: magic numbers 1971:1977 are from R < 0.99.0, and RD[ABX]1 from R 0.99.0 to R 1.3.1. These are all obsolete, and you are strongly recommended to re-save such files in a current format.
The verbose argument Is mainly intended For debugging. If it Is True, Then As objects from the file are loaded, their names will be printed To the console. If verbose Is Set To an Integer value greater than one, additional names corresponding To attributes And other parts Of individual objects will also be printed. Larger values will print names To a greater depth.
Objects can be saved With references To namespaces, usually As part Of the environment Of a Function Or formula. Such objects can be loaded even If the Namespace Is Not available: it Is replaced by a reference to the global environment with a warning. The warning identifies the first object with such a reference (but there may be more than one).
| Name | Type | Description |
|---|---|---|
file | String | a (readable binary-mode) connection or a character string giving the name of the file to load (when tilde expansion is done). |
envir | GlobalEnvironment | the environment where the data should be loaded. |
verbose | Boolean | should item names be printed during loading? |
A character vector of the names of objects created, invisibly.
Save R Objects
writes an external representation of R objects to the specified file. The objects can be read back from the file at a later date by using the function load or attach (or data in some cases).
| Name | Type | Description |
|---|---|---|
objects | Object | the names of the objects to be saved (as symbols or character strings). |
file | String | a (writable binary-mode) connection or the name of the file where the data will be saved (when tilde expansion is done). Must be a file name for save.image or version = 1. |
env | Environment | environment to search for objects to be saved. |
Serialization Interface for Single Objects
Functions to write a single R object to a file, and to restore it.
| Name | Type | Description |
|---|---|---|
object | Object | R object to serialize. |
file | String | a connection Or the name Of the file where the R Object Is saved To Or read from. |
ascii | Boolean | - |
version | String | - |
compress | Boolean | - |
refhook | String | a hook function for handling reference objects. |
env | Environment | - |
Serialization Interface for Single Objects
Functions to write a single R object to a file, and to restore it.
| Name | Type | Description |
|---|---|---|
file | String | a connection Or the name Of the file where the R Object Is saved To Or read from. |
refhook | Object | a hook function for handling reference objects. |
env | Environment | - |
Save R Objects
save.image() is just a short-cut for ‘save my current workspace’, i.e., save(list = ls(all.names = TRUE), file = ".RData", envir = .GlobalEnv). It is also what happens with q("yes").
| Name | Type | Description |
|---|---|---|
file | String | a (writable binary-mode) connection or the name of the file where the data will be saved (when tilde expansion is done). Must be a file name for save.image or version = 1. |
version | String | the workspace format version to use. NULL specifies the current default format (2). Version 1 was the default from R 0.99.0 to R 1.3.1 and version 2 from R 1.4.0. Version 3 is supported from R 3.5.0. |
ascii | Boolean | if TRUE, an ASCII representation of the data is written. The default value of ascii is FALSE which leads to a binary file being written. If NA and version >= 2, a different ASCII representation is used which writes double/complex numbers as binary fractions. |
compress | Object | logical Or character string specifying whether saving to a named file Is to use compression. TRUE corresponds to gzip compression, And character strings "gzip", "bzip2" Or "xz" specify the type of compression. Ignored when file Is a connection And for workspace format version 1. |
safe | Boolean | logical. If TRUE, a temporary file is used for creating the saved workspace. The temporary file is renamed to file if the save succeeds. This preserves an existing workspace file if the save fails, but at the cost of using extra disk space during the save. |
envir | Environment | environment to search for objects to be saved. |
Int32, Environment)Int32, Environment)Int32, Environment)DateTime())Array, Object, Object)