2012-09-18 50 views
2

我有if/then語句描述一棵樹。例如:從規則構建/可視化樹

node1: if VAR1 < X node = 2 else node = 3 
node2: if VAR2 < Y node = 4 else node = 5 
node3: terminal value = Z 
... 

的不平等總是表現爲小於「<」。規則不一定按照樹的深度順序。

忽略解析語句的工作,在R中構建/可視化樹的最簡單方法是什麼?是否有一個對象/函數/包我可以調用一次每個規則迭代地建立樹,然後調用plot()?

+0

你看過派對包嗎? –

+0

尚未......感謝指針! – SFun28

+0

我不認爲你可以在沒有規則排序的情況下派生出一棵獨特的樹。 –

回答

0

從我先前得到評論擴大,這是plot.BinaryTree的例子在party包頂部:

set.seed(290875) 

    airq <- subset(airquality, !is.na(Ozone)) 
    airct <- ctree(Ozone ~ ., data = airq) 

    ### regression: boxplots in each node 
    plot(airct, terminal_panel = node_boxplot, drop_terminal = TRUE) 

並生成基於上述ctree命令下圖:

enter image description here

該軟件包有兩個相當體面的小插曲,應該讓你開始。

+0

謝謝,Dirk!這個軟件包中的視覺效果很好。 – SFun28

0

我試着深入pkg:party方法的代碼,但無法非常有效地遵循依賴關係。我認爲查看rpart軟件包代碼可能會更容易。 (編輯:進一步的思想會看的igraph包)。

require(rpart) 
fit <- rpart(Kyphosis ~ Age + Number + Start, data=kyphosis) 
print(fit) 
#------------ 
n= 81 

node), split, n, loss, yval, (yprob) 
     * denotes terminal node 

1) root 81 17 absent (0.79.20987654) 
    2) Start>=8.5 62 6 absent (0.90322581 0.09677419) 
    4) Start>=14.5 29 0 absent (1.00000000 0.00000000) * 
    5) Start< 14.5 33 6 absent (0.81818182 0.18181818) 
     10) Age< 55 12 0 absent (1.00000000 0.00000000) * 
     11) Age>=55 21 6 absent (0.71428571 0.28571429) 
     22) Age>=111 14 2 absent (0.85714286 0.14285714) * 
     23) Age< 111 7 3 present (0.42857143 0.57142857) * 
    3) Start< 8.5 19 8 present (0.42105263 0.57894737) * 
#---code resumes ------ 
plot(fit) 

enter image description here

rpart:::plot.rpart # will show the code ... depends on rpart::rpconvert 
rpart::rpconvert 
+0

謝謝!我有同樣的想法來解構rpart的作用,但認爲可能有更簡單的方法。 – SFun28

0

另一種選擇將是data.tree包。例如,你可以這樣做:

tree <- Node$new("node1") 
tree$AddChild("node2", edgeLabel = "VAR1 < X") 
tree$AddChild("node3", edgeLabel = "VAR1 >= X") 

print(tree, "edgeLabel") 

這將顯示爲:

levelName edgeLabel 
1 node1    
2 ¦--node2 VAR1 < X 
3 °--node3 VAR1 >= X 

或者是策劃:

SetEdgeStyle(tree, label = function(node) node$edgeLabel) 
plot(tree) 

Nodes

每個節點都可以存儲任何信息,從而對其進行解析時也是直截了當的,因爲你可以在解析時使用樹作爲路由器。