Re: lapply, if statement and concatenating to a list
On Thu, May 5, 2011 at 8:38 AM, Lorenzo Cattarino <[hidden email]> 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)
> list2 <- c(list2,one_elem)
> 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: