Learn R Programming

datadr (version 0.8.6.1)

kvApply: Apply Function to Key-Value Pair

Description

Apply a function to a single key-value pair - not a traditional R "apply" function.

Usage

kvApply(kvPair, fn)

Arguments

kvPair

a key-value pair (a list with 2 elements or object created with kvPair)

fn

a function

Details

Determines how a function should be applied to a key-value pair and then applies it: if the function has two formals, it applies the function giving it the key and the value as the arguments; if the function has one formal, it applies the function giving it just the value. The function is assumed to return a value unless the result is a kvPair object. When the function returns a value the original key will be returned in the resulting key-value pair.

This provides flexibility and simplicity for when a function is only meant to be applied to the value (the most common case), but still allows keys to be used if desired.

Examples

Run this code
# NOT RUN {
kv <- kvPair(1, 2)
kv
kvApply(kv, function(x) x^2)
kvApply(kv, function(k, v) v^2)
kvApply(kv, function(k, v) k + v)
kvApply(kv, function(x) kvPair("new_key", x))
# }

Run the code above in your browser using DataLab