R Language Coding style Guide

Source: Internet
Author: User

The R language is a high-level programming language used primarily for statistical computation and plotting. The R language Coding style guide is designed to make our r code easier to read, share, and check. The following rules are designed in collaboration with Google's R user community.

Overview : R Coding Style Conventions

File name : to. R ( uppercase ) end

Identifier naming : variable.name, functionname, Kconstantname

Single line length : No more than 80 characters

Indent : two spaces, without tabs

Blank

Curly braces : The front brackets are not wrapped, the parentheses are exclusive.

Assignment symbols : using <-instead of =

Semicolon : do not use

Overall layout and order

Annotation Guidelines : All comments begin with #, followed by a space; Inline comments need to add two spaces before #

Definition and invocation of functions

function document

Example functions

Todo writing style : todo( your username )

Overview : R Language Usage rules

Attach: Avoid using

Functions : Errors (error) should be thrown using stop()

Objects and methods : Avoid using S4 objects and methods whenever possible; Never mix S3 and S4.

1 Representation and naming

file naming

The file name should be. R ( uppercase ) ends, and the file name itself is meaningful.

Positive example : predict_ad_revenue. R

Counter example : foo. R

Identifier naming

Do not use underscores ( _ ) or hyphens (-)in identifiers. Identifiers should be named according to the following conventions:

    • The variable name should use the dot ( .)
    • To separate all lowercase letters or words;
    • The first letter of the function name is capitalized, without a dot separation ( the first letter of the word is capitalized );
    • The constant naming convention is the same function, but it needs to start with a K.

Variable.name

Positive example : avg.clicks

Counter example : avg_clicks, Avgclicks

FunctionName

Positive example : calculateavgclicks

Counter example : calculate_avg_clicks, Calculateavgclicks

The function name should be a verb or a verbal phrase.

Exception : When creating an object with a class property, the function name ( also constructor) and the class name ( Class) should match ( for example: LM).

Kconstantname

2 syntax

Single line length

The maximum single line length is 80 characters.

Indent in

Use two spaces to indent the code. Never use tabs or mix them.

Exception : When a folded row occurs within the parentheses, the line is aligned with the first character in the parentheses.

Blank

Add spaces on both sides of all two-dollar operators (=, +, -, <-, and so on ) .

Exception : when passing a parameter in a function call = space on either side can be added without adding.

Do not add a space before the comma, always add a space after the comma

Positive example :

0 " Campaignid "  1<-sum (x[1,])

Counter Example :

Add a space before the front parenthesis, except when the function is called

Positive example : if (debug)

Counter example : If(debug)

Extra spaces

( that is, using more than one space in a row ) is also possible, and if this improves the alignment effect of the equal sign or arrow (<-) .

Do not add spaces to the sides of the code in parentheses or brackets

Exception : always add a space after a comma.

Positive example :

if (Debug) x[1,]

Counter Example :

if (Debug) # on both sides of debug do not add space x[1,] # need to add a space after the comma

Braces

The front bracket should never be exclusive of one line; The post brackets should always be exclusive on one line. You can omit curly braces when the code block contains only a single statement, but you must either use curly braces consistently or all without curly braces when dealing with such a single statement.

if (is. NULL  <-C (00.06)} or (non-miscible)if (is).  Null<-C (00.06) always starts writing the body of a code block on a new line.

Counter Example :

if (is. NULL (Ylim)) Ylim <-C (00.06)if (is.  Null(Ylim)) {Ylim <-C (00.06)}

Assign value

Use <- to assign values without = assignment.

Positive example : x <- 5

Counter example : x = 5

Semicolon

Do not end a line with semicolons, or use semicolons to put more than one command on the same line. ( semicolons are unnecessary and are also omitted in order to be consistent with other Google coding style guidelines.) )

3 Code organization

Overall layout and order

If everyone arranges the contents of the code in the same order, we can read and understand other people's scripts more easily and quickly.

Comments

Copyright Notice Note

Author Information notes

File description comments, including the purpose of the program, input and output

SOURCE() and Library() statements

function definition

The statement to execute, if any ( for example, print, Plot)

The unit test should be in another name named Original _unittest. Independent file of R.

Annotation Guidelines

Comment Your code. The entire line of comments should begin with # followed by a space.

In-line short comments should be followed by two spaces, #, followed by a space in the code.

Definition and invocation of functions

The function definition should first list parameters with no default values, and then list the parameters with default values.

in function definitions and function calls, each line is allowed to write multiple parameters; Wrapping is only allowed outside of an assignment statement.

Positive example :

Counter Example :

PREDICTCTR <-Function (query, property, Numdays, Showplot =true)

Ideally, the unit Test should act as a sample for a function call ( for the program in the package ).

function document

The function should be followed by a comment area immediately below the definition line. These comments should consist of the following : A sentence description of this function;

A list of parameters for this function, denoted by Args: A description of each parameter ( including the data type ); And a description of the return value to

Returns: expressed. These comments should be sufficiently descriptive so that callers can use this function without having to read any code in the function.

Example functions

TODO writing style

Write TODO using a consistent style throughout the code.

TODO( your user name ): A clear description of the action to be taken

4 languages

Attach

There may be countless errors caused by the use of attach. Avoid using it.

Function

Errors should be thrown using Stop() .

Objects and methods

There are two object-oriented systems in the S language, S3 and S4, both of which can be used in R. S3 methods are more interactive, more flexible, and conversely, the S4 approach is more formal and rigorous. ( for descriptions of these two systems, see Thomas Lumley's article "Programmer's niche:a simple Class, in S3 and S4", posted in R News 4/1, 2004 , 36 pages : http://cran.rproject.org/doc/Rnews/Rnews_2004-1.pdf.)

It is recommended to use S3 objects and methods unless you have a strong reason to use S4 objects and methods. One of the main reasons to use the S4 object is to use the object directly in the C+ + code. The primary reason for using a S4 generic / method is to distribute the two parameters. Avoid mixing S3 and S4: The S4 method ignores inheritance in S3 and vice versa.

Exception

Unless there is a good reason not to do so, you should follow the coding conventions described above.

Exceptions include maintenance of legacy code and modification of third-party code.

5 Conclusion

Follow common sense, and be consistent.

If you're editing an existing code, take a few minutes to look at the context of the code and figure out its style. If other people use spaces around the if statement, you should do the same. If their notes are enclosed in a small box of asterisks, you should write the same.

The point of following code-style guidelines is that people have a common vocabulary of programming, so people can focus on what you're saying, not what you say. We are here to provide the global coding style rules so that people can understand these words, but the local style is also very important. If the code in your file appears to be quite different from the existing code around it, the reading rhythm of the code reader will be broken. Try to avoid doing so. OK, you've written enough about how to write code, and the code itself is much more interesting. Happy Coding !

Reference documents

R Language Coding Conventions

http://www.maths.lth.se/help/R/RCC/

This article links:

Http://www.cnblogs.com/homewch/p/5865937.html

R Language Coding style Guide

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.