Search code examples
rlistdataframeextracthierarchy

Extracting data from lists of different levels using a function


Good morning all.

I have a function that uses as a parameter a list to produce different metrics by extracting an element into a df. However, the lists I intend to use are of different hierarchical levels and, therefore, I can't use it on all of them.

I am giving an example (not the real function), below:

# the function pulls out a df from a list
df_func <- function(list){
  
  df_temp <- list[[1]]
  
  return(df_temp)  
  
}

data("iris") 

list_a <- list("list_a" = iris, "list_b" = iris,
                     "list_c" = iris, "list_d" = iris)

list_b <- list()
list_b[["list_a"]] <- list_a
list_b[["list_b"]] <- list_a
list_b[["list_c"]] <- list_a
list_b[["list_d"]] <- list_a

df1 <- df_func(list_a) # correct (returns a df)
df2 <- df_func(list_b) # wrong (returns a list of dfs)

I know that the problem lies in the fact that to access the correct element from list_a we use list_a[[1]] where as to extract the correct element from list_b we have to use list_b[[1]][[1]].

The question I have, is how to code this in the function so that R knows where to look for the df I require?

Thank you all for helping a newbie.


Solution

  • How about using a recursive function ?

    df_func <- function(list){
      tmp <- list[[1]]
      if(class(tmp) == 'list') {
        df_func(tmp)
      } else tmp
    }