Search code examples
rloopsuniquelapply

Looping through several levels


I have a naïve understanding of For loops in R. I would appreciate your help to learn it better. I am working on a project with several tables of data in it. imagine the following structure: dictionary$table$variables$type

In the last level (i.e., type), the values are FALSE and/or TRUE. I need to show for which variables across all the tables the value of type equals only TRUE or only FALSE or a combination of both.

I found this function to suit my purpose: for instance for a table called HARIX, all values equal FALSE.

unique(dictionary$HARIX$variables$type)
[1] FALSE

Now I need to turn it into a loop so that it does the job for all the tables included in the dictionary. I don't know how to write this command. I wrote the one below but it doesn't reach the write level I need (i.e., type).

value <- list()
for(table_name in project$name){
  value[[table_name]] <- unique(dict[[table_name]]$variables$type)
  print(val[[table_name]])
}

I really appreciate your help. If you also have any advice on how to use the lapply function for this purpose, I would love to learn that too.


Solution

  • Get rid of the for loop and use the map function from the purrr package:

    Data sample

    Remember you have to provide a data sample in order to explain your problem better...

    v1 <- c(F, F, F)
    v2 <- c(F, T, F)
    v3 <- c(T, T, T)
    
    dictionary <- list(
      HARIX = list(var1 = list(type = v1), 
                   var2 = list(type = v2),
                   var3 = list(type = v3)),
      OTHER = list(var4 = list(type = v3), 
                   var5 = list(type = v1),
                   var6 = list(type = v2)))
    

    Solution

    require(purrr)
    
    map(dictionary, ~ map(., ~ map(., unique)))
    

    Output

    $HARIX
    $HARIX$var1
    $HARIX$var1$type
    [1] FALSE
    
    
    $HARIX$var2
    $HARIX$var2$type
    [1] FALSE  TRUE
    
    
    $HARIX$var3
    $HARIX$var3$type
    [1] TRUE
    
    
    
    $OTHER
    $OTHER$var4
    $OTHER$var4$type
    [1] TRUE
    
    
    $OTHER$var5
    $OTHER$var5$type
    [1] FALSE
    
    
    $OTHER$var6
    $OTHER$var6$type
    [1] FALSE  TRUE
    

    Here is the map function documentation

    lapply bonus

    You have requested a lapply solution:

      lapply(dictionary,
             function(word) lapply(word,
                                   function(var) lapply(var, unique)))
    

    Explanation

    You have to go down the list till you reach the right level. So you have to use nested map or nested lapply.