Lorenzo Cattarino
2011-May-05 05:38 UTC
[R] lapply, if statement and concatenating to a list
Hi R users I was wondering on how to use lapply & co when the applied function has a conditional statement and the output is a 'growing' object. See example below: list1 <- list('A','B','C') list2 <- c() myfun <- function(x,list2) { one_elem <- x cat('one_elem= ', one_elem, '\n') random <- sample(1:2,1) show(random) if(random==2) { list2 <- c(list2,one_elem) }else{ list2 } } lapply(list1,myfun,list2) Is there a way to get rid of the 'NULL' elements in the output (when there is any?), without using a for loop? Thanks for your help Lorenzo [[alternative HTML version deleted]]
Hi Lorenzo, On Thu, May 5, 2011 at 8:38 AM, Lorenzo Cattarino <l.cattarino at uq.edu.au> wrote:> Hi R users > > I was wondering on how to use lapply & co when the applied function has a conditional statement and the output is a 'growing' object. > See example below: > > list1 <- list('A','B','C') > list2 <- c() > > myfun <- function(x,list2) > { > ?one_elem <- x > ?cat('one_elem= ', one_elem, '\n') > ?random <- sample(1:2,1) > ?show(random) > ?if(random==2) > ?{ > ? ?list2 <- c(list2,one_elem) > ?}else{ > ? ?list2 > ?} > } > > lapply(list1,myfun,list2) > > Is there a way to get rid of the 'NULL' elements in the output (when there is any?), without using a for loop?I don't understand what your example is trying to do and which object you expect to be "growing". list2 ain't growin', and it's not changing (i.e., it remains NULL) in your code. Perhaps you meant to have a <<- there; this would make your list2 "growing", if you really want it to, but in general, that's a bad idea. Lapply goes best with the functional style where everything your function does is computing and returning a value but here you're (if I get your intentions correctly) counting on side effects. If you like side effects, a for (or while) loop may be more logical choice. Getting rid of the NULL elements is simple. One way is: foo <- lapply(list1, yourfun) foo[!sapply(foo, is.null)] Regards, Kenn> ? ? ? ?[[alternative HTML version deleted]]