0 votes
1 view
in R Programming by (5.2k points)

Problem

I would like to test if an element of a list exists, here is an example

foo <- list(a=1)

exists('foo') 

TRUE   #foo does exist

exists('foo$a') 

FALSE  #suggests that foo$a does not exist

foo$a

[1] 1  #but it does exist

In this example, I know that foo$a exists, but the test returns FALSE.

I looked in ?exists and have found that with(foo, exists('a') returns TRUE, but do not understand why exists('foo$a') returns FALSE.

Questions

  • Why does exists('foo$a') return FALSE?
  • Is use of with(...) the preferred approach?

1 Answer

0 votes
by (25.3k points)

The exists function will only check if a variable exists in an environment, not if the parts of an object exist. The string "foo$a" is interpreted literally: Is there a variable called "foo$a"? ...and the answer is FALSEā€¦

To test if an element exists in a list, you can use the following:

 foo <- list(a=1, b=NULL)

> foo

$a

[1] 1

$b

NULL

> is.null(foo[["a"]]) 

[1] FALSE

> is.null(foo[["b"]]) 

[1] TRUE

> is.null(foo[["c"]]) 

[1] TRUE

#OR

> "a" %in% names(foo) 

[1] TRUE

> "b" %in% names(foo) 

[1] TRUE

> "c" %in% names(foo) 

[1] FALSE

Related questions

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...