Learn R Programming

collapse (version 1.5.0)

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 the operation with v and each column of X

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

Arguments

X

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

v

a suitable atomic vector. If X is a list, v can also be a scalar or list of vectors (for column-operations) or a list of scalar atomic elements (for row-operations on data frame's). It is also possible to sweep lists of vectors v out of lists of matrices X (or even lists of data frames X for row-operations).

Value

X where the operation with 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 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

TRA, dapply, 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)
mtcars %>% fwithin %r-% rnorm(11) %c*% 5 %>%
    tfm(mpg = fsum(mpg)) %>% qsu
# }

Run the code above in your browser using DataLab