Indexing specific items in a nested list, for all sockets

I have a list that contains more lists of lists:

results <- sapply(c(paste0("cv_", seq(1:50)), "errors"), function(x) NULL)

## Locations for results to be stored
step_results <- sapply(c("myFit", "forecast", "errors"), function(x) NULL)
step_errors <- sapply(c("MAE", "MSE", "sign_accuracy"), function(x) NULL)
final_error <- sapply(c("MAE", "MSE", "sign_accuracy"), function(x) NULL)

for(i in 1:50){results[[i]] <- step_results}
for(i in 1:50){results[[i]][[3]] <- step_errors}
results$errors <- final_error

Now, in this whole structure, I would like to summarize all the values ​​in sign_accuracyand store them inresults$errors$sign_accuracy

I could do this with for-loop, indexing with i:

## This is just an example - it won't actually work!
sign_acc <- matrix(nrow = 50, ncol = 2)
for (i in 1:50){
     sign_acc[i, ] <- `results[[i]][[3]][[3]]`
     results$errors$sign_accuracy <- sign_acc
}

If I remember correctly, Matlab has something like list(:), which means all the elements. In Python, I saw something like list(0:-1), which also means all elements.

What is the elegant equivalent of R? I don't like cycles.

I have seen methods using the apply family of functions . Something like apply(data, "[[", 2), but can't make it work for deeper lists.

+4
2

, ,

results$errors$sign_accuracy <- do.call(sum, lapply(results, function(x){x[[3]][[3]]}))

lapply results . do.call(sum .

, . , .

+1

c(..., recursive)?

:

sumList <- function(l, label) {
    lc <- c(l, recursive=T)
    filter <- grepl(paste0("\\.",label, "$"), names(lc)) | (names(lc) == label)
    nums <- lc[filter]
    return(sum(as.numeric(nums)))
}

ex <- list(a=56,b=list("5",a=34,list(c="3",a="5")))
sumList(ex,"a")
+3

Source: https://habr.com/ru/post/1624205/


All Articles