Solutions to some select R exercises.

R exercises are sprinkled throughout the textbook. A few short ones from sections 1.5 and 1.6 are provided below.

1.5.8: This exercise asks us to plot the random variable X with CDF:

$$ F(x) = \begin{cases} 0, & x \lt -1 \\ \frac{x+2}{4}, & -1 \le x \lt 1 \\ 1, & 1 \le x \end{cases} $$

There are several ways to assemble a discontinuous function in R. A common though altogether too scheme-ish approach is to use nested ifelse() stanzas. This approach is cumbersome and not very readable but works well. An export of the R session using this method is provided here.

discontinuousFunc <- function(x){ 
  ifelse(( x < -1), 0,
         ifelse((-1<x & x<1), (x+2)/4, 
                ifelse((x>1),1, NA)
          )
  ) 
}

# Create the plot
plot(discontinuousFunc, [...]) 

A cleaner way is to load a data.frame with the data, then plot it:

# Create independent var
x.axis = seq(-2, 2, 0.1)

# Create dependent var, set to 0 (x < -1)
y.axis <- rep(0, 10)

# Dependent var, -1 <= x < 1
x <- seq(-1, 1, 0.1)
y <- (x + 2) / 4
y.axis <- append(y.axis, y)

# Dependent var, x >= 1
y.axis <- append(y.axis, rep(1, 10))

plot.data <- data.frame(x.axis, y.axis)

This does have the side effect of creating plot “points” instead of lines though I am sure we can style around that if necessary. R Studio export here.

1.6.5: This exercise recycles the function from 1.6.2 and asks us to calculate the PMF and then plot the CDF. The code below is adapted from the source code provided by the textbook authors (see here).

ex165 <-
  function(){
     x = 0:5 # x = {0, 1, 2, 3, 4, 5}
     pmf = (choose(20, x) * choose(80, 5-x)) / choose(100, 5)
     tab = rbind(x, pmf)
     plot(pmf~x, xlab="x", ylab="pmf", pch="+", type='b')
     title("Exercise 1.6.5")

     return(tab)
  }

ex165()

The ~ operator used above is subtle and very useful. See help("tilde") for details.

R  amat554 

See also