问题
I have a data frame like below:
df <- data.frame(child = c('item3-1-1','item3-1-2','item3-2','item3-1','item2-1','item2-2','item1'),parent = c('item3-1','item3-1','item3','item3','item2','item2',''))
I want to convert this dataframe in below format:
choices <-
list(
list(id = 1, title = "item1"),
list(id = 2, title = "item2",
subs = list(
list(id = 21, title = "item2-1"),
list(id = 22, title = "item2-2")
)
),
list(id = 3, title = "item3",
subs = list(
list(id = 31, title = "item3-1", isSelectable = FALSE,
subs = list(
list(id = 311, title = "item3-1-1"),
list(id = 312, title = "item3-1-2")
)
),
list(id = 32, title = "item3-2")
)
)
)
I need the nested list with option of 'subs' to traverse the tree drop-down list.
Is there any function or method by which I can achieve this as I have huge dataset.
回答1:
Here is a function which generates the nested list. The id are not the same but anyway we do not use them in ComboTree (but they are required).
dat <- data.frame(
item = c("item1", "item2", "item2-1", "item2-2", "item3", "item3-1",
"item3-1-1", "item3-1-2", "item3-2"),
parent = c("root", "root", "item2", "item2", "root", "item3",
"item3-1", "item3-1", "item3"),
stringsAsFactors = FALSE
)
makeChoices <- function(dat){
f <- function(parent, id = "id"){
i <- match(parent, dat$item)
title <- dat$item[i]
subs <- dat$item[dat$parent==title]
if(length(subs)){
list(
title = title,
id = paste0(id,"-",i),
subs = lapply(subs, f, id = paste0(id,"-",i))
)
}else{
list(title = title, id = paste0(id,"-",i))
}
}
lapply(dat$item[dat$parent == "root"], f)
}
choices <- makeChoices(dat)
> jsonlite::toJSON(choices, auto_unbox = TRUE, pretty = TRUE)
[
{
"title": "item1",
"id": "id-1"
},
{
"title": "item2",
"id": "id-2",
"subs": [
{
"title": "item2-1",
"id": "id-2-3"
},
{
"title": "item2-2",
"id": "id-2-4"
}
]
},
{
"title": "item3",
"id": "id-5",
"subs": [
{
"title": "item3-1",
"id": "id-5-6",
"subs": [
{
"title": "item3-1-1",
"id": "id-5-6-7"
},
{
"title": "item3-1-2",
"id": "id-5-6-8"
}
]
},
{
"title": "item3-2",
"id": "id-5-9"
}
]
}
]
来源:https://stackoverflow.com/questions/60319163/creating-nested-list-in-r