107-1 R Basic TA 3

By CM

Outline

  • function

  • package

  • apply family

Function

In mathematics

e.g.  y = f(x) = x+3

Arguments?

y = f(x) = x+3

Generalization of concept of function

name = function(argument) = do something!

Function in R

(or in CS sense)
# Defining a function
y <- function(x){
    return (x+3)
}

# Using it !
y(5)
>>> 8

# It is equivalent to do...
x <- 5
x+3

Do something else

# Defining a function
y <- function(x, y, z){
    return (x+y+z)
}

# Using it !
y(5, 5, 7)
>>> 17

# It is equivalent to do...
x <- 5
y <- 5
z <- 7
x+y+z

(multi-variables)

More complicated case

#3 Fibonacci sequence
fibonacci <- function(n){
  if ((n == 1) | (n == 2)){
    return (1)
  } else {
    return (fibonacci(n-2) + fibonacci(n-1))
  }
}

fibonacci(10)
>>> 55
for(i in 1:10){
  print(fibonacci(i))
}
>>> 1  1  2  3  5  8  13  21  34  55  

(multi-variables)

Useful built-in function

 

help!

when you meet something new...

# HELP!
help(max)
?seq
args(dbinom)

Package

What is package?

toolkits made by other gods

Packages are collections of R functions, data, and compiled code in a well-defined format.

Installing packages

install.packages("dplyr")
[syntax]
install.packages(package_name)

Using packages

library(dplyr)
require(dplyr)
[syntax]
library(package_name)

or

require(package_name)

Useful packages

Apply

Apply family

Use apply function family instead of loop

We will introduce the following three commonly used functions:

  • lapply
  • sapply
  • vapply
  • ?lapply
  • ?sapply
  • ?vapply
  • :)

lapply

  • lapply(X, FUN, ...)

  • When you want to apply a function to each element of a list in turn and get a list back.

  • returns a list of the same length as X

  • each element of which is the result of applying FUN to the corresponding element of X.

sapply

  • sapply(X, FUN, ...)

  • When you want to apply a function to each element of a list in turn, but you want a vector back, rather than a list.

vapply

  • vapply(X, FUN, FUN.VALUE, ...)

  • similar to sapply

  • The FUN.VALUE argument expects a template for the return argument of this function FUN

  • FUN.VALUE: numeric / logical / ...

  • safer (and sometimes faster) to use

1071 R

By a136489

1071 R

for TA class 3

  • 512