2

I have looked this question and this question, but neither seems to address the problem of checking for the existence of an integer key in a list.

Consider the following example.

mylist=list()
mylist[[5]] = 1

# How do I programmatically check whether 5 is a key for this list?
5 %in% names(mylist) # returns FALSE, because names(mylist) is NULL here.

Update: Clarification, using another language, like Python. Here is the behavior I am trying to replicate in R.

foo = {}
foo[5] = 1
if 5 in foo: # How do I say "if 5 in foo" in R?
   print foo[5]
   # Do other stuff
Community
  • 1
  • 1
merlin2011
  • 71,677
  • 44
  • 195
  • 329

2 Answers2

2

It's probably best to use logical values I think. That way, each list element has either a "yes" or "no" attached to it. Here's a little example. Also, if you're truly using integers, attach an L to the number 1, as R won't recognize it as an integer otherwise. Furthermore, in R it's preferable to initialize the list with finite length, if known.

> mylist <- vector("list", 3)
> mylist[[3]] <- 1
> sapply(mylist, is.null)
# [1]  TRUE  TRUE FALSE
> sapply(mylist, is.integer)
# [1] FALSE FALSE FALSE
> mylist[[3]] <- 1L
> sapply(mylist, is.integer)
# [1] FALSE FALSE  TRUE
Rich Scriven
  • 97,041
  • 11
  • 181
  • 245
0

It seems that lists are not like dictionaries in other languages. When indexing with an integer i, it will access the ith element of the list.

Some example behavior:

mylist = list()
mylist[[3]] = 2
print(mylist)
# [[1]] 
# NULL
# [[2]] 
# NULL
# [[3]]
# [1] 2

mylist[['a']] = 5
print(mylist[['a']])
# [1] 5

mylist[[4]] = 10
print(mylist[['a']])
# [1] 10

So I think that it you want to use lists in R like dictionaries, it is best to stick to only using string keys.

The answer given by alexis_laz, 5 %in% which(!sapply(mylist, is.null)), works as long as you are sure that no values will be null. But it's often acceptable for dictionary entries to be null, in which case that all breaks down. Also, it's not particularly memory efficient, against because lists aren't good dictionary substitutes when using integer keys. If you're using large integers, it's going to initialize large lists full of null values.

list1 = list()
list2 = list()
list1[[1]] = 5
list2[[1000]] = 5
print(object.size(list1))
# 96 bytes
print(object.size(list2))
# 8088 bytes
Roger Fan
  • 4,945
  • 31
  • 38