Here is how to format output in the R console in 5 different ways to make your dataset look better if that’s necessary. In my case, I like to take a quick look at few lines of a data frame and want to add gridlines or other formatting features to make them easier to read.
1. Basic format for R console output
Here is the standard format for the first rows of the iris data frame in the R console. Useful most of the time and shows in colors that are defined by the RStudio theme.
2. Format for R console output with knitr
That is one of my favorites. Use the kable function from knitr if you want to see the output or your data frame in the R console with borders.
If you want your console output results colorful, then the next two approaches can do that.
3. Format for R console output with ColorDF
ColorDF stands for colorful data frames in the R terminal, and you can get really beautiful results with that.
colorDF::colorDF(head(iris), theme = "wb")
Not everything looks great in a specific theme, and it is easier to make a judgment with this function that shows all ColorDF available themes.
You can even use conditional formatting for your data frame content in the console view.
colorDF::highlight(head(iris), iris$Species == "setosa")
4. Format for R console output with huxtable
You can get similar results to the kable from the kintr package, but with the possibility to change the color of data frame content in the R console.
require(huxtable) set_text_color(set_tb_borders(as_huxtable(head(iris))), "orange")
5. Change text color in R console
cli::bg_yellow("This is my text.") cat(crayon::bgCyan("This is my text.")) multicolor::multi_color("This is my text.")
Create your own frequently usable solution
If you want to create your formatting for frequent use, then you can customize your R profile. Here is an example of how to do that and add your function to the namespace of existing packages.
Look at this post to know how to get percentage formatting for your decimal numbers and additional tips. It is important to get the percentage format in R without losing numerical properties.