Download as pdf or txt
Download as pdf or txt
You are on page 1of 18

Computer Programming with R

Writing New R functions


Salma Akter
Lecturer
Department of Statistics
Jagannath University
Writing New R functions

• In R there are many built-in functions: plot, summary, sum, ...


• There are also thousands of functions contributed by the R community (check the help file of any
library).
• You can also write your own function for a particular problem.
Writing New R functions

• The syntax for writing a function is:


function.name <- function(arg1,arg2,…..) {
body of the function
return(return value)
}
Ex: Given a number x, this function returns 2x+5.
myf1 <- function(x) {
y <- 2 * x + 5
return(y)
}
myf1(2)
Writing New R functions

• The return statement can be omitted since by default R will return the last
evaluated expression.
Ex: myf2 <- function(x) {
2*x+5
}
myf2(5)
##Arguments can be given default values
Ex: myf3 <- function(x = 3) {
2*x+5
}
• myf3() # x takes the default value
myf3(5) # overrides the default value
Writing New R functions

• Functions can have several arguments.


Ex: myf4 <- function(x = 3, y = 5) {
2*x+y+5
}
myf4() # default values
myf4(4) # x = 4, y = default
##An R function is allowed to return only a single R object. Lists are useful in R to
return multiple values.
myf5 <- function(x = 3, y = 5) {
z <- 2 * x + y + 5
return(list(input = c(x, y), result = z))
}
• out <- myf5(4, 6)
class(out)
names(out)
Writing New R functions

• Ex: f6<-function(x,y){
x+y
}
f6(3,4)
Ex:
f7<-function(x,y){
2*x+y
x+2*y
2*x+2*y
x/y
}
f7(1,2)
## The function f7 does not have a return statement and thus only report
the last of the computations.
Writing New R functions

• Ex:
f8<-function(x,y){
z1<-2*x+y
z2<-x+2*y
z3<-2*x+2*y
z4<-x/y
return(c(z1,z2,z3,z4))
}
f8(1,2)
Writing New R functions

## Functions can include loops and conditional statements.


Ex: myf9 <- function(x = 3, y = 5) {
if (x > 2) {
print("x is greater than 2")
return(3 * y + 2)
} else {
print("x is lower than or equal to 2")
return(3 * y + 5)
}
myf9(5, 3)
myf9(1, 3)
Writing New R functions

Ex: Write a function that takes a matrix as input and calculate the sum of each row of the matrix
and returns the output as a vector.
myrowSums <- function(a) {
nr <- nrow(a) # number of rows in a
sumr <- numeric(nr) # initialize a vector of length nr
for (i in 1:nr) {
sumr[i] <- sum(a[i, ])
}
return(sumr)
}
a<-matrix(10:15, 2, 3)
myrowSums(a)
Writing New R functions
• This is equivalent to:
rowSums(a)
apply(a, 1, sum)
Ex: Write an R function that will find the column sums as a vector of x
mycolSums <- function(a) {
nr <- ncol(a) # number of rows is a
sumr <- numeric(nr) # initialize a vector of length nr
for (i in 1:nr) {
sumr[i] <- sum(a[, i ])
}
return(sumr)
}
a<-matrix(10:15,2,3)
mycolSums(a)
Writing New R functions

• Ex:
f<-function(x,y){
z1<-2*x+y
z2<-x+2*y
z3<-2*x+2*y
z4<-x/y
list(z1,z2,z3,z4)
}
f(1,2)
Ex: f<-function(x,y){
z1<-x+y
z2<-x+2*y
list(result1=z1,result2=z2)
}
f(3,9)
Writing New R functions
• Ex: f<-function(x){
for(i in 1:x){
y<-i*2
print(y)
}
return(y*2)
}
f(3)
Ex: f<-function(x){
i<-0
while(i<x){
i<-i+1
y<-i*2
print(y)
}
return(y*2)
}
f(5)
Writing New R functions

• Ex: my.total<-function(x){
n<-length(x)
s<-0
for(i in 1:n){
s<-s+x[i]
}
return(s)
}
x<-c(20,25,30)
## data<-rnorm(50,100,15)
my.total(data)
Ex: Write a program to find sum and product of a set of numbers using for loop. Compute sum and
product of the observations 2,4,6,8,10.
Sum.Prod<-function(x){
Sum<-0
Prod<-1
for ( i in 1:length(x)){
Sum<-Sum+x[i]
Prod<-Prod*x[i]
}
return(c(Sum=Sum, Product=Prod))
}
x<-c(2,4,6,8,10)
Sum.Prod(x)
1 1 1
• Ex: Write an R function that will calculate 13 + 33 + ⋯ + 993 and × ×⋯× .
13 33 993
Sum.prod<-function(x){
Sum<-0
Prod<-1
for( i in 1: length(x)){
Sum<-Sum+(x[i])^3
Prod<-Prod*(1/x[i])^3
}
return(c(Sum=Sum,Product=Prod))
}
x<-seq(1,99,2)
Sum.prod(x)
4
Ex: the volume of a sphere of radius r is given by 𝜋𝑟 3 . For spheres having radii 2,3,4,5,…,20. find
3
the corresponding volumes and print the results out in a table.

vol.sphr<-function(r) {
if(r<0) { stop(“need positive value of radius”)}
vol<- (4/3)*pi*r^3
Sphr.vol<-data.frame (radious=r, volume=vol)
return(Sphr.vol)
}
radious<-2:20
vol.sphr(radious)
• Ex: write an R function that will take matrix and a vector Y as inputs and perform all of the
followings:
i) Add a column of 1’s as the first column of X
ii) Calculate 𝛽=(𝑋 ′ 𝑋)−1 𝑋 ′ 𝑌
iii) Calculate 𝑒 = 𝑌 − 𝑋𝛽
iv) Output will be 𝛽 and e
Solution:
ls.model<-function(X,Y){
X<-cbind(1,X)
Bhat<-solve((t(X)%*%X))%*%t(X)%*%Y
E<-Y-X%*%Bhat
list(B.est=Bhat, error=E)
}
### Write R programme for the following Fibonacci numbers
0 1 1 2 3 5 8 13 21 34 55 89 144

Solution:
fibo<-function(n){
fibvals<-c()
fibvals[1]<-0
fibvals[2]<-1
for (i in 3:n){
fibvals[i]<-fibvals[i-1]+fibvals[i-2]
}
return(fibvals)
}
fibo(12)

You might also like