Learn R Programming

collapse (version 1.7.6)

arithmetic: Fast Row/Column Arithmetic for Matrix-Like Objects

Description

Fast operators to perform row- or column-wise replacing and sweeping operations of vectors on matrices, data frames, lists.

Usage

## Perform the operation with v and each row of X

X %rr% v # Replace rows of X with v X %r+% v # Add v to each row of X X %r-% v # Subtract v from each row of X X %r*% v # Multiply each row of X with v X %r/% v # Divide each row of X by v

## Perform a column-wise operation between V and X

X %cr% V # Replace columns of X with V X %c+% V # Add V to columns of X X %c-% V # Subtract V from columns of X X %c*% V # Multiply columns of X with V X %c/% V # Divide columns of X by V

Arguments

X

a vector, matrix, data frame or list like object (with rows (r) columns (c) matching v / V).

v

for row operations: an atomic vector of matching NCOL(X). If X is a data frame, v can also be a list of scalar atomic elements. It is also possible to sweep lists of vectors v out of lists of matrices or data frames X.

V

for column operations: a suitable scalar, vector, or matrix / data frame matching NROW(X). X can also be a list of vectors / matrices in which case V can be a scalar / vector / matrix or matching list of scalars / vectors / matrices.

Value

X where the operation with v / V was performed on each row or column. All attributes of X are preserved.

Details

With a matrix or data frame X, the default behavior of R when calling X op v (such as multiplication X * v) is to perform the operation of v with each column of X. The equivalent operation is performed by X %cop% V, with the difference that it computes significantly faster if X/V is a data frame / list. A more complex but frequently required task is to perform an operation with v on each row of X. This is provided based on efficient C++ code by the %rop% set of functions, e.g. X %r*% v efficiently multiplies v to each row of X.

See Also

setop, TRA, dapply, Efficient Programming, Data Transformations, Collapse Overview

Examples

Run this code
# NOT RUN {
## Using data frame's / lists
v <- mtcars$cyl
mtcars %cr% v
mtcars %c-% v
mtcars %r-% seq_col(mtcars)
mtcars %r-% lapply(mtcars, quantile, 0.28)

mtcars %c*% 5       # Significantly faster than mtcars * 5
mtcars %c*% mtcars  # Significantly faster than mtcars * mtcars

## Using matrices
X <- qM(mtcars)
X %cr% v
X %c-% v
X %r-% dapply(X, quantile, 0.28)
# }
# NOT RUN {
## Chained Operations
library(magrittr) # Note: Used because |> is not available on older R versions
mtcars %>% fwithin() %r-% rnorm(11) %c*% 5 %>%
    tfm(mpg = fsum(mpg)) %>% qsu()
# }

Run the code above in your browser using DataLab