rguides

Reference

Base Functions

Core R functions available in base R.

  1. abs()

    The abs() function computes absolute values for numeric vectors in R, converting negatives to positives. Essential for distance and error calculations.

  2. aggregate()

    aggregate() splits data into subsets by one or more grouping variables and applies a summary function to each, returning a data frame of per-subset results.

  3. apply()

    Apply a function over the margins of an array or matrix in R. A core base R function for iterative operations on rectangular data structures.

  4. by()

    by() applies a function to subsets of a data frame split by one or more factors — the data-frame wrapper for tapply().

  5. c()

    The c() function combines values into a single vector or list in R, the most fundamental way to create vectors from individual elements in everyday programming.

  6. cat()

    The cat() function concatenates and prints R objects to the console or a file with minimal formatting and full control over separators.

  7. ceiling()

    The ceiling() function rounds numeric values up to the nearest integer in R (toward positive infinity), useful for pagination, batching, and safe upper bounds.

  8. class()

    Get or set the class attribute of an R object. Returns the class vector for an object, or can be used to assign a new class.

  9. colnames()

    colnames() gets or sets the column names of a matrix, data frame, or array-like R object, used to inspect and rename columns in tabular data.

  10. connection

    R connection objects: file, url, gzfile, pipe, socket, and the open, close, and isOpen methods that operate on them.

  11. cos()

    cos() computes the trigonometric cosine of numeric values in R, operating element-wise on vectors and accepting angles in radians.

  12. cummax()

    The cummax() function computes the cumulative maximum of a vector in R, returning the running maximum at each position from left to right.

  13. cummin()

    The cummin() function computes the cumulative minimum of a vector in R. It returns the running minimum, each position holding the smallest value seen so far.

  14. cumprod()

    cumprod() computes the cumulative product of a vector in R, useful for compound growth and geometric sequences where each step builds on the previous product.

  15. cumsum()

    The cumsum() function computes the cumulative sum of a vector in R, the simplest way to build running totals in reporting, finance, and time-series analysis.

  16. diff()

    diff() computes lagged differences between successive elements of a numeric vector, useful for detecting changes, trends, and rate of change in sequential data.

  17. dim()

    Get or set the dimensions of an object (matrix, data frame, array). dim() returns the dimensions of an array, matrix, or data frame.

  18. do.call

    Call a function with arguments from a list or environment. Build a call expression with call() first, then evaluate it with do.call.

  19. duplicated()

    The duplicated() function identifies duplicate elements in R objects, returning a logical vector indicating which elements (or rows) are duplicates.

  20. exp()

    exp() computes the exponential of values in R (e^x) and is one of the most frequently called math functions in statistical computing.

  21. expm1()

    The expm1() function computes exp(x) - 1 for small values of x with full precision, avoiding the cancellation that occurs when x is near zero.

  22. file()

    file() opens a file or URL connection in R, returning a connection object for readLines(), writeLines(), readBin(), and other I/O functions.

  23. filter

    Apply linear filters to time series, moving averages via convolution, autoregressive filters via recursion, with alignment and circular wrapping control.

  24. find

    Use find() to locate which environment in the search path contains an object of a given name. Returns environment names or search path positions.

  25. floor()

    Use floor() to round numeric values down to the nearest integer in R. This pattern is commonly used for creating histogram bins or demographic categories.

  26. head()

    head() returns the first parts of a vector, matrix, table, data frame or function in R, complementing tail() which returns the last n elements.

  27. ifelse()

    Transform elements based on a condition, returning one value if TRUE and another if FALSE. The ifelse() function is R's vectorized conditional operator.

  28. intersect()

    intersect() returns the elements that appear in both of two vectors in R, useful for comparing IDs, categories, or labels shared between datasets.

  29. is.na()

    is.na() tests whether elements in an R object are missing values (NA), returning a logical vector of the same length as the input.

  30. is.nan()

    The is.nan() function tests whether elements in an R object are NaN (Not a Number), identifying undefined results from operations like 0/0 or sqrt(-1).

  31. is.null()

    `is.null()` tests whether an R object is NULL — the complete absence of a value, distinct from NA which represents unknown but present data.

  32. is.numeric()

    The is.numeric() function tests whether an R object has numeric type, returning TRUE for both integer and double (floating-point) values.

  33. lapply()

    The lapply() function applies a function to each element of a list or vector, returning a list. It always returns a list of the same length as the input.

  34. length()

    Get or set the length of a vector, list, or other R object in R. It is one of the most frequently used functions in R for determining the size of objects.

  35. log()

    The log() function computes the natural logarithm (base e) of a number in R, with an optional base argument for logarithms in any base.

  36. log10()

    `log10()` computes the base-10 logarithm of a numeric vector, returning the power to which 10 must be raised to produce each value.

  37. log1p()

    log1p() computes the natural logarithm of (1 + x) with high numerical stability for small values of x. It is more accurate than log(1 + x) when x is very small.

  38. log2()

    log2() computes the base-2 logarithm of numeric values. It is vectorized, handles NA and infinite values, and is commonly used in information theory.

  39. Map

    Apply a function to multiple arguments in R with Map. This base function wraps mapply with SIMPLIFY=FALSE, always returning a list of results.

  40. mapply()

    mapply() applies a function to multiple arguments in parallel, processing matching elements together and recycling shorter vectors automatically.

  41. match()

    Find element positions in a vector, returning indices of first matches. returns the position of the first match between elements of in .

  42. max()

    The max() function returns the maximum value across its arguments in R, with na.rm for handling missing values and pmax() for element-wise comparisons.

  43. mean()

    Compute the arithmetic mean of a numeric vector, with optional trimming and NA handling. computes the arithmetic mean.

  44. merge

    Merge two data frames by common columns or row names with R's base merge(). Covers by, all.x, all.y, suffixes, and NA matching.

  45. message

    R base function to output diagnostic messages to stderr without halting execution. sends diagnostic output to the connection.

  46. min()

    Find the minimum value in a vector or across multiple arguments with the min() function. Handles NA values and returns the smallest element.

  47. ncol()

    Get the number of columns in a matrix, array, or data frame with the ncol() function. Returns NULL for atomic vectors since they lack a column dimension.

  48. negate

    Flip a predicate function with purrr negate, TRUE becomes FALSE, FALSE becomes TRUE. Use to discard what you would keep, or keep what you would discard.

  49. nrow()

    The nrow() function gets the number of rows in a matrix, array, or data frame. It returns NULL for atomic vectors since vectors have no dimensions.

  50. on.exit

    on.exit() registers cleanup expressions that run when a function exits, handling resource teardown whether the function returns normally or encounters an error.

  51. order()

    Use order() to return the permutation that sorts a vector, or sort multiple vectors by one. Returns the indices that would sort a vector or set of vectors.

  52. paste()

    The paste() function concatenates strings with a separator, converting vectors to character and optionally collapsing the result into a single string.

  53. paste0()

    paste0() concatenates strings end-to-end without separators. Equivalent to paste(..., sep = ""), it is the fastest way to join strings in base R.

  54. position

    Find positional indices and ranks in R — which.max for maximum position, which.min for minimum, rank for order-based ranks, and order for sorting indices.

  55. print()

    Print objects to the console or output connection. Generic function with methods for different object types. is generic, it dispatches to , , etc.

  56. range()

    range() returns the min and max of a vector as a length-2 vector, or the smallest and largest strings alphabetically for character data.

  57. readline()

    `readline()` reads a line from the terminal in interactive R sessions, pausing execution until the user types a response and presses Enter.

  58. readLines()

    readLines() reads text lines from a file or connection in R, returning each line as an element of a character vector.

  59. Reduce

    Apply a binary function cumulatively to reduce a vector to a single value. Supports initial values, right-to-left reduction, and accumulate mode.

  60. regexpr

    regexpr() returns the position and length of the first regex match in each element of a character vector in R.

  61. rep()

    `rep()` replicates vector elements with `times` for whole-vector repetition or `each` for per-element duplication, for building patterns and test data.

  62. reshape()

    Convert data between wide and long format with the base R reshape() function from the stats package: arguments, examples, gotchas.

  63. rm()

    `rm()` removes objects from the specified R environment by name, freeing memory and reducing namespace clutter.

  64. round()

    Round numeric values to a specified number of decimal places. The round() function rounds numeric values to the specified number of decimal places.

  65. rownames()

    rownames() gets or sets row names on matrices and data frames in R, enabling row-by-name access. It is the row equivalent of colnames().

  66. sample()

    Sample random elements from a vector or take a random subset of elements for simulation, testing, or resampling.

  67. sapply()

    The sapply() function applies a function to each element of a vector or list, simplifying the result to a vector or matrix when possible.

  68. scan

    Read data values from a file, connection, or inline string into an R vector or list using scan(), with full control over separators, NA strings, and comments.

  69. sd()

    `sd()` computes the sample standard deviation of a numeric vector using Bessel's correction (n-1 denominator) for unbiased population estimation.

  70. seq()

    seq() generates regular sequences of numbers with customizable start, end, length, and increment for looping, indexing, and creating test data.

  71. setdiff()

    The setdiff() function returns elements in the first vector but not in the second, performing an asymmetric set difference operation on R vectors.

  72. sin()

    sin() computes the trigonometric sine of numeric values in R. It operates element-wise on vectors and accepts angles in radians.

  73. sort()

    Sort a vector into ascending or descending order. Returns the input vector with elements arranged from smallest to largest.

  74. sprintf()

    Format strings using C-style sprintf formatting to insert values into text templates. sprintf() formats strings using C-style format specifiers.

  75. sqrt()

    sqrt() computes the square root of numeric values in R. It operates element-wise on vectors and returns NaN for negative inputs.

  76. stop

    Signal an error and halt execution in R with stop(), including custom messages, call control, and condition objects.

  77. subset

    Filter rows and pick columns from vectors, matrices, or data frames in base R with subset(). Learn syntax, NA handling, and when to reach for dplyr instead.

  78. substr()

    The substr() function extracts or replaces substrings by position in R. Covers 1-indexed extraction, in-place assignment, and out-of-bounds behavior.

  79. sum()

    Calculate the sum of all elements in a vector or matrix, with optional handling of missing values. adds all elements of its input vectors.

  80. switch()

    switch() selects one alternative from a list based on an integer index or character string match. Returns the selected element or NULL when no match exists.

  81. Sys.sleep

    The Sys.sleep function pauses R execution for a specified number of seconds — a simple, side-effect-only delay for loops, retries, and rate-limiting.

  82. Sys.time

    sys.time() returns the current time as a POSIXct object. Use it to timestamp computations and measure elapsed time in R.

  83. system

    Execute system commands from R. Runs shell commands and returns exit status or captured output. It is a base R function available on all platforms.

  84. system2

    `system2()` executes external commands from R, capturing output and exit status with full control over input and output streams.

  85. table()

    Create contingency tables showing frequency counts for categorical variables, cross-tabulating one or more factors into a table of counts.

  86. tan()

    The tan() function computes the trigonometric tangent of numeric values in R, operating element-wise on vectors and accepting angles in radians.

  87. tapply()

    tapply() applies a function to subsets of a vector grouped by a factor, returning an array of results — the base R equivalent of grouped summarisation.

  88. trunc()

    The trunc() function truncates numeric values toward zero in R, removing the fractional part from each element of a numeric vector.

  89. tryCatch

    Catch and handle R conditions including errors, warnings, and messages with tryCatch(). The function signature is: - is the expression to evaluate.

  90. union()

    Return the union of two vectors, all unique elements from both vectors. The function returns all unique elements that appear in either of two vectors.

  91. unique()

    Extract unique values from a vector or remove duplicated rows in R objects. returns a vector, data frame, or array with duplicate elements removed.

  92. vapply()

    vapply() applies a function to each element of a vector or list with enforced type safety via FUN.VALUE, returning a vector, matrix, or array.

  93. var()

    var() calculates the sample variance of a numeric vector using Bessel's correction. It also accepts a matrix to compute the variance-covariance matrix.

  94. warning

    Signal a warning in R with warning(), controlling call display, warn levels, suppression, and custom handlers.

  95. which.max / which.min()

    `which.max()` and `which.min()` find the index of the minimum or maximum value in a vector, essential for locating extreme values in R.

  96. which()

    The which() function returns the indices of elements that satisfy a logical condition, enabling efficient filtering and subsetting in R.

  97. with

    Evaluate an R expression in a local environment built from a data frame, list, or environment, so columns are reachable by short name. Pairs with `within()`.

  98. withCallingHandlers()

    withCallingHandlers() registers calling handlers for warnings, messages, errors in R while preserving call-stack access. Returns the expression result.

  99. within

    Return a copy of a data frame or list with columns or elements added, modified, or removed by an expression. `within()` is the write counterpart of `with()`.

  100. writeLines()

    The writeLines() function writes text lines to a file or connection in R, with control over line endings and encoding.