Intro to R Programming

Writing your own functions, R Script, Packages & Help pages

Ha Khanh Nguyen

Today’s Goal

  • First mission: assemble R code that will simulate rolling a pair of dice.
  • Then, we’ll weight the dice a bit in your favor.

Roll a Pair of Dice

## [1] 8
  • What is the purpose of the above code?

Roll a Pair of Dice

## [1] 1 2 3 4 5 6
## [1] 6 2
## [1] 8

Roll a Pair of Dice

  • What we want to have:
## [1] 5
## [1] 6
## [1] 8

Writing Your Own Function

  • Every function in R has 3 basic parts:
    • A name
    • A body of code
    • A set of arguments
  • To create a function in R:
  • function() will build a function out of whatever R code you place between the braces.

Writing Your Own Function

  • Code that would display a result:
## [1] 1 5
## [1] 3
## [1] 1.414214

Writing Your Own Function

  • Code that would NOT display a result:

Function Arguments

## [1] 2
## [1] 3
## Error in sample(x = bones, size = 2, replace = TRUE): argument "bones" is missing, with no default

Default Value in Function Arguments

## [1] 8
## [1] 7

Function Arguments

Today’s Goals

  • First mission: assemble R code that will simulate rolling a pair of dice.

Getting Help in R

Let’s switch over to RStudio!

To-do

References