format

format(x, trim=FALSE, digits=NULL)
Format an R object (e.g. a data frame) to print helpful information from a function.
  • x – A data frame, matrix, or other R object.
  • trim – Whether to prevent right-justification.
  • digits – Number of digits to show.

Example. Below a table similar to that of regression output is created. The original data frame has an unnecessary number of digits in some rows when printed as-is. The format function output is cleaned up and includes fewer digits, making it easier to read the table.
> beta    <- c(2.1, 6.21, 4.321, 5.4321)
> SE      <- c(5, 1.49, 11.13, 0.31)
> t       <- beta/SE
> p.value <- 2*pt(-abs(t), 12)
> 
> x <- data.frame(beta, SE, t, p.value)
> row.names(x) <- c("HS GPA", "college", "gender", "age")
> x
          beta    SE         t      p.value
HS GPA  2.1000  5.00  0.420000 6.819077e-01
college 6.2100  1.49  4.167785 1.304575e-03
gender  4.3210 11.13  0.388230 7.046453e-01
age     5.4321  0.31 17.522903 6.491560e-10
> 
> fx <- format(x, digits=3)
> fx
        beta    SE      t  p.value
HS GPA  2.10  5.00  0.420 6.82e-01
college 6.21  1.49  4.168 1.30e-03
gender  4.32 11.13  0.388 7.05e-01
age     5.43  0.31 17.523 6.49e-10
> 
> fx[,1]
[1] "2.10" "6.21" "4.32" "5.43"
Tip. Use format when printing a matrix or data frame as information from a function. This is especially useful when creating a print or summary method for a new class of objects. However, do not return a formatted object from a function since formatting turns numbers into character strings, adds spaces, rounds values, etc.

Leave a Reply