extract elements from list of lists with variable number of elements and NAs R -


i've got list containing groups of 2 sublist. problem of sublist nas , not contain variable number of elements. how can extract elements second sublist (the 1 variable number of elements)?

here's i'm trying:

x <- c('a','b','c') mytestlist <- list() (i in 1:10) {mytestlist[[i]] <- list(cat=sample(x,1),nums=rnorm(sample(c(1,2,3),1)))} ind <- sample(1:10,3) (i in ind) {mytestlist[[i]] <- na} z <- lapply(mytestlist,function(x) {if (is.na(mytestlist[[x]])) c(a=0,b=1,c=0) else mytestlist[[x]]$nums}) 

so can marked answered:

simono101's solution (checking na values):

lapply(mytestlist,         function(x) {            if( all(is.na(x)) ){                 c(a=0,b=1,c=0)            } else {                 x$nums            }         })  

my solution (checking named list elements):

lapply(mytestlist,         function(x) {           if('nums' %in% names(x)) {              x$nums           } else {              c(a=0, b=1, c=0)           }        }) 

Comments

Popular posts from this blog

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

html - How to style widget with post count different than without post count -

url rewriting - How to redirect a http POST with urlrewritefilter -