[R] apply a function to a list of lists

Ivan Krylov kry|ov@r00t @end|ng |rom gm@||@com
Wed Sep 20 09:48:34 CEST 2023


On Tue, 19 Sep 2023 17:14:58 +0200
arnaud gaboury <arnaud.gaboury using gmail.com> wrote:

> non_empty_df <- function(l) {
>     lapply(l, function(df) df[sapply(df, function(df) nrow(df) !=0)])
> }

> If I test this way: non_empty_df(my.list[1]) it does the job. It will
> return the data.frame from the first list of my_list with rows.
> Now I can't find a way to iterate the above function to all the 9
> nested lists.

I think it should already work on the whole my.list. Note that
my.list[1] is a list containing one list of data.frames, not just a
list of data.frames (the latter would be my.list[[1]]).

The outer `l` argument is the list of lists of data.frames. Inside the
first anonymous function, `df` is a list of data.frames. Inside the
second anonymous function, `df` is finally a data frame which you test
for being non-empty. The lapply() call iterates over the lists of lists
and the sapply() iterates over the data.frames inside a list.

-- 
Best regards,
Ivan



More information about the R-help mailing list