How to check if the index will be outside the borders?

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

exists("variable") 

In a script, I work on the fact that I sometimes run into the “index outside” problem after starting, and then my script stops. In the if statement, I would like to be able to check if the index is outside or not. If the result is yes, then run the alternate script world, and if not, then just continue the script as intended.

In my imagination, in the case of a list, it looks something like this:

 if {subscriptOutofBounds(listvariable[[number]]) == TRUE) { ## execute this part of the code } else { ## execute this part } 

Is there something similar in R?

+8
source share
1 answer

You can compare the length of your list with a different number. As an illustration, let's say I have a list with 3 indices, and I want to check by comparing them with a vector from 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 largest number of num vectors is 100, and your list has only 3 indexes (or length = 3), so it will be outside the borders of your list, and then will return Yes

0
source

Source: https://habr.com/ru/post/1205175/


All Articles