Skip to content

exists function on list objects gives always a FALSE

8 messages · Žroutík, Linlin Yan, Duncan Murdoch +3 more

#
SmoothData$span is not an object which can be checked by exists(), but
part of an object which can be checked by is.null().
On Wed, May 20, 2009 at 12:07 AM, ?rout?k <zroutik at gmail.com> wrote:
#
?rout?k wrote:
'SmoothData$span' = 'foo'
    exists("SmoothData$span")
    # TRUE
'SmoothData[[2]]' = 'bar'
    exists("SmoothData[[2]]")
    # TRUE


the problem in your case is that you have an object named 'SmoothData'
with a nested component named 'span', but you're testing for the
existence of an object named 'SmoothData$span'. 

as shown in a recent post, one attempt to do your task would be

    exists('SmoothData') && 'span' %in% names(SmoothData)
    # TRUE

vQ
#
On 5/19/2009 12:07 PM, ?rout?k wrote:
There is no variable with name "SmoothData$span", there is an element of 
SmoothData with name "span".

To test for that, the safest test is probably

"span" %in% names(SmoothData)

but a common convention is to use

is.null(SmoothData$span)

because NULL elements are rare in lists.

Duncan Murdoch
#
?rout?k wrote:
This checks for existance of an object called "SmoothData$span", as in :

`SmoothData$span` <- 1:10
exists("SmoothData$span")

You can do:

is.list( SmoothData ) && !is.null(names(SmoothData)) && "span" %in% 
names(SmoothData)
Similarly:

`SmoothData[[2]]` <- 1
exists("SmoothData[[2]]")

You can do:

is.list( SmoothData ) && length(SmoothData) > 1

  
    
#
Linlin Yan wrote:
is.null is unhelpful here, in that lists can contain NULL as a named
element, and retrieving a non-existent element returns NULL:

    foo = list(bar=NULL)
    is.null(foo$bar)
    # TRUE
    is.null(foo$foo)
    # TRUE

i must admit i find it surprising that ?'$' does not appropriately
explain what happens if a list is indexed with a name not included in
the list's names.  the closest is

" When extracting, a numerical, logical or character 'NA' index
     picks an unknown element and so returns 'NA' in the corresponding
     element of a logical, integer, numeric, complex or character
     result, and 'NULL' for a list. "

but it's valid for NAs in the index, and

"  If no match is found then 'NULL' is returned. "

but it's in the section on environments.


vQ
#
Stavros Macrakis wrote:
kills indeed:

    foo = list(bar=1)

    with(foo, bar)
    # 1

    foo$bar = NULL
    with(foo, bar)
    # error: object 'bar' not found
but:

    # cleanup -- don't do it in mission critical session
    rm(list=ls())

    foo
    # error: object 'foo' not found

    foo = NULL
    foo
    # NULL

that is, foo$bar = NULL kills bar within foo (even though NULL is a
valid component of lists), but foo = NULL does *not* kill foo.
... and its zemanticks.

vQ