Is it Possible to Create S4 Function Objects?
I've completed the S4 example.
Thank you, Herve, for your assistance.
----begin code----
plotf <- function (f)
{ x <- seq (-1, 1,, 200)
plot (x, f (x), type="l")
}
#s4-based function object, with slot
setClass ("Quad.S4", contains="function", slots = list (p="numeric") )
Quad.S4 <- function (p = c (0, 0, 1) )
{ f <- function (x)
{ this <- sys.function ()
p <- this at p
p [1] + p [2] * x + p [3] * x^2
}
new ("Quad.S4", f, p=p)
}
f.s4 <- Quad.S4 ()
plotf (f.s4)
f.s4 at p
On Tue, Feb 23, 2021 at 11:23 AM Abby Spurdle (/??bi/)
<spurdle.a at gmail.com> wrote:
Oh wow. Post of the year! Where's the like button? Note, I was able to rewrite it without the deprecated args. (Don't want one of those CRAN emails, in 12 months from now, saying please change XXXX). I'll have to come back to this later, to see if I can get the body of f() to access the slot On Mon, Feb 22, 2021 at 11:36 AM Herv? Pag?s <hpages.on.github at gmail.com> wrote:
Hi Abby,
Something along the line of:
setClass("S4Function",
contains="function",
representation(name="character", more_stuff="ANY")
)
seems to do what you want:
f <- new("S4Function", function(a) a^2, name="square")
# 'f' is both an S4 object and a function:
is.object(f)
# [1] TRUE
is.function(f)
# [1] TRUE
f at name
# [1] "square"
f(11)
# [1] 121
Hope this helps,
H.