[R] programming questions

ivo welch ivo.welch at gmail.com
Wed Nov 3 20:32:11 CET 2010


thanks, barry and eric.  I didn't do a good job---I did an awful job.

alas, should R not come with an is.defined() function?  a variable may
never have been created, and this is different from a variable
existing but holding a NULL.  this can be the case in the global
environment or in a data frame.

  > is.null(never.before.seen)
  Error: objected 'never.before.seen' not found
  > is.defined(never.before.seen)  ## I need this, because I do not
want an error:
  [1] FALSE

your acs function doesn't really do what I want, either, because {
d=data.frame( x=1:4); exists(acs(d$x)) } tells me FALSE .  I really
need

  > d <- data.frame( x=1:5, y=1:5 )
  > is.defined(d$x)
  TRUE
  > is.defined(d$z)
  FALSE
  > is.defined(never.before.seen)
  FALSE
  > is.defined(never.before.seen$anything)  ## if a list does not
exist, anything in it does not exist either
  FALSE

how would I define this function?

regards,

/iaw

On Wed, Nov 3, 2010 at 2:48 PM, Barry Rowlingson
<b.rowlingson at lancaster.ac.uk> wrote:
> On Wed, Nov 3, 2010 at 6:17 PM, ivo welch <ivo.welch at gmail.com> wrote:
>> yikes.  this is all my fault.  it was the first thing that I ever
>> defined when I started using R.
>>
>>   is.defined <- function(name) exists(as.character(substitute(name)))
>>
>> I presume there is something much better...
>
>  You didn't do a good job testing your is.defined :)
>
>  Let's see what happens when you feed it 'nonexisting$garbage'. What
> gets passed into 'exists'?
>
> acs=function(name){as.character(substitute(name))}
>
>  > acs(nonexisting$garbage)
> [1] "$"           "nonexisting" "garbage"
>
>  - and then your exists test is doing effectively exists("$") which
> exists. Hence TRUE.
>
>  What you are getting here is the expression parsed up as a function
> call ($) and its args. You'll see this if you do:
>
>  > acs(fix(me))
> [1] "fix" "me"
>
> Perhaps you meant to deparse it:
>
>  > acs=function(name){as.character(deparse(substitute(name)))}
>  > acs(nonexisting$garbage)
>  [1] "nonexisting$garbage"
>  > exists(acs(nonexisting$garbage))
>  [1] FALSE
>
> But you'd be better off testing list elements with is.null
>
> Barry
>



More information about the R-help mailing list