rprintingr-glue

Why printing with glue doesn't show array element?


Why

> print("hello")
[1] "hello"

shows a [1] at the start and the string quoted, while:

> library(glue)
> print(glue("hello"))
hello

doesn't?


Solution

  • Glue objects have their own print method, look at print.glue()

    #' @export
    print.glue <- function(x, ..., sep = "\n") {
      x[is.na(x)] <- style_na(x[is.na(x)])
    
      if (length(x) > 0) {
        cat(x, ..., sep = sep)
      }
    
      invisible(x)
    }
    

    You will see that it uses cat which usually does not show the [1]. This [1] indicates the first index of a character printed to console like in print("hello").

    Let's compare

    I commented out the style_na part, and it gives

    print.glue <- function(x, ..., sep = "\n") {
      #x[is.na(x)] <- style_na(x[is.na(x)])
      
      if (length(x) > 0) {
        cat(x, ..., sep = sep)
      }
      
      invisible(x)
    }
    
    > print.glue("Hello")
    Hello
    > print("Hello")
    [1] "Hello"