10

If i want to check the existence of a variable I use

exists("variable")

In a script I am working on I sometimes encounter the problem of a "subscript out of bounds" after running, and then my script stops. In an if statement I would like to be able to check if a subscript will be out of bounds or not. If the outcome is "yes", then execute an alternative peace of the script, and if "not", then just continue the script as it was intended.

In my imagination in case of a list it would look something like:

if {subscriptOutofBounds(listvariable[[number]]) == TRUE) {

## execute this part of the code
}
else {
## execute this part
}

Does something like that exist in R?

rdatasculptor
  • 8,112
  • 14
  • 56
  • 81
  • 4
    possible duplicate of [How to test if list element exists?](http://stackoverflow.com/questions/7719741/how-to-test-if-list-element-exists) (having noted that, if you are solely using indexes for a list, you can see if the index is > `length`) – hrbrmstr Oct 21 '14 at 11:41
  • 1
    I think you would be better comparing the number to the length of the list, or something like `!(number%in%seq(length(listvariable)))` – James Oct 21 '14 at 11:46
  • 5
    I wouldn't try to go around this error, but rather correct the code around: why is `number` greater than the number of items in `listvariable`? – Vincent Guillemot Oct 21 '14 at 11:50
  • using length() worked!! thanks – rdatasculptor Oct 21 '14 at 12:17
  • @vincent, you are completely right, ofcourse. The thing is I let people use a shiny app that builds lists in lists depending on the kind of interaction. I haven't succeeded in building it without subscript errors every now and then. That's why I chose another approach. But then again, I admit it's not the most esthetic solution. – rdatasculptor Oct 21 '14 at 17:06
  • Just as a note, if you're searching for a specific named list element rather than an index, `elementName %in% names(listvariable)` should give you that. – Serenthia Feb 23 '16 at 21:25

1 Answers1

1

You can compare the length of your list with other number. As an illustration, say I have a list with 3 index and want to check by comparing them with a vector of number 1 to 100.

lol <- list(c(1:10),
            c(100:200),
            c(3:50))
lol

check_out <- function(x) {
  maxi <- max(x)
  if (maxi > length(lol)) {

  #Excecute this part of code
  print("Yes")
}
else {
  #Excecute this part of code
  print("No")
}
}

num <- 1:100
check_out(num)

The biggest number of vector num is 100 and your list only has 3 index (or length =3), so it will be out of bound from your list, then it will return Yes