How to do printf in r?

后端 未结 4 1557
青春惊慌失措
青春惊慌失措 2020-12-15 15:24

I\'m looking for how to do printf in r, ie I want to type:

printf(\"hello %d\\n\", 56 )

and get the same output as typing:

         


        
相关标签:
4条回答
  • 2020-12-15 15:45
    printf <- function(...) invisible(print(sprintf(...)))
    

    The outer invisible call may be unnecessary, I'm not 100% clear on how that works.

    0 讨论(0)
  • 2020-12-15 15:45

    My solution:

    > printf <- function(...) cat(sprintf(...))
    > printf("hello %d\n", 56)
    hello 56
    

    The answers given by Zack and mnel print the carriage return symbol as a literal. Not cool.

    > printf <- function(...) invisible(print(sprintf(...)))
    > printf("hello %d\n", 56)
    [1] "hello 56\n"
    > 
    > printf <- function(...)print(sprintf(...))
    > printf("hello %d\n", 56)
    [1] "hello 56\n"
    
    0 讨论(0)
  • 2020-12-15 15:45

    If you want a function that does print(sprintf(...)), define a function that does that.

    printf <- function(...)print(sprintf(...))
    
    
    printf("hello %d\n", 56)
    ## [1] "hello 56\n"
     d <- printf("hello %d\n", 56)
    ## [1] "hello 56\n"
    d
    ## [1] "hello 56\n"
    
    0 讨论(0)
  • 2020-12-15 16:04

    I do it this way:

    printf = function(s, ...) cat(paste0(sprintf(s, ...)), '\n')
    
    0 讨论(0)
提交回复
热议问题