[R] Testing for existence inside a function
Alberto Monteiro
albmont at centroin.com.br
Tue May 15 22:00:41 CEST 2007
Duncan Murdoch wrote:
>
>> Try this:
>>
>> f <- function(x) x + 1
>> f(y.does.not.exist)
>> y.does.not.exist
>>
>> The error message is (almost) the same, and it happens when
>> parsing the line. There's no way to change f to change this.
>
> That description is true in some languages, but not in R. R doesn't
> check that args to functions are valid until it needs to use them.
> For example:
>
> > f <- function(y) 1 # doesn't care if y exists
> > f(y.does.not.exist)
> [1] 1
>
Ok, I guess R optimizes every call to f, ignoring its arguments
unless needed.
f <- function(y) 1 # doesn't care if y exists
g <- function() cat("g was called\n")
f(g())
[1] 1
# g was not called
Another test:
f1 <- function(x, y) if (x == 0) y else 1
f1(1, y.does.not.exist)
f1(1, g())
The y-argument is never called.
So maybe it _might_ be possible to test if y exists inside the
function...
Alberto Monteiro
More information about the R-help
mailing list