简体   繁体   中英

Readably modify elements located deeply in nested lists

I'm during some machine learning stuff which often involves iterating over several variables to find the best model hyperparameters. Therefore, my information about how a model performed for a certain combination of settings is located within lists of lists of lists.

Now let's say I want to retrieve some information and use it to calculate new values at this level in the list.

# create an element to modify deep within a list
predictions <- c(0,1,0,1,0,1,0,1,0,1)
actual <- c(0,0,0,0,1,1,1,1,0,0)

# compare predictions against actual values with a confusion matrix
confusion_matrix <- table(
  factor(predictions, 
         levels = min(predictions) : max(predictions)),
  factor(actual, 
         levels = min(actual) : max(actual)))
confusion_matrix

# create a nested list
my_list <- list(
  first_layer = (
    list(
      second_a = list(
        third = list(confusion_matrix = confusion_matrix)), 
      second_b = list(
        third = list(confusion_matrix = confusion_matrix)), 
      second_c =list(
        third = list(confusion_matrix = confusion_matrix))
)))

str(my_list, max = 4)

# get the individual entries of the confusion matrix and store them in a 
# list on the same level named "Prediction_cases" to calculate Error types later
for (aa in seq_along(my_list)) {
  for (bb in seq_along(my_list[[aa]])) {
    for (cc in seq_along(my_list[[aa]][[bb]])) {
      print(my_list[[aa]][[bb]][[cc]][["confusion_matrix"]])
      my_list[[aa]][[bb]][[cc]][["Prediction_cases"]] <- list(
        True_negative = my_list[[aa]][[bb]][[cc]][["confusion_matrix"]][1,1], 
        False_negative = my_list[[aa]][[bb]][[cc]][["confusion_matrix"]][1,2], 
        False_positive = my_list[[aa]][[bb]][[cc]][["confusion_matrix"]][2,1], 
        True_positive = my_list[[aa]][[bb]][[cc]][["confusion_matrix"]][2,2]
      )
      # it becomes even more fun with dynamic adressing
      print(my_list[[aa]][[bb]][[cc]][["confusion_matrix"]][2,length(my_list[[aa]][[bb]][[cc]][["confusion_matrix"]][,2])])
    }
  }
}

str(my_list, max = 4)

This works perfectly fine, but you can see, as deeper as it goes, the more indices are required. Is there a better way to do this or a more concise way to write this for

a) the definition within the for loop ( for (cc in seq_along(my_list[[aa]][[bb]])) )

b) within the body of the loop? ?

这有帮助吗?

purrr::flatten(my_list)

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