Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Indent code lines 'n' spaces

Tags:

r

For code to be recognized as code on here it must be indented four spaces. This can be accomplished by hand or with the brackets icon or tick marks. What if I wanted to accomplish this through R? Obviously this can be done (just look at formatR). What is the way of going about this with the least amount of code writing?

So for the following lines (a dataframe and a function) what is the best way (least amount of code) to use R to indent every line exactly 4 spaces?

foo<-function(x,y){
   z<-x*y
   super.z<-z^2
   return(super.z)
}

and

     id hs.grad  race gender age
1   ID1     yes asian female  32
2   ID2     yes white female  30
3   ID3     yes white female  34
4   ID4     yes black female  25
5   ID5      no white   male  19
like image 624
Tyler Rinker Avatar asked Dec 27 '22 11:12

Tyler Rinker


1 Answers

Here's a small function that will format an object in a StackOverflow-compatible way:

formatSO <- function(x) {
  y <- get(x, parent.frame())
  d <- deparse(y)

  cat("   ", x, "<-", d[1], "\n")
  cat(paste("    ", d[-1], "\n", sep=""), sep="")
}

And trying it out:

> foo<-function(x,y){
+    z<-x*y
+    super.z<-z^2
+    return(super.z)
+ }
> formatSO("foo")
    foo <- function (x, y)  
    {
        z <- x * y
        super.z <- z^2
        return(super.z)
    }
> x <- 5:3
> formatSO("x")
    x <- c(5L, 4L, 3L) 
like image 168
Tommy Avatar answered Jan 12 '23 15:01

Tommy