Do this before class

Read R4DS chapter 21.

Complete the course Foundations of Functional Programming with purrr at DataCamp.

During class

Solve exercises in R4DS chapter 21.5.3.

A likelihood function

If \(x\) is a vector of \(n\) independent \(Exponential(\lambda)\)-distributed random variables, the likelihood function for \(\lambda\) is

\[ L(\lambda)= \prod_{i=1}^n\lambda\exp(-x_i\lambda) \] This can be computed given a value of \(\lambda\) using

L_exp <- function(x, lambda) {
  prod(dexp(x, lambda))
}

We try with

set.seed(1)
x <- rexp(100, 1)
L_exp(x, 1)
## [1] 1.730976e-45

which seems to work. If we want to plot the function, we need to compute it over a sequence of \(\lambda\)-values. Trying

lambda <- seq(0.5, 2, length.out = 10)
L_exp(x, lambda)
## [1] 7.026489e-50

gives a scalar instead of the intended vector of \(L\)-values, what is computed? Use map_dbl to compute the vector \((L(\lambda_1), \ldots, L(\lambda_{10}))\).

More SHL-players

The function get_player below fetches data on an SHL-player given an url of the type "http://www.shl.se/lag/087a-087aTQv9u__frolunda-hc/qQ9-a5b4QRqdS__ryan-lasch"

library(httr)
library(purrr)
get_player <- function(url){
    response <- GET(paste0(url, "/statistics"))
    player_xml <- content(response, "text") %>% 
        read_html(player_page)
    css <- list(".rmss_c-squad__player-header-name-h", # Namn
                ".rmss_c-squad__player-header-name-info-position", #Position
                ".rmss_c-squad__player-header-info-items-item-value") # Info
    map(css, html_elements, x = player_xml) %>% 
      map(html_text) %>% 
      unlist() %>% 
      unique() %>%
      set_names(c("Namn", "Position", "Födelsedatum", "Ålder", "Nationalitet", "Längd", "Vikt", "Skjuter"))
}

make sure it returns a suitable error-message if the GET-call fails (in a successful call, response$status_code equals 200). Construct a new function get_team, that given an url of the form "https://www.shl.se/lag/8e6f-8e6fUXJvi__malmo-redhawks/roster" generates a data.frame of players and informations from get_player.