====== Programming in R ======
Cheat Sheat and Examples
==== Cheat Sheat ====
reference: {{ :math121b:r-cheat-sheet-3.pdf | CheatSheat PDF}}
=== variable manipulations ===
| function | meaning |
| c(1,3,4,5) | create a vector |
| 2:5 | create a sequence (2,3,4,5)|
| y[3] | say y is a vector, take the 3rd entry out of y |
| seq(2,10, by=0.5) | create a sequence, start from 2, ending at 10, step size = 0.5 |
| rep(1:3, times = 2) | repeat the sequence (1,2,3), 2 times, so get (1,2,3,1,2,3) |
| rep(1:3, each = 2) | repeat the sequence (1,2,3), each entry 2 times, so get (1,1,2,2,3,3) |
=== if .. else .. ===
if (i > 3)
{
print(‘Yes’)
} else {
print(‘No’)
}
=== For loop ===
for (i in 1:4)
{
j <- i + 10
print(j)
}
=== function ===
square <- function(x)
{
squared <- x*x
return(squared)
}
==== Sampling ====
|Distribution | sampling | density function | cumulative density function |
| Normal | rnorm | dnorm | pnorm |
| Poisson | rpois | dpois | ppois |