如何在R中有效地操作嵌套列表的内容

kognpnkq  于 5个月前  发布在  其他
关注(0)|答案(1)|浏览(36)

我目前正在处理包含汽车零件数据的嵌套列表,下面是一个例子:

Partslist                   <- setNames(list(setNames(vector(mode="list", 5),  paste("L", 3, "_",c("type", "year", "parts available", "last update", "make"), sep=""))), "Partslist")
Partslist$Partslist$L3_make <- setNames(vector(mode="list", 2),  c("BMW", "Toyota"))

Partslist$Partslist$L3_make$BMW$Engine    <-setNames(vector(mode="list", 6),  c("L1_type", "L1_year", "L1_parts available", "L1_last update", "L1_components", "L1_status"))
Partslist$Partslist$L3_make$BMW$Powertrain<-setNames(vector(mode="list", 6),  c("L1_type", "L1_year", "L1_parts available", "L1_last update", "L1_components", "L1_status"))
Partslist$Partslist$L3_make$Toyota$Engine <-setNames(vector(mode="list", 6),  c("L1_type", "L1_year", "L1_parts available", "L1_last update", "L1_components", "L1_status"))
Partslist$Partslist$L3_make$Toyota$other  <-setNames(vector(mode="list", 6),  c("L1_type", "L1_year", "L1_parts available", "L1_last update", "L1_components", "L1_status"))

字符串
主要的挑战是这些列表是不规则的,这意味着我不知道每个分支上的嵌套有多深。
我需要的是一种可伸缩的方法来选择和操作嵌套列表中每一层的数据,即更新价格,数量等。
简而言之,我发现自己无法想出一种能够处理列表不断变化的深度的方法。
一种可能的、容易实现的(但很难看)方法是形成所需操作的字符串表达式,然后使用eval(parse(text="”))。
它看起来像这样:

target.string <- "Autoparts$L3_make$BMW$L2_components$Engine§L1_type" 
parts.data<-"hybrid 3i"

eval(parse(text=paste("target.string", "<-", parts.data, sep="")))


但是,我不想诉诸于此,一定有更好的办法……我很感激任何建议。

zour9fqk

zour9fqk1#

我不知道你想做的所有事情,但是使用深度嵌套列表的一种有效方法是使用向量作为顶层的索引。

# Your desired index into autoparts was
# autoparts$L3_make$BMW$L2_components$Engine§L1_type

index <- c("L3_make", "BMW", "L2_components", "Engine", "L1_type")

Autoparts[[index]] <- parts.data

字符串
这个答案的早期版本说不允许按名称索引。这是错误的。不允许的是混合按名称索引和按数字索引。数字将转换为字符并被解释为名称。

相关问题