7

I'm trying to make a formula and I got the error:

$ operator not defined for this S4 class with R.

First of all, what is a S4 class? What am I doing wrong?

Following the code:

as.formula("ctree(d$sex ~ d$ahe , data = d)")

If you want to reproduce it, the dataset (CSV file) d is available here.

Abel Callejo
  • 13,779
  • 10
  • 69
  • 84
Reinaldo Maciel
  • 73
  • 1
  • 1
  • 3

1 Answers1

8

You are giving as.formula the wrong input here. Only d$sex ~ d$ahe should be a formula, so:

ctree(as.formula("d$sex ~ d$ahe"))

Or:

ctree(as.formula("sex ~ ahe"), data = d)
slamballais
  • 3,161
  • 3
  • 18
  • 29
  • 3
    The second option is prefered and usually safer. – Roland Apr 20 '16 at 08:22
  • 1
    This answer doesn't tell about `First of all, what is a S4 class?` – Abel Callejo Jan 21 '20 at 02:15
  • 1
    @AbelCallejo That's because the S4 object has nothing to do with `What am I doing wrong here?`. It's just the error that OP got from misapplying the code, and it could have been a completely different error had OP used a different function than `ctree`. – slamballais Jan 23 '20 at 12:40
  • ... or even simpler `ctree(sex ~ ahe, data = d)`? – Gregor Thomas Jan 23 '20 at 22:01
  • @Gregor-reinstateMonica That could also work, but OP specifically used a string and `as.formula`. (This setup has the unique advantage that you can make strings a priori and then supply them to a function that takes formulas, whereas your answer is hard-coded.) – slamballais Jan 26 '20 at 10:29