how to convert a data.frame to tree structure object such as dendrogram

前端 未结 2 1919
生来不讨喜
生来不讨喜 2020-12-24 09:39

I have a data.frame object. For a simple example:

> data.frame(x=c(\'A\',\'A\',\'B\',\'B\',\'B\'), y=c(\'Ab\',\'Ac\',\'Ba\', \'Ba\',\'Bd\'), z=c(\'Abb\',\         


        
2条回答
  •  失恋的感觉
    2020-12-24 10:15

    I don't know much about the internal structure of dendrograms in R, but the following code will create a nested list structure that has the hierarchy that I think you look for:

    stree = function(x,level=0) {
    #x is a string vector
    #resultis a hierarchical structure of lists (that contains lists, etc.)
    #the names of the lists are the node values.
    
    level = level+1
    if (length(x)==1) {
        result = list()
        result[[substring(x[1],level)]]=list()
        return(result)
    }
    result=list()
    this.level = substring(x,level,level)
    next.levels = unique(this.level)
    for (p in next.levels) {
        if (p=="") {
            result$p = list()
        } else {
            ids = which(this.level==p)
            result[[p]] = stree(x[ids],level)
        }
    }
    result
    }
    

    it operates on a vector of strings. so in case of your dataframe you'd need to call stree(as.character(df[,3]))

    Hope this helps.

提交回复
热议问题