+ - 0:00:00
Notes for current slide
Notes for next slide

STA 326 2.0 Programming and Data Analysis with R

Lesson 5.1: Recap-Functions

Dr Thiyanga Talagala

2020-03-10

1 / 8

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.

2 / 8

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:

flip_coin(10)
[1] "H" "T" "T" "H" "H" "H" "H" "H" "T" "T"
3 / 8
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
}
flip_coin(10)
[1] "T" "T" "H" "H" "H" "T" "H" "T" "T" "T"
4 / 8
  • 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.

5 / 8

Problem 3

Write a function to calculate the median.

help:

5%%2
[1] 1
4%%2
[1] 0
6 / 8

Problem 4

Write a function to calculate the correlation coefficient

r=i=1n(xix¯)(yiy¯)i=1n(xix¯)2i=1n(yiy¯)2

7 / 8

Slides available at: hellor.netlify.com

All rights reserved by Thiyanga S. Talagala

8 / 8

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.

2 / 8
Paused

Help

Keyboard shortcuts

, , Pg Up, k Go to previous slide
, , Pg Dn, Space, j Go to next slide
Home Go to first slide
End Go to last slide
Number + Return Go to specific slide
b / m / f Toggle blackout / mirrored / fullscreen mode
c Clone slideshow
p Toggle presenter mode
s Start & Stop the presentation timer
t Reset the presentation timer
?, h Toggle this help
Esc Back to slideshow