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:

If a hater attacked your age and not the goodness of you

Whether young or old, I've always been known what endures. I've known the very idea of people that were all created equal and deserv...