## Expressions and assignments
(5^2)*(10-8)/3 + 1       ## An expression
x <- (5^2)*(10-8)/3 + 1  ## An assignment
x

## Using and combining assignments
x+1
n <- 50
x/n

## Class
class(x)

## Functions
x <- 1:9  ## Creates a vector of numbers 1, 2, ..., 9
mean(x)
median(x)
sd(x)
min(x)
sum(x)
x^2
sum(x^2)

## Function options
x <- runif(1000)
y <- runif(1000, min=10, max=20)
hist(x)
hist(y, col="gray", border="white", breaks=40)

## Vectors
x <- runif(10)     ## A numeric vector
y <- letters[1:10] ## A character vector
z <- x > 0.5       ## A logical vector
x
y
z

## Combining vectors of different types: Problem
a <- c(x, y) ## Probably not what you want
a[1] + a[2]

## Lists
a <- list(x=x, y=y, z=z)
a$x
a$x[1] + a$x[2]
toupper(a$y[3])
a[[3]]

## Data frame: tips
tips <- read.delim("http://myweb.uiowa.edu/pbreheny/data/tips.txt")
head(tips)
class(tips$TotBill)
class(tips$Sex)

## Attach and with
with(tips, mean(TotBill))
mean(TotBill)
attach(tips)
mean(TotBill)
detach(tips)

## Adding a variable
tips$Rate <- with(tips, Tip/TotBill)

## Factors
table(tips$Sex)
levels(tips$Sex)
barplot(table(tips$Day))

## Releveling
tips$Day <- factor(tips$Day, levels=c("Thu", "Fri", "Sat", "Sun"))
barplot(table(tips$Day))

## Indexing
x <- runif(7, 50, 100)
names(x) <- c("Youwei", "Brandon", "Ziqian", "Biyue", "Jacob", "Ryan", "Anthony")
x[x > 75]  ## Logical vector
x[1:3]  ## Positive integers
x[-(5:6)]  ## Negative integers
x[c("Brandon", "Biyue")]  ## Names
x[]

## Indexing rows only
tips[tips$Tip >= 7, ]

