---
title: "Lect02"
author: "oran.k@chula.ac.th"
date: "2023-07-08"
output: html_document
---

```{r setup, include=FALSE}
  knitr::opts_chunk$set(echo = TRUE)
```

# Lecture 02: Introduction to R/RStudio Programming

## Basic Programming

Algebra:

```{r}
5 + 3 ;
5 * 3 ;
5^3   ;
5 %% 3 ; 
5.6 %\% 3
```

Vector:

```{r}
c(1,2) + c(3,4) 
2*c(1,2)
c(7,6) + 3 
print( c(1,2) * c(3,4) )
```

Variable:

```{r}
##-- create variable 'varName '
varName <- c(1,2) 
length(varName) ; typeof(varName) ; str(varName)
varName[1] <- 2

## --remove 'varName'  
rm(varName) 
```

Sequence:

```{r}
varName <- seq(from=1,to=10,by=2)
sum(varName)
cumsum(varName) + cumprod(varName)
varName <- c(varName ,1:sum(varName))
varName > 10
isOdd <- varName %% 2 == 1
varName[isOdd]
```

Constant:

```{r}
month.name ; month.abb
LETTERS ; letters
pi ; Sys.Date() ; Sys.Time()
```

Function:

```{r}
testFn <- function(x){ 2*log(x) }
varName2 <- testFn(varName)
emptyFn <- function(x){} ## create buffer function
body(emptyFn) <- expression(3*x*sin(3*pi*x)) ## give value
```

General:

```{r}
which.min(varName2)
summary(varName2)
order(varName2 ,decreasing=F)
isExceed20 <- varName2 > 20
```

Matrix:

```{r}
aMat <- matrix( 1:16, ncol=4)
bMat <- cbind( c(1,5,8,9),c(0,1,-2,0),c(3,5,7,9),c(1,1,1,1))
det(aMat + bMat)
solve(aMat %*% t(bMat) )
```

\-\--

## Strength in R

Graphic:

```{r}
tempSeq <- seq(0,20,0.5)
plot(tempSeq ,testFn(tempSeq))
```

Statistic:

```{r}
set.seed(17)
stdNorm <- rnorm(50) 
hist(stdNorm ,breaks=10)
quantile(stdNorm ,prob=0.45)
table(floor(10*stdNorm))
shiftUnif <- runif(1000)-0.5
t.test(shiftUnif ,rnorm(1000))
shapiro.test(rbinom(5000,1000,0.5))
```

Workspace:

```{r}
getwd() ; setwd("C:/") ; R.home()
sink("default.out") ; source("scriptFile.R")
rm(ls(all.names=T)) ; dir()
```

Datasets:

```{r}
saveRDS(iris,"myObj.rds") ; readRDS("myObj.rds")
save(iris,mtcars,file="multiObj.RData")
save.image("allObj.RData") ; load("allObj.RData")
```

------------------------------------------------------------------------

## In-Class Exercise: Engineering Economy

This Engineering Economy Exercise

-   data

```{r}
cashflow <- c(-1350, 363, 551, 681, 761, 821, 1467)
intDef <- 0.08
```

-   concept

```{r}
period <- 0:(length(cashflow) -1)
cashflow.pv <- cashflow /(1+intDef) ^ period
sum(cashflow.pv)
```

-   funciton development

```{r, eval=F}
findPV <- function(cashflow,intDef){
  return("incomplete")
}

findNPV <- function(cashflow,intDef){
  sum(findPV(cashflow,intDef))
}
```

```{r}
intRange <- seq(0.01,0.20,0.01)
npvRange <- sapply(intRange ,findNPV ,cashflow=cashflow)
```

```{r}
plot(intRange ,npvRange)
abline(h=0,col="red") ## draw red line at y=0

##-- Decorate
plot(intRange ,npvRange , cex=0.5, pch=16, type="b",
     title="NPV Vs Intestest", ## specific title
     xlim=c(0,0.45),
     ylim=c(-1200,6000), ## specific scale,
     xaxt='n',yaxt='n',
     ylab="Net Present Value",xlab="interest rate") ## label
axis(2,at = seq(-1000,6000,200),col.tick="grey",cex.axis=0.7)
axis(1,at = seq(0,0.4,0.05),col.axis="blue",cex.axis=0.7)
mtext(4,text = paste("created by OKC on ",Sys.Date()),cex=0.6)
text(0.2,4200, paste( c("cash flow = ",cashflow),collapse=" "),cex=0.8)
```

## Calculus in R

```{r}
expr <- expression( x^2 + 3* sin(x) + log(x) ) 

##-- diff
D(expr,"x")


##-- integrate
integrate( function(x){x^2},0,1)

##-- std and importance trick for future
exprFn <- function(x){}
body(exprFn) <- deriv3(expr,"x") 
exprFn(3)


```
