Learn R Programming

expss (version 0.10.7)

ref: Auxiliary functions to pass arguments to function by reference

Description

These two functions aimed to simplify build functions with side-effects (e. g. for modifying variables in place). Of cause it is not the R way of doing things but sometimes it can save several keystrokes.

Usage

ref(x)

ref(x) <- value

Arguments

x

Reference to variable, it is formula, ~var_name.

value

Value that should be assigned to modified variable.

Value

ref returns value of referenced variable. ref<- modifies referenced variable.

Details

To create reference to variable one can use formula: b = ~a. b is reference to a. So ref(b) returns value of a and ref(b) = new_val will modify a. If argument x of these functions is not formula then these functions have no effect e. g. ref(a) is identical to a and after ref(a) = value a is identical to value. It is not possible to use function as argument x in assignment form. For example, ref(some_function(x)) = some_value will rise error. Use y = some_function(x); ref(y) = some_value instead.

Examples

Run this code
# NOT RUN {
# Simple example
a = 1:3
b = ~a  # b is reference to 'a'
identical(ref(b),a) # TRUE

ref(b)[2] = 4 # here we modify 'a'
identical(a, c(1,4,3)) # TRUE

# usage inside function

# top 10 rows 
head10 = function(x){
 ds = head(ref(x), 10)
 ref(x) = ds
 invisible(ds) # for usage without references
}

data(iris)
ref_to_iris = ~iris
head10(ref_to_iris) # side-effect
nrow(iris) # 10

# argument is not formula - no side-effect 
data(mtcars)
mtcars10 = head10(mtcars)

nrow(mtcars10) # 10
nrow(mtcars) # 32

# }

Run the code above in your browser using DataLab