Become an expert in R — Interactive courses, Cheat Sheets, certificates and more!
Get Started for Free

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.

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.

Value

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

Examples

# 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

expss

Tables, Labels and Some Useful Functions from Spreadsheets and 'SPSS' Statistics

v0.10.7
GPL (>= 2)
Authors
Gregory Demin [aut, cre], Sebastian Jeworutzki [ctb] (<https://orcid.org/0000-0002-2671-5253>)
Initial release

We don't support your browser anymore

Please choose more modern alternatives, such as Google Chrome or Mozilla Firefox.