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
123> 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
12> format(a,trim=TRUE)[1] "8" "9" "10" "11" "12"
123456789> 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
123> 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
1234> 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
1234567> 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 b1 1.1 a2 1.2 b3 1.1 c4 2.2 ddd 
Formatting a List
The list, if it contains sublists, is expanded while formatting
123> a=list("a",c(1,2),list(2,"a"))> format(a)[1] "a" "1, 2" "2, a"