rprintingconsoleword-wrappander

How to wrap text within a column in R when printing to the console?


I'm trying to adjust the way R prints a data frame to the console. Specifically, I want to print a data frame such that the text for a column wraps after a certain width is reached. Ideally, I want something that looks like the following:

     v1              v2     v3
1  TRUE Some text         TRUE
2  TRUE Some more text   FALSE
3  TRUE This text wraps  FALSE
        after a certain  
        width   
4 FALSE Even more text   FALSE
5  TRUE More text         TRUE

Here's a MWE:

data.frame(v1 = c(TRUE, TRUE, TRUE, FALSE, TRUE), v2 = c("Some text", "Some more text", "This text wraps after a certain width", "Even more text", "More text"), y = c(TRUE, FALSE, FALSE, FALSE, TRUE))
options(width=10)

Here's where I'm at:

enter image description here


Solution

  • Take a look at the pandoc.table function in the pander library. It seems to do what you are after http://rapporter.github.io/pander/pandoc_table.html

    library(pander)
    m<-data.frame(v1 = c(TRUE, TRUE, TRUE, FALSE, TRUE), v2 = c("Some text", "Some more text", "This text wraps after a certain width", "Even more text", "More text"), y = c(TRUE, FALSE, FALSE, FALSE, TRUE))
    pandoc.table(m, split.cells = c(5, 20, 5))
    
    #>---------------------------
    #> v1         v2          y  
    #>----- --------------- -----
    #>TRUE     Some text    TRUE 
    #>
    #>TRUE  Some more text  FALSE
    #>
    #>TRUE  This text wraps FALSE
    #>      after a certain      
    #>           width           
    #>
    #>FALSE Even more text  FALSE
    #>
    #>TRUE     More text    TRUE 
    #>---------------------------