gpt4 book ai didi

r - 从 R 中的嵌套列表中提取内容

转载 作者:行者123 更新时间:2023-12-03 03:14:50 25 4
gpt4 key购买 nike

我将客户数据存储在 R 中的嵌套列表中,与此相同:

myinventedlist <- list("LOLETE" = list("Name" = "LOLETE",
"location" = "Huelva",
"Employees" = "22",
"SM" = "eJeK1",
"Groups" = list("ABUELOs" = list("PICHI" = list("fab_name" = "Pichi (ES)", "fab_id" = "2323423ES", "fab_tarif" = "6A"),
"PACHA" = list("fab_name" = "Pacha (AG)", "fab_id" = "1231212AG", "fab_tarif" = "6A"),
"POCHO" = list("fab_name" = "Pocho (ED)", "fab_id" = "2132192ED", "fab_tarif" = "6A")),
"PRIMOts" = list("MONGO" = list("fab_name" = "MONGO (LB)", "fab_id" = "21332238LB", "fab_tarif" = "6A"),
"MINGO" = list("fab_name" = "MINGO (NT)", "fab_id" = "22231220NT", "fab_tarif" = "6B"),
"MUNGO" = list("fab_name" = "MUNGO (CQ)", "fab_id" = "23215001CQ", "fab_tarif" = "6B")))),
"GUPERA" = list("Name" = "GUPERA",
"location" = "Madrid",
"Employees" = "113",
"SM" = "1xa3P",
"Groups" = list("ABUELOs" = list("YYTER" = list("fab_name" = "YYTER (MM)", "fab_id" = "2323423MM", "fab_tarif" = "6A"),
"LOLE" = list("fab_name" = "LOLE (NN)", "fab_id" = "1231212NN", "fab_tarif" = "6A"),
"PEEE" = list("fab_name" = "PEE (EE)", "fab_id" = "2132192EE", "fab_tarif" = "6A")))))

我想从给定名称的客户中提取一个包含所有“fab_id”的向量(在本例中为“LOLETE”或“GUPERA”)。

我可以访问所需的内容,即来自某个客户端的所有“fab_id”,但这是一种可怕的方式:

cliente <- "LOLETE"
firstindex <- which(names(myinventedlist) == eval(cliente))
secondindex <- which(names(myinventedlist[[firstindex]]) == "Groups")
sapply(myinventedlist[[firstindex]][[secondindex]][[1]], "[[", "fab_id")
sapply(myinventedlist[[firstindex]][[secondindex]][[2]], "[[", "fab_id")

这给出:

      PICHI       PACHA       POCHO 
"2323423ES" "1231212AG" "2132192ED"

MONGO MINGO MUNGO
"21332238LB" "22231220NT" "23215001CQ

我希望客户端可以恢复所有“fab_id”,而不管它们所属的“组”。客户端作为字符串传递。

换句话说,我希望能够获取列表中某个标题(如“fab_name”)下标记的所有元素值,尽管它们可能包含在嵌套列表中(如“Groups”) .

我想冒险问一下,在这种用于存储将在项目中递归使用的数据的列表中,是否最好将客户端命名为“CLIENT01”,然后在列表中添加字段“clien_name”或者是否可以直接使用客户的姓名来命名列表。典型的方法是什么?

欢迎任何在这个意义上使用 R 中的列表的良好链接。

提前致谢!

最佳答案

unlist,然后按名称子集 grepl:

res <- unlist(myinventedlist[[ cliente ]])
res[ grepl("fab_id", names(res)) ]
# Groups.ABUELOs.PICHI.fab_id Groups.ABUELOs.PACHA.fab_id Groups.ABUELOs.POCHO.fab_id Groups.PRIMOts.MONGO.fab_id
# "2323423ES" "1231212AG" "2132192ED" "21332238LB"
# Groups.PRIMOts.MINGO.fab_id Groups.PRIMOts.MUNGO.fab_id
# "22231220NT" "23215001CQ"

关于r - 从 R 中的嵌套列表中提取内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50367666/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com