#' @title Add Variables
#'
#' @description Add home_score, away_score, home_points,
#' away_points, home_abbr and away_abbr variables to
#' a matches dataset.
#'
#' @param .data A data.frame with matches data
#' generated by brasileirao package.
#'
#' @return A data.frame with added variables.
#'
#' @export
#'
#' @examples
#' add_variables(matches)
#'
add_variables <- function(.data) {
scores <- .data$score
.data$home_score <- get_home_score(scores)
.data$away_score <- get_away_score(scores)
.data$home_points <- ifelse(
.data$home_score > .data$away_score,
3,
ifelse(.data$home_score == .data$away_score, 1, 0)
)
.data$away_points <- ifelse(
.data$away_score > .data$home_score,
3,
ifelse(.data$away_score == .data$home_score, 1, 0)
)
.data$home_abbr <- simplify2array(lapply(.data$home, get_abbr_name))
.data$away_abbr <- simplify2array(lapply(.data$away, get_abbr_name))
return(.data)
}
#' Get Home Team Score
#'
#' This function extracts the home team score from a vector of scores.
#'
#' @param scores A character vector containing scores.
#'
#' @return A numeric vector of the home team scores extracted from the input
#' scores.
#'
#' @examples
#' scores <- c("3x2", "1x0", "2x2")
#' get_home_score(scores)
#'
#' @export
#'
get_home_score <- function(scores) {
regmatches(scores, regexpr(pattern = "^[0-9]*", text = scores))
}
#' Get Away Team Score
#'
#' This function extracts the away team score from a vector of scores.
#'
#' @param scores A character vector containing scores.
#'
#' @return A numeric vector of the away team scores extracted from the
#' input scores.
#'
#' @examples
#' scores <- c("3x2", "1x0", "2x2")
#' get_away_score(scores)
#'
#' @export
#'
get_away_score <- function(scores) {
regmatches(scores, regexpr(pattern = "[0-9]*$", text = scores))
}
#' Get Abbreviated Team Name
#'
#' This function retrieves the abbreviated name of a team from the Brazilian
#' football league.
#'
#' @param team The full name of the team.
#' @return The abbreviated name of the team.
#'
#' @examples
#' team_name <- "São Paulo"
#' get_abbr_name(team_name)
#'
#' @export
get_abbr_name <- function(team) {
name <- brasileirao::teams$abbr[brasileirao::teams$team == team]
if (length(name) == 0) {
return(NA)
} else {
return(name)
}
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.