2015-08-17 47 views
1

我创建使用软件rpart在R.我还可以打印出来使用path.rpart()函数的决策树产生的规则决策树的元组。要获得其遵循特定规则决策树中的R

对于airquality数据,我有规则的输出作为

$`8` 
[1] "root"   "Temp< 82.5" "Wind>=7.15" "Solar.R< 79.5" 

$`18` 
[1] "root"   "Temp< 82.5" "Wind>=7.15" "Solar.R>=79.5" 
[5] "Temp< 77.5" 

$`19` 
[1] "root"   "Temp< 82.5" "Wind>=7.15" "Solar.R>=79.5" 
5] "Temp>=77.5" 

$`5` 
[1] "root"  "Temp< 82.5" "Wind< 7.15" 

等。

有没有一种方法,我可以写这使我的初始表airquality这些约束来获得其遵循这些规则 这将等同于

airquality[which(airquality$Temp<82.5 & airquality$Wind>=7.15 & Solar.R<79.5)] 

为先治行的代码。

任何帮助,非常感谢。提前致谢。

回答

2
rules = rpart(airquality)  
table(rules$where) 
airquality[rules$where==6,] 

你会给你没有编码规则的拆分数据帧吗?我不确定这是不是你想要的。

+0

是的,它有帮助。谢谢! – Sankalp

3

path.rpart给出了一个很好的概述,但MrFlick已经写了一些代码来显示其观察落在特定的节点。看看here

这只看rpart树。为了查看预测值落在哪个节点上,请看this post

查看我包含的示例代码。该功能来自第一个答案。第二个答案的最后一部分。

library(rpart) 

# split kyphosis into 2 for example 
train <- kyphosis[1:60, ] 
test <- kyphosis[-(1:60), ] 
fit <- rpart(Kyphosis ~ Age + Number + Start, data = train) 

# Show nodes 
print(fit) 

# function to show observations that fall in a node 
# https://stackoverflow.com/questions/23924051/find-the-data-elements-in-a-data-frame-that-pass-the-rule-for-a-node-in-a-tree-m 
subset_rpart <- function (tree, df, nodes) { 
     if (!inherits(tree, "rpart")) 
      stop("Not a legitimate \"rpart\" object") 
     stopifnot(nrow(df)==length(tree$where)) 
     frame <- tree$frame 
     n <- row.names(frame) 
     node <- as.numeric(n) 

     if (missing(nodes)) { 
      xy <- rpart:::rpartco(tree) 
      i <- identify(xy, n = 1L, plot = FALSE) 
      if(i> 0L) { 
        return(df[tree$where==i, ]) 
      } else { 
        return(df[0,]) 
      } 
     } 
     else { 
      if (length(nodes <- rpart:::node.match(nodes, node)) == 0L) 
        return(df[0,]) 
      return (df[tree$where %in% as.numeric(nodes), ]) 
     } 
} 

subset_rpart(fit, train, 7) 


# Find the nodes in which the test observations fall 
# https://stackoverflow.com/questions/13690201/how-to-count-the-observations-falling-in-each-node-of-a-tree?lq=1 
nodes_fit <- fit 
nodes_fit$frame$yval <- as.numeric(rownames(nodes_fit$frame)) 
testnodes <- predict(nodes_fit, test, type="vector") 
print(testnodes)