Rico
Rico

Reputation: 43

R predict func type="class" error

I'm working with a data set to try to be able to fit a classification tree I split the data set:

set.seed(2)
train=sample(1:nrow(mydata),nrow(mydata)/2)
test=-train
training_data=mydata[train,]
testing_data=mydata[test,]
testing_Donates=Donates[test]

After doing that I made a tree model:

tree_model=tree(Donates~.,training_data)
plot(tree_model)
text(tree_model)

Then I tried using the predict function:

tree_pred<- predict(tree_model, testing_data, type="class")

but I keep receiving an error :

Error in predict.tree(tree_model, testing_data, type = "class") :
type "class" only for classification trees

can someone tell me what is wrong and how I could fix this?

Upvotes: 2

Views: 10980

Answers (2)

junior
junior

Reputation: 1

Or you could also used "vector" and it will work perfectly.

If you are working with a regression tree, you should use type = "vector" instead of type = "class" when calling the predict() function.

Hope it help ...

Upvotes: 0

user2696806
user2696806

Reputation: 166

I just had the same issue today and this post is all I could find. Turns out R automatically views integers as interval variables, even though you might sometimes want to view them as categorical values. You can force this by using

as.factor(x)

on the list of categorical integer values. So when creating the model use:

tree_model=tree(as.factor(Donates)~.,training_data)

Upvotes: 4

Related Questions