Pretty printing in R using the Format function.

In the previous tutorial we looked at printing R objects using the print and cat functions. In this tutorial we look at Pretty printing in R using the Format function.. If R encounters a custom object then it calls the toString() generic method of that object. The sprintF method is a wrapper over C’s sprintf method and can be used to combine strings and variables into a formatted string. We will cover that in one of the blog articles later. For now lets look at the format() function.

Using the format() function for pretty printing in R

Lets see how formatting applies to various objects.

  • Formatting a numeric vector

    The vector was formatted such that all elements occupy at least two places since that is the maximum number of digits in the vector. (number 10). use Trim to suppress that

    In first example above the maximum number of digits after decimal is 3 so 0 is apended to other elements that do not have 3 digits after decimal place. For the second example all numbers had 0 as the last digit and is therefore removed by the format function. In the last example the number is formatted to 2 digits.
  • Formatting a character vector

    Similar to a numeric vector make them of equal length. You can also change the justification

    If you have a factor, then the factor is first converted to a character vector and then the factor function is applied.
  • Formatting a data frame.

    To format a data frame, format is applied to all columns depending on their type

  • Formatting a List

    The list, if it contains sublists, is expanded while formatting

Leave a Reply

Your email address will not be published. Required fields are marked *