[R] programming questions

David Winsemius dwinsemius at comcast.net
Wed Nov 3 20:59:54 CET 2010


On Nov 3, 2010, at 3:32 PM, ivo welch wrote:

> thanks, barry and eric.  I didn't do a good job---I did an awful job.
>
>
>> is.defined(never.before.seen$anything)  ## if a list does not
> exist, anything in it does not exist either

Except the $ function return NULL rather than an error and you already  
said you were willing to accept a NULL value as being different than  
not-existing.

You may want to look at the difference between `$` and `[` methods of  
accessing values.

You can test for never.before.seen as an object

is.defined <- function(x) !("try-error" %in% class(try(x)) )

But it won't give your desired result on d$never.before.seen which  
does not throw an error. For that you would need an additional test of  
the sort Iverson is suggesting.

-- 
David.

>  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
>>
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list