Coder Social home page Coder Social logo

formatr's Introduction

This is a repo to host the (Markdown) source files of my personal website, including my Chinese and English blogs, as well as several project websites (such as knitr.) The content of all pages is licensed under CC BY-NC-SA 4.0.

You are welcome to post comments on my site. To do so, you need to log in using your GitHub account at the bottom of a page. If you have any other feedback, comments, or questions, please post them to my GitHub discussion board.

A technical note

To build the website locally, you must clone this repo with its submodule (use the --recursive argument), e.g.,

git clone --recursive [email protected]:yihui/yihui.org.git

The website is built via the R package blogdown. Please read its documentation for how to use it.

I don't recommend you to study how my website is built, because it is complicated. In particular, the way I manage images is fairly complicated.

formatr's People

Contributors

az0 avatar cderv avatar edlee123 avatar egnha avatar iqis avatar kohske avatar krivit avatar ronggui avatar yihui avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

formatr's Issues

Spaces around + but not around / and ^?

This doesn't seem to follow the style guide:

tidy_source(text="x <- a + 2")
# x <- a + 2 
tidy_source(text="x <- a / 2")
# x <- a/2 
tidy_source(text="x <- a ^ 2")
# x <- a^2 

Comments after arguments in functions

Running following code on tidy_app()

foo <- function(ParamA = 1, # comment 
        ParamB="c"){ 
  print("hi") 
}

Produces

Error in base::parse(text = code, srcfile = NULL) : 
  1:26: unexpected SPECIAL
1: foo <- function ( ParamA %InLiNe_IdEnTiFiEr%

Environment:
R version 3.2.1 (2015-06-18)
Platform: x86_64-w64-mingw32/x64 (64-bit)

shiny_0.12.1
formatR_1.2

Parsing Error with try-catch

When using tidy_app() with the following R code

  resultJSON <- NULL
  tryCatch(
    # Get Result from the server
    resultJSON <- RCurl::getURL(url, httpheader= httpHeaders),
    error = function(e) {
      message(paste("Failed calling the service at URL", url))
    }

  )

I get the following error

> formatR::tidy_app()

Listening on http://127.0.0.1:3380
Error in base::parse(text = code, srcfile = NULL) : 
  4:1: unexpected symbol
3: invisible(".BeGiN_TiDy_IdEnTiFiEr_HaHaHa# Get Result from the server.HaHaHa_EnD_TiDy_IdEnTiFiEr")
4: resultJSON
   ^

Here's my sessionInfo:

> sessionInfo()
R version 3.2.0 (2015-04-16)
Platform: x86_64-apple-darwin13.4.0 (64-bit)
Running under: OS X 10.9.5 (Mavericks)

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] formatR_1.2  shiny_0.12.0

loaded via a namespace (and not attached):
 [1] R6_2.0.1         htmltools_0.2.6  tools_3.2.0      rstudioapi_0.3.1 Rcpp_0.11.5      jsonlite_0.9.16  digest_0.6.8     xtable_1.7-4    
 [9] httpuv_1.3.2     mime_0.3        
> 

bug for \\

this is unexpected:

tidy.source(text=c("for (i in 1:10) {", "# asdf", "'\\\\1'", "}"))

for (i in 1:10) {
    # asdf
    "\1"
}

the reason is unmask.source() replaces \\ with \ in a wrong place

Replaces -> with <-

I've been given some code and was trying to quickly format it to save me a headache, but the author has written:

read.csv( "all.clin.data.ABmod.csv")->all.clin.data.ABmod

and the tidy.source function replaces it with this:

read.csv("all.clin.data.ABmod.csv") <- all.clin.data.ABmod

