If-else statement

  1. load in the Orange dataset
  2. Create a new, empty variable
  3. Write a for loop to iterate over the rows of the dataset
  4. Write an if else statement that classifies trees based on their circumference: <= 65.5 – small >65.5 & <= 161.5 – medium >161.5 large
  5. Do the same with ifelse() in one step.
data("Orange")

Hmisc::describe(Orange)
## Orange 
## 
##  3  Variables      35  Observations
## --------------------------------------------------------------------------------
## Tree 
##        n  missing distinct 
##       35        0        5 
## 
## lowest : 3 1 5 2 4, highest: 3 1 5 2 4
##                               
## Value        3   1   5   2   4
## Frequency    7   7   7   7   7
## Proportion 0.2 0.2 0.2 0.2 0.2
## --------------------------------------------------------------------------------
## age 
##        n  missing distinct     Info     Mean      Gmd 
##       35        0        7     0.98    922.1      566 
## 
## lowest :  118  484  664 1004 1231, highest:  664 1004 1231 1372 1582
##                                                     
## Value        118   484   664  1004  1231  1372  1582
## Frequency      5     5     5     5     5     5     5
## Proportion 0.143 0.143 0.143 0.143 0.143 0.143 0.143
## --------------------------------------------------------------------------------
## circumference 
##        n  missing distinct     Info     Mean      Gmd      .05      .10 
##       35        0       30    0.999    115.9    66.97     30.0     32.4 
##      .25      .50      .75      .90      .95 
##     65.5    115.0    161.5    193.4    204.8 
## 
## lowest :  30  32  33  49  51, highest: 177 179 203 209 214
## --------------------------------------------------------------------------------

For, while loop

  1. for each tree (1 to 5), print the ages.
  2. for each tree, print the age, in which they were small.
  3. load esoph dataset.
  4. Using for loop(s), summarize ncontrols by agegp and alcgp, skipping the category alcgp==“120+” & agegp==“25-34”.
  5. Using a for loop simulate the flip a coin twenty times, keeping track of the individual outcomes (1 = heads, 0 = tails) in a vector that you preallocte.
  6. Use a while loop to investigate the number of terms required before the product 1234… reaches above 10 million
  7. Use a nested for loop (a for loop inside a for loop) that produces the following matrix, preallocate the matrix with NA values.

apply, lapply, etc…

  1. define the following dataset:
dataset1 <- cbind(observationA = 16:8, observationB = c(20:19, 6:12))
  1. Calculate row and column means with apply

  2. Use apply to multiply the whole table by 3.

  3. create a list with 3 list elements. Print the length of each element.

lll <- list(list(1,3,5,6,1), list(5,2,1), list(6,2,5,7,3,1,9))