R has a lot of builtin functions which are included in the System Libraries. These
libraries include base, datasets, stats, graphics, methods, utils etc which will be
loaded automatically.
> library()#list all loaded libraries and packages > library("sqldf")#load package "sqldf" > ls("package:sqldf")#list all functions in sqldf [1] "read.csv.sql" "read.csv2.sql" "sqldf"
You can easily define a function of your own. If no return statement is specified, the R function will return the variable on the last line.
> ozml <- function(x){ #fluid ounce to mililiter convert function
+ y <- 29.57353 * x
+ }
> x <- ozml(2)
> x
[1] 59.14706
With multiple arguments:
> ftin_m <- function(f,i){ #feet inches to meter convert function
+ m <- (f * 12 + i) * 0.0254
+ return (m)
+ }
> ftin_m(5,9)
[1] 1.7526
The defined function may have optional arguments with default values, and return error or warning messages if condition not met.
> addtwo <- function(x,y=2){
if (length(x) != 1) {stop ("Unknown data type")}
if (x < 0) {warning ("argument is negative")}
tryCatch ({
v <- x + y
},
error=function(e){
cat ("ERROR: ", conditionMessage(e),"\n")})
return (v)
}
> addtwo(5)[1] 7 > addtwo(5,8)[1] 13 > addtwo(-2)[1] 0 Warning message: In addtwo(-2) : argument is negative > addtwo(c(2,3))Error in addtwo(c(2, 3)) : Unknown data type > addtwo("a")ERROR: non-numeric argument to binary operator Error in addtwo("a") : object 'v' not found
Define a function with unknown number of arguments:
> addmore <- function(x,y,...){
tryCatch({
v <- sum(...)
},
error=function(e){
cat ("ERROR: ", conditionMessage(e),"\n")})
return (v)
}
> addmore(2,3,6,8,9)
[1] 23
Statements can be seperated by ";", or just in different lines.
> total <- 0
> repeat { total <- total + 1; print(total); if (total > 6) break; }
[1] 1 [1] 2 [1] 3 [1] 4 [1] 5 [1] 6 [1] 7
Getting Help, for example function plot():
>?plot#show help page for function plot >help(plot) >??plot >help("xyplot",package="lattice") >help("!")#help for operator ! >help.start()#show HTML R help pages >help.search("plot")#show all functions which name has keyword plot
> apropos("test")
[1] ".valueClassTest" "ansari.test"
[3] "bartlett.test" "binom.test"
[5] "Box.test" "chisq.test"
[7] "cor.test" "file_test"
[9] "fisher.test" "fligner.test"
[11] "friedman.test" "kruskal.test"
[13] "ks.test" "mantelhaen.test"
[15] "mauchly.test" "mcnemar.test"
[17] "mood.test" "oneway.test"
[19] "pairwise.prop.test" "pairwise.t.test"
[21] "pairwise.wilcox.test" "poisson.test"
[23] "power.anova.test" "power.prop.test"
[25] "power.t.test" "PP.test"
[27] "prop.test" "prop.trend.test"
[29] "quade.test" "shapiro.test"
[31] "t.test" "testInheritedMethods"
[33] "testPlatformEquivalence" "testVirtual"
[35] "var.test" "wilcox.test"