You are on page 1of 24

INTRODUCTION TO COMPUTING

FOR ECONOMICS
Tanweer Ul Islam, PhD
Advanced R- Conditional
Execution
• We might want some parts of our code to
be executed only under certain conditions.
• IF statement:
if (condition) {expression1} else
{expression2}
• Condition has to be a single logical value
(TURE/FALSE). If it is TRUE, expression
1 is executed otherwise expression 2.
Conditional Execution
• Example:
• Use the following data to test,
• x=c(10, 12, 8, 5, 15, 17, 5, 8, 12, 9, 10, 4, 15, 14, 8)
ts=t.test(x, mu=10)
if (ts$p.value<=0.05){print("reject Ho")} else
{print("don't reject Ho")}
Loops
• Command Structure:
for (loop variable in vector) { some commands}
• Example:
for (i in 1:6) { if (i<4) { print (i^3)} else {print (i^2)}}
Loops
• Example:
• x=c(10, -12, 8, -5, 15, 17, 5, -8, 12, 9, 10, -4, 15, 14,
8)

for (i in 1:15) {if (x[i]<0) {print("-ve")} else if (x[i]>0)


{print("+ve")} else {print("zero")}}
Functions
• Functions are special kinds of objects in R. There are
many pre-defined functions in R.
• The command function (arg1, arg2, …) defines a new
function which accepts the arguments arg1, arg2, …
• Write your function in R script and save file with
function name and file extension, Rmd.
Functions
• Create a function to print squares of numbers in sequence.
new.function <- function(a) {
for(i in 1:a) {
b <- i^2
print(b)
}
}
• Call the function new.function supplying 6 as an argument.
new.function(6)
Functions- Activity
•Write a function that computes the following
utility function

•Write a function for the following generalized


utility function
Functions- Activity Solution
•Solution for first Question:
uf=function(x1,x2){
u=(x1^0.5)*(x2^0.5)
print(u)
}
Functions- Activity

• Write a function for one sample t-test we


have studied in last lecture don’t use the
built-in one.
Functions- Activity Solution
mt.test=function(x,mu){n=length(x)
mx=mean(x)
sex=sd(x)/sqrt(n)
t=(mx-mu)/sex
p=2*(1-pt(abs(t),n-1))
print(t)
print(p)
}
R Built-in Functions
Almost everything in R is done through functions. Here I'm only
referring to numeric and character functions that are commonly
used in creating or recoding variables.
Function Description
abs(x) absolute value
sqrt(x) square root
ceiling(x) ceiling(3.475) is 4
floor(x) floor(3.475) is 3
trunc(x) trunc(5.99) is 5
R Built-in Functions
Function Description
round(x, digits=n) round(3.475, digits=2) is 3.48
signif(x, digits=n) signif(3.475, digits=2) is 3.5
cos(x), sin(x), tan(x) also acos(x), cosh(x), acosh(x),
etc.
log(x) natural logarithm
log10(x) common logarithm
exp(x) e^x
R Built-in Functions
The following table describe functions related to probability
distributions.
Function Description
dnorm(x) normal density function (by default m=0 sd=1)
# plot standard normal curve
x <- pretty(c(-3,3), 30)
y <- dnorm(x)
plot(x, y, type='l', xlab="Normal Deviate",
ylab="Density", yaxs="i")
pnorm(q) cumulative normal probability for q
(area under the normal curve to the right of q)
pnorm(1.96) is 0.975
R Built-in Functions
Function Description
qnorm(p) normal quantile.
value at the p percentile of normal distribution
qnorm(.9) is 1.28 # 90th percentile
rnorm(n, m=0,sd=1) n random normal deviates with mean m
and standard deviation sd.
#50 random normal variates with mean=50, sd=10
x <- rnorm(50, m=50, sd=10)
mean(x, trim=0.05, # trimmed mean, removing any missing values and
na.rm=TRUE) # 5 percent of highest and lowest scores
mx <- mean(x,trim=0.05,na.rm=TRUE)
R Built-in Functions
Function Description
range(x) range
sum(x) sum
diff(x, lag=1) lagged differences, with lag indicating
which lag to use
scale(x, center=TRUE, standardize the data by subtracting
scale=TRUE) mean and dividing by sd.
R Built-in Functions
Function Description
seq(from , to, by) generate a sequence
indices <- seq(1,10,2)
#indices is c(1, 3, 5, 7, 9)
rep(x, ntimes) repeat x n times
y <- rep(1:3, 2)
# y is c(1, 2, 3, 1, 2, 3)
cut(x, n) divide continuous variable in factor
with n levels
y <- cut(x, 5)
Monte Carlo Simulation
• In real-world applications, we typically have a sample
from a well-defined population.
• We don’t know the population parameters. We may
apply the Monte Carlo Simulations to estimate them.
• The procedure would be:
a. Select a population distribution and its parameters
b. Generate a sample from this distribution
c. Use the sample to estimate the population parameters
Simulation Exercise
• Let’s simulate a situation in which we want to estimate
the ‘mean’ of a normally distributed random variable.

• Draw 1000 samples of size 50 and calculate the sample


average for all of them.
Simulation Exercise
xbar<- numeric(1000)
for (i in 1:1000) {
x<- rnorm(50,10,2)
xbar[i]=mean(x)
}
plot(density(xbar))
curve(dnorm(x,10,sqrt(0.08)),add=TRUE, lty=2)
Simulation Exercise Challenge

• Draw 1000 random normal samples of size 50 with


mean 10 and sd=2 and apply t-test, save p-values &
make a table of correct and wrong decisions.
Simulation Exercise Challenge
s=10
n=50
m=10
sd=2
t=numeric(s)
p=numeric(s)
for (i in 1:s) {
Simulation Exercise Challenge
x=rnorm(n,m,sd)
xx=t.test(x,mu=m)
p[i]=xx$p.value
}
d<- p<=0.05
table(d)
Thank You!

You might also like