Gabriele B
Gabriele B

Reputation: 2685

Apply a function over a list of lists of dataframes in R

I've a nested structure like:

(it's even difficult to me to build a reproducible example of this structure, actually)

I'm searching an effective way to apply a function (let's say toLower) to each cell of the inner dataframes, ofc for each element of the parent list.

I think I could nest some lapply but I have no idea on how to reference the inner elements and which FUN to use as lapply parameter itself

Upvotes: 1

Views: 3985

Answers (1)

John McDonnell
John McDonnell

Reputation: 1490

If I've understood correctly, you have a structure like this:

parent <- list(
    a=list(foo=data.frame(first=c(1,2,3), second=c(4,5,6)),
       bar=data.frame(first=c(1,2,3), second=c(4,5,6)),
       puppy=data.frame(first=c(1,2,3), second=c(4,5,6))
      ),
    b=list(foo=data.frame(first=c(1,2,3), second=c(4,5,6)),
       bar=data.frame(first=c(1,2,3), second=c(4,5,6)),
       puppy=data.frame(first=c(1,2,3), second=c(4,5,6))
      )
    )

And you want to run function f, which applies to each scalar in the data frames, over parent, is that correct?

If so, the following function nested_lapply should do that:

nested_lapply <- function(data, fun) {
    lapply(data, function(sublist) { lapply(sublist, fun) })
}

It can be applied like so:

nested_lapply(parent, sqrt)

Upvotes: 5

Related Questions