groebsgr groebsgr -4 years ago 172
R Question

R indent output

is it possible to indent output in R?

e.g.

cat("text1\n")

indent.switch(indent=4)
cat("random text\n")
print("another random text")
indent.switch(indent=0)

cat("text2\n")


resulting in

text1
random text
another random text
text2


I searched for this a few months ago, found nothing and am now searching again.

My current idea is to "overwrite" (I forgot the special term) the functions
cat
and/or
print
with an additional argument like:

cat("random text", indent=4)


Only I'm stuck with this and I dont like this procedure very much.
Any ideas?

Edit:
I should be more particular, nevertheless thank you for the \t (omg, i totally forgot this -.-) and that I can format it inside cat.
The given solutions work, but only solve my second-choice-path.
A switch as shown in my first codeexample does not exist I suppose?

My problem is that I have parts of a bigger program which have multiple subscripts, and the output of each subscript should be indented. This is absolutely possible with the "\t" or just blanks inside cat() but has to be done in every command, which I dont like very much.

Solution

I used Chris C's code and extended it in a very easy way. (Thank you very much Chris!)

define.catt <- function(ntab = NULL, nspace=NULL){
catt <- function(input = NULL){
if(!is.null(ntab)) cat(paste0(paste(rep("\t", ntab), collapse = ""), input))
if(!is.null(nspace)) cat(paste0(paste(rep(" ", nspace), collapse = ""), input))
if(is.null(ntab) && is.null(nspace)) cat(input)
}
return(catt)
}

Answer Source

The same way you used \n to print a newline, you can use \t to print a tab.

E.g.

cat("Parent level \n \t Child level \n \t \t Double Child \n \t Child \n Parent level")

Evaluates to

Parent level 
     Child level 
         Double Child 
     Child 
 Parent level

As an alternative, you can create a derivative of cat called catt and alter options depending on the script. For example.

define.catt <- function(ntab = NULL){
    catt <- function(input = NULL){
        cat(paste0(paste(rep("\t", ntab), collapse = ""), input))
    }
    return(catt)
}

You would then set catt with however many tabs you wanted by

catt <- define.catt(ntab = 1)
catt("hi")
    hi
catt <- define.catt(ntab = 2)
catt("hi")
        hi

And just use catt() instead of cat().

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download