[英]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)
您可以進行一些調整。
do.call(f, list(x, y))
與使用f(x, y)
相同,因此您可以使用它,但是...print
方法保留函數f
的副本。 您可以將函數存儲為函數。structure
中以正確應用類屬性。print
方法中的對象,您需要使用$
或[[
運算符來引用它們plot
,而不是plot.chart
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.