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

    > a=c(1:10)
    > format(a)
     [1] " 1" " 2" " 3" " 4" " 5" " 6" " 7" " 8" " 9" "10"
    

    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

    > format(a,trim=TRUE)
    [1] "8"  "9"  "10" "11" "12"
    
    > a=c(1.23,1.33,1.345)
    > format(a)
    [1] "1.230" "1.330" "1.345"
    > a=c(1.230,1.330,1.340)
    > format(a)
    [1] "1.23" "1.33" "1.34"
    > a=c(1.23,1.33,1.345)
    > format(a,digits=2)
    [1] "1.2" "1.3" "1.3"
    

    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

    > a=c("a","b","c","dd")
    > format(a)
    [1] "a " "b " "c " "dd"
    

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

    > format(a,justify="left")
    [1] "a  " "b  " "c  " "ddd"
    > format(a,justify="centre")
    [1] " a " " b " " c " "ddd"
    

    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

    > df=data.frame(a=c(1.1,1.21,1.110,2.22222),b=c("a","b","c","ddd"))
    > format(df,justify="centre",digit=2)
        a   b
    1 1.1  a 
    2 1.2  b 
    3 1.1  c 
    4 2.2 ddd
    
  • Formatting a List

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

    > a=list("a",c(1,2),list(2,"a"))
    > format(a)
    [1] "a"    "1, 2" "2, a"
    
    

Leave a Comment