Tyler Rinker
Tyler Rinker

Reputation: 109864

Indent code lines 'n' spaces

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

Upvotes: 4

Views: 337

Answers (4)

Tyler Rinker
Tyler Rinker

Reputation: 109864

I decided to waste my time today actually making this function exactly as I described it. I've created a function that takes data frames or functions and can be typed or clip board fed into the indent function. This will indent the code as many spaces as is desired with the space argument (default is four spaces).

indent <- function(object = "clipboard", space = 4) {        
    y <- if (object == "clipboard") {                        
        as.list(readClipboard())                             
    } else {                                                 
        strsplit(as.vector(object), "[\\n]")                 
    }                                                        
    spacer <- function(x) paste(paste(rep(" ", space - 2),   
        collapse = ""), x)                                   
    z <- if (object == "clipboard") {                        
        sapply(y, spacer)                                    
    } else {                                                 
        lapply(y, spacer)                                    
    }                                                        
    zz <- as.matrix(as.data.frame(z))                        
    dimnames(zz) <- list(c(rep("", nrow(zz))), c(""))        
    noquote(zz)                                              
}                                                            
#==========================================================  
#   Test it out!!!!!!                                        
#==========================================================  
indent("     id hs.grad  race gender age                     
1   ID1     yes white   male  37                             
2   ID2     yes white   male  32                             
3   ID3     yes asian   male  20                             
4   ID4      no black female  24                             
5   ID5      no white female  32")                           
#==========================================================  
indent("ascii<-function(x, header=TRUE,...){                 
      name <-textConnection(x)                               
      DF <- read.table(name, header, ...)                    
      close(name)                                            
      on.exit(closeAllConnections())                         
      DF                                                     
}", space = 10)                                              
#============================================================
#  THE NEXT TWO CAN BE CUT AND PASTED WITH THE CLIPBOARD ARG 
#============================================================
     id hs.grad  race gender age                             
1   ID1     yes white   male  37                             
2   ID2     yes white   male  32                             
3   ID3     yes asian   male  20                             
4   ID4      no black female  24                             
5   ID5      no white female  32                             

indent("clipboard")                                          
#============================================================
ascii<-function(x, header=TRUE,...){                         
      name <-textConnection(x)                               
      DF <- read.table(name, header, ...)                    
      close(name)                                            
      on.exit(closeAllConnections())                         
      DF                                                     
}                                                            

indent()  #clipboard is the default arg not needed

Upvotes: 1

Dason
Dason

Reputation: 61913

Setting

options(prompt = "    ")

will cause any code you write in the console to be formatted so to easily paste here. The output won't have the four spaces at the beginning though and probably requires a different workaround.

Upvotes: 3

MYaseen208
MYaseen208

Reputation: 23898

formatR: Format R Code Automatically can be used for this purpose. Available here

library(formatR)
src <- c("foo<-function(x,y){
   z<-x*y


              super.z<-z^2
   return(super.z)
}
")

tidy.source(text = src, replace.assign = TRUE)


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

Upvotes: 2

Tommy
Tommy

Reputation: 40821

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) 

Upvotes: 4

Related Questions