使用`party`包运行`ctree`,列作为因子而不是字符

时间:2014-03-01 21:17:29

标签: r class dataframe classification multiple-columns

我已提及convert data.frame column format from character to factorConverting multiple data.table columns to factors in R以及Convert column classes in data.table

不幸的是它没有解决我的问题。我正在使用bodyfat数据集,我的数据框称为> BF。我添加了一个名为agegrp的专栏,将不同年龄段的人分类为年轻,中年或老年人:

bf$agegrp<-ifelse(bf$age<=40, "young", ifelse(bf$age>40 & bf$age<55,"middle", "old"))

这是ctree分析:

> set.seed(1234)
> modelsample<-sample(2, nrow(bf), replace=TRUE, prob=c(0.7, 0.3))
> traindata<-bf[modelsample==1, ]
> testdata<-bf[modelsample==2, ]
> predictor<-agegrp~DEXfat+waistcirc+hipcirc+kneebreadth` and ran, `bf_ctree<-ctree(predictor, data=traindata)
> bf_ctree<-ctree(predictor, data=traindata)

我收到以下错误:

Error in trafo(data = data, numeric_trafo = numeric_trafo, factor_trafo = factor_trafo,  : 
  data class character is not supported
In addition: Warning message:
In storage.mode(RET@predict_trafo) <- "double" : NAs introduced by coercion

由于bf$agegrp是“class”类,我跑了,

> bf$agegrp<-as.factor(bf$agegrp)

agegrp列现在被强制为因子。

> Class (bf$agegrp)提供[1] "Factor"

我尝试再次运行ctree,但它会抛出相同的错误。有谁知道问题的根本原因是什么?

1 个答案:

答案 0 :(得分:3)

这对我有用:

library(mboot)
library(party)
bf <- bodyfat
bf$agegrp <- cut(bf$age,c(0,40,55,100),labels=c("young","middle","old"))
predictor <- agegrp~DEXfat+waistcirc+hipcirc+kneebreadth

set.seed(1234)
modelsample <-sample(2, nrow(bf), replace=TRUE, prob=c(0.7, 0.3))
traindata   <-bf[modelsample==1, ]
testdata    <-bf[modelsample==2, ]
bf_ctree    <-ctree(predictor, data=traindata)
plot(bf_ctree)