First, cycle and control
Cycle:
For (i-1:10) print ("Hello World")
I<-10
while (i>0) {
print (i);
i<-i-1;
}
Control
if ()
if () Else
IfElse (judge, True,false)
Switch (type, ...). )
Second, user-defined functions
Mystats <-function (x, Parametric=true, Print=false) {
if (parametric) {
Center <-mean (x); Spread <-SD (x)
} else {
Center <-median (x); Spread <-mad (x)
}
if (print & parametric) {
Cat ("mean=", center, "\ n", "sd=", spread, "\ n")
} else if (print &!parametric) {
Cat ("median=", center, "\ n", "mad=", spread, "\ n")
}
Result <-list (Center=center, Spread=spread)
Return (Result)
}
How to invoke a function we write ourselves
Set.seed (1234)
X <-rnorm (500) generates 500 elements in accordance with normal distribution
Y <-mystats (x)
Y <-mystats (x, Parametric=false, Print=true)
Here is an example of a switch function
MyDate <-function (type= "long") {
switch (type,
long = format (Sys.time (), " %A%B%d%Y "),
short = format (Sys.time (),"%m-%d-%y "),
cat (Type," was not A RECOG nized type\n "))
}
MyDate (" Long ")
MyDate (" short ")
MyDate ()
MyDate (" medium ")