我的客户数据存储在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")))))
我想用所有&#34; fab_id&#34;提取一个向量。来自客户的名字(在这种情况下&#34; LOLETE&#34;或&#34; GUPERA&#34;)。
我可以访问所需的内容,即所有&#34; fab_id&#34;来自某个客户,但这是一种可怕的方式:
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
我希望客户能够恢复所有&#34; fab_id&#34;无视&#34; Group&#34;他们属于。客户端作为String传递。
换句话说,我希望能够获得列表中某些标题下标记的所有元素值(例如&#34; fab_name&#34;),尽管它们可能包含在嵌套列表中(喜欢&#34;群组&#34;)。
我想冒险并询问是否在这种列表中存储将在项目中使用的数据,最好将客户命名为&#34; CLIENT01&#34;然后添加字段&#34; clien_name&#34;在列表中,或者如果可以直接使用客户端的名称命名列表。什么是典型的方式?
欢迎在这种意义上与R中的列表一起使用的任何良好链接。
提前致谢!
答案 0 :(得分:1)
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"