代码之家  ›  专栏  ›  技术社区  ›  ayman

R中的print()命令是否可以静默?

  •  8
  • ayman  · 技术社区  · 16 年前

    在R中,有些函数可以打印信息和返回值,是否可以取消打印?

    print.and.return <- function() {
      print("foo")
      return("bar")
    }
    

    退货

    > print.and.return()
    [1] "foo"
    [1] "bar"
    > 
    

    我可以将退货存储为:

    > z <- print.and.return()
    [1] "foo"
    > z
    [1] "bar"
    > 
    

    我可以抑制打印吗 "foo" ?

    5 回复  |  直到 12 年前
        1
  •  11
  •   mbq    16 年前

    您可以使用R的隐藏函数性质,例如通过定义函数

    deprintize<-function(f){
     return(function(...) {capture.output(w<-f(...));return(w);});
    }
    

    将“打印”功能转换为“静默”功能:

    noisyf<-function(x){
     print("BOO!");
     sin(x);
    }
    
    noisyf(7)
    deprintize(noisyf)(7)
    deprintize(noisyf)->silentf;silentf(7)
    
        2
  •  9
  •   Collin    16 年前
    ?capture.output
    
        3
  •  3
  •   Vince    16 年前

    print.and.return <- function(..., verbose=TRUE) {
      if (verbose) 
        print("foo")
      return("bar")
    }
    
    
    > print.and.return()
    [1] "foo"
    [1] "bar"
    > print.and.return(verbose=FALSE)
    [1] "bar"
    > 
    
        4
  •  3
  •   Richie Cotton Joris Meys    16 年前

    我同意哈德利和mbq的建议 capture.output message 而不是 print . 这样就可以用 suppressMessages .

    print.and.return2 <- function() {
      message("foo")
      return("bar")
    }
    
    # Compare:
    print.and.return2()
    suppressMessages(print.and.return2())
    
        5
  •  3
  •   NelsonGon phoxis    6 年前

    它和 return()

    invisible(variable)
    

    因此,以@ayman为例:

    print.and.return2 <- function() {
      message("foo")
      invisible("bar")
    }