Ctree R function is not working with my for loop

109 views Asked by At

I wanted to make a list for for loop, than I wanted to use it for ctree like below. but I couldn't. I am getting, some errors like "character is not supported" even I change the list to factor

I want to change val variable, with the y list, for for loop.

Is there anyway to make it work?

y <- c("A","B","C")
x <- as.factor(y)
for(val in x) {
      ctree_model<- ctree(FTR ~ val, data = train,controls=ctree_control(minsplit=30,minbucket=10,maxdepth=10))
    }
1

There are 1 answers

15
akrun On BEST ANSWER

The formula should be constructed either with paste or reformulate. In addition, the 'ctree_model' for storing the output can be a list with each element of list stores the model that corresponds to the 'val' of x instead of overriding

ctree_model <- vector('list', length(x))
names(ctree_model) <- levels(x)
for(val in levels(x)) {
   ctree_model[[val]] <- ctree(reformulate(val, response = 'FTR'), 
            data = train, 
     controls = ctree_control(minsplit = 30, minbucket = 10, maxdepth  =10))
 }