which obviously breaks the code (in scripts where he doesn't use -> everything looks much nicer though, so good job!)

Feature Request: Break (format) long comments

Current behavior is to print comments no matter how long they are (and in the case of pgfSweave, let latex do the wrapping). A possible extension here is to break the comments into comment blocks. For example, if the screen width is set to 40 then

# A really really really really really really really really really really really really really really really really long comment

might become

# A really really really really really 
# really really really really really 
# really really really really really 
# really long comment

This of course depends on the choice of where is acceptable to break a comment line, could be hairy...

I had a crack at a function to do this, it is basically brute force and very slow. There is probably a far more elegant way to do it:

https://gist.github.com/772509

Fails on comment between `if` condition an opening brace

The following error happens:

> tidy_source(text="for(i in 1:10) #Loop to ten\n{print(i)}", comment=TRUE)
Error in base::parse(text = code, srcfile = NULL) : 
  1:21: unexpected SPECIAL
1: for ( i in 1 : 10 ) %InLiNe_IdEnTiFiEr%
                        ^

It looks like you stick %InLiNe_IdEnTiFiEr% into the source where the comment was, in order to stick the comment back in later, but it's not allowed there so the parser blows up.

Ideally, this text would be transformed into "for (i in 1:10) { #Loop to ten\n print(i)\n}", which involves transposing the opening brace and the comment. Sounds like it might be tricky though?

Escaped quote throws an error

stop("'file' must be \"\" or an open connection object")
will throw this error:
Error in base::parse(text = code, srcfile = NULL) :
4526:29: entrée inattendu(e)
4526: stop("'file' must be "\

Seems to have put statement on wrong line

Here is the sessionInfo from the run:

R version 3.2.3 (2015-12-10) -- "Wooden Christmas-Tree"
Copyright (C) 2015 The R Foundation for Statistical Computing
Platform: x86_64-w64-mingw32/x64 (64-bit)

R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under certain conditions.
Type 'license()' or 'licence()' for distribution details.

  Natural language support but running in an English locale

R is a collaborative project with many contributors.
Type 'contributors()' for more information and
'citation()' on how to cite R or R packages in publications.

Type 'demo()' for some demos, 'help()' for on-line help, or
'help.start()' for an HTML browser interface to help.
Type 'q()' to quit R.

The following object is masked from package:base:

    setwd

libraries: c:/R/r_libs-3.2.3 C:/R/R-3.2.3/library 
library & Java environment set from C:\Users\jh52822\Documents\.RProfile
> require(formatR)
Loading required package: formatR
Warning message:
package ‘formatR’ was built under R version 3.2.4 
> sessionInfo()
R version 3.2.3 (2015-12-10)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1

locale:
[1] LC_COLLATE=English_United States.1252  LC_CTYPE=English_United States.1252   
[3] LC_MONETARY=English_United States.1252 LC_NUMERIC=C                          
[5] LC_TIME=English_United States.1252    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] formatR_1.3

loaded via a namespace (and not attached):
[1] tools_3.2.3

I was using the 'utils.R' file from the 'formatR' source code and here is what it gave me on a section of code:

# no blank lines before an 'else' statement!
move_else = function(x) {
    blank = grepl("^\\s*$", x)
    if (!any(blank)) 
        return(x) else.line = grep("^\\s*else(\\W|)", x)   ## **** here is the bad line ****
    for (i in else.line) {
        j = i - 1
        while (blank[j]) {
            blank[j] = FALSE
            j = j - 1  # search backwards & rm blank lines
            warning("removed blank line ", j, " (should not put an 'else' in a separate line!)")
        }
    }
    x[blank] = blank.comment
    x
}

Here was the original source

# no blank lines before an 'else' statement!
move_else = function(x) {
  blank = grepl('^\\s*$', x)
  if (!any(blank)) return(x)
  else.line = grep('^\\s*else(\\W|)', x)   ## **** this is on a separate line ****
  for (i in else.line) {
    j = i - 1
    while (blank[j]) {
      blank[j] = FALSE; j = j - 1  # search backwards & rm blank lines
      warning('removed blank line ', j, " (should not put an 'else' in a separate line!)")
    }
  }
  x[blank] = blank.comment
  x
}

apparent difficulty with inline comments in argument list

Hi, this looks like a fantastic piece of software. I'm trying it out on a script that has a few functions with the following general structure:

myfun <- function(
    a, #a comment
    b #another comment
){
    a + b
}

I saved that minimal example to my desktop and ran the following line:

tidy.source("~/Desktop/test.R")

Which results in the following error:

Error in base::parse(text = block.text) : <text>:2:6: unexpected SPECIAL
1: myfun <- function (
2: a ,  %InLiNe_IdEnTiFiEr%
        ^

My best guess is that it doesn't like comments appearing among the function's arguments, but I don't know for sure that this is the issue or if it's something you'd be interested in fixing.

Hope this is useful feedback.

Thanks again,

Dave

Compile notebook chunks

In the comment chunks that RStudio interprets when compiling a notebook, running the reformat code makes the chunk options not function correctly.

e.g.

+ fig.width=16, fig.height=5, message = FALSE, warning = FALSE, echo=FALSE

goes to

+ fig.width=16, fig.height=5, message = FALSE, warning = FALSE,

echo=FALSE

missing dependency 'parser'

I've been unable to install 'formatR' from CRAN or from github due to missing dependency 'parser' on CRAN.

install.packages("parser")
Installing package(s) into ‘/usr/local/lib/R/site-library’
(as ‘lib’ is unspecified)
Warning message:
package ‘parser’ is not available (for R version 2.15.0)

apparently it has been recently orphaned...
http://cran.r-project.org/web/packages/parser/index.html

Package ‘parser’ was removed from the CRAN repository.
Formerly available versions can be obtained from the archive.
Orphaned on 2012-06-18 as the orginal maintainer, Romain Francois [email protected], is unrespsonsive.

-> 符号处理的问题

replace_assignment 函数没有判断"->"符号,虽然很少人会这样写,但语法上确实存在这个问题。

c('11',832)->x2
x2
[1] "11" "832"

tidy.source(text="c('11',832)->x2")
c("11", 832) <- x2

tidy.eval(text="c('11',832)->x2")
c("11", 832) <- x2
Error in eval(expr, envir, enclos) : object 'x2' not found

Incorrect deparse'd output

When keep.space=T I noticed that incorrect output is being generated:

> require(formatR)
> options(keep.space=TRUE)
> deparse.tidy(parse.tidy(text="\t\t# comment")[[1]])
[1] "\\t\\t# comment"

When it should be

"\t\t# comment"

Don't add spaces around = in function arguments

While I completely agree there should be spaces around binary operators (=, +, <-, etc) I don't like them around the = in function arguments.

For instance
mean(x=1:10) is better than mean(x = 1:10).

And even the Google style guide (which I don't always 100% agree with) says they're optional.

Can I get an option so those spaces aren't added automatically?

Thanks.

Not Properly Breaking Function Calls into Multiple Lines

I have a chunk being used with knitr

<<db-query,tidy=TRUE,eval=FALSE>>=
# simple SELECT * query from one table
ordersTable <- sqlQuery(db, "SELECT * FROM Orders", stringsAsFactors=FALSE)
# simple SELECT * query from one table
detailsTable <- sqlQuery(db, "SELECT * FROM [Order Details]", stringsAsFactors=FALSE)
# do a join between the two tables
longQuery <- "SELECT * FROM Orders, [Order Details] WHERE Orders.OrderID = [Order Details].OrderID"
detailsJoin <- sqlQuery(db, longQuery, stringsAsFactors=FALSE)
@

The function calls run over the grey box and do not get broken into multiple lines. I thought formatR would break it before stringsAsFactors. I understand that the long string doesn't get broken (can it be?) but shouldn't the function?

I tried setting options(width.cutoff) to varying sizes to no avail because it is apparently not a global option.

Indenting consistent with Rstudio

This looks very helpful it does not indent the lines that it does in the same way that Rstudio or emacs ESS does by default.

For example, this line:

old.priors <- db.query(paste("select prior_id from pfts_priors where pft_id =", parent.pft.id, ";"), con = con)

is converted to tidy_source() as

old.priors <- db.query(paste("select prior_id from pfts_priors where pft_id =", 
    parent.pft.id, ";"), con = con)

while Rstudio converts it to

  old.priors <- db.query(paste("select prior_id from pfts_priors where pft_id =", 
                               parent.pft.id, ";"), con = con)

the Rstudio way makes it easier to see that the arguments on line 2 are arguments to the paste functions.

Is there a way around this? I've reviewed many isues in this repository and suspect that the answer is 'no' but couldn't find a reference to this in particular.

tidy.gui() font button throws error

I'm running Ubuntu 12.04 currently. If I use tidy.gui and then click on the font button at any point this is what I get:

> tidy.gui()
> Error in widget$getGroup : $ operator not defined for this S4 class

It creates a new window with a frame named "Size" but doesn't populate that window with anything. It's not a big concern for me but I thought you might want to know.

Here's my sessionInfo

> sessionInfo()
R version 2.15.1 (2012-06-22)
Platform: i686-pc-linux-gnu (32-bit)

locale:
 [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
 [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
 [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8   
 [7] LC_PAPER=C                 LC_NAME=C                 
 [9] LC_ADDRESS=C               LC_TELEPHONE=C            
[11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C       

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] gWidgetsRGtk2_0.0-81 gWidgets_0.0-50      formatR_0.6         
[4] local_1.0            devtools_0.8        

loaded via a namespace (and not attached):
 [1] digest_0.5.2    evaluate_0.4.2  httr_0.1.1      memoise_0.1    
 [5] parallel_2.15.1 plyr_1.7.1      RCurl_1.95-0    RGtk2_2.20.25  
 [9] stringr_0.6.1   tools_2.15.1    whisker_0.1  

Comment parse error in 'if' block when 'tidy.source' is called

If a comment is made after the if statement but before the { #code } block is invoked, an error results when using tidy.source.

To reproduce the error, create a file called test.r and add the following code:

world_ends <- TRUE                                                                                                                                                                                                                                                              
if (world_ends) # The world will end in 2012                                                                                                                                                                                                                                    
{                                                                                                                                                                                                                                                                               
  message("Goodbye, cruel world.")                                                                                                                                                                                                                                              
} 

Here's the error:

> tidy.source("test.r")
Error in base::parse(text = text, srcfile = NULL) (from tidy.R#112) :
  2:18: unexpected SPECIAL
1: world_ends <- TRUE                                                                                                                                                                                                                                                           
2: if (world_ends)  %InLiNe_IdEnTiFiEr%
                   ^

I'm using version 0.7.2 and the latest commit to the master branch on github.

Problem in using formatR package

Here is the lines in a file that are causing the problem. I just highlight and copy the statements and then call tidy_source and get the error:

> tidy_source()
Error in base::parse(text = code, keep.source = FALSE) : 
  <text>:1:15: unexpected '['
1: qry_lookup <- [
                  ^

Enter a frame number, or 0 to exit   

1: tidy_source()
2: tidy_block(text, width.cutoff, arrow && length(grep("=", text)))
3: parse_only(text)
4: base::parse(text = code, keep.source = FALSE)

Here is the sessionInfo:
> sessionInfo()
R version 3.2.3 (2015-12-10)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1

locale:
[1] LC_COLLATE=English_United States.1252  LC_CTYPE=English_United States.1252   
[3] LC_MONETARY=English_United States.1252 LC_NUMERIC=C                          
[5] LC_TIME=English_United States.1252    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] formatR_1.3

loaded via a namespace (and not attached):
[1] tools_3.2.3

move { to the next line

some people prefer

if (foo)
{
  bar
}

to

if (foo) {
  bar
}

is it always safe to gsub('{$', '\n{', code)?

Suggestion: Kernighan and Ritchie style

The original indentation style pioneered by Kernighan and Ritchie in the book that defined the C language specified keeping open curly bracket on the same line for if, for, and other statements, but to put it on a line by itself for a function. The Linux kernel follows this style and so do I in my R code.

There is also a practical reason to use this formatting: vi/vim doesn't understand the beginnings of R functions unless the curly bracket is on a line by itself. As a result you can't highlight by function or easily move around by function in vim unless the curly bracket is by itself for a function. The same advantages are not present for other statements so putting it by itself everywhere is not necessary.

What I suggest is an option to enable the following formatting:

f <- function(x)
{
  if (x>0) {
    return(x^2)
  } else {
    return(-x^2)
  }
}

This is the formatting of the pure in heart. I think it would be great to be able to achieve this within the context of formatR. Thanks!

unexpected string constant

Attempted to run tidy.dir() on code from https://github.com/systematicinvestor/SIT/tree/sit.gz.

Contains one long file "code.r" (12000+ lines).

Errors out with this:

tidy.dir()
tidying ./code.r
Error in base::parse(text = text, srcfile = NULL) :
7438:50: unexpected string constant
9121: colnames(temp) = tickers
9122: rownames(temp) = spl('Avg Pos,Max Pos,Min Pos, %InLiNe_IdEnTiFiEr% "
^

There is no " %InLiNe_IdEnTiFiEr% " in the code.

The real text of the line it hangs on reads:

    rownames(temp) = spl('Avg Pos,Max Pos,Min Pos,# Periods')

located at approximately line 8980.

(note, the author of that code is actively updating it, so the line number may change).

Feature Request: Maintain parse2 and deparse2 in formatR

I wonder if you would consider maintaining parse2() and deparse2() in the formatR package? There are a number of reasons I see this as beneficial (besides it being less work for me ;) ):

  • This seems more natural since they only concern tidy'd code.
  • Users of formatR might find them useful in another context.
  • parse2 could respect all of the tidy.source() options and new options could be added by you who would know them the best. Also, these options would no longer be "hidden."

I also suggest they be renamed them something like parse.tidy() and deparse.tidy() for clarity. Here are the most recent versions of the functions:

## to replace the default parse()
parse.tidy <- function(text, ...) {

      # Respected tidy.source options
    keep.blank.line <- ifelse(is.null(getOption('keep.blank.line')), 
      FALSE, getOption('keep.blank.line'))
    keep.space <- ifelse(is.null(getOption('keep.space')), 
      FALSE, getOption('keep.space'))

      # This corrects for a very subtle printing problem with deparse.tidy'd 
      # code: 
      #  If a line with an inline comment would normally fit in the width but 
      #  the "%InLiNe_IdEnTiFiEr%" pushes it over the width, the line will 
      #  break when it shouldn't causing unmask.source to fail at unmasking
    width.add <- nchar("%InLiNe_IdEnTiFiEr%")

    tidy.res <- formatR::tidy.source(text = text, out = FALSE, 
      keep.blank.line = keep.blank.line, 
      keep.space = keep.space,
      width.cutoff = getOption("width") + width.add) 

    base::parse(text = tidy.res$text.mask)
}

## to replace the default deparse()
deparse.tidy <- function(expr, ...) {
  unmask.source(base::deparse(expr, ...))
}

parser problem in R2.15.2 and updated packages?

Last year there was the issue yihui/knitr#18 where running knitR with highlight=TRUE resulted in the error:

Error in match(data$token, grammar_symbols$token) : 
  object 'grammar_symbols' not found

I have been using knitr w/o problems but now after updating to R2.15.2 and the latest packages I get the same problem. Code compiles with highlight=FALSE but not =TRUE

In the .Rnw source:

opts_knit$set(...., highlight=TRUE)  ## gives the above error
opts_knit$set(...., highlight=FALSE) ## no error but code does not format correctly

versions (all up-to-date via update.packages(dependencies=TRUE):

> version
               _                            
platform       x86_64-apple-darwin9.8.0     
arch           x86_64                       
os             darwin9.8.0                  
system         x86_64, darwin9.8.0          
status                                      
major          2                            
minor          15.2                         
year           2012                         
month          10                           
day            26                           
svn rev        61015                        
language       R                            
version.string R version 2.15.2 (2012-10-26)
nickname       Trick or Treat  

> 
> help(package="knitr")$info[[1]][4]
[1] "Version:            0.9"
> help(package="parser")$info[[1]][4]
[1] "Version:            0.1"
> help(package="formatR")$info[[1]][4]
[1] "Version:            0.7"

move 'else ' back one line

else should not start with a new line; this happens for deparse() when the if-else statement is inside a function

> formatR::tidy.source(text='function(){if(T){1+1} else 2}')
function() {
    if (T) {
        1 + 1
    }
    else 2
} 

in unmask.source(), find the line ^[[:space:]]*else and move it back for one line

brace in comment throws an error

Hi,
If you have a brace in a comment line, tidy.source will break.
Example in source:
# if (test) { # disabled for now
will throw:
Error in base::parse(text = code, srcfile = NULL) :
3763:12: symbole inattendu(e)
3762: invisible(".BeGiN_TiDy_IdEnTiFiEr_HaHaHa# if (test) {
3763: invisible(".BeGiN_TiDy_IdEnTiFiEr_HaHaHa

Is it a bug or a feature? ;-)

注释这么处理是你的本意么?

Hi, 益辉
我刚才试用了一下(用install.packages安装的),源代码是这样的

# Up and Running with R
# Ex06_04
# Comparing means with the t-test

# Load data file about Google searches by state
google <- read.csv("google_correlate.csv", header = T)
names(google)

# independent 2-group t-test
t.test(google$nba ~ google$has_nba)

转换后,前几行注释被处理成一行了

# Up and Running with R Ex06_04 Comparing means with the t-test

# Load data file about Google searches by state
google <- read.csv("google_correlate.csv", header = T)
names(google)

# independent 2-group t-test
t.test(google$nba ~ google$has_nba)

这么处理是你的本意么? 谢谢!

Unable to format text with unicode characters.

Hi, I just discovered knitr (which is awesome btw!), and it seems to have problems with unicode characters in code chunks. I think that the problem is because of formatR:

formatR:::tidy.source(text = "σ <- 2")
Unable to parse the R code! The error most likely came from line 1;
the surrounding lines are:

σ <- 2

See the reference in help(tidy.source) for possible reasons

Error in formatR:::tidy.source(text = "σ <- 2") :
Error in parser(text = text.lines) :
/tmp/RtmpSn34lJ/file1b53bfb1:1:0
unexpected input

Sys.getlocale()
[1] "LC_CTYPE=en_US.utf8;LC_NUMERIC=C;LC_TIME=en_US.utf8;LC_COLLATE=en_US.utf8;LC_MONETARY=en_US.utf8;LC_MESSAGES=en_US.utf8;LC_PAPER=C;LC_NAME=C;LC_ADDRESS=C;LC_TELEPHONE=C;LC_MEASUREMENT=en_US.utf8;LC_IDENTIFICATION=C"

Line breaking behavior needs improvement

The formatR package work well in most aspects and I love this package for it makes R programmers life easier.

I find the line breaking behavior looks not working pretty well especially when lines are long, like:

if (profile$settings$backtest$dynamic$quantiles$enable) {
  qts <- quantile(tick$res[max(1, i - profile$settings$backtest$dynamic$quantiles$window + 1):i], as.numeric(profile$strategy$quantiles), na.rm = TRUE, names = FALSE)
  names(qts) <- names(profile$strategy$quantiles)
  for (qts.name in names(qts)) {
    tick[i + 1, qts.name] <- learning.rate * qts[qts.name] + (1 - learning.rate) * tick[i, qts.name]
  }
}

The code is formatted as

if (profile$settings$backtest$dynamic$quantiles$enable) {
    qts <- quantile(tick$res[max(1, i - profile$settings$backtest$dynamic$quantiles$window + 
        1):i], as.numeric(profile$strategy$quantiles), na.rm = TRUE, names = FALSE)
    names(qts) <- names(profile$strategy$quantiles)
    for (qts.name in names(qts)) {
        tick[i + 1, qts.name] <- learning.rate * qts[qts.name] + (1 - learning.rate) 
* 
            tick[i, qts.name]
    }
} 

where in 80-column text-width, the codes does not look well because several lines that involve long variable names are not successfully broken down so that several arithmetic operators occupies new lines in 80-column view, which is quite unappealing.

Is there any possibility to improve the line breaking behavior?

Output of formatR has a trailing whitespace

While using formatR from the terminal, I noticed that the output has an extra space at the last line of the output. Shouldn't be there.

Steps to reproduce:

Rscript -e 'library(formatR)' -e 'formatR::tidy_source({{filename.R}})'

destroyed shebang

If I format my R script the formatR destroy my shebang and my R scripts doesn't run.

Before:

#! /usr/bin/Rscript --vanilla

After

# ! /usr/bin/Rscript --vanilla

Curly braces inside function prototype gets broken into new lines by tidy_source()

Not sure if this is intended behavior or not. Would it be possible for the user to control this behavior (ie turn it off if undesired)?

exampleFunc <- function(x, y={if (x > 5) -1 else NA}, z=0) {
  print ("hello World")
}

   vvvvv tidy_source() vvvvvvvv

exampleFunc <- function(x, y = {
    if (x > 5)
        -1 else NA
}, z = 0) {
    print("hello World")
}

Behavior for block comments

First time using github issues so please let me know if any of this is out of etiquette.

I have a file with multiline comments that don't retain their structure after a tidy.source() call. For example, my file is:

# Comment first line
#
# Comment second line

And I call:

tidy.source("foosource.R", file = "foosource.R", width.cutoff = 60)

And the result is:

# Comment first line Comment second line 

Is there a way to get this to stay the same while also wrapping lines longer than the width cutoff?

tidy_source() fails when two newlines separate function arguments

Create file test.R containing the following code:

x <- rnorm(100)
y <- rnorm(100)

plot(x,

     y)

Then we get:

> tidy_source("test.R")
Error in base::parse(text = code, srcfile = NULL) : 
  6:1: unexpected symbol
5: invisible(".BeGiN_TiDy_IdEnTiFiEr_HaHaHa.HaHaHa_EnD_TiDy_IdEnTiFiEr")
6: y
   ^

But when the file is like this:

x <- rnorm(100)
y <- rnorm(100)

plot(x,
     y)

Then it works:

> tidy_source("test.R")
x <- rnorm(100)
y <- rnorm(100)

plot(x, y) 

Recommend/implement as a style guide?

Great package. It would be quite nice to use this to check/make code conform to a standard style guide for R, such as Hadley's recommendations. Some of these might just trigger warnings that the user could fix manually.

It's nice to see that the changes you implement are consistent with those recommendations, might be a selling point for the package. Looks like the package focuses on spacing, but would be cool to have it enforce line length and brace habits as well. I suppose ideally these would be options you could include,eg tidy("mycode.R", spaces=T, braces=T, linelength=T, ..,)

anyway, brilliant work.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.