2
votes

I get Error: $ operator not defined for this S4 class when I try to run a ctree from the party package, but only when the formula is writen as a string that I transform using as.formula().

Below the example :

#This works fine :
y <- ctree(formula = quotation ~ minute + temp, data=test[[1]], controls = ctree_control(mincriterion = 0.99))

#While this doesn't :
x <- "ctree(formula = quotation ~ minute + temp, data=test[[1]], controls = ctree_control(mincriterion = 0.99))"

y <- as.formula(x)
Error: $ operator not defined for this S4 class

My ultimate purpose is to create a function that iterates through the list test to create multiple trees.

Any idea ?

1
The as.formula only applies to the formula part. So it should be x <- as.formula(quotation ~ minute + temp); and the line after y <- ctree(formula=x, ...). For example if I use iris data set, it would be: x1 <- as.formula(Species ~ Petal.Length + Petal.Width);y1 <- ctree(formula = x1, data=iris) - chappers
Thanks for your answer, but how is ctree considered if not as a formula ? I need to iterate outside of the scope of what you described as x. - Yohan Obadia
I would recommend you check out the caret package. It has train function with tuneGrid argument which sounds like what you're after. - chappers

1 Answers

1
votes

ctree is a function and not a formula. formula is the class of the object resulting from the function '~' (tilde). You can learn more about formulas from help('~') and help('formula').

The most common way to use as.formula is to convert a string that represents the formula syntax to an object of class formula. Something like as.formula('y ~ x'). Also, check class(as.formula(y~x)).

In your case you saved a string representing function ctree to variable x. Function ctree only contains a string representing a formula syntax (quotation ~ minute + temp) but it cannot be coerced to formula (it does not represent a formula, it just contains a formula syntax string) because it does not follow the formula syntax.

If you want to execute a function from text you need to use eval(parse(text = x)) although this technique is not encouraged..