2011-11-18 88 views
4

要在此處將代碼識別爲代碼,它必須縮進四個空格。這可以通過手動或使用括號圖標或刻度標記來完成。如果我想通過R完成這個任務呢?顯然這可以完成(只看格式R)。用最少的代碼編寫來做這件事的方式是什麼?縮進代碼行'n'空格

因此對於下面的行(一個數據框和一個函數),使用R來縮進每行完全4個空格的最佳方式(最少代碼量)是多少?

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

 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 
+0

這是什麼目的? –

+0

對於Emacs + ESS用戶,這與「C-x r t ''一樣簡單。 (只是覺得我會提到,作爲一個例子,對於那些想給Emacs一個嘗試的人來說,'駝峯的另一端') –

回答

1

我決定去浪費我的時間今天實際上正如我描述的那樣完成這個功能。我創建了一個可以獲取數據框架或函數的函數,可以將其輸入到縮進函數中或鍵入剪貼板。這會將代碼縮小爲空格參數所需的空間(默認值爲四個空格)。

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 
3

設置

options(prompt = " ") 

會導致你在控制檯中寫任何代碼進行格式化,因此很容易貼在這裏。輸出在開始時不會有四個空格,但可能需要採用不同的解決方法。

+0

和'options(continue =「」)*編輯*顯然有4個空格,但SO似乎在評論中刪除了多個空格...... – James

2

formatR: Format R Code Automatically可用於此目的。可用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) 
} 
+1

感謝這個例子;一個小點:'replace.assign'參數在這個特定的例子中沒有用;當'='用於賦值時(例如,'z = x * y'將變爲'z <-x * y'),它被用來將'='替換爲'<-'。 –

4

這裏的一個小功能,將在StackOverflow上兼容的方式格式化對象:

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

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

,並試圖出來:

> 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) 
+0

這是最接近的格式,但該方法將數據幀轉換爲其結構(),而不是更美觀的data.frame格式。 –