【问题标题】:Indexing certain elements in a nested list, for all nests为所有嵌套索引嵌套列表中的某些元素
【发布时间】:2016-04-19 06:42:05
【问题描述】:

我有一个包含更多列表的列表:

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

现在在整个结构中,我想总结sign_accuracy中的所有值并将它们保存在results$errors$sign_accuracy

我也许可以用一个 for 循环来做到这一点,用 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
}

如果我没记错的话,在 Matlab 中有类似 list(:) 的东西,表示所有元素。 In Python我见过类似list(0:-1)的东西,也就是所有元素的意思。

什么是优雅的 R 等价物?我不太喜欢循环。

我见过methods using the apply 系列函数。使用 apply(data, "[[", 2) 之类的东西,但无法让它用于更深的列表。

【问题讨论】:

    标签: r list indexing nested-lists lapply


    【解决方案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")
    

    【讨论】:

    • 只要没有可怕的人说出列表项"a.b.c" 或类似的东西...
    【解决方案2】:

    在这种情况下,你可以做你想做的事

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

    lapply循环遍历results的第一层,并为每个元素拉出第三个元素的第三个元素。 do.call(sum 捕获所有结果并将它们相加。

    当嵌套更不规则时,或者当您需要遍历多个索引时,列表的真正问题就会出现。它总是可以用同样的方式完成,但它很快就会变得非常丑陋。

    【讨论】:

    • 这是我最终使用的解决方案,谢谢!
    猜你喜欢
    • 1970-01-01
    • 2011-01-25
    • 1970-01-01
    • 2023-02-04
    • 2013-01-17
    • 2023-02-06
    • 2016-10-26
    • 2017-04-18
    • 1970-01-01
    相关资源
    最近更新 更多