2016-04-04 160 views
0

正在關注my question 我想知道我應該添加什麼來獲取節點的值並將它連接到它的名字。 我有一個J48決策樹:獲取J48的屬性值

library(RWeka) 
data(iris) 
res = J48(Species ~., data = iris) 
> res 
J48 pruned tree 
------------------ 

    Petal.Width <= 0.6: setosa (50.0) 
Petal.Width > 0.6 
| Petal.Width <= 1.7 
| | Petal.Length <= 4.9: versicolor (48.0/1.0) 
| | Petal.Length > 4.9 
| | | Petal.Width <= 1.5: virginica (3.0) 
| | | Petal.Width > 1.5: versicolor (3.0/1.0) 
| Petal.Width > 1.7: virginica (46.0/1.0) 

Number of Leaves :  5 

Size of the tree : 9 

,並得到結果如下字符串:

(Petal.Width () Petal.Width (Petal.Length () Petal.Width ())) 

我想獲得以下(值的串聯):

(Petal.Width0.6 () Petal.Width1.7 (Petal.Length4.9 () Petal.Width1.5 ())) 

下面是我使用的代碼:

library("partykit") 
pres <- as.party(res) 
partykit:::.list.rules.party(pres) 

nam <- names(pres$data) 
tr <- as.list(pres$node) 
str <- "(" 
update_str <- function(x) { 
    if(is.null(x$kids)) { 
    str <<- paste(str, ")") 
    } else { 
    str <<- paste(str, nam[x$split$varid], "(") 
    for(i in x$kids) update_str(tr[[i]]) 
    } 
} 
update_str(tr[[1]]) 
    > str 
[1] "(Petal.Width () Petal.Width (Petal.Length () Petal.Width ()))" 

回答

0

只需更改遞歸:

update_str <- function(x) { 
    if(is.null(x$kids)) { 
    str <<- paste(str, ")") 
    } else { 
    str <<- paste(str, nam[x$split$varid], x$split$breaks, "(") 
    for(i in x$kids) update_str(tr[[i]]) 
    } 
} 

update_str(tr[[1]]) 

> str 
[1] "(Petal.Width 0.6 () Petal.Width 1.7 (Petal.Length 4.9 () Petal.Width 1.5 ()))"