POP77001 Computer Programming for Social Scientists
\[ \begin{equation} Median = \begin{cases} Y_{(n + 1)/2} & \text{when n is odd}\\ \frac{1}{2} (Y_{(n/2} + Y_{n/2 + 1}) & \text{when n is even}\\ \end{cases} \end{equation} \]
if)for)length())ifif - defines condition under which some code is executedif (<boolean_expression>) {
<some_code>
}
if - elseif - else - defines both condition under which some code is executed and alternative code to executeif - else if - elseif - else if - ... - else - defines both condition under which some code is executed and several alternativesif (<boolean_expression>) {
<some_code>
} else if (<boolean_expression>) {
<some_other_code>
} else if (<boolean_expression>) {
...
...
} else {
<some_more_code>
}
ifelse() functionif - else construct.ifelse(<boolean_expression>, <if_true>, <if_false>)
TRUE or FALSE.4.2.0.whilewhile defines a condition under which some code (loop body) is executed repeatedly.while (<boolean_expression>) {
<some_code>
}
forfor defines elements and sequence over which some code is executed iteratively.for (<element> in <sequence>) {
<some_code>
}
Iterations can be combined with conditional statements to create more complex control flows.
:: allow to generate sequences of integers.<from>:<to>
seq()seq() function that we encountered in subsetting can be used in looping.: that allows to specify the step size.seq_len() and seq_along()seq(<from>, <to>, <by>)
seq_len(<length>)
seq_along(<object>)
1:length(x).Error in rnorm(10, means[[i]]): invalid arguments
seq_along(x) instead.break and nextbreak - terminates the loop in which it is containednext - exits the iteration of a loop in which it is contained