You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

关于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_fit class (used for obj) is part of the growthrates package, which includes a custom plot method tailored to handle objects of this type (and its parent growthrates_fit class). That's why plot(obj) works smoothly.
  • Your custom nonlinear class, however, has no associated plot method. When you call plot(obj2), R falls back to its default generic plot function, 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 22:07:27