从R中的索引命名嵌套列表的元素

我有这个嵌套列表:

dico <- list(list(list(c("dim.", "dimension", "dimensions", "mesures"
), c("45 cm", "45", "45 CM", "0.45m")), list(c("tamano", "volumen", 
"dimension", "talla"), c("45 cm", "45", "0.45 M", "45 centimiento"
)), list(c("measures", "dimension", "measurement"), c("45 cm", 
"0.45 m", "100 inches", "100 pouces"))), list(list(c("poids", 
"poid", "poids net"), c("100 grammes", "100 gr", "100")), list(
    c("peso", "carga", "peso especifico"), c("100 gramos", "100g", 
    "100", "100 g")), list(c("weight", "net wieght", "weight (grammes)"
), c("100 grams", "100", "100 g"))), list(list(c("Batterie oui/non", 
"batterie", "présence batterie"), c("Oui", "batterie", "OUI"
)), list(c("bateria", "bateria si or no", "bateria disponible"
), c("si", "bateria furnindo", "1")), list(c("Battery available", 
"battery", "battery yes or no"), c("yes", "Y", "Battery given"
))))

[[1]]
[[1]][[1]]
[[1]][[1]][[1]]
[1] "dim."       "dimension"  "dimensions" "mesures"   

[[1]][[1]][[2]]
[1] "45 cm" "45"    "45 CM" "0.45m"

我想要的是创建一个具有相同结构的列表,但不是拥有原始值,我希望有一种“索引”名称,如:

[[1]]
[[1]][[1]]
[[1]][[1]][[1]]
[1] "1|1|1|1"       "1|1|1|2"  "1|1|1|3" "1|1|1|4"   

[[1]][[1]][[2]]
[1] "1|1|2|1" "1|1|2|2"    "1|1|2|3" "1|1|2|4"

等等……

当然,通过不同的嵌套索引,元素的数量不是恒定的.谁知道怎么做?我听说过rapply,但我无法做到.

最佳答案
我们可以使用melt(来自reshape2)将嵌套列表转换为带有索引列(‘L1′,’L2′,’L3′)和’value’列的data.frame,将其转换为data.table(setDT) (…)),按’L1′,’L2’,’L3’分组,我们得到行的序列(1:.N),用do.call将行的元素粘贴到单个向量,然后通过指定骨架将其重新放入与’dico’结构相同的列表中.

library(data.table)
library(reshape2)
dico2 <- relist(do.call(paste, c(setDT(melt(dico))[, 1:.N ,
          by =  .(L1, L2, L3)], sep="|")), skeleton = dico)
dico2
#[[1]]
#[[1]][[1]]
#[[1]][[1]][[1]]
#[1] "1|1|1|1" "1|1|1|2" "1|1|1|3" "1|1|1|4"

#[[1]][[1]][[2]]
#[1] "1|1|2|1" "1|1|2|2" "1|1|2|3" "1|1|2|4"

#...

#[[3]][[3]]
#[[3]][[3]][[1]]
#[1] "3|3|1|1" "3|3|1|2" "3|3|1|3"

#[[3]][[3]][[2]]
#[1] "3|3|2|1" "3|3|2|2" "3|3|2|3"

转载注明原文:从R中的索引命名嵌套列表的元素 - 代码日志