Saturday

How to code your own function in R programming language?

Advantage of a function

To automate certain tasks that you have to repeat over and over

Syntax

<object name> = function(<set of parameters>) {
    <set of R statements>
}


Examples

# Firstly, check the new function name
# so that this name is not the built-in functions in R
> getBasicStats
Error: object 'getBasicStats' not found

> getBasicStats = function(x) {
    stats = list()
    stats$length = length(x)  #$ used to reference an item
                              #in the list by its key name
    stats$mean = mean(x)
    stats$sd = sd(x)
    stats$median = median(x)
    unlist(stats)  #show stats as a horizontal vector
                   #instead of as a vertical list
}

> getBasicStats(c(1,2,3,4,5))
  length     mean       sd   median
5.000000 3.000000 1.581139 3.000000


/* */

No comments:

Measure execution time with Julia, example using sorting algorithms

# random integers between 1 and 100 inclusive, generate thousands of them x = rand ( 1 : 100 , 100000 ) @time sort (x; alg=InsertionSort, r...