【问题标题】:Running `ctree` using `party` package, column as factor and not character使用“party”包运行“ctree”,列作为因子而不是字符
【发布时间】:2014-04-02 22:49:08
【问题描述】:

我已经推荐了convert data.frame column format from character to factorConverting multiple data.table columns to factors in RConvert 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 是我跑的“字符”类,

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

agegrp 列现在被强制转换为因子。

&gt; Class (bf$agegrp) 给出[1] "Factor"

我尝试再次运行ctree,但它引发了同样的错误。有谁知道问题的根本原因是什么?

【问题讨论】:

  • 试试br$agegrp &lt;- as.factor(bf$agegrp)
  • 这将创建一个新变量。我将如何在我现有的 bf 数据框中使用它来运行 c-tree?
  • @jlhoward bf$agegrp&lt;-as.factor(bf$agegrp) 返回 bf$agegrp 作为因子,但我的 ctree 返回相同的错误!
  • 对不起,错字:我的意思是bf$agegrp &lt;- as.factor(bf@agegrp)
  • 我会尝试从头顶上拿下整个东西!

标签: r class dataframe classification multiple-columns


【解决方案1】:

这对我有用:

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)

【讨论】:

  • 加油!问题似乎在于我将变量$agegrpifelse 添加的方式。知道为什么这可能会导致问题吗?
  • 并非如此。因子水平与as.factor(ifelse(...ifelse(...))) 的顺序不同。也许这与它有关。
猜你喜欢
  • 2014-04-27
  • 2021-07-20
  • 1970-01-01
  • 2013-08-26
  • 2018-07-18
  • 2018-05-17
  • 1970-01-01
  • 2019-02-20
  • 1970-01-01
相关资源
最近更新 更多