Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making an R promise object (lazy evaluation) from scratch

I want to lazily read in data from different text files, similar to lazy loading of data sets (e.g. typing iris into R lazily loads the data set from the datasets package). The difference here is that I want an R expression to be run whenever some variable (here I use x) is typed into the R console or is used by some other code.

# The expression that I want run if the variable x is called by some other code
expn = quote( {x = read.table(text = "a b  \n 1 2", header=TRUE)} )

# When I type this, I want the language object 'expn' to be evaluated
# (e.g. eval(expn)) so that the variable x now exists
x

Is there a way to do this with an R promise object? Must I create an R package to get this behavior?

like image 576
kdauria Avatar asked Mar 03 '14 18:03

kdauria


People also ask

What is a lazy function evaluation in R give some example?

Lazy evaluation is an evaluation strategy which holds the evaluation of an expression until its value is needed. It avoids repeated evaluation. Haskell is a good example of such a functional programming language whose fundamentals are based on Lazy Evaluation.

Does R do lazy evaluation?

R performs a lazy evaluation to evaluate an expression if its value is needed.

What does promise mean in R?

A promise is an object that represents the eventual result of a specific asynchronous operation. Whenever you launch an async task, you get a promise object back. That promise is what lets you know: When the task completes (if ever) Whether the task completed successfully or failed.


1 Answers

You're looking for delayedAssign.

delayedAssign('x', read.table(text = "a b  \n 1 2", header=TRUE))

You can see that the expression executes when x is first requested:

delayedAssign('x', {
      message('assigning')
      read.table(text = "a b  \n 1 2", header=TRUE)
  })
x
# assigning
#   a b
# 1 1 2
like image 108
Matthew Plourde Avatar answered Oct 28 '22 17:10

Matthew Plourde