    # assuming D is your starting data.frame
    library(data.table)
    DT <- data.table(D)

    DT[, c( "N0", "N1", "N2", "N3" ) := NULL]

    DT[, N0 := NULL]
   
    DT[, N0 := list ( 
        if(parent=="" & grandparent != "") list(list(name=grandparent, age=age)) else list(NA)
      ), by=age]
    
    DT[, N1 := list ( 
        if(child=="" & parent != "") list(list(name=parent, age=age)) else list(NA)
      ), by=age]

    DT[, N2 := list ( 
        if(grandchild=="" & child != "") list(list(name=child, age=age)) else list(NA)
      ), by=age]

    DT[, N3 := list ( 
        if(        grandchild != "") list(list(name=grandchild, age=age)) else list(NA)
      ), by=age]


    rList <- list()
    j <- 1
#    while (j < nrow(DT))

        rList[length(rList)+1] <- list(grandparent=(DT[j, N0][[1]]))
        j <- j+1
      
 #     while (is.na(DT[j, N0])
        chldrn <- list()
        
        while(!is.na(DT[j, N1])) {
          chldrn[length(chldrn)+1] <- list(parent=(DT[j, N1][[1]]))
          j <- j+1
        }

        rList[length(rList)][["children"]] <- 
        list(rList[length(rList)][[1]], list("children"=chldrn))
        rList

        rList[length(rList)] <- 
          list(parent=(DT[j, N1][[1]]))
          list(
            c(rList[length(rList)], children=DT[j, N1])
)
        rList[length(rList)][["children"]] <- 
          list(c(rList[length(rList)][["children"]], children=DT[j, N1]))
  
         := DT[j, N0]

    }

    DT[parent=="", N0 := list(list(list(name=grandparent, age=age)) )]
    DT[sapply(N0, length) == 0, N0 := NA]

    DT[parent !="" & child=="", N1 := list(list(list(parent, age)))]
    DT[child!="" & grandchild=="", N2 := list(list(list(child, age)))]
    DT[grandchild != "", N3 := list(list(list(grandchild, age)))]
