## ------------------------------------------------------
a <- 0

if (a != 0) {
  print(1/a)
} else{
  print("No reciprocal for 0.")
}


## ------------------------------------------------------
library(dslabs)
murder_rate <- murders$total / murders$population*100000


## ------------------------------------------------------
ind <- which.min(murder_rate)

if (murder_rate[ind] < 0.5) {
  print(murders$state[ind]) 
} else{
  print("No state has murder rate that low")
}


## ------------------------------------------------------
if (murder_rate[ind] < 0.25) {
  print(murders$state[ind]) 
} else{
  print("No state has a murder rate that low.")
}


#### Exercise
scores<-c(55, 82, 91, 40, 67, 78, 100, 62, 35, 88)


####"Build a Grading Machine"
#### 
##### Write a if/else statemnt to determine Pass/Fail (>=60 or not) for score[1]

if(scores[2]>=60){
	print("PASS")
}else{
	print("FAIL")	
}



#### Exercise 2 
####"Build a Grading Machine"
##### Write a if/else statemnt to determine score[9]
### score >= 90, A
### score >= 80, B
### score >= 70, C
### otherwise, F

if(scores[9]>=90){
	print("A")
}else if(scores[9] >=80){
	print("B")
}else if (scores[9]>=70){
	print("C")
}else{
	print("F")
}

## ------------------------------------------------------
a <- 0
ifelse(a > 0, 1/a, NA)


## ------------------------------------------------------
a <- c(0, 1, 2, -4, 5)
result <- ifelse(a > 0, 1/a, NA)

b<-c(0, 1, 1, 0)
ans<-ifelse(b==0, "MALE", "FEMALE")



## ------------------------------------------------------
no_nas <- ifelse(is.na(na_example), 0, na_example) 
sum(is.na(no_nas))




## ------------------------------------------------------
z <- c(TRUE, TRUE, FALSE)
any(z)
all(z)


################################# 
#### For Loops 
############################
------------------------------------------------------
for (i in 1:5) {
  print(i)
}



## ------------------------------------------------------
m <- 25
s_n <- vector(length = m) # create an empty vector
for (n in 1:m) {
  s_n[n] <- sum(1:n)
}

############### 
#### Exercise: 
#### 
################
scores<-c(55, 82, 91, 40, 67, 78, 100, 62, 35, 88)

#### write a for loop to return letter grades for all students  


for (i in scores){
	if(i >=90){
		print("A")
	}else if(i >=80){
		print("B")
	}else if (i >=70){
		print("C")
	}else{
		print("F")
	}
}


####### 

newfunction<-function(x, y){
	ans<-x^2 + y^2
	return(ans)
} 

plot(x<-seq(-3, 3, by=0.01), square_me(x))



## ------------------------------------------------------
avg <- function(x){
  s <- sum(x)
  n <- length(x)
  s/n
}


## ------------------------------------------------------
x <- 1:100
identical(mean(x), avg(x))


## ------------------------------------------------------
s <- 3
avg(1:10)
s


## ---- eval=FALSE---------------------------------------
## my_function <- function(VARIABLE_NAME){
##   perform operations on VARIABLE_NAME and calculate VALUE
##   VALUE
## }


## ------------------------------------------------------
avg <- function(x, arithmetic = TRUE){
  n <- length(x)
  ifelse(arithmetic, sum(x)/n, prod(x)^(1/n))
}


## ------------------------------------------------------
compute_s_n <- function(n) { 
  sum(1:n)
}





## ----sum-of-consecutive-squares, out.width="50%", echo=FALSE----
n <- 1:m
plot(n, s_n)


## ------------------------------------------------------
x <- 1:10
sqrt(x)
y <- 1:10
x*y

############### 
#### Exercise: 
#### 
################
scores<-c(55, 82, 91, 40, 67, 78, 100, 62, 35, 88)

#### write a function (named grade_it) to return letter grade for a score

grade_it<-function(grade){
	if(grade >=90){
		return("A")
	}else if(grade >=80){
		return("B")
	}else if (grade >=70){
		return("C")
	}else{
		return("F")
	}
}


grade_it(30)


#############################################   
#### Exercise: 
#### Write a for loop using the grade_it function 
##############################################  
scores<-c(55, 82, 91, 40, 67, 78, 100, 62, 35, 88)

letter_grade<-rep("NA", length(scores))
for(i in 1:length(scores)){
	letter_grade[i]<-grade_it(scores[i])
}



## ------------------------------------------------------
x <- 1:10
sapply(x, sqrt)



############### 
#### Exercise: 
#### Build a grading machine 
################
#### Use sapply using the grade_it function 

scores
letter_grade<-sapply(scores, grade_it)



############ apply 
mat<-matrix(1:20, ncol=2)
cMean<-apply(mat, 2, mean)
cMean
rMean<-apply(mat, 1, mean)
rMean



###########################################################################  
#### Exercise 
#  1. Generate 30 random numbers from normal distribution (rnorm)
#  2. Randomly assign 15 to the control group and 15 to the treatment group 
#  3. Perfom t test and report p value
#############################################################################

obs<-rnorm(30, mean=0, sd=1)
## sample
set.seed(123)
sample(c("A", "B", "C"), 1)

############# not goood!! 
control<-sample(obs, 15)
trt<-sample(obs, 15)
###################

################### This is good!! 
icontrol<-sample(1:30, 15)
control<-obs[icontrol]
trt<-obs[-icontrol]
res<-t.test(control, trt)
str(res)
pvalue<-res$p.value

##### do this 1000 times

sim=1000
n<-15
pvalue<-numeric(sim)
for(i in 1:sim){
	obs<-rnorm(2*n)
	icontrol<-sample(1:(2*n), n)
	control<-obs[icontrol]
	trt<-obs[-icontrol]
	res<-t.test(control, trt)
	pvalue[i]<-res$p.value
}

#### Note that iter is never actually used inside the function 
###########  it's just a placeholder so sapply has something to iterate over. This is a common pattern in R simulations.
getpvalue<-function(iter, n){
	obs<-rnorm(2*n)
	icontrol<-sample(1:(2*n), n)
	control<-obs[icontrol]
	trt<-obs[-icontrol]
	res<-t.test(control, trt)
	ans<-res$p.value
	return(ans)
}
set.seed(1)
pvalue_sapply<-sapply(1:1000, getpvalue, n=15)

################
## Alternative 
#################
set.seed(1)
pvalue_replicate <- replicate(1000, getpvalue(iter = NULL, n = 15))
   
identical(pvalue_sapply, pvalue_replicate)   
