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?
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.
R performs a lazy evaluation to evaluate an expression if its value is needed.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With