基于一个 class 具有不同属性的调用对象

Call objects based on one class with the different attributes

是否可以根据一个来调用不同属性的对象class? 例如,我想为一个对象而不是另一个对象设置 zlab 属性。 我尝试将 do.callstructure 一起使用,但它不起作用,正如我所想的那样。或者也许它应该以其他方式构建?

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)

也许这有帮助

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)

您可以简单地为每个参数添加默认值,这样如果有任何参数被跳过,它们就有一个合理的回退。使用 f 有点困难,但可以使用 missingmatch.callquote:

的组合在函数内部完成
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 package (v2.0.1)

于 2022-05-30 创建