First, the basic concept
Statement (statement): A separate R statement or a set of compound statements (a set of R statements contained in {}, separated by semicolons);
Condition (cond): An expression that is eventually resolved to true or false;
Expression (expr): A piece of data or a string of job-seeking statements;
Sequence (seq): A numeric or string-evaluated statement.
II. control structure of the R language
2.1 Cycle Structure
2.1.1 for structure
Syntax: for (var in seq) {statement1;satement2; ...}
Description: Until the value of the variable is no longer contained in the sequence
1> n<-02> for(IinchSeq1:7)){3+ N = n+y[i]*F[i]4+print (n)5+ }6 #输出7[1]08[1] the9[1] theTen[1] the One[1]142 A[1]147 -[1]159
2.1.2 While structure
Grammar:
I <-seq # (Initialize value)
while (cond (i)) {Statement1;statement2; ...}
1> I <-Ten2> while(i>0){3+ i = i-14+print (i)5+ }6 #输出7[1]98[1]89[1]7Ten[1]6 One[1]5 A[1]4 -[1]3 -[1]2 the[1]1 -[1]0
2.2 Article statements
2.2.1 If-else Structure
Grammar:
if (cond) {Statement1;statement2; ...}
if (cond) {Statement1;statement2; ...} Else{statement3;statement4, ...}
Description
If cond is true, the statement in the first {} is executed, otherwise the statement in {} after the else is executed (if else exists).
1> a<-Ten; b<-9; c<-82>if(a<b) {3+ Print ('Hello')4+ }Else{5+ Print ('R')6+ }7 #输出8[1]"R"
2.2.2 IfElse Structure
Grammar:
IfElse (Cond, Statement1, Statement2)
Description
If cond is true, execute statement1, otherwise execute statement2
1 > IfElse (b>c, print ('hello'), print ('R' ) ))2#输出 3 [1"hello"
Third, function
Syntax: variable name = function (variable list) {Functional Body}
MyFunction <-function (arg1, arg2, ...) {
Statements
Return (object)
}
Description
1. Function () {} to create functions;
2. How to call the function, add the parentheses ' () ' After the variable name, such as MyFunction (Arg1, arg2, ...);
3. The function's call is related to its parameter's position and name, can be called by location, call by name, or set default parameters;
4. A function is a ' closure ', a variable defined only in function parameters and in the body of a function, and the variable is a local variable that is exclusive to the function if it is not defined before the function is defined. When the function is finished, these variables also disappear automatically, cannot be called in subsequent analysis, and does not cause a naming conflict. We use the super-assignment notation "<<-" to change the local variable to a global variable for subsequent analysis.
5. Extension: In the R language, {Statement1;statement2; ...} A closure is defined, and the variables in the closure are a local variable that will disappear once the execution is finished. If you want to continue to use in subsequent analyses, use the value assignment notation. Also, these variable names do not cause naming conflicts.
R Language Programming syntax