class: center, middle, inverse, title-slide # STA 326 2.0 Programming and Data Analysis with R ## Lesson 5.1: Recap-Functions ### Dr Thiyanga Talagala ### 2020-03-10 --- # Problem 1 Write a function to prints out standard random normal numbers (use rnorm()) but stops (breaks) if you get a number bigger than 1. Using next adapt the loop from last exercise so that doesn’t print negative numbers. --- # Problem 2 Write a function to simulate the flip a coin `\(n\)` times, keeping track of the individual outcomes (1 = heads, 0 = tails) in a vector that you preallocte. Assume `\(P(H)=0.5\)`. Example output: ```r flip_coin(10) ``` ``` [1] "H" "T" "T" "H" "H" "H" "H" "H" "T" "T" ``` --- ```r flip_coin <- function(n){ out <- numeric(n) for (i in 1:n){ coin.out <- rbinom(1, p=0.5, n=1) if(coin.out==1){ out[i] <- "H" } else { out[i] <- "T" } } out } ``` ```r flip_coin(10) ``` ``` [1] "T" "T" "H" "H" "H" "T" "H" "T" "T" "T" ``` --- - Modify the function so that it takes another argument, which will be the `\(P(H)\)`. - Run the function 10, 100, 1000 and 10000 times with `\(P(H)=0.8\)` and report the proportion of times that head is selected. --- # Problem 3 Write a function to calculate the median. help: ```r 5%%2 ``` ``` [1] 1 ``` ```r 4%%2 ``` ``` [1] 0 ``` --- # Problem 4 Write a function to calculate the correlation coefficient `$$r=\frac{\sum_{i=1}^{n}(x_i-\bar{x})(y_i-\bar{y})}{\sqrt{\sum_{i=1}^n(x_i-\bar{x})^2\sum_{i=1}^n(y_i-\bar{y})^2}}$$` --- class: center, middle Slides available at: hellor.netlify.com All rights reserved by [Thiyanga S. Talagala](https://thiyanga.netlify.com/)