在R中打印函数的方法,即使函数输出被赋值给对象,也会打印摘要



我正在创建一个新的R包,并添加一个函数,将产生一个列表。下面是这个函数如何工作的例子。我为这个函数分配了一个print方法,该方法提供了输出的单独解释/描述性摘要。请看下面的例子。

fun_example <- function(xvar, yvar){
# Plots
plot1 = ggplot2::ggplot(data.frame(xvar, yvar), ggplot2::aes(x = xvar, y = yvar)) + ggplot2::geom_line()
plot2 = ggplot2::ggplot(data.frame(xvar, yvar), ggplot2::aes(x = xvar, y = yvar)) + ggplot2::geom_line()
plots <- list(plot1, plot2)

# Correlation
Cor <- cor(xvar, yvar)

result <- list(plots, Cor)
names(result) <- c("plots", "Cor")
class(result) <- "fun_example"
suppressMessages(return(result))
}
#-------------------------------------------
## S3Methods print() // Updated 06.02.2021
#-------------------------------------------
#' S3Methods for Printing
#'
#' @name prints
#'
#' @aliases
#' print.fun_example
#'
#' @usage
#' method{print}{fun_example}(x, ...)
#'
#' @description Prints for code{package_example} objects
#'
#' @param x Object from code{package_example} package
#'
#' @param ... Additional arguments
#'
#' @return Prints code{package_example} object
#'
# Print fun_example
#' @export
print.fun_example <- function(x, ...){
cat("Visually inspect each plot in the plots object to check for linearity.n")
if(x$Cor > 0.8){
cat("A correlation greater than 0.8 was found.")
} else {
cat("A correlation less than or equal to 0.8 was found.")
}
}

问题:

当函数本身运行且未赋值给对象时,print函数按预期工作。实际的输出(一个列表)不会出现在控制台中。但是,函数的用户应该将其保存到一个对象中。

> fun_example(xvar = 1:3, yvar = 4:6)
Visually inspect each plot in the plots object to check for linearity.
A correlation greater than 0.8 was found.

当函数的输出被分配给一个对象时,输出(列表)被分配给一个对象,但是print方法在控制台中不显示任何内容。

> test <- fun_example(xvar = 1:3, yvar = 4:6)
> 

我想看的:

我想做的是指定打印方法,这样列表将被分配给一个对象,打印将显示在控制台中,例如:

> test <- fun_example(xvar = 1:3, yvar = 4:6)
Visually inspect each plot in the plots object to check for linearity.
A correlation greater than 0.8 was found.

用户可以手动输入下面的示例,将赋值值放在括号中,但我宁愿让函数自动完成。

> (test <- fun_example(xvar = 1:3, yvar = 4:6))
Visually inspect each plot in the plots object to check for linearity.
A correlation greater than 0.8 was found.

在函数中指定打印而不是使用打印方法是行不通的。

如有任何帮助,不胜感激。

根据@MrFlick的评论,我将函数更改为:

fun_example <- function(xvar, yvar){
# Plots
plot1 = ggplot2::ggplot(data.frame(xvar, yvar), ggplot2::aes(x = xvar, y = yvar)) + ggplot2::geom_line()
plot2 = ggplot2::ggplot(data.frame(xvar, yvar), ggplot2::aes(x = xvar, y = yvar)) + ggplot2::geom_line()
plots <- list(plot1, plot2)

# Correlation
Cor <- cor(xvar, yvar)
message("Visually inspect each plot in the plots object to check for linearity.n")
if(x$Cor > 0.8){
message("A correlation greater than 0.8 was found.")
} else {
message("A correlation less than or equal to 0.8 was found.")
}

result <- list(plots, Cor)
names(result) <- c("plots", "Cor")
class(result) <- "fun_example"
suppressMessages(return(result))
}

请注意,如果消息没有在return()函数之前出现,这对我不起作用。

最新更新