Nguyen Cong Nghia

2 minute read

Programming in R

Input and Output

Typical print message:

x <- 5.8
cat("The result is",x,"N/m.\n")
## The result is 5.8 N/m.
x <- readline("Enter x: \n")
## Enter x:
x
## [1] ""
x <- as.numeric(x)
x
## [1] NA

Conditional Execution

The traditional if… else… syntax in R

x <- 6
y <- 0.5
if (x>2 & y<1){
  print(x)
  print(y)
}else{
  cat("Warning, x<=2 or y>-1\n")
}
## [1] 6
## [1] 0.5

Loops

R has powerful indexing power, therefore loops are needed considerably less ofen than in any conventional programming language.

for (f in seq(1,10,by=2)){
  cat("Square root of",f,"is",sqrt(f),"\n")
}
## Square root of 1 is 1 
## Square root of 3 is 1.732051 
## Square root of 5 is 2.236068 
## Square root of 7 is 2.645751 
## Square root of 9 is 3

Try to avoid loops if possible. Here is an alternative of the above codes:

x <- seq(1,10,by=2)
ee <- paste("Square root of",x,"is",sqrt(x),"\n")
cat(ee)
## Square root of 1 is 1 
##  Square root of 3 is 1.73205080756888 
##  Square root of 5 is 2.23606797749979 
##  Square root of 7 is 2.64575131106459 
##  Square root of 9 is 3

Commands apply, tapply, sapply are commonly a better approach.

User-defined Functions

function.name <- function(argument1,argument2,…)expression

For example: calculating a geometric mean, which defined as \(n^{th}\) root of the product of n numbers:

\[S = \sqrt{\prod_{i = 1}^{n} f(x_i)}\]

geo.mean <- function(x){
  z <- prod(x)^(1/length(x))
  return(z)
}
x = seq(1,100)
geo.mean(x)
## [1] 37.99269

Arguments to Functions

  • Pass them in the order matching the function’s definition

  • Supply the arguments in the form argument.name = value in an arbitrary sequence

my.plot <- function(x,y,symb="+",color="red"){
  plot(x,y,pch=symb,col=color)
}
x = seq(1,20,1)
y = seq(5,24,1)
my.plot(x,y)

my.plot(x,y,"o")

my.plot(x,y,color="blue")

args("my.plot")
## function (x, y, symb = "+", color = "red") 
## NULL

An alternative to Loops - sapply

sapply(x,FUN): apply a function FUN over a vector x.

sapply(seq(1,10,by=2), function(i){
  z <- paste("Square root of",i,"is",round(sqrt(i),3))
})
## [1] "Square root of 1 is 1"     "Square root of 3 is 1.732"
## [3] "Square root of 5 is 2.236" "Square root of 7 is 2.646"
## [5] "Square root of 9 is 3"
comments powered by Disqus