簡體   English   中英

S3 模板,可以將不同的公式和數值向量作為參數

[英]S3 template which can take different formulas and numeric vectors as arguments

請幫助我使我的代碼正常工作。 在這里,我試圖創建一個 S3 模板,它可以將不同的公式和數字向量作為參數。 我還想添加一個繪圖方法,繪制結果圖。 現在它拋出一個錯誤:

Error in do.call(f, list(x, y)) : 'what' must be a function or character string

如何在此處正確使用 do.call?

# template
chart <- function(x, y, f, ...) {
list(x, y,
do.call(f, list(x, y)),
class = "myChart")
}

# plot method
plot.myChart <- function(obj, ...) {
persp(x, y, z = outer(x, y, f))
}

# new object
c <- chart(seq(-6, 6, length = 100),
seq(-6, 6, length = 100),
f=sqrt(x^2+y^2))
c
plot.myChart(c)

您可以進行一些調整。

  1. 使用do.call(f, list(x, y))與使用f(x, y)相同,因此您可以使用它,但是...
  2. ...您可能根本不想在創建對象期間調用該函數,因為這只會創建一個您似乎不使用的未命名數據成員。
  3. 您需要為print方法保留函數f的副本。 您可以將函數存儲為函數。
  4. 最好命名對象的元素,並將其包裝在structure中以正確應用類屬性。
  5. 要訪問print方法中的對象,您需要使用$[[運算符來引用它們
  6. 您只需要調用plot ,而不是plot.chart
  7. f在對象創建期間需要是一個函數。 您正在傳遞一個函數調用
chart <- function(x, y, f, ...) {
  structure(list(x = x, y = y, f = f), class = "myChart")
}

# plot method
plot.myChart <- function(obj, ...) {
  persp(obj$x, obj$y, z = outer(obj$x, obj$y, obj$f), ...)
}

# new object
ch <- chart(x = seq(-6, 6, length = 100),
            y = seq(-6, 6, length = 100),
            f = function(x, y) sqrt(x^2 + y^2))

plot(ch)

在此處輸入圖像描述

reprex 包於 2022-05-10 創建 (v2.0.1)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM