Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/76.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何解决使用R构建决策树的问题_R_Machine Learning_Decision Tree - Fatal编程技术网

如何解决使用R构建决策树的问题

如何解决使用R构建决策树的问题,r,machine-learning,decision-tree,R,Machine Learning,Decision Tree,我使用R构建了一个决策树模型,当预测值大于50%时,我想在树中添加一个新列,并在该列中打印yes 注意:数据集中的目标coulmun是布尔值1=心脏病,0=正常 library(rpart) tree<-rpart(target ~ .,method ='class', data=train) print(summary(tree)) tree.preds<-predict(tree,test) print(head(tree.preds)) tree.preds<-as.d

我使用R构建了一个决策树模型,当预测值大于50%时,我想在树中添加一个新列,并在该列中打印yes

注意:数据集中的目标coulmun是布尔值1=心脏病,0=正常

library(rpart)
tree<-rpart(target ~ .,method ='class', data=train)
print(summary(tree))
tree.preds<-predict(tree,test)
print(head(tree.preds))

tree.preds<-as.data.frame(tree.preds)
joiner<-function(x){
  if(x>=0.5)
    return('yes')
    
  else
    return('no')
      
}
tree.preds$disease<-sapply(tree.preds$yes,joiner)

print(head(tree.preds))
库(rpart)

树您可以使用
ifelse
代替使用
sapply
进行迭代:

library(rpart)

dat = iris[,-5]
dat$target = as.numeric(iris$Species=="versicolor")
idx = sample(nrow(dat),100)
train = dat[idx,]
test = dat[-idx,]

tree = rpart(target ~ .,method ='class', data=train)
tree.preds = data.frame(predict(tree,test))
tree.preds$Species = ifelse(tree.preds[,2]>0.5,"yes","no")

欢迎来到SO。请参阅如何创建一个。
library(rpart)

dat = iris[,-5]
dat$target = as.numeric(iris$Species=="versicolor")
idx = sample(nrow(dat),100)
train = dat[idx,]
test = dat[-idx,]

tree = rpart(target ~ .,method ='class', data=train)
tree.preds = data.frame(predict(tree,test))
tree.preds$Species = ifelse(tree.preds[,2]>0.5,"yes","no")