# Understanding rpart package - unexpected behavior when swaping two columns in explanatory varaibles table

I have a problem understanding the behavior of rpart function of R.

Here is the r code part :

library(rpart);

library(rpart.plot)

data(ptitanic);

attr(ptitanic$age,"class") <- NULL; class(ptitanic$age);

#This is a function which draws the tree

arbre=function(data){

set.seed(415)

ptitanicTree  = rpart(survived~., data = data,
control = rpart.control(minsplit = 5, cp = 0),
method = "class")

ptitanicOptimal = prune(ptitanicTree,
cp = ptitanicTree$cptable[which.min(ptitanicTree$cptable[,4]),1] )

prp(ptitanicOptimal,extra=1)
}

data1=ptitanic[,c(1,2,3,4,5,6)];

arbre(data1)

# I change the position switching column 5 and 6
data2=ptitanic[,c(1,2,3,4,6,5)];

# Here i get an another tree : why ?
arbre(data2)


Is anyone able to explain why we get two different trees we have only changed the position of columns in data input ?

• You did not provide a reproducible example, there is no ptitanic data in base R, nor in rpart package. As about the results, they are nearly the same -- the only difference is that pruning returned one extra level. – Tim Jun 16 '17 at 14:24
• @tim : thank's I have edited the post, the data frame is in the R package rpart.plot (also used to plot the trees). Best regards – TheBridge Jun 16 '17 at 14:35
• By the way the parameter "cp" seems involved in this curious behavior but I can't explain how. regards – TheBridge Jun 16 '17 at 14:38
• You might get more responses if your change your title. Your title Understanding rpart package is too vague. A better title would be something like Why does rpart generate a different tree when the order of the variables in the data is changed?. – Stephen Milborrow Aug 10 '18 at 2:02