Pergunta

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?

Foi útil?

Solução

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
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top