是否可以基于一個類呼叫具有不同屬性的物件?例如,在這里我想zlab為一個物件而不是另一個物件具有屬性。我嘗試使用do.callwith structure,但正如我所想的那樣,它不起作用。或者也許它應該以其他方式構建?
chart <- function(domain, n, f, col, zlab, ...) {
x <- y <- seq(min(domain), max(domain), length.out = n)
fun <- function(x, y) {}
body(fun) <- substitute(f)
do.call(
lapply, structure(list(x = x, y = y, f = fun,
col=col, zlab = zlab, ...), ...),
class = "myChart")
}
# plot method
plot.myChart <- function(x, ...) {
z = outer(x$x, x$y, x$f)
persp(x$x, x$y, z, col = x$col, zlab = x$zlab, ...)
}
# object call
chr1 <- chart(c(-6, 6),
n = 30,
sqrt(x^2 y^2),
col = 'blue',
zlab = "Height")
chr2 <- chart(c(-5, 5),
n = 30,
x^2 y^2,
col = 'green')
plot(chr1)
plot(chr2)
uj5u.com熱心網友回復:
您可以簡單地為每個引數添加默認值,這樣如果任何一個被跳過,它們就有一個合理的回退。這有點困難f,但可以在函式內部使用missing,match.call和的組合來完成quote:
chart <- function(domain = c(-1, 1), n = 10, f, col = 'gray90', zlab = '', ...)
{
x <- y <- seq(min(domain), max(domain), length.out = n)
f <- if(missing(f)) quote(x y) else match.call()$f
structure(list(x = x, y = y, f = as.function(c(alist(x=, y=), f)),
col = col, zlab = zlab, ...),
class = "myChart")
}
# plot method
plot.myChart <- function(x, ...) {
z = outer(x$x, x$y, x$f)
persp(x$x, x$y, z, col = x$col, zlab = x$zlab, ...)
}
# object call
chr1 <- chart(c(-6, 6),
n = 30,
sqrt(x^2 y^2),
col = 'blue',
zlab = "Height")
chr2 <- chart(c(-5, 5),
n = 30,
x^2 y^2,
col = 'green')
plot(chr1)

plot(chr2)

請注意,我們甚至得到一個根本沒有傳遞任何引數的結果chart。
chr3 <- chart()
plot(chr3)

由reprex 包于 2022-05-30 創建(v2.0.1)
uj5u.com熱心網友回復:
也許這有幫助
chart <- function(domain, n, f, col, zlab, ...) {
x <- y <- seq(min(domain), max(domain), length.out = n)
fun <- function(x, y) {}
body(fun) <- substitute(f)
structure(c(list(x = x, y = y, f = fun, col=col, zlab = zlab),
c(...)), class = "myChart")
}
-測驗
chr1 <- chart(c(-6, 6),
n = 30,
sqrt(x^2 y^2),
col = 'blue',
zlab = "Height")
chr2 <- chart(c(-5, 5),
n = 30,
x^2 y^2,
zlab = NULL,
col = 'green')
plot(chr1)
plot(chr2)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/483876.html
上一篇:PythonOOP-更改類文本
