r - Test if an element of a list exists, without named indices -


looking @ this question possible test if element of list exists, provided list has names:

foo <- list(a=1) "a" %in% names(list)  # true "b" %in% names(list)  # false 

however not clear if or how can extended list isn't named:

foo <- list(1) names(list)    # null 

i can test using trycatch isn't particularly elegant:

indexexists <- function(list, index) {   trycatch({     list[[index]]  # efficiency if element exist , large??     true   }, error = function(e) {     false   }) } 

is there better way of going this?

hong ooi's answer works 1 dimension, thought add answer works multiple dimension indices.

indexexists <- function(ind, form) {     if (ind[[1]] > length(form) || ind[[1]] < 1)         return(false)     dim <- 1     while (dim + 1 <= length(ind)) {         if (ind[dim + 1] > length(form[[ ind[1:dim] ]] ) || ind[dim + 1] < 1)             return(false)         dim <- dim + 1     }     return(true) } 

here sample output:

> alist <- list( list(1,2,list(1,10,100,1000),3), 5 ) > indexexists(c(1), alist) [1] true > indexexists(c(2), alist) [1] true > indexexists(c(0), alist) [1] false > indexexists(c(3), alist) [1] false > indexexists(c(1,1), alist) [1] true > indexexists(c(1,3), alist) [1] true > indexexists(c(1,4), alist) [1] true > indexexists(c(1,0), alist) [1] false > indexexists(c(1,5), alist) [1] false > indexexists(c(1,3,4), alist) [1] true > indexexists(c(1,3,5), alist) [1] false 

note don't think efficiency of answer in question depends on size of list elements because in case r create new object in memory if modify copied object. might suggests assigning list[[index]] though (this makes clear you're assigning , not e.g. printing).


Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -