从rpart.object获取原始名称
我保存了使用R中的rpart包创建的模型。我正在尝试从这些保存的模型中检索一些信息;特别是从rpart.object。虽然文档很有帮助,但有一些事情尚不清楚:从rpart.object获取原始名称,r,rpart,R,Rpart,我保存了使用R中的rpart包创建的模型。我正在尝试从这些保存的模型中检索一些信息;特别是从rpart.object。虽然文档很有帮助,但有一些事情尚不清楚: 如何找出哪些变量是分类变量,哪些是数字变量?目前,我所做的是引用拆分矩阵中的“索引”列。我注意到,仅对于数值变量,条目不是整数。有没有更干净的方法 csplit矩阵指的是分类变量可以使用整数获取的各种值,即R将原始名称映射为整数。有没有办法访问此映射?例如,如果我的原始变量(例如,Country可以取任何值法国、德国、日本等),cspli
Country
可以取任何值法国、德国、日本等),csplit矩阵让我知道某个分割是基于Country==1、2
。在这里,rpart分别用1、2
替换了对法国、德国的引用。如何从模型文件中获取原始名称—法国、德国、日本
?另外,我如何知道名称和整数之间的映射是什么
一般来说,
术语
组件将具有此类信息<代码>请参见?rpart::rpart.object
fit <- rpart::rpart(Kyphosis ~ Age + Number + Start, data = kyphosis)
fit$terms # notice that the attribute dataClasses has the information
attr(fit$terms, "dataClasses")
#------------
Kyphosis Age Number Start
"factor" "numeric" "numeric" "numeric"
对注释的回应:如果您只有该模型,请使用str()查看它。在我创建的示例中,我看到一个“有序”叶,其因子标签存储在名为“xlevels”的属性中:
谢谢术语component确实明确地给出了变量类型。是否有办法访问名称到整数的映射?您需要帮助理解该短语的含义。为问题添加详细信息。再次感谢您的回答!要获取使用的级别名称,请使用
后凸$Numlev
。但在这个阶段,我只能访问模型文件。我没有数据。如果你调用fit
> fit <- rpart::rpart(Kyphosis ~ Age + factor(findInterval(Number,c(0,4,6,Inf))) + Start, data = kyphosis)
> fit$csplit
[,1] [,2] [,3]
[1,] 1 1 3
[2,] 1 1 3
[3,] 3 1 3
[4,] 1 3 3
[5,] 3 1 3
[6,] 3 3 1
[7,] 3 1 3
[8,] 1 1 3
> attr(fit$terms, "dataClasses")
Kyphosis
"factor"
Age
"numeric"
factor(findInterval(Number, c(0, 4, 6, Inf)))
"factor"
Start
"numeric"
> kyphosis$Numlev <- factor(findInterval(kyphosis$Number, c(0, 4, 6, Inf)), labels=c("low","med","high"))
> str(kyphosis)
'data.frame': 81 obs. of 5 variables:
$ Kyphosis: Factor w/ 2 levels "absent","present": 1 1 2 1 1 1 1 1 1 2 ...
$ Age : int 71 158 128 2 1 1 61 37 113 59 ...
$ Number : int 3 3 4 5 4 2 2 3 2 6 ...
$ Start : int 5 14 5 1 15 16 17 16 16 12 ...
$ Numlev : Factor w/ 3 levels "low","med","high": 1 1 2 2 2 1 1 1 1 3 ...
> fit <- rpart::rpart(Kyphosis ~ Age +Numlev + Start, data = kyphosis)
> Levels <- fit$csplit
> Levels[] <- levels(kyphosis$Numlev)[Levels]
> Levels
[,1] [,2] [,3]
[1,] "low" "low" "high"
[2,] "low" "low" "high"
[3,] "high" "low" "high"
[4,] "low" "high" "high"
[5,] "high" "low" "high"
[6,] "high" "high" "low"
[7,] "high" "low" "high"
[8,] "low" "low" "high"
$ ordered : Named logi [1:3] FALSE FALSE FALSE
..- attr(*, "names")= chr [1:3] "Age" "Numlev" "Start"
- attr(*, "xlevels")=List of 1
..$ Numlev: chr [1:3] "low" "med" "high"
- attr(*, "ylevels")= chr [1:2] "absent" "present"
- attr(*, "class")= chr "rpart"