如何创建函数向已有列表的列表中添加新列表以生成预期结构?
如何正确构建R语言的列表嵌套结构
我想要创建一个列表的列表,通过调用不同函数填充内容,但当前代码生成的输出结构混乱、无法使用,需要更合理的实现方式。以下是简化的问题代码:
choices <- list() ############### add_wealth <- function(ch, wealth) { a <- list(type="wealth", parameter =wealth) list(ch, a) } wealth <- 1 choices <- add_wealth(choices, wealth) ############## add_diversification <- function(ch, div) { a <- list(type="diversification", parameter =div) list(ch, a) } div <- .7 choices <- add_diversification(choices, div) ############## add_margin <- function(ch, bounds) { a <- list(type="margin", parameter=bounds) list(ch, a) } bounds <- c(1, 3) choices <- add_margin(choices, bounds) choices
问题分析
这段代码的核心问题是:每次调用add_*函数时,都用list(ch, a)将原列表与新生成的子列表嵌套包装,导致最终的choices变成多层嵌套的结构(如list(list(list(), a1), a2)),而非预期的一维嵌套列表。
理想输出结构
我需要的理想输出如下(或类似结构):
[[1]] [[1]]$type [1] "wealth" [[1]]$parameter [1] 1 [[2]] [[2]]$type [1] "diversification" [[2]]$parameter [1] 0.7 [[3]] [[3]]$type [1] "margin" [[3]]$parameter [1] 1 3
解决方案
要实现预期结构,只需修改每个add_*函数,将新子列表追加到原列表末尾,而非嵌套包装。可以用c()函数(需将新子列表用list()包裹,避免元素拆分)或append()函数:
修改后的完整代码:
choices <- list() # 修改add_wealth函数 add_wealth <- function(ch, wealth) { a <- list(type="wealth", parameter =wealth) c(ch, list(a)) # 将a作为单个元素合并到原列表 } wealth <- 1 choices <- add_wealth(choices, wealth) # 修改add_diversification函数 add_diversification <- function(ch, div) { a <- list(type="diversification", parameter =div) append(ch, list(a)) # 直接追加元素到列表末尾 } div <- .7 choices <- add_diversification(choices, div) # 修改add_margin函数 add_margin <- function(ch, bounds) { a <- list(type="margin", parameter=bounds) c(ch, list(a)) } bounds <- c(1, 3) choices <- add_margin(choices, bounds) # 查看结果 choices
运行上述代码后,即可得到预期的一维嵌套列表结构,每个子元素都是包含type和parameter的独立列表。
内容的提问来源于stack exchange,提问作者SuperLeo
相关产品推荐
相关产品推荐

