Vectors and Functions

f(x)

Outline

Review

Vectors

Writing functions

Conditional statements

{version control review}

Using Github

Your machine

fork

Your copy

Starter repo

git clone

git add *

Edit files

Staging area

git commit -m ".."

git push

{vectors}

Vectors

Sequence of elements of the same type

Can be stored in a variable

Made by combining elements

x <- c(2,5,1,3)

Indexed starting at 1

x[1] # the number 2

Some helpful functions

Sequence (seq)

Colon operator (:)

Repeat (rep)

Length (length)

x <- seq(1,5) # 1,2,3,4,5
x <- 1:5 # 1,2,3,4,5
x <- rep(2, 4) # 2,2,2,2
length(c(1,2)) # 2

{exercise 1}

Recycling

Adding vectors

Add vectors of different length

Shorter vectors get recycled

x <- c(1,2) + c(1,2) # 2,4
x <- c(1,2) + 3 # 4,5
x <- c(1,1,1,1) + c(1,2) #2,3,2,3

Vector Manipulation

Retrieve a value at a given position

Retrieve multiple elements

Use a vector of Boolean values

x <- c('one','two','three')
x[2] # 'two'
x[c(1,2)] # 'one','two'
x[1:2] # 'one','two'
x[c(TRUE, FALSE, TRUE)] # 'one','three'
x <- c(1,2,3,4,5)
indices <- x > 3 # FALSE,FALSE,FALSE,TRUE,TRUE
x[indices]#3,4,5
x[x>3] #3,4,5

{exercise 2}

{writing functions}

Functions

Capabilities built into R

Accept a number of arguments

Return a single value

x <- c(2,5,1,3) # 2,5,1,3

function name 'c'

arguments

returns a vector

Writing functions

Generic

Example

function_name <- function(arguments) {
    statements
    return(object)
}
greet <- function(name) {
    obj <- paste('Good morning', name, 'today is', date(), sep=" ")
    return(obj)
}

greet("Mike") # Good morning Mike today is Thu Jan 14 15:24:26 2016

{exercise 3}

{conditional statements}

Conditional Statements

Only execute code under certain conditions

Provides greater control over program

Allows you to provide alternatives

Conditional Statements

Only execute code under a condition

if (SOME CONDITION IS TRUE) {
    do something
}

Perform different actions under different conditions

if (SOME CONDITION IS TRUE) {
    do something
} else if (SOME OTHER CONDITION IS TRUE) {
    do something else
} else {
    do a default action
}

Conditional Statements

if(condition1) {
    statements
} else if (condition2) {
    statements
} else {
    statements
}

Syntax:

Conditions

Conditions must be boolean (TRUE, FALSE)

# Boolean
if(TRUE) {
    print("it's true!")
}

# Evaluated as a Boolean
if(x > 1) {
    print("x is greater than one!")
}

{exercise 4}

Assignments

Assignment-2: Foundational skills (due Wed. 1/20)

r-2

By Michael Freeman