Learn R Programming

lambda.tools (version 1.0.9)

foldblock: Successively apply a function to adjacent blocks of a sequence

Description

Apply a function to non-overlapping sub-sequences and the accumulated value of the function application

Arguments

x
Any indexable data structure
window
The number of elements in each sub-sequence
fn
The function applied to the sub-sequence
acc
The intermediate accumulated value

Value

The accumulated value

Usage

foldblock(x, window, fn, acc=0)

Details

This function is the fold counterpart of mapblock. Like mapblock the usefulness of this function is for the 2D case, as it can simplify interacting with matrices. See the example below for using foldblock as a summation operator over matrices

See Also

map fold foldrange

Examples

Run this code
# Sum 5 2 x 2 matrices
ms <- matrix(sample(40,20, replace=TRUE), nrow=2)
foldblock(ms,2, function(a,b) a + b)

# 1D foldblock is equivalent to 2D fold
x <- 1:12
f <- function(a,b) mean(a) + b
foldblock(x,3,f) == fold(matrix(x, nrow=3),f, 0)

Run the code above in your browser using DataLab