Introduction to Programming

CSULB Intro to R

April 13, 2018

Introduction

Agenda

  1. Some basics
  2. Making a sandwich
  3. Discussion & vocab lesson
  4. Programming Languages
  5. The R language

Why Program?

Computer Systems

Computer Systems

What is a Program?

Examples of Algorithms

Active Learning

Algorithm for making a BLT

Input: Slices of bread, slices of tomato, pieces of lettuce, strips of cooked bacon

Output: BLT sandwich

put down a slice of bread

put a slice of tomato on top of the bread

put a piece of lettuce on top of the tomato

put 3 strips of cooked bacon on top of the lettuce

put a second slice of bread on top of the bacon

return a BLT sandwich

Active Learning

Algorithm for swapping two variables

Input: Two variables: var1 and var2

Output: Same variables with values swapped

Copy value of var1 to temp

Copy value of var2 to var1

Copy value of temp to var2

Active Learning - Discussion

Programming Languages

  1. Syntax: describes valid combinations of symbols
    • 2 + 2 is syntactically correct, but + 2 2 isn’t
  2. Semantics: meaning given to those combinations
    • 2 + 2 means add 2 to 2
  3. Implementation (interpreted vs. compiled)

What is R?

RStudio

How R Works

Fundamentals of R

Naming Conventions for Objects

Simple Example

Let’s try some simple assignment operations…

n <- 10  # assign the value 10 to an object named n
n  # look at what R stored it as
## [1] 10
N <- 5  # assign the value 5 to an object named N
N  # inspect the result
## [1] 5
n == N  # are n and N equal?
## [1] FALSE
n + N  # add n and N
## [1] 15

Making a BLT in R

Let’s implement our BLT sandwich in R

# ingredients
bread <- "slice of bread"
tomato <- "slice of tomato"
lettuce <- "piece of romaine lettuce"
bacon <- "cooked strips of bacon"

# output the sandwich
print(bread)
print(bacon)
print(lettuce)
print(tomato)
print(bread)
## [1] "slice of bread"
## [1] "cooked strips of bacon"
## [1] "piece of romaine lettuce"
## [1] "slice of tomato"
## [1] "slice of bread"

Swapping two variables in R

Let’s implement our swap algorithm in R

# inputs
var1 <- 10
var2 <- 15

# perform the swap
temp <- var1
var1 <- var2
var2 <- temp

# inspect the results
var1
## [1] 15
var2
## [1] 10

Summary

Up Next