R Lecture#3
R Lecture#3
R Lecture#3
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)