在R函数中,在return()语句后打印(一些文本)

use*_*672 1 text r return function

f <- function(x){
  print(paste0("x is: ",x))
  return(mean(rnorm(x))) #return() not neccessary
}
Run Code Online (Sandbox Code Playgroud)

然后,

set.seed(8)
f(5)
Run Code Online (Sandbox Code Playgroud)

输出:

[1] "x is: 5"
[1] 0.09550734
Run Code Online (Sandbox Code Playgroud)

我怎样才能使print语句出现在函数结果之后,所以输出将是:

[1] 0.09550734
[1] "x is: 5"
Run Code Online (Sandbox Code Playgroud)

可以在不将文本作为return参数一部分放置的情况下,在同一函数中完成此操作吗?

小智 5

将函数更改为不可见地返回,并用于print按所需顺序显示事物:

f <- function(x) {
  out <- mean(rnorm(x))
  print(out)
  print(paste("x is:", x))
  invisible(out)
}
Run Code Online (Sandbox Code Playgroud)