Home > database >  How to count how many data frames are in a list in R
How to count how many data frames are in a list in R

Time:09-10

I have a list that has some lists inside (data at the end), and at the very end, it has a dataframe. How can I count how many dataframes are in total?

I was trying with:

sapply(b, function(x) sum(is.data.frame(x))

But it only counted at the first level, what can I do to get to the very last level?

How can I accomplish this?

Data


dput() is massive, (even in the smallest example), so I upload it here

CodePudding user response:

I think a well-controlled recursive function should suffice.

func <- function(z) {
  if (inherits(z, "data.frame")) return(TRUE)
  if (is.list(z)) return(sum(sapply(z, func)))
  FALSE
}

L <- list(a=1, b=mtcars, d=list(mtcars,mtcars), e=list(mtcars,list(mtcars)))
func(L)
# [1] 5
  • Related