1). 以字符串形式,对代码格式化
> tidy.source(text = c("{if(TRUE)1 else 2; if(FALSE){1+1", "## comments", "} else 2}")){ if (TRUE) 1 else 2 if (FALSE) { 1 + 1 ## comments } else 2} 2). 以文件形式,对代码格式化
> messy = system.file("format", "messy.R", package = "formatR")> messy[1] "C:/Program Files/R/R-3.0.1/library/formatR/format/messy.R"原始代码输出
> src = readLines(messy)> cat(src,sep="\n") # a single line of comments is preserved1+1if(TRUE){x=1 # inline comments}else{x=2;print('Oh no... ask the right bracket to go away!')}1*3 # one space before this comment will become two!2+2+2 # 'short comments'lm(y~x1+x2, data=data.frame(y=rnorm(100),x1=rnorm(100),x2=rnorm(100))) ### only 'single quotes' are allowed in comments1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1 ## comments after a long line'a character string with \t in it'## here is a long long long long long long long long long long long long long long long long long long long long comment格式化后的代码输出
> tidy.source(messy)# a single line of comments is preserved1 + 1if (TRUE) { x = 1 # inline comments} else { x = 2 print("Oh no... ask the right bracket to go away!")}1 * 3 # one space before this comment will become two!2 + 2 + 2 # 'short comments'lm(y ~ x1 + x2, data = data.frame(y = rnorm(100), x1 = rnorm(100), x2 = rnorm(100))) ### only 'single quotes' are allowed in comments1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 ## comments after a long line"a character string with \t in it"## here is a long long long long long long long long long long long long long long long long## long long long long comment 3). 格式化并输出R脚本文件
新建R脚本文件:demo.r
~ vi demo.ra<-1+1;a;matrix(rnorm(10),5);if(a>2) { b=c('11',832);"#a>2";} else print('a is invalid!!')格式化demo.r
> x = "demo.r"> tidy.source(x)a <- 1 + 1amatrix(rnorm(10), 5)if (a > 2) { b = c("11", 832) "#a>2"} else print("a is invalid!!") 输出格式化结果到文件:demo2.r
> f="demo2.r"> tidy.source(x, keep.blank.line = TRUE, file = f)> file.show(f)