Skip to content

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

1 message · Bert Gunter

#
Here is a simpler, less clumsy version of my previous recursive R
solution that I sent you privately, which I'll also cc to the list
this time. It's now almost a one-liner.

To avoid problems with unused factor levels, I still prefer to have
character vectors not factors, as the data frame columns so:

df <- data.frame(a=c('A','A', 'A', 'B','B','C','C','C'), b=c('Aa',
'Ab','Ab','Ba','Bd', 'C1','C2','C3'), c=c('Aa1', 'Ab1', 'Ab2', 'Ba1',
'Bd2', 'C11','C12','C13'), stringsAsFactors=FALSE)

makeTree2 <-function(x, i,n)
{
  if(i==n)df[x,i]
  else {
    spl <- split(x,df[x,i])
    lapply(spl,function(x)makeTree2(x,i+1,n))   ##Can't use Recall()
  }
}

This is now called as
## yielding (with the root implicit now)

$A
$A$Aa
[1] "Aa1"

$A$Ab
[1] "Ab1" "Ab2"


$B
$B$Ba
[1] "Ba1"

$B$Bd
[1] "Bd2"


$C
$C$C1
[1] "C11"

$C$C2
[1] "C12"

$C$C3
[1] "C13"
On Wed, Mar 13, 2013 at 10:25 AM, Not To Miss <not.to.miss at gmail.com> wrote: