Creating your own function

There are a few important items to note about the creation of functions in R. Functions return a value. As a rule, functions return the value of the last expression in the function body.

Local variables are set temporarily for the duration of the function call, and they are cleared when the function exists.

Function parameters affect the function locally, and the original caller's value is not changed.

You can create your own functions using the function keyword. Here is an example of a function created from an earlier piece of code:

myfunction <- function(x, y, z) tapply(x,y,z)

So, if we take our earlier example, we could change it so that it uses functions:

output <-
  data.frame(MinPetalLength=myfunction(iris$Petal.Length,iris$Species,max),
             MaxPetalLength=myfunction(iris$Petal.Length,iris$Species,max),
             MeanPetalLength=myfunction(iris$Petal.Length,iris$Species,mean),
             NumberofSamples=myfunction(iris$Petal.Length,iris$Species,length))
print(output)
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset