Creating nested list in R

时间秒杀一切 提交于 2020-02-25 04:15:52

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!