我想創建一個列印方法、列印物件類、顏色和 3d 表面公式。但是在物件呼叫中,這個表面公式需要像現在一樣,這就是使用的body原因substitute。所以我的方法正確列印了類和顏色,但是對于表面公式cat不起作用并print給出以下輸出closure:
function (x, y) 1 5*exp(-x^2 - y^2) <environment: 0x0000020dd971cd10>
我無法將此閉包轉換為字串或將其子集以僅提取表面公式1 5*exp(-x^2 - y^2)
幫助..
# object template
chrt <- function(domain, n, f, col, ...) {
x <- y <- seq(min(domain), max(domain), length.out = n)
fun <- function(x, y) {}
body(fun) <- substitute(f)
structure(list(x = x,
y = y, f = fun, col=col, ...),
class = "mychr")
}
# print method
print.mychr <- function(object) {
`%G%` <- paste0
cat("\nObject has class: " %G% class(object) %G%
", color: " %G% as.character(object$col) %G% "\n\n")
print(object$f)
}
# object call
chr1 <- chrt(c(-6, 6),
n = 30,
1 5*exp(-x^2 - y^2),
col = 'blue')
print(chr1)
uj5u.com熱心網友回復:
使用as.list并列印第三個元素,即公式。
print.mychr <- function(object) {
`%G%` <- paste0
cat("\nObject has class: " %G% class(object) %G%
", color: " %G% as.character(object$col) %G% "\n\n")
print(as.list(object$f)[[3]])
}
print(chr1)
# Object has class: mychr, color: blue
#
# 1 5 * exp(-x^2 - y^2)
uj5u.com熱心網友回復:
您可以deparse將body其f轉換為字符:
print.mychr <- function(object) {
`%G%` <- paste0
cat("\nObject has class: ", class(object),
", color: ", as.character(object$col),
", formula: ", deparse(body(object$f)))
}
# object call
chr1 <- chrt(c(-6, 6),
n = 30,
1 5*exp(-x^2 - y^2),
col = 'blue')
print(chr1)
#>
#> Object has class: mychr , color: blue , formula: 1 5 * exp(-x^2 - y^2)
由reprex 包于 2022-05-28 創建(v2.0.1)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/483879.html
