Search code examples
rstringcoercion

Outside of format, should toString ever be used?


The very first line of the documentation for toString clearly calls it a helper function for the format function. Does this suggest that it should never be used outside of the internal code for the format function? If so, why does R leave it available to useRs?


Solution

  • You are actually asking 2 questions:

    1. should toString be used outside of format?
    2. why is it available to users of R?

    Regarding 1., see @Rui Barradas comment, you can use it outside of format and there are apparently usecases. This answers also 2., but there is actually a second reason, also stated in the help:

    This is a generic function for which methods can be written: only the default method is described here.

    This means that it is accessible to the users so that they can easily expand it. E.g. say that you're not satisfied with the functionality of toString.default for matrix objects:

    test_matrix <- matrix(1:4, ncol = 2)
    test_matrix
         [,1] [,2]
    [1,]    1    3
    [2,]    2    4
    
    toString(test_matrix)
    [1] "1, 2, 3, 4"
    

    It operates columnwise, but you want the ability to choose if it should operate rowwise or columnwise. Now you can easily expand it by writing a new S3 method for matrix objects:

    toString.matrix <- function(x, width = NULL, rowwise = TRUE) {
      if (rowwise) {
        marg <- 1
      } else {
        marg <- 2
      }
      temp <- apply(x, marg, paste, collapse = ", ")
      string <- paste(temp, collapse = ", ")
      
      if (missing(width) || is.null(width) || width == 0) 
        return(string)
      if (width < 0) 
        stop("'width' must be positive")
      if (nchar(string, type = "w") > width) {
        width <- max(6, width)
        string <- paste0(strtrim(string, width - 4), "....")
      }
      string
    }
    
    toString(test_matrix)
    [1] "1, 3, 2, 4"
    
    toString(test_matrix, rowwise = FALSE)
    [1] "1, 2, 3, 4"