Lab1: Introduction to R


Getting Started with R

Click on the R icon

(If no R icon, go to the C drive and the Programs folder to find R or search for R)

To quit R:

> q()

What does it ask you? What does this mean?

For R HELP, for example to get help about the function runif ,

> help(runif)

For R HELP in html format

If you go to Help on the R toolbar and select R language (html), you will get the html version of help.


Example 1: Let the games begin.

Generate a sample of 100 N(0,1) random variables.

> help(rnorm)

> temp <- rnorm(100)

What is in the object temp?

What is the length of the oject temp?

Make a informative plot of temp?

If this were part of a homework problem, you might want to copy and paste the R code and plot into a Word Document?
Say what? Let's try knitr today after we go through R Lab.

Try it!

Note: To copy and paste from the graphics window,
Right click on the mouse and select Copy as metafile, then Paste.


Example 2: The Binomial Distribution

For the binomial distribution, these functions are pbinom, qbinom, dbinom, and rbinom.

For help, use the help function on one of the four functions above.

Problem: Dr. Dribble has a probability of .8 of making free throws each time he shoots. What is the probability of him making at least 8 out of 10 free throws?

Assume his shots are independent of each other.

Let X be the number of free throws made. X is has a Binomial(10, 0.8) distribution. What does this look like?

Let's generate a large number of Binomial(n,p) random variables and look at the histogram.

> set.seed(1)
> bindat <- rbinom(n=10000, size=10, prob=0.8)
> hist(bindat, breaks=seq(2, 10, 1), freq=F)
We want to find the probability of making at least 8 out of 10 free throws.

Let's calculate P(X <= 7) when X is has the Binomial(10, 0.8) distribution using the pbinom function.

Now, to answer the question: P(X >= 8) = 1 - P(X <= 7) = 1-0.3222005 = 0.6777995


Example 3: Binomial Test

> help(binom.test)

Class example: Binom(25,0.4). If B=15, what do you conclude?

> binom.test(15,25,0.4, alternative="greater")

Calculate P(B >= 15) in R. For the signficance level, P(B >= 14)?

What about CI's for this test? (see help function)


Intro to knitr:

Here are some knitr resources
Send me more and I will gladly add to this!

Here is a HW template that I have made for you (Thanks Nick!): STAT672HW0knitr.Rnw


Intro to R:

Try going through the following Intro. Lessons. The # sign is a comment, so you can copy and paste.

  • R vectors, lists and functions
  • R arithmetic and logical operators
  • R simple functions
  • R univariate random variable generators