关于growthrates包中getClass("nonlinear_fit")功能及自定义类plot报错的问询
Hey there! Let's break down your questions about the growthrates package and your custom S4 class issue:
1. What does getClass("nonlinear_fit") do?
In R's S4 object system, getClass("nonlinear_fit") retrieves the full definition of the nonlinear_fit class from the growthrates package. This includes:
- Its inheritance hierarchy (your console output shows it extends
growthrates_fit, meaning it inherits all slots and methods from that parent class) - The slots (data components) that objects of this class must contain (like
fit,par,FUN, etc., which you're already using when creating instances) - Any class-specific metadata or constraints
It's a handy way to inspect how the package's core objects are structured, which helps when working with or extending the package's functionality.
2. Why does plot(obj2) throw an error?
The error Error in as.double(y) : cannot coerce type 'S4' to vector of type 'double' happens because:
- The
nonlinear_fitclass (used forobj) is part of thegrowthratespackage, which includes a customplotmethod tailored to handle objects of this type (and its parentgrowthrates_fitclass). That's whyplot(obj)works smoothly. - Your custom
nonlinearclass, however, has no associatedplotmethod. When you callplot(obj2), R falls back to its default genericplotfunction, which doesn't know how to interpret your S4 object's structure—hence the coercion error when it tries to treat the S4 object as a numeric vector.
Fixes you can try:
Option 1: Inherit from the package's base class
Let your nonlinear class inherit from growthrates_fit (just like nonlinear_fit does). This way, it will automatically inherit all existing methods (including plot) from the parent class:
setClass("nonlinear", contains = "growthrates_fit", representation( fit = "modFit", par = "numeric", FUN = "function_growthmodel", obs = "data.frame", rsquared = "numeric" ))
Option 2: Write a custom plot method for your class
If you want full control over the plotting behavior, define a specific plot method for your nonlinear class. Here's a basic example that plots your observed data and the fitted curve:
setMethod("plot", signature(x = "nonlinear"), function(x, main = "Custom Nonlinear Growth Fit", ...) { # Plot observed data plot(x@obs$time, x@obs$y, pch = 16, col = "black", main = main, xlab = "Time", ylab = "Growth", ...) # Add the fitted curve curve(x@FUN(x = x, par = x@par), add = TRUE, col = "red", lwd = 2) })
After implementing either option, plot(obj2) should work as expected.
内容的提问来源于stack exchange,提问作者Chang il

