简体   繁体   中英

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

I've a nested structure like:

  • A parent list 'parent' made of a variable number of items
  • Each node of the parent list is a list of three named elements (let's say 'foo', 'bar', 'puppy')
  • These (named) elements of the inner list are dataframes made of a variable number of columns

(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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM