content
stringlengths
0
14.9M
filename
stringlengths
44
136
#' Create a package skeleton #' # ------------------------------------------------------------------------- #' `new_package()` create a package skeleton based on my preferred folder #' structure. #' # ------------------------------------------------------------------------- #' #' @param name `[character]` #' #' Package name #' #' @param dir `[character]` #' #' Directory to start in. #' #' @param firstname `[character]` #' #' Maintainer's firstname. #' #' @param surname `[character]` #' #' Maintainer's surname. #' #' @param email `[character]` #' #' Maintainer's email address. #' #' @param orcid `[character]` #' #' Maintainer's ORCID. #' #' @param enter `[bool]` #' #' Should you move in to the package directory after creation. #' #' Only applicable in interactive sessions. # ------------------------------------------------------------------------- #' @return #' #' Created directory (invisibly) #' # ------------------------------------------------------------------------- #' @examples #' #' # usage without entering directory #' p <- new_package("my_package_1", dir = tempdir(), enter = FALSE) #' #' # clean up #' unlink(p, recursive = TRUE) #' # ------------------------------------------------------------------------- #' @export new_package <- function( name = "mypackage", dir = ".", firstname = getOption("ympes.firstname", "Joe"), surname = getOption("ympes.surname", "Bloggs"), email = getOption("ympes.email", "[email protected]"), orcid = getOption("ympes.orcid", default = NULL), enter = TRUE ) { # helpers .x <- function() message("(X)") .done <- function() message("(DONE)") # create directory structure root <- file.path(normalizePath(dir), name) message("\nCreating directory structure ...... ", appendLF = FALSE) if (dir.exists(root)) { .x() stop(sprintf("Directory '%s' already exists.", root)) } if (!dir.create(root, recursive = TRUE, showWarnings = FALSE)) { .x() stop(sprintf("Unable to create directory '%s'.", root)) } Rpath <- file.path(root, "R") if (!dir.create(Rpath, showWarnings = FALSE)) { .x() unlink(root, recursive = TRUE) stop(sprintf("Unable to create '%s' directory.", Rpath)) } .done() # add makefile message("Adding Makefile ................... ", appendLF = FALSE) tmp <- file.copy( system.file("skeletons", "pkg.Makefile", package = "ympes"), file.path(root, "Makefile") ) if (!tmp) { .x() unlink(root, recursive = TRUE) stop("Unable to create 'Makefile'.") } .done() # add .gitignore message("Adding .gitignore ................. ", appendLF = FALSE) tmp <- file.copy( system.file("skeletons", "pkg.gitignore", package = "ympes"), file.path(root, ".gitignore") ) if (!tmp) { .x() unlink(root, recursive = TRUE) stop("Unable to create '.gitignore'.") } .done() # add .Rbuildignore message("Adding .Rbuildignore .............. ", appendLF = FALSE) tmp <- file.copy( system.file("skeletons", "pkg.Rbuildignore", package = "ympes"), file.path(root, ".Rbuildignore") ) if (!tmp) { .x() unlink(root, recursive = TRUE) stop("Unable to create '.Rbuildignore'.") } .done() # add .Rproj message("Adding .Rproj ..................... ", appendLF = FALSE) rprojname <- sprintf("%s.Rproj", name) tmp <- file.copy( system.file("skeletons", "rproj", package = "ympes"), file.path(root, rprojname) ) if (!tmp) { .x() unlink(root, recursive = TRUE) stopf("Unable to create '%s.Rproj'.", name) } .done() # get roxygen details roxy <- tryCatch( utils::packageVersion("roxygen2"), error = function(e) NULL ) roxy <- if (is.null(roxy)) "7.2.3" else as.character(roxy) # This is slightly tweaked from utils::package.skeleton message("Creating DESCRIPTION .............. ", appendLF = FALSE) description <- file(file.path(root, "DESCRIPTION"), "wt") on.exit({ close(description) unlink(root, recursive = TRUE) }) if (is.null(orcid)) { author <- sprintf( ' person( given = "%s", family = "%s", role = c("aut", "cre", "cph"), email = "%s" )', firstname, surname, email ) } else { author <- sprintf( ' person( given = "%s", family = "%s", role = c("aut", "cre", "cph"), email = "%s", comment = c(ORCID = "%s") )', firstname, surname, email, orcid )} tmp <- try( cat("Package: ", name, "\n", "Type: Package\n", "Title: What the package does (short line)\n", "Version: 0.0.0.9000\n", "Authors@R:\n", author, "\n", "Description: More about what it does (maybe more than one line)\n", "License: What license is it under?\n", "Encoding: UTF-8\n", "Roxygen: list(markdown = TRUE)\n", "RoxygenNote: ", roxy, "\n", file = description, sep = "" ) ) on.exit() close(description) if (inherits(tmp, "try-error")) { .x() unlink(root, recursive = TRUE) stop("Unable to create 'DESCRIPTION'.") } .done() # Change directory if (interactive() && enter) { message("Entering package directory ........ ", appendLF = FALSE) tmp <- try(setwd(root)) if (inherits(tmp, "try-error")) { .x() unlink(root, recursive = TRUE) stop("Unable to enter package directory (setwd failed).") } .done() } # return the root directory invisibly message(sprintf("\nComplete.\n\nPackage skeleton created in\n %s", root)) invisible(root) } #' @rdname new_package #' @export np <- new_package
/scratch/gouwar.j/cran-all/cranData/ympes/R/new_package.R
#' Plot a colour palette #' # ------------------------------------------------------------------------- #' `plot_palette()` plots a palette from a vector of colour values (name or hex). #' # ------------------------------------------------------------------------- #' @param values `[character]` #' #' Vector of named or hex colours. #' #' @param label `[bool]` #' #' Do you want to label the plot or not? #' #' If `values` is a named vector the names are used for labels, otherwise, #' the values. #' #' @param square `[bool]` #' #' Display palette as square? #' # ------------------------------------------------------------------------- #' @return #' #' The input (invisibly). #' # ------------------------------------------------------------------------- #' @examples #' #' plot_palette(c("#5FE756", "red", "black")) #' plot_palette(c("#5FE756", "red", "black"), square=TRUE) #' # ------------------------------------------------------------------------- #' @importFrom graphics axis image text #' @importFrom grDevices col2rgb #' @export plot_palette <- function(values, label = TRUE, square = FALSE) { n <- length(values) lbls <- if (is.null(names(values))) values else names(values) if (isTRUE(square)) { # function to determine whether you should use black or white text for # the given background colour (https://stackoverflow.com/a/3943023) .bw_contrast <- function(x) { dat <- as.data.frame(t(col2rgb(x))) / 255 index <- dat <= 0.03928 dat[index] <- dat[index] / 12.92 dat[!index] <- ((dat[!index] + 0.055) / 1.055) ^ 2.4 l <- 0.2126 * dat$red + 0.7152 * dat$green + 0.0722 * dat$blue condition <- (l + 0.05) / (0.0 + 0.05) > (1.0 + 0.05) / (l + 0.05) ifelse(condition, "black", "white") } dimension <- ceiling(sqrt(n)) total <- dimension ^ 2 remainder <- total - n cols <- c(values, rep("white", remainder)) lbls <- c(lbls, rep("", remainder)) x <- apply(matrix(total:1, dimension), 2, rev) if (n == 1) { image(matrix(1), col = values, axes = FALSE, lab.breaks = NULL) if (label) text(0, 0, labels = lbls, col = .bw_contrast(cols)) } else { image(x, col = matrix(cols, dimension), axes = FALSE, lab.breaks = NULL) if (label) { e <- expand.grid( seq(0, 1, length.out = dimension), seq(1, 0, length.out = dimension) ) text(e, labels = lbls, col = .bw_contrast(cols)) } } } else { # h/t hrbrmstr https://stackoverflow.com/a/25726442 image( 1:n, 1, as.matrix(1:n), col = values, xlab = "", ylab = "", xaxt = "n", yaxt = "n", bty = "n" ) if (label) axis(1, at = 1:n, labels = lbls, tick = FALSE) } invisible(values) }
/scratch/gouwar.j/cran-all/cranData/ympes/R/palette.R
stopf <- function(fmt, ..., .use_call = TRUE, .call = sys.call(-1L)) { .call <- if (isTRUE(.use_call)) .call[1L] else NULL msg <- sprintf(fmt, ...) err <- simpleError(msg, .call) stop(err) }
/scratch/gouwar.j/cran-all/cranData/ympes/R/utils.R
#' @keywords internal "_PACKAGE" ## usethis namespace: start ## usethis namespace: end NULL
/scratch/gouwar.j/cran-all/cranData/ympes/R/ympes-package.R
# helper function for fixed errors expect_fixed_error <- function(current, pattern) { expect_error(current = current, pattern = pattern, fixed = TRUE) } # scalar assertions one layer deep fun <- function(i, d, l, chr, b) { ympes:::.assert_scalar_int(i) ympes:::.assert_scalar_dbl(d) ympes:::.assert_scalar_lgl(l) ympes:::.assert_string(chr) ympes:::.assert_bool(b) TRUE } # all arguments correct expect_true( fun(i=1L, d=1, l=NA, chr="cat", b=TRUE)) # missing arguments expect_fixed_error( fun( d=1, l=NA, chr="cat", b=TRUE), "argument `i` is missing, with no default." ) expect_fixed_error( fun(i=1L, l=NA, chr="cat", b=TRUE), "argument `d` is missing, with no default." ) expect_fixed_error( fun(i=1L, d=1, chr="cat", b=TRUE), "argument `l` is missing, with no default." ) expect_fixed_error( fun(i=1L, d=1, l=NA, b=TRUE), "argument `chr` is missing, with no default." ) expect_fixed_error( fun(i=1L, d=1, l=NA, chr="cat" ), "argument `b` is missing, with no default." ) # incorrect arguments expect_fixed_error( fun(i=1, d=1, l=NA, chr="cat", b=TRUE ), "`i` must be an integer vector of length 1.") expect_fixed_error( fun(i=1:2, d=1, l=NA, chr="cat", b=TRUE ), "`i` must be an integer vector of length 1.") expect_fixed_error( fun(i=1L, d=1L, l=NA, chr="cat", b=TRUE ), "`d` must be a double vector of length 1.") expect_fixed_error( fun(i=1L, d=c(1, 1), l=NA, chr="cat", b=TRUE ), "`d` must be a double vector of length 1.") expect_fixed_error( fun(i=1L, d=1, l=1, chr="cat", b=TRUE ), "`l` must be a logical vector of length 1.") expect_fixed_error( fun(i=1L, d=1, l=c(NA, NA), chr="cat", b=TRUE ), "`l` must be a logical vector of length 1.") expect_fixed_error( fun(i=1L, d=1, l=1, chr="cat", b=TRUE ), "`l` must be a logical vector of length 1.") expect_fixed_error( fun(i=1L, d=1, l=NA, chr=1, b=TRUE ), "`chr` must be a character vector of length 1.") expect_fixed_error( fun(i=1L, d=1, l=NA, chr=letters, b=TRUE ), "`chr` must be a character vector of length 1.") expect_fixed_error( fun(i=1L, d=1, l=NA, chr="cat", b=NA ), "`b` must be boolean (TRUE/FALSE).") expect_fixed_error( fun(i=1L, d=1, l=NA, chr="cat", b=c(TRUE, TRUE)), "`b` must be boolean (TRUE/FALSE).") # scalar assertions work nested_functions" internal_fun <- function(ii, dd, ll, chrchr, bb) { ympes:::.assert_scalar_int(ii, arg = deparse(substitute(ii)), call = sys.call(-1L)) ympes:::.assert_scalar_dbl(dd, arg = deparse(substitute(dd)), call = sys.call(-1L)) ympes:::.assert_scalar_lgl(ll, arg = deparse(substitute(ll)), call = sys.call(-1L)) ympes:::.assert_string(chrchr, arg = deparse(substitute(chrchr)), call = sys.call(-1L)) ympes:::.assert_bool(bb, arg = deparse(substitute(bb)), call = sys.call(-1L)) TRUE } external_fun <- function(i, d, l, chr, b) { internal_fun(ii=i, dd=d, ll=l, chrchr=chr, bb=b) } # all arguments correct expect_true( external_fun(i=1L, d=1, l=NA, chr="cat", b=TRUE)) # missing arguments expect_fixed_error( external_fun( d=1, l=NA, chr="cat", b=TRUE), "argument `i` is missing, with no default.") expect_fixed_error( external_fun(i=1L, l=NA, chr="cat", b=TRUE), "argument `d` is missing, with no default.") expect_fixed_error( external_fun(i=1L, d=1, chr="cat", b=TRUE), "argument `l` is missing, with no default.") expect_fixed_error( external_fun(i=1L, d=1, l=NA, b=TRUE), "argument `chr` is missing, with no default.") expect_fixed_error( external_fun(i=1L, d=1, l=NA, chr="cat" ), "argument `b` is missing, with no default.") # incorrect arguments expect_fixed_error( external_fun(i=1, d=1, l=NA, chr="cat", b=TRUE ), "`i` must be an integer vector of length 1.") expect_fixed_error( external_fun(i=1:2, d=1, l=NA, chr="cat", b=TRUE ), "`i` must be an integer vector of length 1.") expect_fixed_error( external_fun(i=1L, d=1L, l=NA, chr="cat", b=TRUE ), "`d` must be a double vector of length 1.") expect_fixed_error( external_fun(i=1L, d=c(1, 1), l=NA, chr="cat", b=TRUE ), "`d` must be a double vector of length 1.") expect_fixed_error( external_fun(i=1L, d=1, l=1, chr="cat", b=TRUE ), "`l` must be a logical vector of length 1.") expect_fixed_error( external_fun(i=1L, d=1, l=c(NA, NA), chr="cat", b=TRUE ), "`l` must be a logical vector of length 1.") expect_fixed_error( external_fun(i=1L, d=1, l=1, chr="cat", b=TRUE ), "`l` must be a logical vector of length 1.") expect_fixed_error( external_fun(i=1L, d=1, l=NA, chr=1, b=TRUE ), "`chr` must be a character vector of length 1.") expect_fixed_error( external_fun(i=1L, d=1, l=NA, chr=letters, b=TRUE ), "`chr` must be a character vector of length 1.") expect_fixed_error( external_fun(i=1L, d=1, l=NA, chr="cat", b=NA ), "`b` must be boolean (TRUE/FALSE).") expect_fixed_error( external_fun(i=1L, d=1, l=NA, chr="cat", b=c(TRUE, TRUE)), "`b` must be boolean (TRUE/FALSE).") # integer assertions x <- 1 y <- 1L z <- NA_integer_ expect_null(ympes:::.assert_int(y)) expect_null(ympes:::.assert_scalar_int_not_na(y)) expect_fixed_error(ympes:::.assert_int(x), "`x` must be an integer vector.") expect_fixed_error(ympes:::.assert_int(arg="TEST"), "argument `TEST` is missing, with no default.") expect_fixed_error(ympes:::.assert_scalar_int_not_na(z), "`z` must be an integer vector of length 1 and not NA.") # double assertions x <- 1 y <- 1L z <- NA_real_ expect_null(ympes:::.assert_dbl(x)) expect_fixed_error(ympes:::.assert_dbl(y), "`y` must be a double vector.") expect_fixed_error(ympes:::.assert_dbl(arg="TEST"), "argument `TEST` is missing, with no default.") expect_null(ympes:::.assert_scalar_dbl_not_na(x)) expect_fixed_error(ympes:::.assert_scalar_dbl_not_na(z), "`z` must be a double vector of length 1 and not NA.") # numeric assertions x <- 1 y <- "cat" z <- NA_real_ expect_null(ympes:::.assert_num(x)) expect_fixed_error(ympes:::.assert_num(y), "`y` must be a numeric vector.") expect_fixed_error(ympes:::.assert_num(arg="TEST"), "argument `TEST` is missing, with no default.") expect_null(ympes:::.assert_scalar_num_not_na(x)) expect_fixed_error(ympes:::.assert_scalar_num_not_na(z), "`z` must be a numeric vector of length 1 and not NA.") # character assertions x <- 1 y <- "cat" z <- NA_character_ expect_null(ympes:::.assert_chr(y)) expect_fixed_error(ympes:::.assert_chr(x), "`x` must be a character vector.") expect_fixed_error(ympes:::.assert_chr(arg="TEST"), "argument `TEST` is missing, with no default.") expect_null(ympes:::.assert_scalar_chr_not_na(y)) expect_fixed_error(ympes:::.assert_scalar_chr_not_na(z), "`z` must be a character vector of length 1 and not NA.") # logical assertions work x <- 1 y <- NA expect_null(ympes:::.assert_lgl(y)) expect_fixed_error(ympes:::.assert_lgl(x), "`x` must be a logical vector.") expect_fixed_error(ympes:::.assert_lgl(arg="TEST"), "argument `TEST` is missing, with no default.") # numeric assertions x <- 1 y <- 1L z <- "cat" w <- 1:10 expect_null(ympes:::.assert_scalar_num(x)) expect_null(ympes:::.assert_scalar_num(y)) expect_fixed_error(ympes:::.assert_scalar_num(z), "`z` must be a numeric vector of length 1.") expect_fixed_error(ympes:::.assert_scalar_num(w), "`w` must be a numeric vector of length 1.") expect_fixed_error(ympes:::.assert_scalar_num(arg="TEST"), "argument `TEST` is missing, with no default.") expect_null(ympes:::.assert_num(w)) expect_fixed_error(ympes:::.assert_num(z), "`z` must be a numeric vector.") expect_fixed_error(ympes:::.assert_num(arg="TEST"), "argument `TEST` is missing, with no default.") # data frame assertions l <- .subset(mtcars) expect_null(ympes:::.assert_data_frame(mtcars)) expect_fixed_error(ympes:::.assert_data_frame(l), "`l` must be a data frame.") expect_fixed_error(ympes:::.assert_data_frame(arg="TEST"), "argument `TEST` is missing, with no default.") # list assertions l <- list(1, b=2) b <- "bat" expect_null(ympes:::.assert_list(l)) expect_fixed_error(ympes:::.assert_list(b), "`b` must be a list.") expect_fixed_error(ympes:::.assert_list(arg="TEST"), "argument `TEST` is missing, with no default.") # negativity/positivity assertions zero_length <- integer() expect_null(ympes:::.assert_non_negative_or_na(zero_length)) expect_null(ympes:::.assert_non_positive_or_na(zero_length)) expect_null(ympes:::.assert_non_negative(zero_length)) expect_null(ympes:::.assert_non_positive(zero_length)) expect_null(ympes:::.assert_positive(zero_length)) expect_null(ympes:::.assert_negative(zero_length)) expect_null(ympes:::.assert_positive_or_na(zero_length)) expect_null(ympes:::.assert_negative_or_na(zero_length)) all_na <- c(NA_integer_, NA_integer_) expect_null(ympes:::.assert_non_negative_or_na(all_na)) expect_null(ympes:::.assert_non_positive_or_na(all_na)) expect_null(ympes:::.assert_positive_or_na(all_na)) expect_null(ympes:::.assert_negative_or_na(all_na)) expect_fixed_error(ympes:::.assert_non_negative(all_na), "`all_na` values must be non-negative and not NA.") expect_fixed_error(ympes:::.assert_non_positive(all_na), "`all_na` values must be non-positive and not NA.") expect_fixed_error(ympes:::.assert_positive(all_na), "`all_na` values must be positive and not NA.") expect_fixed_error(ympes:::.assert_negative(all_na), "`all_na` values must be negative and not NA.") pos <- 1:10 expect_null(ympes:::.assert_non_negative_or_na(pos)) expect_fixed_error(ympes:::.assert_non_positive_or_na(pos), "`pos` values must be non-positive or NA.") expect_null(ympes:::.assert_positive_or_na(pos)) expect_fixed_error(ympes:::.assert_negative_or_na(pos), "`pos` values must be negative or NA.") expect_null(ympes:::.assert_non_negative(pos)) expect_fixed_error(ympes:::.assert_non_positive(pos), "`pos` values must be non-positive and not NA.") expect_null(ympes:::.assert_positive(pos)) expect_fixed_error(ympes:::.assert_negative(pos), "`pos` values must be negative and not NA.") pos0 <- pos - 1L expect_null(ympes:::.assert_non_negative_or_na(pos0)) expect_fixed_error(ympes:::.assert_non_positive_or_na(pos0), "`pos0` values must be non-positive or NA.") expect_fixed_error(ympes:::.assert_positive_or_na(pos0), "`pos0` values must be positive or NA.") expect_fixed_error(ympes:::.assert_negative_or_na(pos0), "`pos0` values must be negative or NA.") expect_null(ympes:::.assert_non_negative(pos0)) expect_fixed_error(ympes:::.assert_non_positive(pos0), "`pos0` values must be non-positive and not NA.") expect_fixed_error(ympes:::.assert_positive(pos0), "`pos0` values must be positive and not NA.") expect_fixed_error(ympes:::.assert_negative(pos0), "`pos0` values must be negative and not NA.") all_neg <- -pos expect_fixed_error(ympes:::.assert_non_negative_or_na(all_neg), "`all_neg` values must be non-negative or NA.") expect_null(ympes:::.assert_non_positive_or_na(all_neg)) expect_fixed_error(ympes:::.assert_positive_or_na(all_neg), "`all_neg` values must be positive or NA.") expect_null(ympes:::.assert_negative_or_na(all_neg)) expect_fixed_error(ympes:::.assert_non_negative(all_neg), "`all_neg` values must be non-negative and not NA.") expect_null(ympes:::.assert_non_positive(all_neg)) expect_fixed_error(ympes:::.assert_positive(all_neg), "`all_neg` values must be positive and not NA.") expect_null(ympes:::.assert_negative(all_neg)) all_neg0 <- -pos0 expect_fixed_error(ympes:::.assert_non_negative_or_na(all_neg0), "`all_neg0` values must be non-negative or NA.") expect_null(ympes:::.assert_non_positive_or_na(all_neg0)) expect_fixed_error(ympes:::.assert_positive_or_na(all_neg0), "`all_neg0` values must be positive or NA.") expect_fixed_error(ympes:::.assert_negative_or_na(all_neg0), "`all_neg0` values must be negative or NA.") expect_fixed_error(ympes:::.assert_non_negative(all_neg0), "`all_neg0` values must be non-negative and not NA.") expect_null(ympes:::.assert_non_positive(all_neg0)) expect_fixed_error(ympes:::.assert_positive(all_neg0), "`all_neg0` values must be positive and not NA.") expect_fixed_error(ympes:::.assert_negative(all_neg0), "`all_neg0` values must be negative and not NA.") both <- seq.int(-2L, 2L) expect_fixed_error(ympes:::.assert_non_negative_or_na(both), "`both` values must be non-negative or NA.") expect_fixed_error(ympes:::.assert_non_positive_or_na(both), "`both` values must be non-positive or NA.") expect_fixed_error(ympes:::.assert_positive_or_na(both), "`both` values must be positive or NA.") expect_fixed_error(ympes:::.assert_negative_or_na(both), "`both` values must be negative or NA.") expect_fixed_error(ympes:::.assert_non_negative(both), "`both` values must be non-negative and not NA.") expect_fixed_error(ympes:::.assert_non_positive(both), "`both` values must be non-positive and not NA.") expect_fixed_error(ympes:::.assert_positive(both), "`both` values must be positive and not NA.") expect_fixed_error(ympes:::.assert_negative(both), "`both` values must be negative and not NA.") pos_single_na <- pos; pos_single_na[2L] <- NA_integer_ expect_null(ympes:::.assert_non_negative_or_na(pos_single_na)) expect_fixed_error(ympes:::.assert_non_positive_or_na(pos_single_na), "`pos_single_na` values must be non-positive or NA.") expect_null(ympes:::.assert_positive_or_na(pos_single_na)) expect_fixed_error(ympes:::.assert_negative_or_na(pos_single_na), "`pos_single_na` values must be negative or NA.") expect_fixed_error(ympes:::.assert_non_negative(pos_single_na), "`pos_single_na` values must be non-negative and not NA.") expect_fixed_error(ympes:::.assert_non_positive(pos_single_na), "`pos_single_na` values must be non-positive and not NA.") expect_fixed_error(ympes:::.assert_positive(pos_single_na), "`pos_single_na` values must be positive and not NA.") expect_fixed_error(ympes:::.assert_negative(pos_single_na), "`pos_single_na` values must be negative and not NA.")
/scratch/gouwar.j/cran-all/cranData/ympes/inst/tinytest/test_assertions.R
expect_identical( cc( dale, audrey, laura , hawk, ), c("dale", "audrey", "laura", "hawk", "") )
/scratch/gouwar.j/cran-all/cranData/ympes/inst/tinytest/test_cc.R
# from regexpr example ---------------------------------------------------- notables <- c( " Ben Franklin and Jefferson Davis", "\tMillard Fillmore", "Bob", NA_character_ ) regex <- "(?<first>[[:upper:]][[:lower:]]+) (?<last>[[:upper:]][[:lower:]]+)" proto <- data.frame("", "") expect_identical( utils::strcapture(regex, notables, proto, perl = TRUE), fstrcapture(regex, notables, proto) ) expect_identical( utils::strcapture(regex, notables, proto, perl = TRUE), fstrcapture(regex, notables, proto, perl = TRUE) ) proto <- data.frame(a="", b="") expect_identical( utils::strcapture(regex, "", proto, perl = TRUE), fstrcapture(regex, "", proto) ) expect_identical( utils::strcapture(regex, NA_character_, proto, perl = TRUE), fstrcapture(regex, NA_character_, proto) ) # from strcapture example ------------------------------------------------- x <- "chr1:1-1000" pattern <- "(.*?):([[:digit:]]+)-([[:digit:]]+)" proto <- data.frame(chr=character(), start=integer(), end=integer()) expect_identical( strcapture(pattern, x, proto), fstrcapture(pattern, x, proto, perl = FALSE) ) expect_identical( strcapture(pattern, x, proto, perl = TRUE), fstrcapture(pattern, x, proto) )
/scratch/gouwar.j/cran-all/cranData/ympes/inst/tinytest/test_fstrcapture.R
dat <- data.frame( first = letters, second = factor(rev(LETTERS)), third = "Q" ) # simple case expect_identical( greprows(dat, "A|b"), dat[c(2L, 26L),] ) # passing additional arguments through to grep expect_identical( greprows(dat, "A|b", ignore.case = TRUE), dat[c(1:2, 25:26), ] ) # indices expect_identical(greprows(dat, "c", value = FALSE), 3L)
/scratch/gouwar.j/cran-all/cranData/ympes/inst/tinytest/test_greprows.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 14 Apr 2016 # Function: batsmanCumulativeAverageRuns # This function computes and plots the cumulative average runs by a batsman # ########################################################################################### #' @title #' Batsman's cumulative average runs #' #' @description #' This function computes and plots the cumulative average runs of a batsman #' #' @usage #' batsmanCumulativeAverageRuns(df,name= "A Leg Glance",dateRange,staticIntv=1) #' #' @param df #' Data frame #' #' @param name #' Name of batsman #' #' @param dateRange #' Date interval to consider #' #' @param staticIntv #' Static or interactive -staticIntv =1 (static plot) & staticIntv =2 (interactive plot) #' #' @return None #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' @examples #' \dontrun{ #' #Get the data frame for Kohli #' kohli <- getBatsmanDetails(team="India",name="Kohli",dir=pathToFile) #' batsmanCumulativeAverageRuns(kohli,"Kohli",dateRange) #' } #' @seealso #' \code{\link{batsmanCumulativeStrikeRate}} #' \code{\link{bowlerCumulativeAvgEconRate}} #' \code{\link{bowlerCumulativeAvgWickets}} #' \code{\link{batsmanRunsVsStrikeRate}} #' \code{\link{batsmanRunsPredict}} #' #' @export #' #' batsmanCumulativeAverageRuns <- function(df,name="A Leg Glance",dateRange,staticIntv=1){ runs=cs=no=NULL ggplotly=NULL df=df %>% filter(date >= dateRange[1] & date <= dateRange[2]) b <- select(df,runs) b$no<-seq.int(nrow(b)) c <- select(b,no,runs) d <- mutate(c,cs=cumsum(runs)/no) plot.title= paste(name,"- Cumulative Average vs No of innings") if(staticIntv ==1){ #ggplot2 ggplot(d) + geom_line(aes(x=no,y=cs),col="blue") + xlab("No of innings") + ylab("Cumulative Avg. runs") + ggtitle(bquote(atop(.(plot.title), atop(italic("Data source:http://cricsheet.org/"),"")))) } else { #ggplotly g <- ggplot(d) + geom_line(aes(x=no,y=cs),col="blue") + ggtitle(plot.title) + xlab("No of innings") + ylab("Cumulative Avg. runs") ggplotly(g) } }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/batsmanCumulativeAverageRuns.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 14 Apr 2016 # Function: batsmanCumulativeStrikeRate # This function computes and plots the cumulative average strike rate of a batsman # ########################################################################################### #' @title #' Batsman's cumulative average strike rate #' #' @description #' This function computes and plots the cumulative average strike rate of a batsman #' #' @usage #' batsmanCumulativeStrikeRate(df,name= "A Leg Glance",dateRange, staticIntv=1) #' #' @param df #' Data frame #' #' @param name #' Name of batsman #' #' @param dateRange #' Date interval to consider #' #' @param staticIntv #' Static or interactive -staticIntv =1 (static plot) & staticIntv =2 (interactive plot) #' #' @return None #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' @examples #' \dontrun{ #' #Get the data frame for Kohli #' kohli <- getBatsmanDetails(team="India",name="Kohli",dir=pathToFile) #' batsmanCumulativeStrikeRate(kohli,"Kohli",dateRange) #' } #' @seealso #' \code{\link{batsmanCumulativeAverageRuns}} #' \code{\link{bowlerCumulativeAvgEconRate}} #' \code{\link{bowlerCumulativeAvgWickets}} #' \code{\link{batsmanRunsVsStrikeRate}} #' \code{\link{batsmanRunsPredict}} #' #' @export #' #' batsmanCumulativeStrikeRate <- function(df,name= "A Leg Glance",dateRange,staticIntv=1){ strikeRate=cs=no=NULL ggplotly=NULL df=df %>% filter(date >= dateRange[1] & date <= dateRange[2]) b <- select(df,strikeRate) b$no<-seq.int(nrow(b)) c <- select(b,no,strikeRate) d <- mutate(c,cs=cumsum(strikeRate)/no) plot.title= paste(name,"- Cumulative Strike Rate vs No of innings") if(staticIntv ==1){ #ggplot2 ggplot(d) + geom_line(aes(x=no,y=cs),col="blue") + xlab("No of innings") + ylab("Cumulative Avg. Strike Rates") + ggtitle(bquote(atop(.(plot.title), atop(italic("Data source:http://cricsheet.org/"),"")))) } else { g <- ggplot(d) + geom_line(aes(x=no,y=cs),col="blue") + xlab("No of innings") + ylab("Cumulative Avg. Strike Rates") + ggtitle(plot.title) ggplotly(g) } }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/batsmanCumulativeStrikeRate.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 25 Mar 2016 # Function: batsmanDismissals # This function computes and plots the dismissal types for the batsman # ########################################################################################### #' @title #' Dismissal type of batsmen #' #' @description #' This function computes and plots the type of dismissals of the #' the batsman #' @usage #' batsmanDismissals(df,name="A Leg Glance",dateRange) #' #' @param df #' Data frame #' #' @param name #' Name of batsman #' #' @param dateRange #' Date interval to consider #' #' @return None #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' @examples #' \dontrun{ #' #Get the data frame for Kohli #' kohli <- getBatsmanDetails(team="India",name="Kohli",dir=pathToFile) #' batsmanDismissals(kohli,"Kohli",dateRange) #' } #' @seealso #' \code{\link{batsmanFoursSixes}}\cr #' \code{\link{batsmanRunsVsDeliveries}}\cr #' \code{\link{batsmanRunsVsStrikeRate}}\cr #' #' @import dplyr #' @import ggplot2 #' @import reshape2 #' @import yaml #' @import rpart.plot #' @importFrom gridExtra grid.arrange #' @importFrom stats complete.cases loess #' @importFrom utils head #' @importFrom graphics legend lines plot #' #' #' @export #' batsmanDismissals <- function(df,name="A Leg Glance",dateRange){ batsman <- wicketKind <-dismissal <- NULL DismissalType <- NULL df=df %>% filter(date >= dateRange[1] & date <= dateRange[2]) b <-select(df,batsman,wicketKind) c <- summarise(group_by(b,batsman,wicketKind),dismissal=n()) d <- mutate(c,wicketKind=paste(wicketKind,"(",dismissal,")",sep="")) names(d) <-c("batsman","DismissalType","dismissal") plot.title = paste(name,"- Dismissals") # Does not handle polar coordinates in ggplotly ggplot(d, aes(x="", y=dismissal, fill=DismissalType))+ geom_bar(width=1,stat = "identity")+ coord_polar("y", start=0) + ggtitle(bquote(atop(.(plot.title), atop(italic("Data source:http://cricsheet.org/"),"")))) }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/batsmanDismissals.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 25 Mar 2016 # Function: batsmanFoursSixes # This function computes and plots the total runs,fours and sixes hit by the batsman # ########################################################################################### #' @title #' Batsman's total runs, fours and sixes #' #' @description #' This function computes and plots the total runs, fours and sixes of #' the batsman #' @usage #' batsmanFoursSixes(df,name= "A Leg Glance",dateRange,staticIntv) #' #' @param df #' Data frame #' #' @param name #' Name of batsman #' #' @param dateRange #' Date interval to consider #' #' @param staticIntv #' Static or interactive -staticIntv =1 (static plot) & staticIntv =2 (interactive plot) #' #' @return None #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' @examples #' \dontrun{ #' #Get the data frame for Kohli #' kohli <- getBatsmanDetails(team="India",name="Kohli",dir=pathToFile) #' kohli46 <- select(kohli,batsman,ballsPlayed,fours,sixes,runs) #' batsmanFoursSixes(kohli46,"Kohli",dateRange) #' } #' @seealso #' \code{\link{batsmanDismissals}} #' \code{\link{batsmanRunsVsDeliveries}} #' \code{\link{batsmanRunsVsStrikeRate}} #' \code{\link{batsmanRunsVsStrikeRate}} #' \code{\link{batsmanRunsPredict}} #' #' @export #' batsmanFoursSixes <- function(df,name= "A Leg Glance",dateRange,staticIntv){ fours <- sixes <- batsman <- ballsPlayed <- RunsFromFours <- runs <- NULL ggplotly=NULL RunsFromSixes <- TotalRuns <- value <- variable <- NULL df=df %>% filter(date >= dateRange[1] & date <= dateRange[2]) df <- select(df,batsman,ballsPlayed,fours,sixes,runs) names(df) <- c("batsman","ballsPlayed","fours","sixes","TotalRuns") print(head(df,30)) c <- mutate(df, RunsFromFours=fours*4,RunsFromSixes=sixes*6) d <- select(c, batsman,ballsPlayed,RunsFromFours,RunsFromSixes,TotalRuns) e <- melt(d,id=c("batsman","ballsPlayed")) plot.title = paste(name,"- Total runs, 4s and 6s vs Balls Faced") if(staticIntv ==1){ #ggplot2{ ggplot(e) + geom_point(aes(x=ballsPlayed, y=value, colour=variable)) + geom_smooth(aes(x=ballsPlayed, y=value, colour=variable)) + scale_colour_manual(values=c("red","green","blue")) + xlab("Deliveries faced") + ylab("Runs") + ggtitle(bquote(atop(.(plot.title), atop(italic("Data source:http://cricsheet.org/"),"")))) } else { g <- ggplot(e) + geom_point(aes(x=ballsPlayed, y=value, colour=variable)) + geom_smooth(aes(x=ballsPlayed, y=value, colour=variable)) + scale_colour_manual(values=c("red","green","blue")) + xlab("Deliveries faced") + ylab("Runs") + ggtitle(plot.title) ggplotly(g) } }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/batsmanFoursSixes.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 25 Mar 2016 # Function: batsmanMovingAverage # This function computes and plots the moving average the batsman # ########################################################################################### #' @title #' Moving average of batsman #' #' @description #' This function plots the runs scored by the batsman over the career as a time #' series. A loess regression line is plotted on the moving average of the batsman #' the batsman #' #' @usage #' batsmanMovingAverage(df, name= "A Leg Glance",dateRange,staticIntv=1) #' #' @param df #' Data frame #' #' @param name #' Name of batsman #' #' @param dateRange #' Date interval to consider #' #' @param staticIntv #' Static or interactive -staticIntv =1 (static plot) & staticIntv =2 (interactive plot) #' #' @return None #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' @examples #' \dontrun{ #' #Get the data frame for Kohli #' kohli <- getBatsmanDetails(team="India",name="Kohli",dir=pathToFile) #' batsmanMovingAverage(kohli,"Kohli",dateRange) #' } #' @seealso #' \code{\link{batsmanDismissals}}\cr #' \code{\link{batsmanRunsVsDeliveries}}\cr #' \code{\link{batsmanRunsVsStrikeRate}}\cr #' \code{\link{batsmanRunsPredict}}\cr #' \code{\link{teamBatsmenPartnershipAllOppnAllMatches}}\cr #' #' @export #' #' batsmanMovingAverage <- function(df,name = "A Leg Glance",dateRange,staticIntv=1){ batsman = runs = NULL ggplotly=NULL df=df %>% filter(date >= dateRange[1] & date <= dateRange[2]) b <- select(df,batsman,runs,date) plot.title = paste(name,"- Moving average of runs in career") if(staticIntv ==1){ #ggplot2 ggplot(b) + geom_line(aes(x=date, y=runs),colour="darkgrey") + geom_smooth(aes(x=date, y=runs)) + xlab("Date") + ylab("Runs") + ggtitle(bquote(atop(.(plot.title), atop(italic("Data source:http://cricsheet.org/"),"")))) } else { #ggplotly g <- ggplot(b) + geom_line(aes(x=date, y=runs),colour="darkgrey") + geom_smooth(aes(x=date, y=runs)) + xlab("Date") + ylab("Runs") + ggtitle(plot.title) ggplotly(g) } }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/batsmanMovingAverage.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 26 Mar 2016 # Function: batsmanRunsAgainstOpposition # This function computes and plots the runs scored by the batsman against different oppositions # ########################################################################################### #' @title #' Batsman runs against different oppositions #' #' @description #' This function computes and plots the mean runs scored by the batsman against different #' oppositions #' @usage #' batsmanRunsAgainstOpposition(df, name= "A Leg Glance",dateRange,staticIntv=1) #' #' @param df #' Data frame #' #' @param name #' Name of batsman #' #' @param dateRange #' Date interval to consider #' #' @param staticIntv #' Static or interactive -staticIntv =1 (static plot) & staticIntv =2 (interactive plot) #' #' @return None #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' @examples #' \dontrun{ #' #Get the data frame for Kohli #' kohli <- getBatsmanDetails(team="India",name="Kohli",dir=pathToFile) #' batsmanRunsAgainstOpposition(kohli,"Kohli",dateRange) #' } #' #' @seealso #' \code{\link{batsmanFoursSixes}}\cr #' \code{\link{batsmanRunsVsDeliveries}}\cr #' \code{\link{batsmanRunsVsStrikeRate}}\cr #' \code{\link{batsmanRunsPredict}}\cr #' \code{\link{teamBatsmenPartnershipAllOppnAllMatches}}\cr #' #' @export #' batsmanRunsAgainstOpposition <- function(df,name= "A Leg Glance",dateRange,staticIntv=1){ batsman = runs = opposition = meanRuns = NULL ggplotly=NULL df=df %>% filter(date >= dateRange[1] & date <= dateRange[2]) b <- select(df,batsman,runs,opposition) c <-b[complete.cases(b),] d <- summarise(group_by(c,opposition),meanRuns=mean(runs),numMatches=n()) plot.title = paste(name,"- Mean runs against opposition") if(staticIntv ==1){ #ggplot2 ggplot(d,height=600, aes(x=opposition, y=meanRuns, fill=opposition))+ geom_bar(stat = "identity",position="dodge") + xlab("Opposition") + ylab("Mean Runs") + geom_hline(aes(yintercept=50))+ ggtitle(bquote(atop(.(plot.title), atop(italic("Data source:http://cricsheet.org/"),""))))+ theme(axis.text.x = element_text(angle = 90, hjust = 1)) } else { #ggplotly g <- ggplot(d, aes(x=opposition, y=meanRuns, fill=opposition))+ geom_bar(stat = "identity",position="dodge") + xlab("Opposition") + ylab("Mean Runs") + geom_hline(aes(yintercept=50))+ ggtitle(plot.title) + theme(axis.text.x = element_text(angle = 90, hjust = 1)) ggplotly(g,height=600) } }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/batsmanRunsAgainstOpposition.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 16 Apr 2016 # Function: batsmanRunsVenue # This function computes and plots the runs scored by the batsman at different venues # ########################################################################################### #' @title #' Batsman runs at different venues #' #' @description #' This function computes and plots the mean runs scored by the batsman at different #' venues of the world #' @usage #' batsmanRunsVenue(df, name= "A Leg Glance",dateRange,staticIntv=1) #' #' @param df #' Data frame #' #' @param name #' Name of batsman #' #' @param dateRange #' Date interval to consider #' #' @param staticIntv #' Static or interactive -staticIntv =1 (static plot) & staticIntv =2 (interactive plot) #' #' @return None #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' @examples #' \dontrun{ #' #Get the data frame for Kohli #' kohli <- getBatsmanDetails(team="India",name="Kohli",dir=pathToFile) #' batsmanRunsVenue(kohli,"Kohli",dateRange) #' } #' #' @seealso #' \code{\link{batsmanFoursSixes}}\cr #' \code{\link{batsmanRunsVsDeliveries}}\cr #' \code{\link{batsmanRunsVsStrikeRate}}\cr #' \code{\link{batsmanRunsPredict}}\cr #' \code{\link{teamBatsmenPartnershipAllOppnAllMatches}}\cr #' \code{\link{batsmanRunsAgainstOpposition}}\cr #' #' @export #' batsmanRunsVenue <- function(df,name= "A Leg Glance",dateRange,staticIntv=1){ batsman = runs = venue = numMatches = meanRuns = NULL ggplotly=NULL df=df %>% filter(date >= dateRange[1] & date <= dateRange[2]) b <- select(df,batsman,runs,venue) c <- summarise(group_by(b,venue),meanRuns=mean(runs),numMatches=n()) d <- mutate(c,venue=paste(venue,"(",numMatches,")",sep="")) e <- arrange(d,desc(numMatches)) # Select only available rows or 25 rows sz <- dim(e) if(sz[1] > 25){ f <- e[1:25,] } else{ f <- e[1:sz[1],] } plot.title = paste(name,"- Mean runs at venue") if(staticIntv ==1){ #ggplot2 ggplot(f,height=600,aes(x=venue, y=meanRuns, fill=venue))+ geom_bar(stat = "identity",position="dodge") + geom_hline(aes(yintercept=50))+ ggtitle(bquote(atop(.(plot.title), atop(italic("Data source:http://cricsheet.org/"),""))))+ theme(axis.text.x = element_text(size=8,angle = 90, hjust = 1)) } else { #ggplotly g <- ggplot(f, aes(x=venue, y=meanRuns, fill=venue))+ geom_bar(stat = "identity",position="dodge") + geom_hline(aes(yintercept=50))+ ggtitle(plot.title) + theme(axis.text.x = element_text(size=8, angle = 90, hjust = 1)) ggplotly(g,height=600) } }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/batsmanRunsVenue.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 25 Mar 2016 # Function: batsmanRunsVsStrikeRate # This function plots the runs scored versus the strike rate ########################################################################################### #' @title #' Batsman runs versus strike rate #' #' @description #' This function plots the runs scored by the batsman and the runs scored #' by the batsman. A loess line is fitted over the points #' #' @usage #' batsmanRunsVsStrikeRate(df, name= "A Late Cut",dateRange,staticIntv=1) #' #' @param df #' Data frame #' #' @param name #' Name of batsman #' #' @param dateRange #' Date interval to consider #' #' @param staticIntv #' Static or interactive -staticIntv =1 (static plot) & staticIntv =2 (interactive plot) #' #' @return None #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' @examples #' \dontrun{ #' #Get the data frame for Kohli #' kohli <- getBatsmanDetails(team="India",name="Kohli",dir=pathToFile) #' batsmanRunsVsStrikeRate(kohli,"Kohli",dateRange) #' } #' #' @seealso #' \code{\link{batsmanDismissals}}\cr #' \code{\link{batsmanRunsVsDeliveries}}\cr #' \code{\link{batsmanRunsVsStrikeRate}}\cr #' \code{\link{batsmanRunsPredict}}\cr #' \code{\link{teamBatsmenPartnershipAllOppnAllMatches}}\cr #' #' @export #' batsmanRunsVsStrikeRate <- function(df,name= "A Late Cut",dateRange,staticIntv=1){ batsman = runs = strikeRate = NULL ggplotly=NULL df=df %>% filter(date >= dateRange[1] & date <= dateRange[2]) b <- select(df,batsman,runs,strikeRate) plot.title = paste(name,"- Runs vs Strike Rate") if(staticIntv ==1){ #ggplot2 ggplot(b) + geom_point(aes(x=runs, y=strikeRate),colour="darkgrey") + geom_smooth(aes(x=runs, y=strikeRate)) + xlab("Strike rate(%)") + ylab("Runs") + ggtitle(bquote(atop(.(plot.title), atop(italic("Data source:http://cricsheet.org/"),"")))) } else { #ggplotly g <- ggplot(b) + geom_point(aes(x=runs, y=strikeRate),colour="darkgrey") + geom_smooth(aes(x=runs, y=strikeRate)) + xlab("Strike rate(%)") + ylab("Runs") + ggtitle(plot.title) ggplotly(g) } }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/batsmanRunsVsStrikeRate.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 26 Jan 2022 # Function: batsmanVsBowlerPerf # This function computes the performance of the batsman vs bowler # ########################################################################################### #' @title #' Performance of batsman vs bowler #' #' @description #' This function computes the performance of batsman vs bowler #' #' @usage #' batsmanVsBowlerPerf(t20MDF,batsman1,bowler1) #' #' @param t20MDF #' Dataframe #' #' @param batsman1 #' The batsman #' #' @param bowler1 #' The bowler #' @return None #' #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' @examples #' \dontrun{ #' #' batsmanVsBowlerPerf(t20MDF,batsman1,bowler1) #' } #' @seealso #' \code{\link{batsmanFoursSixes}}\cr #' \code{\link{batsmanRunsVsDeliveries}}\cr #' \code{\link{batsmanRunsVsStrikeRate}}\cr #' #' #' @export #' batsmanVsBowlerPerf <- function(t20MDF,batsman1,bowler1){ batsman=bowler=runs=fours=totalRuns=ballsFaced=wicketPlayerOut=NULL sixes=fours=timesOut=NULL a <- t20MDF %>% filter(batsman==batsman1 & bowler==bowler1) b <- select(a,batsman,bowler,runs) c <- b %>% summarize(ballsFaced=n(),totalRuns=sum(runs)) d <- b %>% mutate(fours=(runs>=4 & runs <6)) %>% filter(fours==TRUE) %>% summarise(fours=n()) e <- b %>% mutate(sixes=(runs ==6)) %>% filter(sixes == TRUE) %>% summarise(sixes=n()) f <- cbind(batsman1,bowler1,c,d,e) g <- f %>% mutate(SR=(totalRuns/ballsFaced)*100) h <- select(a,batsman,bowler,wicketPlayerOut) i <- h %>% filter(wicketPlayerOut==batsman1) %>% summarise(timesOut=n()) j <- cbind(g,i) j <- j %>% arrange(batsman1) j }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/batsmanVsBowlerPerf.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 10 Mar 2023 # Function: batsmanWinProbDL # This function computes the ball by ball win probability using Deep Learning Keras # ########################################################################################### #' @title #' Plot the batsman win probability contribution using Deep Learning model #' #' @description #' This function plots the win probability of batsman in a T20 match #' #' @usage #' batsmanWinProbDL(match,t1,t2,plot=1) #' #' @param match #' The dataframe of the match #' #' @param t1 #' The 1st team of the match #' #' @param t2 #' the 2nd team in the match #' #' @param plot #' Plot=1 (static), Plot=2(interactive) #' #' @return none #' #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' @examples #' \dontrun{ #' #Get the match details #' a <- getMatchDetails("England","Pakistan","2006-09-05",dir="../temp") #' #' # Plot tne match worm plot #' batsmanWinProbDL(a,'England',"Pakistan") #' } #' @seealso #' \code{\link{getBatsmanDetails}}\cr #' \code{\link{getBowlerWicketDetails}}\cr #' \code{\link{batsmanDismissals}}\cr #' \code{\link{getTeamBattingDetails}}\cr #' #' @export #' batsmanWinProbDL <- function(match,t1,t2,plot=1){ team=ball=totalRuns=wicketPlayerOut=ballsRemaining=runs=numWickets=runsMomentum=perfIndex=isWinner=NULL predict=ml_model=winProbability=ggplotly=runs=runRate=batsman=bowler=NULL batsmanIdx=bowlerIdx=NULL if (match$winner[1] == "NA") { print("Match no result ************************") return() } team1Size=0 requiredRuns=0 # Read batsman, bowler vectors batsmanMap=readRDS("batsmanMap.rds") bowlerMap=readRDS("bowlerMap.rds") teams=unique(match$team) teamA=teams[1] # Filter the performance of team1 a <-filter(match,team==teamA) #Balls in team 1's innings ballsIn1stInnings= dim(a)[1] b <- select(a,batsman, bowler,ball,totalRuns,wicketPlayerOut,team1,team2,date) c <-mutate(b,ball=gsub("1st\\.","",ball)) # Compute the total runs scored by team d <- mutate(c,runs=cumsum(totalRuns)) # Check if team1 won or lost the match if(match$winner[1]== teamA){ d$isWinner=1 } else{ d$isWinner=0 } #Get the ball num d$ballNum = seq.int(nrow(d)) # Compute the balls remaining for the team d$ballsRemaining = ballsIn1stInnings - d$ballNum +1 # Wickets lost by team d$wicketNum = d$wicketPlayerOut != "nobody" d=d %>% mutate(numWickets=cumsum(d$wicketNum==TRUE)) #Performance index is based on run rate (runs scored/ ball number) with wickets in hand d$perfIndex = (d$runs/d$ballNum) * (11 - d$numWickets) # Compute run rate d$runRate = (d$runs/d$ballNum) d$runsMomentum = (11 - d$numWickets)/d$ballsRemaining df8 = select(d, batsman,bowler,ballNum, ballsRemaining, runs, runRate,numWickets,runsMomentum,perfIndex, isWinner) df9=left_join(df8,batsmanMap) df9=left_join(df9,bowlerMap) dfa = select(df9, batsmanIdx,bowlerIdx,ballNum,ballsRemaining,runs,runRate,numWickets, runsMomentum,perfIndex, isWinner) print(dim(dfa)) ############################################################################################# ######## Team 2 # Compute for Team 2 # Required runs is the team made by team 1 + 1 requiredRuns=d[dim(d)[1],]$runs +1 teamB=teams[2] # Filter the performance of team1 a1 <-filter(match,team==teamB) #Balls in team 1's innings ballsIn2ndInnings= dim(a1)[1] + 1 b1 <- select(a1,batsman,bowler,ball,totalRuns,wicketPlayerOut,team1,team2,date) c1 <-mutate(b1,ball=gsub("2nd\\.","",ball)) # Compute total Runs d1 <- mutate(c1,runs=cumsum(totalRuns)) # Check of team2 is winner if(match$winner[1]== teamB){ d1$isWinner=1 } else{ d1$isWinner=0 } # Compute ball number d1$ballNum= ballsIn1stInnings + seq.int(nrow(d1)) # Compute remaining balls in 2nd innings d1$ballsRemaining= ballsIn2ndInnings - seq.int(nrow(d1)) # Compute wickets remaining d1$wicketNum = d1$wicketPlayerOut != "nobody" d1=d1 %>% mutate(numWickets=cumsum(d1$wicketNum==TRUE)) ballNum=d1$ballNum - ballsIn1stInnings #Performance index is based on run rate (runs scored/ ball number) with wickets in hand d1$perfIndex = (d1$runs/ballNum) * (11 - d1$numWickets) #Compute required runs d1$requiredRuns = requiredRuns - d1$runs d1$runRate = (d1$requiredRuns/d1$ballsRemaining) d1$runsMomentum = (11 - d1$numWickets)/d1$ballsRemaining # Rename required runs as runs df10 = select(d1,batsman,bowler,ballNum,ballsRemaining, requiredRuns,runRate,numWickets,runsMomentum,perfIndex, isWinner) names(df10) =c("batsman","bowler","ballNum","ballsRemaining","runs","runRate","numWickets","runsMomentum","perfIndex","isWinner") print(dim(df10)) df11=left_join(df10,batsmanMap) df11=left_join(df11,bowlerMap) df2=rbind(df9,df11) dfb = select(df11, batsmanIdx,bowlerIdx,ballNum,ballsRemaining,runs,runRate,numWickets, runsMomentum,perfIndex, isWinner) print(dim(dfb)) # load the model m=predict(dl_model,dfa,type = "prob") m1=m*100 m2=matrix(m1) n=predict(dl_model,dfb,type="prob") n1=n*100 n2=matrix(n1) m3= 100-n2 n3=100-m2 team1=rbind(m2,m3) team2=rbind(n3,n2) team11=as.data.frame(cbind(df2$ballNum,team1)) names(team11) = c("ballNum","winProbability") team22=as.data.frame(cbind(df2$ballNum,team2)) names(team22) = c("ballNum","winProbability") print("***************************************************************") cat("t1=",t1,"teamA= ",teamA," t2=",t2,"teamB= ",teamB,"\n") print("***************************************************************") if(t1 == teamA){ aa = cbind(df8,m2) aa2 = aa %>% select(batsman,m2) batsmen=unique(aa2$batsman) columns=c("batsman","delta") dfm = data.frame(matrix(nrow = 0, ncol = length(columns))) for (b in batsmen){ print(b) d <- aa2 %>% filter(batsman == b) print(d) delta =0 if(dim(d)[1] != 1){ delta = d$m2[dim(d)[1]] - d$m2[1] df1 = data.frame(b,delta) dfm = rbind(dfm,df1) } } } else if(t1 == teamB){ aa = cbind(df10,n2) aa2 = aa %>% select(batsman,n2) batsmen=unique(aa2$batsman) columns=c("batsman","delta") dfm = data.frame(matrix(nrow = 0, ncol = length(columns))) for (b in batsmen){ print(b) d <- aa2 %>% filter(batsman == b) print(d) delta =0 if(dim(d)[1] != 1){ delta = d$n2[dim(d)[1]] - d$n2[1] df1 = data.frame(b,delta) dfm = rbind(dfm,df1) } } } print(dfm) plot.title <- paste("Batsman Win Probability(DL) contribution-",t1," vs ",t2) # Plot both lines if(plot ==1){ #ggplot ggplot(data=dfm, aes(x=b, y=delta,fill=b)) + geom_bar(stat="identity") + geom_hline(yintercept = 0,color="blue") + ylab("Win probability(DL)") + ggtitle(plot.title) }else { #ggplotly g <- ggplot(data=dfm, aes(x=b, y=delta,fill=b)) + geom_bar(stat="identity") + geom_hline(yintercept = 0,color="blue")+ ylab("Win probability (DL)") + ggtitle(plot.title) ggplotly(g) } }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/batsmanWinProbDL.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 15 Mar 2023 # Function: batsmanWinProbLR # This function computes the ball by ball win probability using Logistic Regression model # ########################################################################################### #' @title #' Plot the batsman win probability using Logistic Regression model #' #' @description #' This function plots the batsman win probability of the teams in a T20 match #' #' @usage #' batsmanWinProbLR(match,t1,t2,plot=1) #' #' @param match #' The dataframe of the match #' #' @param t1 #' The 1st team of the match #' #' @param t2 #' the 2nd team in the match #' #' @param plot #' Plot=1 (static), Plot=2(interactive) #' #' @return none #' #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' @examples #' \dontrun{ #' #Get the match details #' a <- getMatchDetails("England","Pakistan","2006-09-05",dir="../temp") #' #' # Plot tne match worm plot #' batsmanWinProbLR(a,'England',"Pakistan") #' } #' @seealso #' \code{\link{getBatsmanDetails}}\cr #' \code{\link{getBowlerWicketDetails}}\cr #' \code{\link{batsmanDismissals}}\cr #' \code{\link{getTeamBattingDetails}}\cr #' #' @export #' batsmanWinProbLR <- function(match,t1,t2,plot=1){ team=ball=totalRuns=wicketPlayerOut=ballsRemaining=runs=numWickets=runsMomentum=perfIndex=isWinner=NULL predict=winProbability=ggplotly=runs=runRate=batsman=bowler=NULL if (match$winner[1] == "NA") { print("Match no result ************************") return() } team1Size=0 requiredRuns=0 teams=unique(match$team) teamA=teams[1] # Filter the performance of team1 a <-filter(match,team==teamA) #Balls in team 1's innings ballsIn1stInnings= dim(a)[1] b <- select(a,batsman, bowler,ball,totalRuns,wicketPlayerOut,team1,team2,date) c <-mutate(b,ball=gsub("1st\\.","",ball)) # Compute the total runs scored by team d <- mutate(c,runs=cumsum(totalRuns)) # Check if team1 won or lost the match if(match$winner[1]== teamA){ d$isWinner=1 } else{ d$isWinner=0 } #Get the ball num d$ballNum = seq.int(nrow(d)) # Compute the balls remaining for the team d$ballsRemaining = ballsIn1stInnings - d$ballNum +1 # Wickets lost by team d$wicketNum = d$wicketPlayerOut != "nobody" d=d %>% mutate(numWickets=cumsum(d$wicketNum==TRUE)) #Performance index is based on run rate (runs scored/ ball number) with wickets in hand d$perfIndex = (d$runs/d$ballNum) * (11 - d$numWickets) # Compute run rate d$runRate = (d$runs/d$ballNum) d$runsMomentum = (11 - d$numWickets)/d$ballsRemaining df = select(d, batsman,bowler,ballNum, ballsRemaining, runs, runRate,numWickets,runsMomentum,perfIndex, isWinner) print(dim(df)) ############################################################################################# ######## Team 2 # Compute for Team 2 # Required runs is the team made by team 1 + 1 requiredRuns=d[dim(d)[1],]$runs +1 teamB=teams[2] # Filter the performance of team1 a1 <-filter(match,team==teamB) #Balls in team 1's innings ballsIn2ndInnings= dim(a1)[1] + 1 b1 <- select(a1,batsman,bowler,ball,totalRuns,wicketPlayerOut,team1,team2,date) c1 <-mutate(b1,ball=gsub("2nd\\.","",ball)) # Compute total Runs d1 <- mutate(c1,runs=cumsum(totalRuns)) # Check of team2 is winner if(match$winner[1]== teamB){ d1$isWinner=1 } else{ d1$isWinner=0 } # Compute ball number d1$ballNum= ballsIn1stInnings + seq.int(nrow(d1)) # Compute remaining balls in 2nd innings d1$ballsRemaining= ballsIn2ndInnings - seq.int(nrow(d1)) # Compute wickets remaining d1$wicketNum = d1$wicketPlayerOut != "nobody" d1=d1 %>% mutate(numWickets=cumsum(d1$wicketNum==TRUE)) ballNum=d1$ballNum - ballsIn1stInnings #Performance index is based on run rate (runs scored/ ball number) with wickets in hand d1$perfIndex = (d1$runs/ballNum) * (11 - d1$numWickets) #Compute required runs d1$requiredRuns = requiredRuns - d1$runs d1$runRate = (d1$requiredRuns/d1$ballsRemaining) d1$runsMomentum = (11 - d1$numWickets)/d1$ballsRemaining # Rename required runs as runs df1 = select(d1,batsman,bowler,ballNum,ballsRemaining, requiredRuns,runRate,numWickets,runsMomentum,perfIndex, isWinner) names(df1) =c("batsman","bowler","ballNum","ballsRemaining","runs","runRate","numWickets","runsMomentum","perfIndex","isWinner") print(dim(df1)) df2=rbind(df,df1) # load the model #ml_model <- readRDS("glmLR.rds") a1=select(df,batsman,bowler,ballNum,ballsRemaining, runs,runRate,numWickets,runsMomentum,perfIndex) m=predict(final_lr_model,a1,type = "prob") m1=m$.pred_1*100 m2=matrix(m1) b1=select(df1,batsman,bowler,ballNum,ballsRemaining, runs,runRate,numWickets,runsMomentum,perfIndex) n=predict(final_lr_model,b1,type="prob") n1=n1=n$.pred_1*100 n2=matrix(n1) m3= 100-n2 n3=100-m2 team1=rbind(m2,m3) team2=rbind(n3,n2) team11=as.data.frame(cbind(df2$ballNum,team1)) names(team11) = c("ballNum","winProbability") team22=as.data.frame(cbind(df2$ballNum,team2)) names(team22) = c("ballNum","winProbability") print("***************************************************************") cat("t1=",t1,"teamA= ",teamA," t2=",t2,"teamB= ",teamB,"\n") print("***************************************************************") if(t1 == teamA){ aa = cbind(df,m2) aa2 = aa %>% select(batsman,m2) batsmen=unique(aa2$batsman) columns=c("batsman","delta") dfm = data.frame(matrix(nrow = 0, ncol = length(columns))) for (b in batsmen){ print(b) d <- aa2 %>% filter(batsman == b) print(d) delta =0 if(dim(d)[1] != 1){ delta = d$m2[dim(d)[1]] - d$m2[1] df1 = data.frame(b,delta) dfm = rbind(dfm,df1) } } } else if(t1 == teamB){ aa = cbind(df1,n2) aa2 = aa %>% select(batsman,n2) batsmen=unique(aa2$batsman) columns=c("batsman","delta") dfm = data.frame(matrix(nrow = 0, ncol = length(columns))) for (b in batsmen){ print(b) d <- aa2 %>% filter(batsman == b) print(d) delta =0 if(dim(d)[1] != 1){ delta = d$n2[dim(d)[1]] - d$n2[1] df1 = data.frame(b,delta) dfm = rbind(dfm,df1) } } } print(dfm) plot.title <- paste("Batsman Win Probability(LR) contribution-",t1," vs ",t2) # Plot both lines if(plot ==1){ #ggplot ggplot(data=dfm, aes(x=b, y=delta,fill=b)) + geom_bar(stat="identity") + geom_hline(yintercept = 0,color="blue") + ylab("Win probability(LR)") + ggtitle(plot.title) }else { #ggplotly g <- ggplot(data=dfm, aes(x=b, y=delta,fill=b)) + geom_bar(stat="identity") + geom_hline(yintercept = 0,color="blue")+ ylab("Win probability (LR)") + ggtitle(plot.title) ggplotly(g) } }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/batsmanWinProbLR.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 26 Mar 2016 # Function: batsmanRunsPredict # This function uses rpart classiication tree to predict the number of deliveries and the # runs scored by batsman # ########################################################################################### #' @title #' Predict deliveries to runs scored #' #' @description #' This function uses a classification tree to predict the number of deliveries required for #' the batsman to score the runs. It uses the package rpart to perform the classification #' #' @usage #' batsmanRunsPredict(df, name= "A Leg Glance",dateRange) #' #' @param df #' Data frame #' #' @param name #' Name of batsman #' #' @param dateRange #' Date interval to consider #' #' @return None #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' @examples #' \dontrun{ #' #Get the data frame for Kohli #' kohli <- getBatsmanDetails(team="India",name="Kohli",dir=pathToFile) #' batsmanRunsVsStrikeRate(kohli,"Kohli",dateRange) #' } #' #' @seealso #' \code{\link{batsmanDismissals}}\cr #' \code{\link{batsmanRunsVsDeliveries}}\cr #' \code{\link{batsmanRunsVsStrikeRate}}\cr #' \code{\link{batsmanRunsPredict}}\cr #' \code{\link{teamBatsmenPartnershipAllOppnAllMatches}}\cr #' #' @export #' batsmanRunsPredict <- function(df,name= "A Leg Glance",dateRange){ batsman = ballsPlayed = runs = rpart = NULL df=df %>% filter(date >= dateRange[1] & date <= dateRange[2]) b <- select(df,batsman,ballsPlayed,runs) names(b) <-c("batsman","deliveries","runs") m <-rpart(runs~deliveries,data=b) atitle <- paste(name,"- Runs vs Required number of Deliveries") rpart.plot(m,main=atitle) }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/batsmansRunsPredict.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 25 Mar 2016 # Function: batsmanRunsVsDeliveries # This function plots the runs scored vs deliveries faced # ########################################################################################### #' @title #' Runs versus deliveries faced #' #' @description #' This function plots the runs scored and the deliveries required. A regression #' smoothing function is used to fit the points #' #' @usage #' batsmanRunsVsDeliveries(df, name= "A Late Cut",dateRange,staticIntv=1) #' #' @param df #' Data frame #' #' @param name #' Name of batsman #' #' @param dateRange #' Date interval to consider #' #' @param staticIntv #' Static or interactive -staticIntv =1 (static plot) & staticIntv =2 (interactive plot) #' #' @return None #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' @examples #' \dontrun{ #' #Get the data frame for Kohli #' kohli <- getBatsmanDetails(team="India",name="Kohli",dir=pathToFile) #' batsmanRunsVsDeliveries(kohli,"Kohli") #' } #' #' @seealso #' \code{\link{batsmanFoursSixes}}\cr #' \code{\link{batsmanRunsVsDeliveries}}\cr #' \code{\link{batsmanRunsVsStrikeRate}}\cr #' #' @export #' batsmanRunsVsDeliveries <- function(df,name= "A Late Cut",dateRange, staticIntv=1){ batsman = runs = ballsPlayed= NULL ggplotly=NULL print(as.Date(dateRange[1])) print(as.Date(dateRange[2])) df=df %>% filter(date >= dateRange[1] & date <= dateRange[2]) plot.title = paste(name,"- Runs vs balls faced") if(staticIntv ==1){ #ggplot2 ggplot(df,aes(x=ballsPlayed,y=runs)) + geom_point(size=2) + geom_smooth() + xlab("Deliveries faced") + ylab("Runs") + ggtitle(bquote(atop(.(plot.title), atop(italic("Data source:http://cricsheet.org/"),"")))) } else { #ggplotly g <-ggplot(df,aes(x=ballsPlayed,y=runs)) + geom_point(size=2) + geom_smooth() + xlab("Deliveries faced") + ylab("Runs") + ggtitle(plot.title) ggplotly(g) } }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/batsmansRunsVsDeliveries.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 14 Apr 2016 # Function: bowlerCumulativeAvgEconRate # This function computes and plots the cumulative average economy rate s of a bowler # ########################################################################################### #' @title #' Bowler's cumulative average economy rate #' #' @description #' This function computes and plots the cumulative average economy rate of a bowler #' #' @usage #' bowlerCumulativeAvgEconRate(df,name,dateRange,staticIntv1=1) #' #' @param df #' Data frame #' #' @param name #' Name of batsman #' #' @param dateRange #' Date interval to consider #' #' @param staticIntv1 #' Static or interactive -staticIntv1 =1 (static plot) & staticIntv1 =2 (interactive plot) #' #' @return None #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' @examples #' \dontrun{) #' #'Get the data frame for RA Jadeja #' jadeja <- getBowlerWicketDetails(team="India",name="Jadeja",dir=pathToFile) #' bowlerCumulativeAvgEconRate(jadeja,"RA Jadeja",dateRange) #' } #' @seealso #' \code{\link{batsmanCumulativeAverageRuns}} #' \code{\link{bowlerCumulativeAvgWickets}} #' \code{\link{batsmanCumulativeStrikeRate}} #' \code{\link{batsmanRunsVsStrikeRate}} #' \code{\link{batsmanRunsPredict}} #' #' @export #' bowlerCumulativeAvgEconRate <- function(df,name,dateRange,staticIntv1=1){ economyRate=cs=no=NULL ggplotly=NULL df=df %>% filter(date >= dateRange[1] & date <= dateRange[2]) b <- select(df,economyRate) b$no<-seq.int(nrow(b)) c <- select(b,no,economyRate) d <- mutate(c,cs=cumsum(economyRate)/no) plot.title= paste(name,"- Cum. avg Econ Rate vs No innings") if(staticIntv1 ==1){ #ggplot2 ggplot(d) + geom_line(aes(x=no,y=cs),col="blue") + xlab("No of innings") + ylab("Cumulative Avg. Economy Rate") + ggtitle(bquote(atop(.(plot.title), atop(italic("Data source:http://cricsheet.org/"),"")))) } else { #ggplotly g <- ggplot(d) + geom_line(aes(x=no,y=cs),col="blue") + xlab("No of innings") + ylab("Cumulative Avg. Economy Rate") + ggtitle(plot.title) ggplotly(g) } }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/bowlerCumulativeAvgEconRate.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 14 Apr 2016 # Function: bowlerCumulativeAvgWickets # This function computes and plots the cumulative average wickets of a bowler # ########################################################################################### #' @title #' Bowler's cumulative average wickets #' #' @description #' This function computes and plots the cumulative average wickets of a bowler #' #' @usage #' bowlerCumulativeAvgWickets(df,name,dateRange,staticIntv1=1) #' #' @param df #' Data frame #' #' @param name #' Name of batsman #' #' @param dateRange #' Date interval to consider #' #' @param staticIntv1 #' Static or interactive -staticIntv1 =1 (static plot) & staticIntv1 =2 (interactive plot) #' #' @return None #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' @examples #' \dontrun{) #' #'Get the data frame for RA Jadeja #' jadeja <- getBowlerWicketDetails(team="India",name="Jadeja",dir=pathToFile) #' bowlerCumulativeAvgWickets(jadeja,"RA Jadeja",dateRange) #' } #' @seealso #' \code{\link{batsmanCumulativeAverageRuns}} #' \code{\link{bowlerCumulativeAvgEconRate}} #' \code{\link{batsmanCumulativeStrikeRate}} #' \code{\link{batsmanRunsVsStrikeRate}} #' \code{\link{batsmanRunsPredict}} #' #' @export #' bowlerCumulativeAvgWickets <- function(df,name,dateRange,staticIntv1=1){ wickets=cs=no=NULL ggplotly=NULL df=df %>% filter(date >= dateRange[1] & date <= dateRange[2]) b <- select(df,wickets) b$no<-seq.int(nrow(b)) c <- select(b,no,wickets) d <- mutate(c,cs=cumsum(wickets)/no) plot.title= paste(name,"- Cumulative avg wkts vs No innings") if(staticIntv1 ==1){ #ggplot2 ggplot(d) + geom_line(aes(x=no,y=cs),col="blue") + xlab("No of innings") + ylab("Cumulative Avg. wickets") + ggtitle(bquote(atop(.(plot.title), atop(italic("Data source:http://cricsheet.org/"),"")))) } else { g <- ggplot(d) + geom_line(aes(x=no,y=cs),col="blue") + xlab("No of innings") + ylab("Cumulative Avg. wickets") + ggtitle(plot.title) ggplotly(g) } }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/bowlerCumulativeAvgWickets.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 2 May 2020 # Function: bowlerDeliveryWickets # This function creates a data frame of deliveries bowled and wickets # ########################################################################################### #' @title #' Number of deliveries to wickets #' #' @description #' This function creates a dataframe of balls bowled versus the wickets taken by #' the bowler #' @usage #' bowlerDeliveryWickets(match,theTeam,name) #' #' @param match #' Data frame of the match #' #' @param theTeam #' The team for which the delivery wickets have to be computed #' #' @param name #' The name of the bowler #' #' @return dataframe #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' @examples #' \dontrun{ #' #Get match data #' match <- getMatchDetails("England","Pakistan","2006-09-05",dir="../data") #' bowlerDeliveryWickets(match,"India","Jadeja") #' } #' #' @seealso #' \code{\link{batsmanFoursSixes}}\cr #' \code{\link{batsmanRunsVsDeliveries}}\cr #' \code{\link{batsmanRunsVsStrikeRate}}\cr #' \code{\link{bowlerDeliveryWickets}}\cr #' \code{\link{bowlerMeanEconomyRate}}\cr #' \code{\link{bowlerMeanRunsConceded}}\cr #' #' bowlerDeliveryWickets <- function(match,theTeam,name){ team = bowler = wicketPlayerOut =delivery = wicketNo = NULL ggplotly=NULL d <- NULL #a <-filter(match,opposition!=theTeam) #b <- filter(match,grepl(name,bowler)) b=match[match$bowler==name,] if(dim(b)[1] != 0){ print(head(b)) # Compute the delivery in which wicket was taken (1.. no of deliveries) b$delivery<- seq(1:dim(b)[1]) c <- filter(b,wicketPlayerOut != "nobody") if(dim(c)[1] !=0){ c$wicketNo <- seq(1:dim(c)[1]) # wicket no 1.. no of wickets d <- select(c,bowler,delivery,wicketNo,date) } } d }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/bowlerDeliveryWickets.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 26 Mar 2016 # Function: bowlerMeanEconomyRate # # ########################################################################################### #' @title #' Mean economy rate versus number of overs #' #' @description #' This function computes and plots mean economy rate and the number of #' overs bowled by the bowler #' @usage #' bowlerMeanEconomyRate(df, name,dateRange,staticIntv1=1) #' #' @param df #' Data frame #' #' @param name #' Name of bowler #' #' @param dateRange #' Date interval to consider #' #' @param staticIntv1 #' Static or interactive -staticIntv1 =1 (static plot) & staticIntv1 =2 (interactive plot) #' #' @return None #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' @examples #' \dontrun{ #' # Get the data frame for RA Jadeja #' jadeja <- getBowlerWicketDetails(team="India",name="Jadeja",dir=pathToFile) #' bowlerMeanEconomyRate(jadeja,"RA Jadeja") #' } #' #' @seealso #' \code{\link{bowlerMovingAverage}}\cr #' \code{\link{bowlerWicketsVenue}}\cr #' \code{\link{bowlerMeanRunsConceded}}\cr #' #' @export #' bowlerMeanEconomyRate <- function(df,name,dateRange,staticIntv1=1){ overs =meanEconomyRate = economyRate = NULL ggplotly=NULL print(dateRange[1]) df=df %>% filter(date >= dateRange[1] & date <= dateRange[2]) c <- summarise(group_by(df,overs),meanEconomyRate=mean(economyRate)) plot.title <- paste(name,"- Mean Economy Rate vs Overs") if(staticIntv1 ==1){ #ggplot2 ggplot(c, width = "auto", height = "auto",aes(x=overs, y=meanEconomyRate,fill=overs)) + geom_bar(data=c,stat="identity" ) + xlab("Overs") + ylab("Mean Economy Rate") + ggtitle(bquote(atop(.(plot.title), atop(italic("Data source:http://cricsheet.org/"),"")))) } else { #ggplotly g<- ggplot(c,aes(x=overs, y=meanEconomyRate,fill=overs)) + geom_bar(data=c,stat="identity" ) + xlab("Overs") + ylab("Mean Economy Rate") + ggtitle(plot.title) ggplotly(g) } }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/bowlerMeanEconomyRate.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 26 Mar 2016 # Function: bowlerMeanRunsConceded # This function plots the overs versus the mean runs conceded # ########################################################################################### #' @title #' Mean runs conceded versus overs #' #' @description #' This function computes and plots mean runs conceded by the bowler for the #' number of overs bowled by the bowler #' @usage #' bowlerMeanRunsConceded(df, name,dateRange,staticIntv1=1) #' #' @param df #' Data frame #' #' @param name #' Name of bowler #' #' @param dateRange #' Date interval to consider #' #' @param staticIntv1 #' Static or interactive -staticIntv1 =1 (static plot) & staticIntv1 =2 (interactive plot) #' #' @return None #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' @examples #' \dontrun{ #' # Get the data frame for RA Jadeja #' jadeja <- getBowlerWicketDetails(team="India",name="Jadeja",dir=pathToFile) #' bowlerMeanRunsConceded(jadeja,"RA Jadeja",dateRange) #' } #' #' @seealso #' \code{\link{bowlerMovingAverage}}\cr #' \code{\link{bowlerWicketsVenue}}\cr #' \code{\link{bowlerMeanRunsConceded}}\cr #' #' @export #' bowlerMeanRunsConceded <- function(df,name,dateRange,staticIntv1=1){ overs = runs = maidens = meanRuns = wickets = NULL ggplotly=NULL df=df %>% filter(date >= dateRange[1] & date <= dateRange[2]) c <- summarise(group_by(df,overs),meanRuns=mean(runs),meanMaidens=mean(maidens), meanWickets=mean(wickets)) plot.title <- paste(name,"- Average runs conceded vs Overs") if(staticIntv1 ==1){ #ggplot2 ggplot(c,aes(x=overs, y=meanRuns,fill=overs)) + geom_bar(data=c,stat="identity" ) + xlab("Overs") + ylab("Average runs conceded") + ggtitle(bquote(atop(.(plot.title), atop(italic("Data source:http://cricsheet.org/"),"")))) }else { #ggplotly g <- ggplot(c,aes(x=overs, y=meanRuns,fill=overs)) + geom_bar(data=c,stat="identity" ) + xlab("Overs") + ylab("Average runs conceded") + ggtitle(plot.title) ggplotly(g) } }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/bowlerMeanRunsConceded.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 26 Mar 2016 # Function: bowlerMovingAverage # This function plots the moving average of wickets taken by bowler in career # ########################################################################################### #' @title #' Bowler's moving average of wickets #' #' @description #' This function computes and plots the wickets taken by the bowler over career. A loess #' regression fit plots the moving average of wickets taken by bowler #' @usage #' bowlerMovingAverage(df, name,dateRange,staticIntv1=1) #' #' @param df #' Data frame #' #' @param name #' Name of bowler #' #' @param dateRange #' Date interval to consider #' #' @param staticIntv1 #' Static or interactive -staticIntv1 =1 (static plot) & staticIntv1 =2 (interactive plot) #' #' @return None #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' @examples #' \dontrun{ #' # Get the data frame for RA Jadeja #' jadeja <- getBowlerWicketDetails(team="India",name="Jadeja",dir=pathToFile) #' bowlerMeanRunsConceded(jadeja,"RA Jadeja",dateRange,staticIntv=1) #' } #' #' @seealso #' \code{\link{bowlerMeanEconomyRate}}\cr #' \code{\link{bowlerWicketsVenue}}\cr #' \code{\link{bowlerMeanRunsConceded}}\cr #' #' @export #' bowlerMovingAverage <- function(df,name,dateRange,staticIntv1=1){ bowler = wickets = NULL ggplotly=NULL df=df %>% filter(date >= dateRange[1] & date <= dateRange[2]) c <- select(df,bowler,wickets,date) plot.title = paste(name,"- Moving average of wickets in career") if(staticIntv1 ==1){ #ggplot2 ggplot(c) + geom_line(aes(x=date, y=wickets),colour="darkgrey") + geom_smooth(aes(x=date, y=wickets)) + xlab("Date") + ylab("Wickets") + ggtitle(bquote(atop(.(plot.title), atop(italic("Data source:http://cricsheet.org/"),"")))) } else { #ggplotly g <- ggplot(c) + geom_line(aes(x=date, y=wickets),colour="darkgrey") + geom_smooth(aes(x=date, y=wickets)) + xlab("Date") + ylab("Wickets") + ggtitle(plot.title) ggplotly(g) } }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/bowlerMovingAverage.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 26 Jan 2022 # Function: bowlerVsBatsmanPerf # This function computes the performance of the bowler vs batsman # ########################################################################################### #' @title #' Performance of bowler vs batsman #' #' @description #' This function computes the performance of bowler vs batsman #' #' @usage #' bowlerVsBatsmanPerf(t20MDF,batsman1,bowler1) #' #' @param t20MDF #' Dataframe #' #' @param batsman1 #' The batsman #' #' @param bowler1 #' The bowler #' @return None #' #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' @examples #' \dontrun{ #' #' bowlerVsBatsmanPerf(t20MDF,batsman1,bowler1) #' } #' @seealso #' \code{\link{batsmanFoursSixes}}\cr #' \code{\link{batsmanRunsVsDeliveries}}\cr #' \code{\link{batsmanRunsVsStrikeRate}}\cr #' #' #' @export #' bowlerVsBatsmanPerf <- function(t20MDF,batsman1,bowler1){ batsman=bowler=runs=wides=noballs=wicketKind=wicketPlayerOut=runsConceded=balls=ER=wicketTaken=NULL a <- t20MDF %>% filter(batsman==batsman1 & bowler==bowler1) b <- select(a,batsman,bowler,runs,wides,noballs,wicketKind,wicketPlayerOut) c <- summarise(group_by(a,bowler),balls=n(), runsConceded=sum(runs,wides,noballs)) d <- c %>% mutate(ER=runsConceded*6/balls) %>% select(balls,runsConceded,ER) e <- b %>% select(bowler,batsman,wicketKind,wicketPlayerOut) f <- e %>% filter(wicketPlayerOut==batsman1) %>% summarise(wicketTaken=n()) if(nrow(a) == 0){ df <- data.frame(matrix(ncol = 4, nrow = 0)) names <- c("balls","runsConceded","ER","wicketTaken") colnames(df) <- names df[1,] <- c(0,0,0,0) g <- cbind(bowler1,batsman1,df) } else{ g <- cbind(bowler1,batsman1,d,f) g <- g %>% arrange(bowler1) } g }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/bowlerVsBatsmanPerf.R
matchWormGraph <- function(match,t1,t2,plot=1) { team=ball=totalRuns=total=NULL ggplotly=NULL # Filter the performance of team1 a <-filter(matches,team!=t1) # Power play a1 <- a %>% filter(between(as.numeric(str_extract(ball, "\\d+(\\.\\d+)?$")), 0.1, 5.9)) a2 <- select(a1,date,bowler,wicketPlayerOut) a3 <- a2 %>% group_by(bowler,date) %>% filter(wicketPlayerOut != "nobody") %>% mutate(wickets =n()) a4 <- a3 %>% select(date,bowler,wickets) %>% distinct(date,bowler,wickets) %>% group_by(bowler) %>% summarise(wicketsPowerPlay=sum(wickets)) %>% arrange(desc(wicketsPowerPlay)) # Middle overs I b1 <- a %>% filter(between(as.numeric(str_extract(ball, "\\d+(\\.\\d+)?$")), 6.1, 15.9)) b2 <- select(b1,date,bowler,wicketPlayerOut) b3 <- b2 %>% group_by(bowler,date) %>% filter(wicketPlayerOut != "nobody") %>% mutate(wickets =n()) b4 <- b3 %>% select(date,bowler,wickets) %>% distinct(date,bowler,wickets) %>% group_by(bowler) %>% summarise(wicketsMiddleOvers=sum(wickets)) %>% arrange(desc(wicketsMiddleOvers)) #Midle overs 2 c1 <- a %>% filter(between(as.numeric(str_extract(ball, "\\d+(\\.\\d+)?$")), 16.1, 20.0)) c2 <- select(c1,date,bowler,wicketPlayerOut) c3 <- c2 %>% group_by(bowler,date) %>% filter(wicketPlayerOut != "nobody") %>% mutate(wickets =n()) c4 <- c3 %>% select(date,bowler,wickets) %>% distinct(date,bowler,wickets) %>% group_by(bowler) %>% summarise(wicketsDeathOvers=sum(wickets)) %>% arrange(desc(wicketsDeathOvers)) val=min(dim(a4)[1],dim(b4)[1],dim(c4)[1]) m=cbind(a4[1:val,],b4[1:val,],c4[1:val,]) #################### # Filter the performance of team2 a <-filter(match,team==t2) # Power play a11 <- a %>% filter(between(as.numeric(str_extract(ball, "\\d+(\\.\\d+)?$")), 0.1, 5.9)) a21 <- select(a11,team,wicketPlayerOut) a31 <- a21 %>% filter(wicketPlayerOut != "nobody") %>% mutate(wickets =n()) a31wickets=ifelse(!is.na(a31$wickets[1]), a31$wickets[1], 0) a31$opposition=t1 if(!is.na(a31$wickets[1])) a31$type="1-PowerPlay" b11 <- a %>% filter(between(as.numeric(str_extract(ball, "\\d+(\\.\\d+)?$")), 6.1, 15.9)) b21 <- select(b11,team,wicketPlayerOut) b31 <- b21 %>% filter(wicketPlayerOut != "nobody") %>% mutate(wickets =n()) b31wickets=ifelse(!is.na(b31$wickets[1]), b31$wickets[1], 0) b31$opposition=t1 if(!is.na(b31$wickets[1])) b31$type="2-Middle overs" #Midle overs 2 c11 <- a %>% filter(between(as.numeric(str_extract(ball, "\\d+(\\.\\d+)?$")), 16.1, 20.0)) c21 <- select(c11,team,wicketPlayerOut) c31 <- c21 %>% filter(wicketPlayerOut != "nobody") %>% mutate(wickets =n()) c31wickets=ifelse(!is.na(c31$wickets[1]), c31$wickets[1], 0) c31$opposition=t1 if(!is.na(c31$wickets[1])) c31$type="3-Death overs" m=rbind(a3,b3,c3,a31,b31,c31) plot.title= paste("Wickets across 20 overs of ",t1, "and", t2, sep=" ") ggplot(data = m,mapping=aes(x=type, y=wickets, fill=opposition)) + geom_bar(stat="identity", position = "dodge") + ggtitle(bquote(atop(.(plot.title), atop(italic("Data source:http://cricsheet.org/"),"")))) # Plot both lines if(plot ==1){ #ggplot2 ggplot() + geom_segment(aes(x=0,xend=20,y=0,yend=0)) + geom_segment(aes(x=0,xend=0,y=0,yend=15)) + geom_segment(aes(x=0,xend=6,y=a3count,yend=a3count,color="t1")) + geom_segment(aes(x=6,xend=12,y=b3count,yend=b3count,color="t1")) + geom_segment(aes(x=12,xend=17,y=c3count,yend=c3count,color="t1")) + geom_segment(aes(x=17,xend=20,y=d3count,yend=d3count,color="t1")) + geom_segment(aes(x=6,xend=6,y=a3count,yend=b3count,color="t1")) + geom_segment(aes(x=12,xend=12,y=b3count,yend=c3count,color="t1")) + geom_segment(aes(x=17,xend=17,y=c3count,yend=d3count,color="t1")) + #Team 2 geom_segment(aes(x=0,xend=6,y=a31count,yend=a31count,color="t2")) + geom_segment(aes(x=6,xend=12,y=b31count,yend=b31count,color="t2")) + geom_segment(aes(x=12,xend=17,y=c31count,yend=c31count,color="t2")) + geom_segment(aes(x=17,xend=20,y=d31count,yend=d31count,color="t2")) + geom_segment(aes(x=6,xend=6,y=a31count,yend=b31count,color="t2")) + geom_segment(aes(x=12,xend=12,y=b31count,yend=c31count,color="t2")) + geom_segment(aes(x=17,xend=17,y=c31count,yend=d31count,color="t2"))+ ggtitle(bquote(atop(.("Over performance"), atop(italic("Data source:http://cricsheet.org/"),"")))) }else { #ggplotly g <- ggplot() + geom_segment(aes(x=0,xend=20,y=0,yend=0)) + geom_segment(aes(x=0,xend=0,y=0,yend=10)) + geom_segment(aes(x=0,xend=6,y=a3count,yend=a3count,color="t1")) + geom_segment(aes(x=6,xend=12,y=b3count,yend=b3count,color="t1")) + geom_segment(aes(x=12,xend=17,y=c3count,yend=c3count,color="t1")) + geom_segment(aes(x=17,xend=20,y=d3count,yend=d3count,color="t1")) + geom_segment(aes(x=6,xend=6,y=a3count,yend=b3count,color="t1")) + geom_segment(aes(x=12,xend=12,y=b3count,yend=c3count,color="t1")) + geom_segment(aes(x=17,xend=17,y=c3count,yend=d3count,color="t1")) + #Team 2 geom_segment(aes(x=0,xend=6,y=a31count,yend=a31count,color="t2")) + geom_segment(aes(x=6,xend=12,y=b31count,yend=b31count,color="t2")) + geom_segment(aes(x=12,xend=17,y=c31count,yend=c31count,color="t2")) + geom_segment(aes(x=17,xend=20,y=d31count,yend=d31count,color="t2")) + geom_segment(aes(x=6,xend=6,y=a31count,yend=b31count,color="t2")) + geom_segment(aes(x=12,xend=12,y=b31count,yend=c31count,color="t2")) + geom_segment(aes(x=17,xend=17,y=c31count,yend=d31count,color="t2")) + ggtitle("Over performance") ggplotly(g) } }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/bowlerWicketsAcrossOvers.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 26 Mar 2016 # Function: bowlerWicketsAgainstOpposition # This function plots the mean wickets taken by the bowler against different oppositions # ########################################################################################### #' @title #' Bowler wickets versus different teams #' #' @description #' This function computes and plots mean number of wickets taken by the bowler against different #' opposition #' @usage #' bowlerWicketsAgainstOpposition(df, name,dateRange,staticIntv1=1) #' #' @param df #' Data frame #' #' @param name #' Name of bowler #' #' @param dateRange #' Date interval to consider #' #' @param staticIntv1 #' Static or interactive -staticIntv1 =1 (static plot) & staticIntv1 =2 (interactive plot) #' #' @return None #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' @examples #' \dontrun{ #' # Get the data frame for RA Jadeja #' jadeja <- getBowlerWicketDetails(team="India",name="Jadeja",dir=pathToFile) #' bowlerWicketsAgainstOpposition(jadeja,"RA Jadeja",dateRange) #' } #' #' @seealso #' \code{\link{bowlerMovingAverage}}\cr #' \code{\link{bowlerWicketsVenue}}\cr #' \code{\link{bowlerMeanRunsConceded}}\cr #' #' @export #' bowlerWicketsAgainstOpposition <- function(df,name,dateRange,staticIntv1=1){ meanWickets = numMatches = wickets = opposition = NULL ggplotly=NULL df=df %>% filter(date >= dateRange[1] & date <= dateRange[2]) c <- summarise(group_by(df,opposition),meanWickets=mean(wickets),numMatches=n()) d <- mutate(c,opposition=paste(opposition,"(",numMatches,")",sep="")) plot.title = paste(name,"- Wickets against Opposition(number innings)") if(staticIntv1 ==1){ #ggplot2 ggplot(d, height=600,aes(x=opposition, y=meanWickets, fill=opposition))+ geom_bar(stat = "identity",position="dodge") + geom_hline(aes(yintercept=2))+ xlab("Opposition") + ylab("Average wickets taken") + ggtitle(bquote(atop(.(plot.title), atop(italic("Data source:http://cricsheet.org/"),""))))+ theme(axis.text.x = element_text(angle = 90, hjust = 1)) } else { #ggplotly g <- ggplot(d, aes(x=opposition, y=meanWickets, fill=opposition))+ geom_bar(stat = "identity",position="dodge") + geom_hline(aes(yintercept=2))+ xlab("Opposition") + ylab("Average wickets taken") + ggtitle(plot.title)+ theme(axis.text.x = element_text(angle = 90, hjust = 1)) ggplotly(g,height=600) } }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/bowlerWicketsAgainstOppn.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 26 Mar 2016 # Function: bowlerWicketsVenue # This function plots the performance of bowlers at different venues # ########################################################################################### #' @title #' Bowler performance at different venues #' #' @description #' This function computes and plots mean number of wickets taken by the bowler in different #' venues #' @usage #' bowlerWicketsVenue(df, name,dateRange,staticIntv1=1) #' #' @param df #' Data frame #' #' @param name #' Name of bowler #' #' @param dateRange #' Date interval to consider #' #' @param staticIntv1 #' Static or interactive -staticIntv1 =1 (static plot) & staticIntv1 =2 (interactive plot) #' #' @return None #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' @examples #' \dontrun{ #' # Get the data frame for RA Jadeja #' jadeja <- getBowlerWicketDetails(team="India",name="Jadeja",dir=pathToFile) #' bowlerWicketsVenue(jadeja,"RA Jadeja",dateRange) #' } #' #' @seealso #' \code{\link{bowlerMovingAverage}}\cr #' \code{\link{bowlerWicketsVenue}}\cr #' \code{\link{bowlerMeanRunsConceded}}\cr #' #' @export #' bowlerWicketsVenue <- function(df,name,dateRange,staticIntv1=1){ meanWickets = numMatches =wickets = venue = NULL ggplotly=NULL df=df %>% filter(date >= dateRange[1] & date <= dateRange[2]) c <- summarise(group_by(df,venue),meanWickets=mean(wickets),numMatches=n()) d <- mutate(c,venue=paste(venue,"(",numMatches,")",sep="")) e <- arrange(d,desc(meanWickets)) f <- e[1:20,] plot.title = paste(name,"- Wickets in venue(number innings)") if(staticIntv1 ==1){ #ggplot2 ggplot(f,aes(x=venue, y=meanWickets, fill=venue))+ geom_bar(stat = "identity",position="dodge") + geom_hline(aes(yintercept=2))+ xlab("Venue") + ylab("Average wickets taken") + ggtitle(bquote(atop(.(plot.title), atop(italic("Data source:http://cricsheet.org/"),""))))+ theme(axis.text.x = element_text(angle = 90, hjust = 1)) } else { #ggplotly g <- ggplot(f, aes(x=venue, y=meanWickets, fill=venue))+ geom_bar(stat = "identity",position="dodge") + geom_hline(aes(yintercept=2))+ xlab("Venue") + ylab("Average wickets taken") + ggtitle(plot.title) + theme(axis.text.x = element_text(angle = 90, hjust = 1)) ggplotly(g,height=600) } }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/bowlerWicketsVenue.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 14 Mar 2023 # Function: bowlerWinProbDL # This function computes the ball by ball win probability using Deep Learning Keras # ########################################################################################### #' @title #' Plot the Bowler win probability contribution using Deep Learning model #' #' @description #' This function plots the win probability of bowlers in a T20 match #' #' @usage #' bowlerWinProbDL(match,t1,t2,plot=1) #' #' @param match #' The dataframe of the match #' #' @param t1 #' The 1st team of the match #' #' @param t2 #' the 2nd team in the match #' #' @param plot #' Plot=1 (static), Plot=2(interactive) #' #' @return none #' #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' @examples #' \dontrun{ #' #Get the match details #' a <- getMatchDetails("England","Pakistan","2006-09-05",dir="../temp") #' #' # t #' bowlerWinProbDL(a,'England',"Pakistan") #' } #' @seealso #' \code{\link{getBatsmanDetails}}\cr #' \code{\link{getBowlerWicketDetails}}\cr #' \code{\link{batsmanDismissals}}\cr #' \code{\link{getTeamBattingDetails}}\cr #' #' @export #' bowlerWinProbDL <- function(match,t1,t2,plot=1){ team=ball=totalRuns=wicketPlayerOut=ballsRemaining=runs=numWickets=runsMomentum=perfIndex=isWinner=NULL predict=ml_model=winProbability=ggplotly=runs=runRate=batsman=bowler=NULL batsmanIdx=bowlerIdx=NULL if (match$winner[1] == "NA") { print("Match no result ************************") return() } team1Size=0 requiredRuns=0 # Read batsman, bowler vectors batsmanMap=readRDS("batsmanMap.rds") bowlerMap=readRDS("bowlerMap.rds") teams=unique(match$team) teamA=teams[1] # Filter the performance of team1 a <-filter(match,team==teamA) #Balls in team 1's innings ballsIn1stInnings= dim(a)[1] b <- select(a,batsman, bowler,ball,totalRuns,wicketPlayerOut,team1,team2,date) c <-mutate(b,ball=gsub("1st\\.","",ball)) # Compute the total runs scored by team d <- mutate(c,runs=cumsum(totalRuns)) # Check if team1 won or lost the match if(match$winner[1]== teamA){ d$isWinner=1 } else{ d$isWinner=0 } #Get the ball num d$ballNum = seq.int(nrow(d)) # Compute the balls remaining for the team d$ballsRemaining = ballsIn1stInnings - d$ballNum +1 # Wickets lost by team d$wicketNum = d$wicketPlayerOut != "nobody" d=d %>% mutate(numWickets=cumsum(d$wicketNum==TRUE)) #Performance index is based on run rate (runs scored/ ball number) with wickets in hand d$perfIndex = (d$runs/d$ballNum) * (11 - d$numWickets) # Compute run rate d$runRate = (d$runs/d$ballNum) d$runsMomentum = (11 - d$numWickets)/d$ballsRemaining df8 = select(d, batsman,bowler,ballNum, ballsRemaining, runs, runRate,numWickets,runsMomentum,perfIndex, isWinner) df9=left_join(df8,batsmanMap) df9=left_join(df9,bowlerMap) dfa = select(df9, batsmanIdx,bowlerIdx,ballNum,ballsRemaining,runs,runRate,numWickets, runsMomentum,perfIndex, isWinner) print(dim(dfa)) ############################################################################################# ######## Team 2 # Compute for Team 2 # Required runs is the team made by team 1 + 1 requiredRuns=d[dim(d)[1],]$runs +1 teamB=teams[2] # Filter the performance of team1 a1 <-filter(match,team==teamB) #Balls in team 1's innings ballsIn2ndInnings= dim(a1)[1] + 1 b1 <- select(a1,batsman,bowler,ball,totalRuns,wicketPlayerOut,team1,team2,date) c1 <-mutate(b1,ball=gsub("2nd\\.","",ball)) # Compute total Runs d1 <- mutate(c1,runs=cumsum(totalRuns)) # Check of team2 is winner if(match$winner[1]== teamB){ d1$isWinner=1 } else{ d1$isWinner=0 } # Compute ball number d1$ballNum= ballsIn1stInnings + seq.int(nrow(d1)) # Compute remaining balls in 2nd innings d1$ballsRemaining= ballsIn2ndInnings - seq.int(nrow(d1)) # Compute wickets remaining d1$wicketNum = d1$wicketPlayerOut != "nobody" d1=d1 %>% mutate(numWickets=cumsum(d1$wicketNum==TRUE)) ballNum=d1$ballNum - ballsIn1stInnings #Performance index is based on run rate (runs scored/ ball number) with wickets in hand d1$perfIndex = (d1$runs/ballNum) * (11 - d1$numWickets) #Compute required runs d1$requiredRuns = requiredRuns - d1$runs d1$runRate = (d1$requiredRuns/d1$ballsRemaining) d1$runsMomentum = (11 - d1$numWickets)/d1$ballsRemaining # Rename required runs as runs df10 = select(d1,batsman,bowler,ballNum,ballsRemaining, requiredRuns,runRate,numWickets,runsMomentum,perfIndex, isWinner) names(df10) =c("batsman","bowler","ballNum","ballsRemaining","runs","runRate","numWickets","runsMomentum","perfIndex","isWinner") print(dim(df10)) df11=left_join(df10,batsmanMap) df11=left_join(df11,bowlerMap) df2=rbind(df9,df11) dfb = select(df11, batsmanIdx,bowlerIdx,ballNum,ballsRemaining,runs,runRate,numWickets, runsMomentum,perfIndex, isWinner) print(dim(dfb)) # load the model m=predict(dl_model,dfa,type = "prob") m1=m*100 m2=matrix(m1) n=predict(dl_model,dfb,type="prob") n1=n*100 n2=matrix(n1) m3= 100-n2 n3=100-m2 team1=rbind(m2,m3) team2=rbind(n3,n2) team11=as.data.frame(cbind(df2$ballNum,team1)) names(team11) = c("ballNum","winProbability") team22=as.data.frame(cbind(df2$ballNum,team2)) names(team22) = c("ballNum","winProbability") print("***************************************************************") cat("t1=",t1,"teamA= ",teamA," t2=",t2,"teamB= ",teamB,"\n") print("***************************************************************") if(t1 != teamA){ aa = cbind(df8,m2) aa2 = aa %>% select(bowler,m2) bowlers=unique(aa2$bowler) columns=c("bowler","delta") dfm = data.frame(matrix(nrow = 0, ncol = length(columns))) for (b in bowlers){ print(b) d <- aa2 %>% filter(bowler == b) print(d) delta =0 if(dim(d)[1] != 1){ delta = d$m2[dim(d)[1]] - d$m2[1] df1 = data.frame(b,delta) dfm = rbind(dfm,df1) } } } else if(t1 != teamB){ aa = cbind(df10,n2) aa2 = aa %>% select(bowler,n2) bowlers=unique(aa2$bowler) columns=c("bowler","delta") dfm = data.frame(matrix(nrow = 0, ncol = length(columns))) for (b in bowlers){ print(b) d <- aa2 %>% filter(bowler == b) print(d) delta =0 if(dim(d)[1] != 1){ delta = d$n2[dim(d)[1]] - d$n2[1] df1 = data.frame(b,delta) dfm = rbind(dfm,df1) } } } print(dfm) plot.title <- paste("Bowler Win Probability(DL) contribution-",t1," vs ",t2) # Plot both lines if(plot ==1){ #ggplot ggplot(data=dfm, aes(x=b, y=100-delta,fill=b)) + geom_bar(stat="identity") + geom_hline(yintercept = 0,color="blue") + ylab("Win probability(DL)") + ggtitle(plot.title) }else { #ggplotly g <- ggplot(data=dfm, aes(x=b, y=100-delta,fill=b)) + geom_bar(stat="identity") + geom_hline(yintercept = 0,color="blue") + ylab("Win probability (DL)") + ggtitle(plot.title) ggplotly(g) } }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/bowlerWinProbDL.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 15 Mar 2023 # Function: bowlerWinProbLR # This function computes the ball by ball win probability using Logistic Regression model # ########################################################################################### #' @title #' Plot the bowler win probability using Logistic Regression model #' #' @description #' This function plots the win probability of the teams in a T20 match #' #' @usage #' bowlerWinProbLR(match,t1,t2,plot=1) #' #' @param match #' The dataframe of the match #' #' @param t1 #' The 1st team of the match #' #' @param t2 #' the 2nd team in the match #' #' @param plot #' Plot=1 (static), Plot=2(interactive) #' #' @return none #' #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' @examples #' \dontrun{ #' #Get the match details #' a <- getMatchDetails("England","Pakistan","2006-09-05",dir="../temp") #' #' # Plot tne match worm plot #' bowlerWinProbLR(a,'England',"Pakistan") #' } #' @seealso #' \code{\link{getBatsmanDetails}}\cr #' \code{\link{getBowlerWicketDetails}}\cr #' \code{\link{batsmanDismissals}}\cr #' \code{\link{getTeamBattingDetails}}\cr #' #' @export #' bowlerWinProbLR <- function(match,t1,t2,plot=1){ team=ball=totalRuns=wicketPlayerOut=ballsRemaining=runs=numWickets=runsMomentum=perfIndex=isWinner=NULL predict=winProbability=ggplotly=runs=runRate=batsman=bowler=NULL if (match$winner[1] == "NA") { print("Match no result ************************") return() } team1Size=0 requiredRuns=0 teams=unique(match$team) teamA=teams[1] # Filter the performance of team1 a <-filter(match,team==teamA) #Balls in team 1's innings ballsIn1stInnings= dim(a)[1] b <- select(a,batsman, bowler,ball,totalRuns,wicketPlayerOut,team1,team2,date) c <-mutate(b,ball=gsub("1st\\.","",ball)) # Compute the total runs scored by team d <- mutate(c,runs=cumsum(totalRuns)) # Check if team1 won or lost the match if(match$winner[1]== teamA){ d$isWinner=1 } else{ d$isWinner=0 } #Get the ball num d$ballNum = seq.int(nrow(d)) # Compute the balls remaining for the team d$ballsRemaining = ballsIn1stInnings - d$ballNum +1 # Wickets lost by team d$wicketNum = d$wicketPlayerOut != "nobody" d=d %>% mutate(numWickets=cumsum(d$wicketNum==TRUE)) #Performance index is based on run rate (runs scored/ ball number) with wickets in hand d$perfIndex = (d$runs/d$ballNum) * (11 - d$numWickets) # Compute run rate d$runRate = (d$runs/d$ballNum) d$runsMomentum = (11 - d$numWickets)/d$ballsRemaining df = select(d, batsman,bowler,ballNum, ballsRemaining, runs, runRate,numWickets,runsMomentum,perfIndex, isWinner) print(dim(df)) ############################################################################################# ######## Team 2 # Compute for Team 2 # Required runs is the team made by team 1 + 1 requiredRuns=d[dim(d)[1],]$runs +1 teamB=teams[2] # Filter the performance of team1 a1 <-filter(match,team==teamB) #Balls in team 1's innings ballsIn2ndInnings= dim(a1)[1] + 1 b1 <- select(a1,batsman,bowler,ball,totalRuns,wicketPlayerOut,team1,team2,date) c1 <-mutate(b1,ball=gsub("2nd\\.","",ball)) # Compute total Runs d1 <- mutate(c1,runs=cumsum(totalRuns)) # Check of team2 is winner if(match$winner[1]== teamB){ d1$isWinner=1 } else{ d1$isWinner=0 } # Compute ball number d1$ballNum= ballsIn1stInnings + seq.int(nrow(d1)) # Compute remaining balls in 2nd innings d1$ballsRemaining= ballsIn2ndInnings - seq.int(nrow(d1)) # Compute wickets remaining d1$wicketNum = d1$wicketPlayerOut != "nobody" d1=d1 %>% mutate(numWickets=cumsum(d1$wicketNum==TRUE)) ballNum=d1$ballNum - ballsIn1stInnings #Performance index is based on run rate (runs scored/ ball number) with wickets in hand d1$perfIndex = (d1$runs/ballNum) * (11 - d1$numWickets) #Compute required runs d1$requiredRuns = requiredRuns - d1$runs d1$runRate = (d1$requiredRuns/d1$ballsRemaining) d1$runsMomentum = (11 - d1$numWickets)/d1$ballsRemaining # Rename required runs as runs df1 = select(d1,batsman,bowler,ballNum,ballsRemaining, requiredRuns,runRate,numWickets,runsMomentum,perfIndex, isWinner) names(df1) =c("batsman","bowler","ballNum","ballsRemaining","runs","runRate","numWickets","runsMomentum","perfIndex","isWinner") print(dim(df1)) df2=rbind(df,df1) # load the model #ml_model <- readRDS("glmLR.rds") a1=select(df,batsman,bowler,ballNum,ballsRemaining, runs,runRate,numWickets,runsMomentum,perfIndex) m=predict(final_lr_model,a1,type = "prob") m1=m$.pred_1*100 m2=matrix(m1) b1=select(df1,batsman,bowler,ballNum,ballsRemaining, runs,runRate,numWickets,runsMomentum,perfIndex) n=predict(final_lr_model,b1,type="prob") n1=n1=n$.pred_1*100 n2=matrix(n1) m3= 100-n2 n3=100-m2 team1=rbind(m2,m3) team2=rbind(n3,n2) team11=as.data.frame(cbind(df2$ballNum,team1)) names(team11) = c("ballNum","winProbability") team22=as.data.frame(cbind(df2$ballNum,team2)) names(team22) = c("ballNum","winProbability") print("***************************************************************") cat("t1=",t1,"teamA= ",teamA," t2=",t2,"teamB= ",teamB,"\n") print("***************************************************************") if(t1 != teamA){ aa = cbind(df,m2) aa2 = aa %>% select(bowler,m2) bowlers=unique(aa2$bowler) columns=c("bowler","delta") dfm = data.frame(matrix(nrow = 0, ncol = length(columns))) for (b in bowlers){ print(b) d <- aa2 %>% filter(bowler == b) print(d) delta =0 if(dim(d)[1] != 1){ delta = d$m2[dim(d)[1]] - d$m2[1] df1 = data.frame(b,delta) dfm = rbind(dfm,df1) } } } else if(t1 != teamB){ aa = cbind(df1,n2) aa2 = aa %>% select(bowler,n2) bowlers=unique(aa2$bowler) columns=c("bowler","delta") dfm = data.frame(matrix(nrow = 0, ncol = length(columns))) for (b in bowlers){ print(b) d <- aa2 %>% filter(bowler == b) print(d) delta =0 if(dim(d)[1] != 1){ delta = d$n2[dim(d)[1]] - d$n2[1] df1 = data.frame(b,delta) dfm = rbind(dfm,df1) } } } print(dfm) plot.title <- paste("Bowler Win Probability (LR) contribution-",t1," vs ",t2) # Plot both lines if(plot ==1){ #ggplot ggplot(data=dfm, aes(x=b, y=100-delta,fill=b)) + geom_bar(stat="identity") + geom_hline(yintercept = 0,color="blue") + ylab("Win probability (LR)") + ggtitle(plot.title) }else { #ggplotly g <- ggplot(data=dfm, aes(x=b, y=100-delta,fill=b)) + geom_bar(stat="identity") + geom_hline(yintercept = 0,color="blue") + ylab("Win probability(LR)") + ggtitle(plot.title) ggplotly(g) } }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/bowlerWinProbLR.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 26 Mar 2016 # Function: bowlerWktsPredict # This function predicts the number of deliveries to wickets for a bowler using #classification trees # ########################################################################################### #' @title #' Predict the deliveries required to wickets #' #' @description #' This function uses a classification tree to compute the number deliveries needed #' versus the wickets taken #' #' @usage #' bowlerWktsPredict(df, name,dateRange) #' #' @param df #' Data frame #' #' @param name #' Name of bowler #' #' @param dateRange #' Date interval to consider #' #' @return None #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' @examples #' \dontrun{ #' # Get the data frame for RA Jadeja #' jadeja1 <- getDeliveryWickets(team="India",name="Jadeja",save=FALSE) #' bowlerWktsPredict(jadeja1,"RA Jadeja",dateRange) #' } #' #' @seealso #' \code{\link{bowlerMovingAverage}}\cr #' \code{\link{bowlerWicketsVenue}}\cr #' \code{\link{bowlerMeanRunsConceded}}\cr #' #' @export #' bowlerWktsPredict <- function(df,name,dateRange){ rpart = NULL df=df %>% filter(date >= dateRange[1] & date <= dateRange[2]) print(names(df)) m <-rpart(wicketNo~delivery,data=df) atitle <- paste(name,"- No of deliveries to Wicket") rpart.plot(m,main=atitle) }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/bowlerWktsPredict.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 2 May 2020 # Function: convertAllYaml2RDataframes # This function converts all yaml files to dataframes and stores as .RData from a given source # directory to target directory. # The target file is the name of the opposing teams and the date of the match # ########################################################################################### #' @title #' Convert and save all Yaml files to dataframes #' #' @description #' This function coverts all Yaml files from source directory to data frames. The data frames #' are then stored as .RData. The saved files are of the format team1-team2-date.RData #' For e.g. England-India-2008-04-06.RData etc #' @usage #' convertAllYaml2RDataframes(sourceDir=".",targetDirMen=".",targetDirWomen=".") #' #' @param sourceDir #' The source directory of the yaml files #' #' @param targetDirMen #' The target directory in which the data frames for men are stored as RData files #' #' @param targetDirWomen #' The target directory in which the data frames for women are stored as RData files #' #' @return None #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' @examples #' \dontrun{ #' # In the example below ../yamldir is the source dir for the yaml files #' convertAllYaml2RDataframes("../yamldir","../data") #' } #' @seealso #' \code{\link{bowlerMovingAverage}}\cr #' \code{\link{bowlerWicketsVenue}}\cr #' \code{\link{convertYaml2RDataframe}}\cr #' #' @export #' convertAllYaml2RDataframes <- function(sourceDir=".",targetDirMen=".",targetDirWomen="."){ yaml.load_file=info.dates=info.match_type=info.overs=info.venue=NULL info.teams=matchType=winner=result=venue=info.gender=ball=team=batsman=gender=NULL bowler=nonStriker=byes=legbyes=noballs=wides=nonBoundary=penalty=runs=extras=totalRuns=NULL wicketFielder=wicketKind=wicketPlayerOut=replacementIn=replacementOut=replacementReason=replacementRole=NULL files <- list.files(sourceDir) print(length(files)) for(iii in 1:length(files)){ overs <- NULL pth = paste(sourceDir,"/",files[iii],sep="") cat("i=",iii," file=",pth,"\n") # Load yaml file a <- yaml.load_file(pth) # This is a temporary change. # Removing elements of Players,Registry and balls per over from yaml file a[[2]][['players']] <- NULL #Players a[[2]][['registry']] <- NULL #Registry a[[2]][['balls_per_over']] <- NULL #balls per over # Cast as data frame for easy processing tryCatch(b <- as.data.frame(a), error = function(e) { print("Error!") eFile <- files[iii] errorFile <- paste(targetDirMen,"/","errors.txt",sep="") write(eFile,errorFile,append=TRUE) } ) sz <- dim(b) # Gather the meta information meta <- select(b,info.dates,info.match_type,info.overs, info.venue, info.teams,info.gender) names(meta) <- c("date","matchType","overs","venue","team1","gender") # Check if there was a winner or if there was no result (tie,draw) if(!is.null(b$info.outcome.winner)){ meta$winner <- b$info.outcome.winner meta$result <- "NA" } else if(!is.null(b$info.result)){ meta$winner <- "NA" meta$result <- b$info.result } else if(!is.null(b$info.outcome.result)){ meta$winner <- "NA" meta$result <- b$info.outcome.result } meta$team2 = meta[2,5] meta <- meta[1,] #Reorder columns meta <- select(meta,date,matchType,overs,venue,team1,team2,winner,result,gender) # Remove the innings and deliveries from the column names names(b) <-gsub("innings.","",names(b)) names(b) <- gsub("deliveries.","",names(b)) # Fix for changed order of columns-28 Apr 2020 idx = which(names(b) == "1st.team") # Search for column name 1st.team # Select the column after that which includes ball-by-ball detail idx=idx+1 m <- b[1,idx:sz[2]] #Transpose to the details of the match match <- t(m) rnames <- rownames(match) match <- as.data.frame(cbind(rnames,match)) # Gather details for first team # Set the number of overs to 50 for ODI matches numOver <- seq(from=0,to=50,by=1) # Create string of delivery in each over upto delivery 16 in case of no balls, # wides etc. # Note: The over can be more than .6 when you have no balls, wides etc d <- c(".1",".2",".3",".4",".5",".6",".7",".8",".9",".1",".1", ".1",".1",".1",".1") m <- 1 # Create a vector of deliveries from 0 to 50 by concatenating string delivery <- NULL for(k in 1:length(numOver)){ for(l in 1:length(d)){ delivery[m] <- paste(numOver[k],d[l],sep="") m=m+1 } } #Create string for 1st team print("first loop") s <- paste("1st.",delivery,"\\.",sep="") team1 <- b$`1st.team`[1] # Parse the yaml file over by over and store as a row of data overs1 <- parseYamlOver(match,s,team1,delivery,meta) # Create string for 2nd team print("second loop") s1 <- paste("2nd.",delivery,"\\.",sep="") team2 <- b$`2nd.team`[1] overs2 <- parseYamlOver(match,s1,team2,delivery,meta) # Row bind the 1dst overs <- rbind(overs1,overs2) colList=list("batsman"="batsman","bowler"="bowler","non_striker"="nonStriker","runs.batsman" ="runs", "runs.extras" ="extras","runs.total"="totalRuns","byes"="byes","legbyes"="legbyes","noballs"="noballs", "wides"="wides","nonBoundary"="nonBoundary","penalty" ="penalty","wicket.fielders"="wicketFielder", "wicket.kind"="wicketKind","wicket.player_out" ="wicketPlayerOut", "replacements.role.in"="replacementIn","replacements.role.out"="replacementOut", "replacements.role.reason"="replacementReason","replacements.role.role"="replacementRole", "ball"="ball","team"="team","date"="date","matchType"="matchType","overs" ="overs", "venue"="venue","team1" ="team1","team2" ="team2", "winner"="winner","result"="result", "gender"="gender") # Get the column names for overs cols <- names(overs) newcols <- NULL for(i in 1: length(cols)){ newcols <- c(newcols, colList[[cols[i]]]) } # Rename the columns names(overs) <- newcols overs <- select(overs, ball,team,batsman,bowler,nonStriker, byes,legbyes,noballs, wides,nonBoundary,penalty, runs, extras,totalRuns,wicketFielder, wicketKind,wicketPlayerOut, replacementIn, replacementOut, replacementReason, replacementRole,date,matchType,overs,venue,team1,team2,winner,result,gender) # Change factors to appropiate type overs$byes <- as.numeric(as.character(overs$byes)) overs$legbyes <- as.numeric(as.character(overs$legbyes)) overs$wides <- as.numeric(as.character(overs$wides)) overs$noballs <- as.numeric(as.character(overs$noballs)) overs$nonBoundary <- as.numeric(as.character(overs$nonBoundary)) overs$penalty <- as.numeric(as.character(overs$penalty)) overs$runs <- as.numeric(as.character(overs$runs)) overs$extras <- as.numeric(as.character(overs$extras)) overs$totalRuns <- as.numeric(as.character(overs$totalRuns)) overs$date = as.Date(overs$date) overs$overs <- as.numeric(as.character(overs$overs)) # Add missing elements overs[overs$wicketFielder == 0,]$wicketFielder="nobody" overs[overs$wicketKind == 0,]$wicketKind="not-out" overs[overs$wicketPlayerOut==0,]$wicketPlayerOut ="nobody" sapply(overs,class) teams <- as.character(unique(overs$team)) print(dim(overs)) #Create a unique file which is based on the opposing teams and the date of the match filename <- paste(meta$team1,"-",meta$team2,"-",meta$date,".", "RData",sep="") # Write men and women in separate folders gender=overs$gender if(gender[1] =="male"){ to <- paste(targetDirMen,"/",filename,sep="") } else{ to <- paste(targetDirWomen,"/",filename,sep="") } # Save as .RData save(overs,file=to) # Write the name of the file that was converted and the converted file for reference convertedFile <- paste(files[iii],filename,sep=":") if(gender[1] == "male") outputFile <- paste(targetDirMen,"/","convertedFiles.txt",sep="") else outputFile <- paste(targetDirWomen,"/","convertedFiles.txt",sep="") write(convertedFile,outputFile,append=TRUE) } }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/convertAllYaml2RDataframes.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 20 Mar 2016 # Function: convertAllYaml2RDataframesT20 # This function converts all yaml files to dataframes and stores as .RData from a given source # directory to target directory. # The target file is the name of the opposing teams and the date of the match # ########################################################################################### #' @title #' Convert and save all T20 Yaml files to dataframes #' #' @description #' This function coverts all T20 Yaml files from source directory to data frames. The data frames #' are then stored as .RData. The saved files are of the format team1-team2-date.RData #' For e.g. England-India-2008-04-06.RData etc #' @usage #' convertAllYaml2RDataframesT20(sourceDir=".",targetDirMen=".",targetDirWomen=".") #' #' @param sourceDir #' The source directory of the yaml files #' #' @param targetDirMen #' The target directory in which the data frames of men are stored as RData files #' #' @param targetDirWomen #' The target directory in which the data frames of women are stored as RData files #' #' @return None #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' @examples #' \dontrun{ #' # In the example below ../yamldir is the source dir for the yaml files #' convertAllYaml2RDataframesT20("../yamldir","../data") #' } #' @seealso #' \code{\link{bowlerMovingAverage}}\cr #' \code{\link{bowlerWicketsVenue}}\cr #' \code{\link{convertYaml2RDataframeT20}}\cr #' #' @export #' convertAllYaml2RDataframesT20 <- function(sourceDir=".",targetDirMen=".",targetDirWomen="."){ yaml.load_file=info.dates=info.match_type=info.overs=info.venue=NULL info.teams=matchType=winner=result=venue=info.gender=ball=team=batsman=NULL bowler=nonStriker=byes=legbyes=noballs=wides=nonBoundary=penalty=runs=extras=totalRuns=NULL wicketFielder=wicketKind=wicketPlayerOut=replacementIn=replacementOut=replacementReason=replacementTeam=NULL files <- list.files(sourceDir) print(length(files)) for(iii in 1:length(files)){ overs <- NULL pth = paste(sourceDir,"/",files[iii],sep="") cat("i=",iii," file=",pth,"\n") # Load yaml file a <- yaml.load_file(pth) # This is a temporary change. # Removing elements of Players,Registry and balls per over from yaml file a[[2]][['players']] <- NULL #Players a[[2]][['registry']] <- NULL #Registry a[[2]][['balls_per_over']] <- NULL #balls per over # Cast as data frame for easy processing tryCatch(b <- as.data.frame(a), error = function(e) { print("Error!") eFile <- files[iii] errorFile <- paste(targetDirMen,"/","errors.txt",sep="") write(eFile,errorFile,append=TRUE) } ) sz <- dim(b) # Gather the meta information meta <- select(b,info.dates,info.match_type,info.overs, info.venue, info.teams,info.gender) names(meta) <- c("date","matchType","overs","venue","team1","gender") # Check if there was a winner or if there was no result (tie,draw) if(!is.null(b$info.outcome.winner)){ meta$winner <- b$info.outcome.winner meta$result <- "NA" } else if(!is.null(b$info.result)){ meta$winner <- "NA" meta$result <- b$info.result } else if(!is.null(b$info.outcome.result)){ meta$winner <- "NA" meta$result <- b$info.outcome.result } meta$team2 = meta[2,5] meta <- meta[1,] #Reorder columns meta <- select(meta,date,matchType,overs,venue,team1,team2,winner,result,gender) # Remove the innings and deliveries from the column names names(b) <-gsub("innings.","",names(b)) names(b) <- gsub("deliveries.","",names(b)) # Fix for changed order of columns-28 Apr 2020 idx = which(names(b) == "1st.team") # Search for column name 1st.team # Select the column after that which includes ball-by-ball detail idx=idx+1 m <- b[1,idx:sz[2]] #Transpose to the details of the match match <- t(m) rnames <- rownames(match) match <- as.data.frame(cbind(rnames,match)) # Gather details for first team # Set the number of overs to 50 for ODI matches numOver <- seq(from=0,to=20,by=1) # Create string of delivery in each over upto delivery 16 in case of no balls, # wides etc. # Note: The over can be more than .6 when you have no balls, wides etc d <- c(".1",".2",".3",".4",".5",".6",".7",".8",".9",".1",".1", ".1",".1",".1",".1") m <- 1 # Create a vector of deliveries from 0 to 50 by concatenating string delivery <- NULL for(k in 1:length(numOver)){ for(l in 1:length(d)){ delivery[m] <- paste(numOver[k],d[l],sep="") m=m+1 } } #Create string for 1st team print("first loop") s <- paste("1st.",delivery,"\\.",sep="") team1 <- b$`1st.team`[1] # Parse the yaml file over by over and store as a row of data overs1 <- parseYamlOver(match,s,team1,delivery,meta) # Create string for 2nd team print("second loop") s1 <- paste("2nd.",delivery,"\\.",sep="") team2 <- b$`2nd.team`[1] overs2 <- parseYamlOver(match,s1,team2,delivery,meta) # Row bind the 1dst overs <- rbind(overs1,overs2) colList=list("batsman"="batsman","bowler"="bowler","non_striker"="nonStriker","runs.batsman" ="runs", "runs.extras" ="extras","runs.total"="totalRuns","byes"="byes","legbyes"="legbyes","noballs"="noballs", "wides"="wides","runs.non_boundary"="nonBoundary","penalty" ="penalty","wicket.fielders"="wicketFielder", "wicket.kind"="wicketKind","wicket.player_out" ="wicketPlayerOut", "replacements.match.in"="replacementIn","replacements.match.out"="replacementOut", "replacements.match.reason"="replacementReason","replacements.match.team"="replacementTeam", "ball"="ball","team"="team","date"="date","matchType"="matchType","overs" ="overs", "venue"="venue","team1" ="team1","team2" ="team2", "winner"="winner","result"="result", "gender"="gender") # Get the column names for overs cols <- names(overs) newcols <- NULL for(i in 1: length(cols)){ newcols <- c(newcols, colList[[cols[i]]]) } # Rename the columns names(overs) <- newcols overs <- select(overs, ball,team,batsman,bowler,nonStriker, byes,legbyes,noballs, wides,nonBoundary,penalty, runs, extras,totalRuns,wicketFielder, wicketKind,wicketPlayerOut, replacementIn, replacementOut, replacementReason, replacementTeam,date,matchType,overs,venue,team1,team2,winner,result,gender) # Change factors to appropiate type overs$byes <- as.numeric(as.character(overs$byes)) overs$legbyes <- as.numeric(as.character(overs$legbyes)) overs$wides <- as.numeric(as.character(overs$wides)) overs$noballs <- as.numeric(as.character(overs$noballs)) overs$nonBoundary <- as.numeric(as.character(overs$nonBoundary)) overs$penalty <- as.numeric(as.character(overs$penalty)) overs$runs <- as.numeric(as.character(overs$runs)) overs$extras <- as.numeric(as.character(overs$extras)) overs$totalRuns <- as.numeric(as.character(overs$totalRuns)) overs$date = as.Date(overs$date) overs$overs <- as.numeric(as.character(overs$overs)) # Add missing elements overs[overs$wicketFielder == 0,]$wicketFielder="nobody" overs[overs$wicketKind == 0,]$wicketKind="not-out" overs[overs$wicketPlayerOut==0,]$wicketPlayerOut ="nobody" sapply(overs,class) teams <- as.character(unique(overs$team)) #Create a unique file which is based on the opposing teams and the date of the match filename <- paste(meta$team1,"-",meta$team2,"-",meta$date,".", "RData",sep="") # Write men and women in separate folders gender=overs$gender if(gender[1] =="male"){ to <- paste(targetDirMen,"/",filename,sep="") } else{ to <- paste(targetDirWomen,"/",filename,sep="") } # Save as .RData save(overs,file=to) # Write the name of the file that was converted and the converted file for reference convertedFile <- paste(files[iii],filename,sep=":") if(gender[1] == "male") outputFile <- paste(targetDirMen,"/","convertedFiles.txt",sep="") else outputFile <- paste(targetDirWomen,"/","convertedFiles.txt",sep="") write(convertedFile,outputFile,append=TRUE) } }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/convertAllYaml2RDataframesT20.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 2 May 2020 # Function: convertYaml2RDataframe # This function converts a given yaml file to a data frame and stores this as n .RData # The yaml file is read from a given source directory coverted and saved to a target directory. # The target file is the created by using the name of the opposing teams and the date of the match # ########################################################################################### #' @title #' Converts and save yaml files to dataframes #' #' @description #' This function coverts all Yaml files from source directory to data frames. The data frames #' are then stored as .RData. The saved file is of the format team1-team2-date.RData #' For e.g. England-India-2008-04-06.RData etc #' @usage #' convertYaml2RDataframe(yamlFile,sourceDir=".",targetDir=".") #' #' @param yamlFile #' The yaml file to be converted to dataframe and saved #' #' @param sourceDir #' The source directory of the yaml file #' #' @param targetDir #' The target directory in which the data frame is stored as RData file #' #' @return None #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' @examples #' \dontrun{ #' # In the example below ../yamldir c #' convertYaml2RDataframe("225171.yaml",".","../data") #' } #' #' @seealso #' \code{\link{bowlerMovingAverage}}\cr #' \code{\link{bowlerWicketsVenue}}\cr #' \code{\link{convertAllYaml2RDataframes}}\cr #' #' @export #' convertYaml2RDataframe <- function(yamlFile,sourceDir=".",targetDir="."){ yaml.load_file=info.dates=info.match_type=info.overs=info.venue=NULL info.teams=matchType=winner=result=venue=info.gender=ball=team=batsman=gender=NULL bowler=nonStriker=byes=legbyes=noballs=wides=nonBoundary=penalty=runs=extras=totalRuns=NULL wicketFielder=wicketKind=wicketPlayerOut=replacementIn=replacementOut=replacementReason=replacementRole=NULL pth = paste(sourceDir,"/",yamlFile,sep="") print(pth) # Load yaml file a <- yaml.load_file(pth) # This is a temporary change. # Removing elements of Players,Registry and balls per over from yaml file a[[2]][['players']] <- NULL #Players a[[2]][['registry']] <- NULL #Registry a[[2]][['balls_per_over']] <- NULL #balls per over # Cast as data frame for easy processing tryCatch(b <- as.data.frame(a), error = function(e) { print("Error!") eFile <- yamlFile errorFile <- paste(targetDir,"/","errors.txt",sep="") write(errorFile,eFile,append=TRUE) } ) sz <- dim(b) # Gather the meta information meta <- select(b,info.dates,info.match_type,info.overs, info.venue, info.teams,info.gender) names(meta) <- c("date","matchType","overs","venue","team1","result","gender") # Check if there was a winner or if there was no result (tie,draw) if(!is.null(b$info.outcome.winner)){ meta$winner <- b$info.outcome.winner meta$result <- "NA" } else if(!is.null(b$info.result)){ meta$winner <- "NA" meta$result <- b$info.result } else if(!is.null(b$info.outcome.result)){ meta$winner <- "NA" meta$result <- b$info.outcome.result } meta$team2 = meta[2,5] meta <- meta[1,] #Reorder columns meta <- select(meta,date,matchType,overs,venue,team1,team2,winner,result,gender) # Remove the innings and deliveries from the column names names(b) <-gsub("innings.","",names(b)) names(b) <- gsub("deliveries.","",names(b)) # Fix for changed order of columns-28 Apr 2020 idx = which(names(b) == "1st.team") # Search for column name 1st.team # Select the column after that which includes ball-by-ball detail idx=idx+1 m <- b[1,idx:sz[2]] #Transpose to the details of the match match <- t(m) rnames <- rownames(match) match <- as.data.frame(cbind(rnames,match)) # Gather details for first team # Set the number of overs to 50 for ODI matches numOver <- seq(from=0,to=50,by=1) # Create string of delivery in each over upto delivery 16 in case of no balls, # wides etc. # Note: The over can be more than .6 when you have no balls, wides etc d <- c(".1",".2",".3",".4",".5",".6",".7",".8",".9",".1",".1", ".1",".1",".1",".1") m <- 1 # Create a vector of deliveries from 0 to 50 by concatenating string delivery <- NULL for(k in 1:length(numOver)){ for(l in 1:length(d)){ delivery[m] <- paste(numOver[k],d[l],sep="") m=m+1 } } #Create string for 1st team print("first loop") s <- paste("1st.",delivery,"\\.",sep="") team1 <- b$`1st.team`[1] # Parse the yaml file over by over and store as a row of data overs1 <- parseYamlOver(match,s,team1,delivery,meta) # Create string for 2nd team print("second loop") s1 <- paste("2nd.",delivery,"\\.",sep="") team2 <- b$`2nd.team`[1] overs2 <- parseYamlOver(match,s1,team2,delivery,meta) # Row bind the 1dst overs <- rbind(overs1,overs2) # Fix for changed order of columns-28 Apr 2020 colList=list("batsman"="batsman","bowler"="bowler","non_striker"="nonStriker","runs.batsman" ="runs", "runs.extras" ="extras","runs.total"="totalRuns","byes"="byes","legbyes"="legbyes","noballs"="noballs", "wides"="wides","nonBoundary"="nonBoundary","penalty" ="penalty","wicket.fielders"="wicketFielder", "wicket.kind"="wicketKind","wicket.player_out" ="wicketPlayerOut", "replacements.role.in"="replacementIn","replacements.role.out"="replacementOut", "replacements.role.reason"="replacementReason","replacements.role.role"="replacementRole", "ball"="ball","team"="team","date"="date","matchType"="matchType","overs" ="overs", "venue"="venue","team1" ="team1","team2" ="team2", "winner"="winner","result"="result", "gender"="gender") # Get the column names for overs cols <- names(overs) newcols <- NULL for(i in 1: length(cols)){ newcols <- c(newcols, colList[[cols[i]]]) } # Rename the columns names(overs) <- newcols overs <- select(overs, ball,team,batsman,bowler,nonStriker, byes,legbyes,noballs, wides,nonBoundary,penalty, runs, extras,totalRuns,wicketFielder, wicketKind,wicketPlayerOut, replacementIn, replacementOut, replacementReason, replacementRole,date,matchType,overs,venue,team1,team2,winner,result,gender) # Change factors to appropiate type overs$byes <- as.numeric(as.character(overs$byes)) overs$legbyes <- as.numeric(as.character(overs$legbyes)) overs$wides <- as.numeric(as.character(overs$wides)) overs$noballs <- as.numeric(as.character(overs$noballs)) overs$nonBoundary <- as.numeric(as.character(overs$nonBoundary)) overs$penalty <- as.numeric(as.character(overs$penalty)) overs$runs <- as.numeric(as.character(overs$runs)) overs$extras <- as.numeric(as.character(overs$extras)) overs$totalRuns <- as.numeric(as.character(overs$totalRuns)) overs$date = as.Date(overs$date) overs$overs <- as.numeric(as.character(overs$overs)) # Add missing elements overs[overs$wicketFielder == 0,]$wicketFielder="nobody" overs[overs$wicketKind == 0,]$wicketKind="not-out" overs[overs$wicketPlayerOut==0,]$wicketPlayerOut ="nobody" sapply(overs,class) teams <- as.character(unique(overs$team)) #Create a unique file which is based on the opposing teams and the date of the match filename <- paste(meta$team1,"-",meta$team2,"-",meta$date,".", "RData",sep="") to <- paste(targetDir,"/",filename,sep="") # Save as .RData save(overs,file=to) # Write the name of the file that was converted and the converted file for reference convertedFile <- paste(yamlFile,filename,sep=":") outputFile <- paste(targetDir,"/","convertedFiles.txt",sep="") write(convertedFile,outputFile,append=TRUE) }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/convertYaml2RDataframe.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 2 May 2020 # Function: convertYaml2RDataframeT20 # This function converts a given T20 yaml file to a data frame and stores this as n .RData # The yaml file is read from a given source directory coverted and saved to a target directory. # The target file is the created by using the name of the opposing teams and the date of the match # ########################################################################################### #' @title #' Converts and save T20 yaml files to dataframes #' #' @description #' This function coverts all T20 Yaml files from source directory to data frames. The data frames #' are then stored as .RData. The saved file is of the format team1-team2-date.RData #' For e.g. England-India-2008-04-06.RData etc #' @usage #' convertYaml2RDataframeT20(yamlFile,sourceDir=".",targetDir=".") #' #' @param yamlFile #' The yaml file to be converted to dataframe and saved #' #' @param sourceDir #' The source directory of the yaml file #' #' @param targetDir #' The target directory in which the data frame is stored as RData file #' #' @return None #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' @examples #' \dontrun{ #' # In the example below ../yamldir c #' convertYaml2RDataframe("225171.yaml",".","../data") #' } #' #' @seealso #' \code{\link{bowlerMovingAverage}}\cr #' \code{\link{bowlerWicketsVenue}}\cr #' \code{\link{convertAllYaml2RDataframesT20}}\cr #' #' @export #' convertYaml2RDataframeT20 <- function(yamlFile,sourceDir=".",targetDir="."){ yaml.load_file=info.dates=info.match_type=info.overs=info.venue=NULL info.teams=matchType=winner=result=venue=gender=ball=team=batsman=NULL bowler=nonStriker=byes=legbyes=noballs=wides=nonBoundary=penalty=runs=extras=totalRuns=NULL wicketFielder=wicketKind=wicketPlayerOut=replacementIn=replacementOut=replacementReason=replacementTeam=NULL pth = paste(sourceDir,"/",yamlFile,sep="") print(pth) # Load yaml file a <- yaml.load_file(pth) # This is a temporary change. # Removing elements of Players,Registry and balls per over from yaml file a[[2]][['players']] <- NULL #Players a[[2]][['registry']] <- NULL #Registry a[[2]][['balls_per_over']] <- NULL #balls per over # Cast as data frame for easy processing tryCatch(b <- as.data.frame(a), error = function(e) { print("Error!") eFile <- yamlFile errorFile <- paste(targetDir,"/","errors.txt",sep="") write(errorFile,eFile,append=TRUE) } ) sz <- dim(b) # Gather the meta information meta <- select(b,info.dates,info.match_type,info.overs, info.venue, info.teams) names(meta) <- c("date","matchType","overs","venue","team1") # Check if there was a winner or if there was no result (tie,draw) if(!is.null(b$info.outcome.winner)){ meta$winner <- b$info.outcome.winner meta$result <- "NA" } else if(!is.null(b$info.result)){ meta$winner <- "NA" meta$result <- b$info.result } else if(!is.null(b$info.outcome.result)){ meta$winner <- "NA" meta$result <- b$info.outcome.result } meta$team2 = meta[2,5] meta <- meta[1,] #Reorder columns meta <- select(meta,date,matchType,overs,venue,team1,team2,winner,result) # Remove the innings and deliveries from the column names names(b) <-gsub("innings.","",names(b)) names(b) <- gsub("deliveries.","",names(b)) # Fix for changed order of columns-28 Apr 2020 idx = which(names(b) == "1st.team") # Search for column name 1st.team # Select the column after that which includes ball-by-ball detail idx=idx+1 m <- b[1,idx:sz[2]] #Transpose to the details of the match match <- t(m) rnames <- rownames(match) match <- as.data.frame(cbind(rnames,match)) # Gather details for first team # Set the number of overs to 50 for ODI matches numOver <- seq(from=0,to=20,by=1) # Create string of delivery in each over upto delivery 16 in case of no balls, # wides etc. # Note: The over can be more than .6 when you have no balls, wides etc d <- c(".1",".2",".3",".4",".5",".6",".7",".8",".9",".1",".1", ".1",".1",".1",".1") m <- 1 # Create a vector of deliveries from 0 to 50 by concatenating string delivery <- NULL for(k in 1:length(numOver)){ for(l in 1:length(d)){ delivery[m] <- paste(numOver[k],d[l],sep="") m=m+1 } } #Create string for 1st team print("first loop") s <- paste("1st.",delivery,"\\.",sep="") team1 <- b$`1st.team`[1] # Parse the yaml file over by over and store as a row of data overs1 <- parseYamlOver(match,s,team1,delivery,meta) # Create string for 2nd team print("second loop") s1 <- paste("2nd.",delivery,"\\.",sep="") team2 <- b$`2nd.team`[1] overs2 <- parseYamlOver(match,s1,team2,delivery,meta) # Row bind the 1dst overs <- rbind(overs1,overs2) # Fix for changed order of columns-28 Apr 2020 colList=list("batsman"="batsman","bowler"="bowler","non_striker"="nonStriker","runs.batsman" ="runs", "runs.extras" ="extras","runs.total"="totalRuns","byes"="byes","legbyes"="legbyes","noballs"="noballs", "wides"="wides","runs.non_boundary"="nonBoundary","penalty" ="penalty","wicket.fielders"="wicketFielder", "wicket.kind"="wicketKind","wicket.player_out" ="wicketPlayerOut", "replacements.match.in"="replacementIn","replacements.match.out"="replacementOut", "replacements.match.reason"="replacementReason","replacements.match.team"="replacementTeam", "ball"="ball","team"="team","date"="date","matchType"="matchType","overs" ="overs", "venue"="venue","team1" ="team1","team2" ="team2", "winner"="winner","result"="result", "gender"="gender") # Get the column names for overs cols <- names(overs) newcols <- NULL for(i in 1: length(cols)){ newcols <- c(newcols, colList[[cols[i]]]) } # Rename the columns names(overs) <- newcols overs <- select(overs, ball,team,batsman,bowler,nonStriker, byes,legbyes,noballs, wides,nonBoundary,penalty, runs, extras,totalRuns,wicketFielder, wicketKind,wicketPlayerOut, replacementIn, replacementOut, replacementReason, replacementTeam,date,matchType,overs,venue,team1,team2,winner,result,gender) # Change factors to appropiate type overs$byes <- as.numeric(as.character(overs$byes)) overs$legbyes <- as.numeric(as.character(overs$legbyes)) overs$wides <- as.numeric(as.character(overs$wides)) overs$noballs <- as.numeric(as.character(overs$noballs)) overs$nonBoundary <- as.numeric(as.character(overs$nonBoundary)) overs$penalty <- as.numeric(as.character(overs$penalty)) overs$runs <- as.numeric(as.character(overs$runs)) overs$extras <- as.numeric(as.character(overs$extras)) overs$totalRuns <- as.numeric(as.character(overs$totalRuns)) overs$date = as.Date(overs$date) overs$overs <- as.numeric(as.character(overs$overs)) # Add missing elements overs[overs$wicketFielder == 0,]$wicketFielder="nobody" overs[overs$wicketKind == 0,]$wicketKind="not-out" overs[overs$wicketPlayerOut==0,]$wicketPlayerOut ="nobody" sapply(overs,class) teams <- as.character(unique(overs$team)) #Create a unique file which is based on the opposing teams and the date of the match filename <- paste(meta$team1,"-",meta$team2,"-",meta$date,".", "RData",sep="") to <- paste(targetDir,"/",filename,sep="") # Save as .RData save(overs,file=to) # Write the name of the file that was converted and the converted file for reference convertedFile <- paste(yamlFile,filename,sep=":") outputFile <- paste(targetDir,"/","convertedFiles.txt",sep="") write(convertedFile,outputFile,append=TRUE) }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/convertYaml2RDataframeT20.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 2 May 2020 # Function: getAllMatchesAllOpposition # This function gets the data for all matches against all opposition for a given team. # The user can choose to save the file for later use # # ########################################################################################### #' @title #' Get data on all matches against all opposition #' #' @description #' This function gets all the matches for a particular team for e.g India, Pakistan, #' Australia etc against all other oppositions. It constructs a huge dataframe of all these #' matches. This can be saved by the user which can be used in function in which analyses are #' done for all matches and for all oppositions. This is done by loading the saved .RData for #' each match and performing an rbind of the data frames for each match #' #' @usage #' getAllMatchesAllOpposition(team,dir=".",save=FALSE,odir=".") #' #' @param team #' The team for which all matches and all opposition has to be obtained e.g. India, Pakistan #' #' @param dir #' The input directory #' #' @param odir #' The output directory #' #'@param save #' Default=FALSE. This parameter indicates whether the combined data frame needs to be saved or not. It is recommended #' to save this large dataframe as the creation of this data frame takes a several seconds depending #' on the number of matches #' #' @return match #' The combined data frame #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' @examples #' \dontrun{ #' # Get all matches for team India #' getAllMatchesAllOpposition("India",dir="../data/",save=TRUE) #' getAllMatchesAllOpposition("Australia",dir="./mysavedata/",save=TRUE) #' } #' #' @seealso #' \code{\link{bowlerMovingAverage}}\cr #' \code{\link{bowlerWicketsVenue}}\cr #' \code{\link{bowlerMeanRunsConceded}}\cr #' #' @export #' getAllMatchesAllOpposition <- function(team,dir=".",save=FALSE,odir="."){ overs=NULL # Gather team data against all ooposition d1 <- paste("*",team,"*",sep="") path=paste(dir,"/",d1,sep="") fl <- Sys.glob(path) if(length(fl) !=0){ matches <- NULL for(i in 1:length(fl)){ # Add try-catch to handle issues tryCatch({ load(fl[i]) matches <- rbind(matches,overs) }, error=function(e){cat("ERROR :",conditionMessage(e), "\n")}) } b <- paste(odir,"/","allMatchesAllOpposition-",team,".RData",sep="") if(save){ save(matches,file=b) } matches } }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/getAllMatchesAllOpposition.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 2 May 2020 # Function: getAllMatchesBetweenTeams # This function gets all the data for matches palyed between teams and creates a large data # frame. This data frame can be saved for suture use # and the date the match was played # ########################################################################################### #' @title #' Get data on all matches between 2 opposing teams #' #' @description #' This function gets all the data on matches between opposing teams for e.g India-Pakistan, #' Englad-Australia, South Africa- Sri Lanka etc. It constructs a huge dataframe of all these #' matches. This can be saved by the user which can be used in function in which analyses are #' done for all matches between these teams. This is done by loading the saved .RData for #' each match and performing an rbind of the data frames for each match #' #' @usage #' getAllMatchesBetweenTeams(team1,team2,dir=".",save=FALSE,odir = ".") #' #' @param team1 #' One of the team in consideration e.g (India, Australia, England) #' #' @param team2 #' The other team for which matches are needed e.g( India, Sri Lanka, Pakistan) #' #' @param dir #' The input directory which has the RData files of matches between teams #' #' @param odir #' The output directory #' #' @param save #' Default=FALSE. This parameter indicates whether the combined data frame needs to be saved or not. It is recommended #' to save this large dataframe as the creation of this data frame takes a several seconds depending #' on the number of matches #' #' @return matches #' The combined data frame #' #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' @examples #' \dontrun{ #' # Get all matches for team India #' getAllMatchesAllOpposition("India",dir="../data/",save=TRUE) #' getAllMatchesAllOpposition("Australia",dir="./mysavedata/",save=TRUE) #' } #' #' @seealso #' \code{\link{bowlerMovingAverage}}\cr #' \code{\link{bowlerWicketsVenue}}\cr #' \code{\link{getAllMatchesAllOpposition}}\cr #' #' @export #' getAllMatchesBetweenTeams <- function(team1,team2,dir=".",save=FALSE,odir="."){ overs=NULL # Create 2 filenames with both combinations of team1 and team2 d1 <- paste(team1,"-",team2,"*",sep="") d2 <- paste(team2,"-",team1,"*",sep="") path1=paste(dir,"/",d1,sep="") path2=paste(dir,"/",d2,sep="") # Capture both combinations fl1 <- Sys.glob(path1) fl2 <- Sys.glob(path2) fl3 <-c(fl1,fl2) if(length(fl3) != 0){ # Create a data frame with all matches matches <- NULL for(i in 1:length(fl3)){ # Add try-catch to handle issues tryCatch({ load(fl3[i]) matches <- rbind(matches,overs) }, error=function(e){cat("ERROR :",conditionMessage(e), "\n")}) } b <- paste(odir,"/",team1,"-",team2,"-allMatches.RData",sep="") if(save){ save(matches,file=b) } matches } }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/getAllMatchesBetweenTeams.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 5 Jan 2021 # Function: getBBLBattingDetails # This function creates BBL batting details # ########################################################################################### #' @title #' Gets the BBL batting details #' #' @description #' This function creates a single datframe of all BBL batsmen #' @usage #' getBBLBattingDetails(dir='.',odir=".") #' #' @param dir #' The input directory #' #' @param odir #' The output directory #' #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' #' @seealso #' \code{\link{getIPLBattingDetails}}\cr #' \code{\link{getIPLBowlingDetails}}\cr #' \code{\link{getNTBBattingDetails}}\cr #' \code{\link{getNTBBowlingDetails}}\cr #' @export #' getBBLBattingDetails <- function(dir='.',odir=".") { currDir= getwd() teams <-c("Adelaide Strikers", "Brisbane Heat", "Hobart Hurricanes", "Melbourne Renegades", "Melbourne Stars", "Perth Scorchers", "Sydney Sixers", "Sydney Thunder") battingDetails=batsman=runs=strikeRate=matches=meanRuns=meanSR=battingDF=val=NULL details=df=NULL teams1 <- NULL for(team in teams){ print(team) tryCatch({ batting <- getTeamBattingDetails(team,dir=dir, save=TRUE,odir=odir) teams1 <- c(teams1,team) }, error = function(e) { print("No data") } ) } }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/getBBLBattingDetails.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 5 Jan 2021 # Function: getBBLBowlingDetails # This function creates BBL bowling details # ########################################################################################### #' @title #' Gets the BBL bowling details #' #' @description #' This function creates a single datframe of all BBL bowling #' @usage #' getBBLBowlingDetails(dir='.',odir=".") #' #' @param dir #' The input directory #' #' @param odir #' The output directory #' #' #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' #' @seealso #' \code{\link{getIPLBattingDetails}}\cr #' \code{\link{getIPLBowlingDetails}}\cr #' \code{\link{getNTBBattingDetails}}\cr #' \code{\link{getNTBBattingDetails}}\cr #' @export #' getBBLBowlingDetails <- function(dir='.',odir=".") { bowlingDetails=bowler=wickets=economyRate=matches=meanWickets=meanER=totalWickets=NULL currDir= getwd() teams <-c("Adelaide Strikers", "Brisbane Heat", "Hobart Hurricanes", "Melbourne Renegades", "Melbourne Stars", "Perth Scorchers", "Sydney Sixers", "Sydney Thunder") # Get all bowling details details=df=NULL teams1 <- NULL for(team in teams){ print(team) tryCatch({ bowling <- getTeamBowlingDetails(team,dir=dir, save=TRUE,odir=odir) teams1 <- c(teams1,team) }, error = function(e) { print("No data") } ) } }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/getBBLBowlingDetails.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 25 Mar 2016 # Function: getBatsmanDetails # This function gets the batting details of a batsman # ########################################################################################### #' @title #' Get batting details of batsman from match #' #' @description #' This function gets the batting details of a batsman given the match data as a RData file #' @usage #' getBatsmanDetails(team,name,dir=".") #' #' @param team #' The team of the batsman e.g. India #' #' @param name #' Name of batsman #' #' @param dir #' The directory where the source file exists #' #' @return None #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' #' @examples #' \dontrun{ #' getBatsmanDetails(team="India",name="Kohli",dir=pathToFile) #' } #' #' #' @seealso #' \code{\link{batsmanRunsPredict}}\cr #' \code{\link{batsmanMovingAverage}}\cr #' \code{\link{bowlerWicketsVenue}}\cr #' \code{\link{bowlerMeanRunsConceded}}\cr #' #' @export #' #' getBatsmanDetails <- function(team, name,dir="."){ batsman=battingDetails=NULL fl <- paste(dir,"/",team,"-BattingDetails.RData",sep="") print(fl) load(fl) details <- battingDetails batsmanDetails <- filter(details,grepl(name,batsman)) batsmanDetails }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/getBatsmanDetails.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 25 Mar 2016 # Function: getBowlerWicketDetails # This function gets the bowling details of a bowler # ########################################################################################### #' @title #' Get the bowling details of a bowler #' #' @description #' This function gets the bowling of a bowler (overs,maidens,runs,wickets,venue, opposition) #' #' @usage #' getBowlerWicketDetails(team,name,dir=".") #' #' @param team #' The team to which the bowler belongs #' #' @param name #' The name of the bowler #' #' @param dir #' The source directory of the data #' #' @return dataframe #' The dataframe of bowling performance #' #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' #' @examples #' \dontrun{ #' # Get the bowling details of bowlers of a team e.g. India. This is saved as a dataframe #' c <- getTeamBowlingDetails("India",dir="../data",save=TRUE) #' #Get the bowler details from this overall data frame #' #' jadeja <- getBowlerWicketDetails(team="India",name="Jadeja",dir=".") #' #' # The dataframe from the above call is used in many functions #' #bowlerMeanEconomyRate(jadeja,"RA Jadeja") #' } #' #' @seealso #' \code{\link{bowlerMovingAverage}}\cr #' \code{\link{getTeamBowlingDetails}}\cr #' \code{\link{bowlerMeanRunsConceded}}\cr #' \code{\link{teamBowlersWicketRunsOppnAllMatches}}\cr #' #' @export #' getBowlerWicketDetails <- function(team,name,dir="."){ bowlingDetails=bowler=wicketPlayerOut=overs=maidens=NULL runs=economyRate=opposition=wickets=venue=NULL fl <- paste(dir,"/",team,"-BowlingDetails.RData",sep="") load(fl) details <- bowlingDetails bowlerDetails <- filter(details,grepl(name,bowler)) bowlerDetails <- arrange(bowlerDetails,date) # Count wickets taken # Replace nobody by 0 wickets a <- filter(bowlerDetails,wicketPlayerOut == "nobody") a$wickets <- 0 a1 <- c <- select(a,bowler,overs,maidens,runs,economyRate,date, opposition,wickets,venue) # Get rows which have wickets b <- filter(bowlerDetails,wicketPlayerOut != "nobody") c <- select(b,bowler,overs,maidens,runs,economyRate,date,opposition,venue) # Count wickets d <- summarise(group_by(b,date),wickets=length(unique(wicketPlayerOut))) # Join tables e <- full_join(c,d,by="date") f <- rbind(a1,e) f <- select(f,bowler,overs,maidens,runs,wickets,economyRate,date,opposition,venue) g <- arrange(f,date) g }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/getBowlerWicketDetails.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 26 Jan 2021 # Function: getCPLBattingDetails # This function creates CPL batting details # ########################################################################################### #' @title #' Gets the CPL batting details #' #' @description #' This function creates a single datframe of all CPL batting #' @usage #' getCPLBattingDetails(dir='.',odir=".") #' #' @param dir #' The input directory #' #' @param odir #' The output directory #' #' #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' #' @seealso #' \code{\link{getBBLBattingDetails}}\cr #' \code{\link{getBBLBowlingDetails}}\cr #' \code{\link{getNTBBattingDetails}}\cr #' \code{\link{getNTBBowlingDetails}}\cr #' @export #' getCPLBattingDetails <- function(dir='.',odir=".") { currDir= getwd() teams <-c("Antigua Hawksbills","Barbados Tridents","Guyana Amazon Warriors","Jamaica Tallawahs", "St Kitts and Nevis Patriots","St Lucia Zouks","Trinbago Knight Riders") battingDetails=batsman=runs=strikeRate=matches=meanRuns=meanSR=battingDF=val=NULL details=df=NULL teams1 <- NULL for(team in teams){ print(team) tryCatch({ batting <- getTeamBattingDetails(team,dir=dir, save=TRUE,odir=odir) teams1 <- c(teams1,team) }, error = function(e) { print("No data") } ) } }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/getCPLBattingDetails.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 26 Jan 2021 # Function: getCPLBowlingDetails # This function creates CPL bowling details # ########################################################################################### #' @title #' Gets the CPL bowling details #' #' @description #' This function creates a single datframe of all CPL bowling #' @usage #' getCPLBowlingDetails(dir='.',odir=".") #' #' @param dir #' The input directory #' #' @param odir #' The output directory #' #' #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' #' @seealso #' \code{\link{getIPLBattingDetails}}\cr #' \code{\link{getIPLBowlingDetails}}\cr #' \code{\link{getNTBBattingDetails}}\cr #' \code{\link{getNTBBowlingDetails}}\cr #' @export #' getCPLBowlingDetails <- function(dir='.',odir=".") { bowlingDetails=bowler=wickets=economyRate=matches=meanWickets=meanER=totalWickets=NULL currDir= getwd() teams <-c("Antigua Hawksbills","Barbados Tridents","Guyana Amazon Warriors","Jamaica Tallawahs", "St Kitts and Nevis Patriots","St Lucia Zouks","Trinbago Knight Riders") # Get all bowling details details=df=NULL teams1 <- NULL for(team in teams){ print(team) tryCatch({ bowling <- getTeamBowlingDetails(team,dir=dir, save=TRUE,odir=odir) teams1 <- c(teams1,team) }, error = function(e) { print("No data") } ) } }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/getCPLBowlingDetails.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 2 May 2020 # Function: getDeliveryWickets # This function creates a data frame of delivery and wickets # ########################################################################################### #' @title #' Get datframe of deliveries bowled and wickets taken #' #' @description #' This function creates a data frame of deliveries bowled and wickets taken. This data frame is #' then used by bowlerWktsPredict to predict the number of deliveries to wickets taken #' #' @usage #' getDeliveryWickets(team,dir=".",name,save=FALSE) #' #' @param team #' The team for which dataframe is to be obtained #' #' @param dir #' The source directory in which the match .RData files exist #' #' @param name #' The name of the bowler #' #' @param save #' Whether the data frame needs to be saved to a file or nor #' #' @return dataframe #' The dataframe of delivery wickets #' #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' @examples #' \dontrun{ #' # Create a data frame of deliveries to wickets from the stored .RData files #' jadeja1 <- getDeliveryWickets(team="India",dir="../data",name="Jadeja",save=FALSE) #' #' # Use this to create a classification tree of deliveries to wickets #' bowlerWktsPredict(jadeja1,"RA Jadeja") #' } #' #' @seealso #' \code{\link{bowlerMovingAverage}}\cr #' \code{\link{getTeamBowlingDetails}}\cr #' \code{\link{bowlerWktsPredict}}\cr #' \code{\link{teamBowlersWicketRunsOppnAllMatches}} #' #' @export #' getDeliveryWickets <- function(team,dir=".",name,save=FALSE){ overs=bowlingDetails=NULL a <- paste(dir,"/","*",team,"*",sep="") # Gather team against all opposition fl <- Sys.glob(a) print(length(fl)) cat(team,"dir=",dir,"name=",name,"\n") deliveryWKts <- NULL for(i in 1:length(fl)){ tryCatch({ load(fl[i]) match <- overs #print(i) details <- bowlerDeliveryWickets(match,team,name) print(dim(details)) # If the side has not batted details will be NULL. Skip in that case if(!is.null(dim(details))){ deliveryWKts <- rbind(deliveryWKts,details) }else { #print("Empty") next } }, error=function(e){cat("ERROR :",conditionMessage(e), "\n")}) } print(head(deliveryWKts)) deliveryWKts }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/getDeliveryWickets.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 5 Jan 2021 # Function: getIPLBattingDetails # This function creates IPL batting details # ########################################################################################### #' @title #' Gets the IPL batting details #' #' @description #' This function creates a single datframe of all IPL batting #' @usage #' getIPLBattingDetails(dir='.',odir=".") #' #' @param dir #' The input directory #' #' @param odir #' The output directory #' #' #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' #' @seealso #' \code{\link{getBBLBattingDetails}}\cr #' \code{\link{getBBLBowlingDetails}}\cr #' \code{\link{getNTBBattingDetails}}\cr #' \code{\link{getNTBBowlingDetails}}\cr #' @export #' getIPLBattingDetails <- function(dir='.',odir=".") { currDir= getwd() teams <-c("Chennai Super Kings","Delhi Capitals", "Deccan Chargers","Delhi Daredevils", "Kings XI Punjab","Punjab Kings", 'Kochi Tuskers Kerala',"Kolkata Knight Riders", "Mumbai Indians", "Pune Warriors","Rajasthan Royals", "Royal Challengers Bangalore","Sunrisers Hyderabad","Gujarat Lions", "Rising Pune Supergiants","Lucknow Super Giants","Gujarat Titans", "Royal Challengers Bengaluru") battingDetails=batsman=runs=strikeRate=matches=meanRuns=meanSR=battingDF=val=NULL details=df=NULL teams1 <- NULL for(team in teams){ print(team) tryCatch({ batting <- getTeamBattingDetails(team,dir=dir, save=TRUE,odir=odir) teams1 <- c(teams1,team) }, error = function(e) { print("No data") } ) } }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/getIPLBattingDetails.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 5 Jan 2021 # Function: getIPLBowlingDetails # This function creates IPL bowling details # ########################################################################################### #' @title #' Gets the IPL bowling details #' #' @description #' This function creates a single datframe of all IPL bowling #' @usage #' getIPLBowlingDetails(dir='.',odir=".") #' #' @param dir #' The input directory #' #' @param odir #' The output directory #' #' #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' #' @seealso #' \code{\link{getIPLBattingDetails}}\cr #' \code{\link{getIPLBowlingDetails}}\cr #' \code{\link{getNTBBattingDetails}}\cr #' \code{\link{getNTBBowlingDetails}}\cr #' @export #' getIPLBowlingDetails <- function(dir='.',odir=".") { bowlingDetails=bowler=wickets=economyRate=matches=meanWickets=meanER=totalWickets=NULL currDir= getwd() teams <-c("Chennai Super Kings","Delhi Capitals","Deccan Chargers","Delhi Daredevils", "Kings XI Punjab","Punjab Kings", 'Kochi Tuskers Kerala',"Kolkata Knight Riders", "Mumbai Indians", "Pune Warriors","Rajasthan Royals", "Royal Challengers Bangalore","Sunrisers Hyderabad","Gujarat Lions", "Rising Pune Supergiants","Lucknow Super Giants","Gujarat Titans", "Royal Challengers Bengaluru") # Get all bowling details details=df=NULL teams1 <- NULL for(team in teams){ print(team) tryCatch({ bowling <- getTeamBowlingDetails(team,dir=dir, save=TRUE,odir=odir) teams1 <- c(teams1,team) }, error = function(e) { print("No data") } ) } }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/getIPLBowlingDetails.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 20 Mar 2016 # Function: getMatchDetails # This function loads the data for a specified match given the teams in the match # and the date the match was played # ########################################################################################### #' @title #' Get match details of 2 countries #' #' @description #' This function gets the details of a matc palyed between 2 countries from the saved RData files #' and returns a dataframe #' #' @usage #' getMatchDetails(team1,team2,date,dir=".") #' #' @param team1 #' The 1st team in the match #' #' @param team2 #' The 2nd team in the matcj #' #' @param date #' The date on which the match was played #' #' @param dir #' The source directory of the RData files with all matches #' #' @return match #' The dataframe of the match #' #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' @examples #' \dontrun{ #' # convertAllYaml2RDataframes() & convertYaml2RDataframe convert yaml files #' # to data frame and store as RData #' # We have to point to this directory for the call below #' a <- getMatchDetails("England","Pakistan","2006-09-05",dir="../data") #' #' # Use this to create a classification tree of deliveries to wickets #' bowlerWktsPredict(jadeja1,"RA Jadeja") #' } #' #' @seealso #' \code{\link{getBatsmanDetails}}\cr #' \code{\link{getBowlerWicketDetails}}\cr #' \code{\link{getTeamBattingDetails}}\cr #' \code{\link{getTeamBowlingDetails}}\cr #' #' @export #' getMatchDetails <- function(team1,team2,date,dir="."){ overs <- NULL match <- NULL # Create 2 filenames with both combinations of team1 and team2 d1 <- paste(team1,"-",team2,"-",date,".RData",sep="") d2 <- paste(team2,"-",team1,"-",date,".RData",sep="") path1=paste(dir,"/",d1,sep="") path2=paste(dir,"/",d2,sep="") if(file.exists(path1)){ load(path1) match <- overs } else if(file.exists(path2)){ load(path2) match <- overs }else { cat("Match file not found at",dir, "\n") } }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/getMatchDetails.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 5 Jan 2021 # Function: getNTBBattingDetails # This function creates NTB batting details # ########################################################################################### #' @title #' Gets the NTB batting details #' #' @description #' This function creates a single datframe of all NTB batting #' @usage #' getNTBBattingDetails(dir='.',odir=".") #' #' @param dir #' The input directory #' #' @param odir #' The output directory #' #' #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' #' @seealso #' \code{\link{getBBLBattingDetails}}\cr #' \code{\link{getBBLBowlingDetails}}\cr #' \code{\link{getIPLBattingDetails}}\cr #' \code{\link{getIPLBowlingDetails}}\cr #' @export #' getNTBBattingDetails <- function(dir='.',odir=".") { currDir= getwd() teams <- c("Birmingham Bears","Derbyshire", "Durham", "Essex", "Glamorgan", "Gloucestershire", "Hampshire", "Kent","Lancashire", "Leicestershire", "Middlesex","Northamptonshire", "Nottinghamshire","Somerset","Surrey","Sussex","Warwickshire", "Worcestershire","Yorkshire") battingDetails=batsman=runs=strikeRate=matches=meanRuns=meanSR=battingDF=val=NULL details=df=NULL teams1 <- NULL for(team in teams){ print(team) tryCatch({ batting <- getTeamBattingDetails(team,dir=dir, save=TRUE,odir=odir) teams1 <- c(teams1,team) }, error = function(e) { print("No data") } ) } }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/getNTBBattingDetails.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 5 Jan 2021 # Function: getNTBBowlingDetails # This function creates NTB bowling details # ########################################################################################### #' @title #' Gets the NTB bowling details #' #' @description #' This function creates a single datframe of all NTB bowling #' @usage #' getNTBBowlingDetails(dir='.',odir=".") #' #' @param dir #' The input directory #' #' @param odir #' The output directory #' #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' #' @seealso #' \code{\link{getIPLBattingDetails}}\cr #' \code{\link{getIPLBowlingDetails}}\cr #' \code{\link{getNTBBattingDetails}}\cr #' \code{\link{getNTBBattingDetails}}\cr #' @export #' getNTBBowlingDetails <- function(dir='.',odir=".") { bowlingDetails=bowler=wickets=economyRate=matches=meanWickets=meanER=totalWickets=NULL currDir= getwd() teams <- c("Birmingham Bears","Derbyshire", "Durham", "Essex", "Glamorgan", "Gloucestershire", "Hampshire", "Kent","Lancashire", "Leicestershire", "Middlesex","Northamptonshire", "Nottinghamshire","Somerset","Surrey","Sussex","Warwickshire", "Worcestershire","Yorkshire") # Get all bowling details details=df=NULL teams1 <- NULL for(team in teams){ print(team) tryCatch({ bowling <- getTeamBowlingDetails(team,dir=dir, save=TRUE,odir=odir) teams1 <- c(teams1,team) }, error = function(e) { print("No data") } ) } }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/getNTBBowlingDetails.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 5 Jan 2021 # Function: getODIBattingDetails # This function creates ODI batting details # ########################################################################################### #' @title #' Gets the ODI batting details #' #' @description #' This function creates a single datframe of all ODI batting #' @usage #' getODIBattingDetails(dir='.',odir=".") #' #' @param dir #' The input directory #' #' @param odir #' The output directory #' #' #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' #' @seealso #' \code{\link{getBBLBattingDetails}}\cr #' \code{\link{getBBLBowlingDetails}}\cr #' \code{\link{getNTBBattingDetails}}\cr #' \code{\link{getNTBBowlingDetails}}\cr #' @export #' getODIBattingDetails <- function(dir='.',odir=".") { # This needs to be done once. After it is done, we can use the RData files currDir= getwd() teams <-c("Australia","India","Pakistan","West Indies", 'Sri Lanka', "England", "Bangladesh","Netherlands","Scotland", "Afghanistan", "Zimbabwe","Ireland","New Zealand","South Africa","Canada", "Bermuda","Kenya","Hong Kong","Nepal","Oman","Papua New Guinea", "United Arab Emirates","Namibia","Cayman Islands","Singapore", "United States of America","Bhutan","Maldives","Botswana","Nigeria", "Denmark","Germany","Jersey","Norway","Qatar","Malaysia","Vanuatu", "Thailand") #teams <- c("Australia","India","Singapore","West Indies") battingDetails=batsman=runs=strikeRate=matches=meanRuns=meanSR=battingDF=val=NULL details=df=NULL teams1 <- NULL for(team in teams){ print(team) tryCatch({ batting <- getTeamBattingDetails(team,dir=dir, save=TRUE,odir=odir) teams1 <- c(teams1,team) }, error = function(e) { print("No data") } ) } }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/getODIBattingDetails.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 5 Jan 2021 # Function: getODIBowlingDetails # This function creates ODI bowling details # ########################################################################################### #' @title #' Gets the ODI bowling details #' #' @description #' This function creates a single datframe of all ODI bowling #' @usage #' getODIBowlingDetails(dir='.',odir=".") #' #' @param dir #' The input directory #' #' @param odir #' The output directory #' #' #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' #' @seealso #' \code{\link{getIPLBattingDetails}}\cr #' \code{\link{getIPLBowlingDetails}}\cr #' \code{\link{getNTBBattingDetails}}\cr #' \code{\link{getNTBBattingDetails}}\cr #' @export #' getODIBowlingDetails <- function(dir='.',odir=".") { bowlingDetails=bowler=wickets=economyRate=matches=meanWickets=meanER=totalWickets=NULL currDir= getwd() teams <-c("Australia","India","Pakistan","West Indies", 'Sri Lanka', "England", "Bangladesh","Netherlands","Scotland", "Afghanistan", "Zimbabwe","Ireland","New Zealand","South Africa","Canada", "Bermuda","Kenya","Hong Kong","Nepal","Oman","Papua New Guinea", "United Arab Emirates","Namibia","Cayman Islands","Singapore", "United States of America","Bhutan","Maldives","Botswana","Nigeria", "Denmark","Germany","Jersey","Norway","Qatar","Malaysia","Vanuatu", "Thailand") #teams <- c("Australia","India","Singapore","West Indies") # Get all bowling details details=df=NULL teams1 <- NULL for(team in teams){ print(team) tryCatch({ bowling <- getTeamBowlingDetails(team,dir=dir, save=TRUE,odir=odir) teams1 <- c(teams1,team) }, error = function(e) { print("No data") } ) } }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/getODIBowlingDetails.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 5 Jan 2021 # Function: getPSLBattingDetails # This function creates PSL batting details # ########################################################################################### #' @title #' Gets the PSL batting details #' #' @description #' This function creates a single datframe of all PSL batting #' @usage #' getPSLBattingDetails(dir='.',odir=".") #' #' @param dir #' The input directory #' #' @param odir #' The output directory #' #' #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' #' @seealso #' \code{\link{getBBLBattingDetails}}\cr #' \code{\link{getBBLBowlingDetails}}\cr #' \code{\link{getNTBBattingDetails}}\cr #' \code{\link{getNTBBowlingDetails}}\cr #' @export #' getPSLBattingDetails <- function(dir='.',odir=".") { currDir= getwd() teams <- c("Islamabad United","Karachi Kings", "Lahore Qalandars", "Multan Sultans", "Peshawar Zalmi", "Quetta Gladiators") battingDetails=batsman=runs=strikeRate=matches=meanRuns=meanSR=battingDF=val=NULL details=df=NULL teams1 <- NULL for(team in teams){ print(team) tryCatch({ batting <- getTeamBattingDetails(team,dir=dir, save=TRUE,odir=odir) teams1 <- c(teams1,team) }, error = function(e) { print("No data") } ) } }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/getPSLBattingDetails.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 5 Jan 2021 # Function: getPSLBowlingDetails # This function creates PSL bowling details # ########################################################################################### #' @title #' Gets the PSL bowling details #' #' @description #' This function creates a single datframe of all PSL bowling #' @usage #' getPSLBowlingDetails(dir='.',odir=".") #' #' @param dir #' The input directory #' #' @param odir #' The output directory #' #' #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' #' @seealso #' \code{\link{getIPLBattingDetails}}\cr #' \code{\link{getIPLBowlingDetails}}\cr #' \code{\link{getNTBBattingDetails}}\cr #' \code{\link{getNTBBattingDetails}}\cr #' @export #' getPSLBowlingDetails <- function(dir='.',odir=".") { bowlingDetails=bowler=wickets=economyRate=matches=meanWickets=meanER=totalWickets=NULL currDir= getwd() teams <- c("Islamabad United","Karachi Kings", "Lahore Qalandars", "Multan Sultans", "Peshawar Zalmi", "Quetta Gladiators") # Get all bowling details details=df=NULL teams1 <- NULL for(team in teams){ print(team) tryCatch({ bowling <- getTeamBowlingDetails(team,dir=dir, save=TRUE,odir=odir) teams1 <- c(teams1,team) }, error = function(e) { print("No data") } ) } }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/getPSLBowlingDetails.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 24 May 2021 # Function: getSSMBattingDetails # This function creates SSM batting details # ########################################################################################### #' @title #' Gets the SSM batting details #' #' @description #' This function creates a single datframe of all SSM batsmen #' @usage #' getSSMBattingDetails(dir='.',odir=".") #' #' @param dir #' The input directory #' #' @param odir #' The output directory #' #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' #' @seealso #' \code{\link{getIPLBattingDetails}}\cr #' \code{\link{getIPLBowlingDetails}}\cr #' \code{\link{getNTBBattingDetails}}\cr #' \code{\link{getNTBBowlingDetails}}\cr #' @export #' getSSMBattingDetails <- function(dir='.',odir=".") { currDir= getwd() teams <-c("Auckland", "Canterbury", "Central Districts", "Northern Districts", "Otago", "Wellington") battingDetails=batsman=runs=strikeRate=matches=meanRuns=meanSR=battingDF=val=NULL details=df=NULL teams1 <- NULL for(team in teams){ print(team) tryCatch({ batting <- getTeamBattingDetails(team,dir=dir, save=TRUE,odir=odir) teams1 <- c(teams1,team) }, error = function(e) { print("No data") } ) } }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/getSSMBattingDetails.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 24 May 2021 # Function: getSSMBowlingDetails # This function creates SSM bowling details # ########################################################################################### #' @title #' Gets the SSM bowling details #' #' @description #' This function creates a single datframe of all SSM bowling #' @usage #' getSSMBowlingDetails(dir='.',odir=".") #' #' @param dir #' The input directory #' #' @param odir #' The output directory #' #' #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' #' @seealso #' \code{\link{getIPLBattingDetails}}\cr #' \code{\link{getIPLBowlingDetails}}\cr #' \code{\link{getNTBBattingDetails}}\cr #' \code{\link{getNTBBattingDetails}}\cr #' @export #' getSSMBowlingDetails <- function(dir='.',odir=".") { bowlingDetails=bowler=wickets=economyRate=matches=meanWickets=meanER=totalWickets=NULL currDir= getwd() teams <-c("Auckland", "Canterbury", "Central Districts", "Northern Districts", "Otago", "Wellington") # Get all bowling details details=df=NULL teams1 <- NULL for(team in teams){ print(team) tryCatch({ bowling <- getTeamBowlingDetails(team,dir=dir, save=TRUE,odir=odir) teams1 <- c(teams1,team) }, error = function(e) { print("No data") } ) } }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/getSSMBowlingDetails.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 5 Jan 2021 # Function: getT20BattingDetails # This function creates T20 batting details # ########################################################################################### #' @title #' Gets the T20 batting details #' #' @description #' This function creates a single datframe of all T20 batting #' @usage #' getT20BattingDetails(dir='.',odir=".") #' #' @param dir #' The input directory #' #' @param odir #' The output directory #' #' #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' #' @seealso #' \code{\link{getBBLBattingDetails}}\cr #' \code{\link{getBBLBowlingDetails}}\cr #' \code{\link{getNTBBattingDetails}}\cr #' \code{\link{getNTBBowlingDetails}}\cr #' @export #' getT20BattingDetails <- function(dir='.',odir=".") { currDir= getwd() teams <-c("Australia","India","Pakistan","West Indies", 'Sri Lanka', "England", "Bangladesh","Netherlands","Scotland", "Afghanistan", "Zimbabwe","Ireland","New Zealand","South Africa","Canada", "Bermuda","Kenya","Hong Kong","Nepal","Oman","Papua New Guinea", "United Arab Emirates","Namibia","Cayman Islands","Singapore", "United States of America","Bhutan","Maldives","Botswana","Nigeria", "Denmark","Germany","Jersey","Norway","Qatar","Malaysia","Vanuatu", "Thailand") #teams <- c("Australia","India","Singapore","West Indies") battingDetails=batsman=runs=strikeRate=matches=meanRuns=meanSR=battingDF=val=NULL details=df=NULL teams1 <- NULL for(team in teams){ print(team) tryCatch({ batting <- getTeamBattingDetails(team,dir=dir, save=TRUE,odir=odir) teams1 <- c(teams1,team) }, error = function(e) { print("No data") } ) } }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/getT20BattingDetails.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 5 Jan 2021 # Function: getT20BowlingDetails # This function creates T20 bowling details # ########################################################################################### #' @title #' Gets the T20 bowling details #' #' @description #' This function creates a single datframe of all T20 bowling #' @usage #' getT20BowlingDetails(dir='.',odir=".") #' #' @param dir #' The input directory #' #' @param odir #' The output directory #' #' #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' #' @seealso #' \code{\link{getIPLBattingDetails}}\cr #' \code{\link{getIPLBowlingDetails}}\cr #' \code{\link{getNTBBattingDetails}}\cr #' \code{\link{getNTBBattingDetails}}\cr #' @export #' getT20BowlingDetails <- function(dir='.',odir=".") { bowlingDetails=bowler=wickets=economyRate=matches=meanWickets=meanER=totalWickets=NULL currDir= getwd() teams <-c("Australia","India","Pakistan","West Indies", 'Sri Lanka', "England", "Bangladesh","Netherlands","Scotland", "Afghanistan", "Zimbabwe","Ireland","New Zealand","South Africa","Canada", "Bermuda","Kenya","Hong Kong","Nepal","Oman","Papua New Guinea", "United Arab Emirates","Namibia","Cayman Islands","Singapore", "United States of America","Bhutan","Maldives","Botswana","Nigeria", "Denmark","Germany","Jersey","Norway","Qatar","Malaysia","Vanuatu", "Thailand") #teams <- c("Australia","India","Singapore","West Indies") # Get all bowling details details=df=NULL teams1 <- NULL for(team in teams){ print(team) tryCatch({ bowling <- getTeamBowlingDetails(team,dir=dir, save=TRUE,odir=odir) teams1 <- c(teams1,team) }, error = function(e) { print("No data") } ) } }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/getT20BowlingDetails.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 2 May 2020 # Function: getTeamBattingDetails # This function gets the Batting details of a team against all opposition # ########################################################################################### #' @title #' Get team batting details #' #' @description #' This function gets the batting details of a team in all matchs against all #' oppositions. This gets all the details of the batsmen balls faced,4s,6s,strikerate, runs, venue etc. #' This function is then used for analyses of batsmen. This function calls teamBattingPerfDetails() #' #' @usage #' getTeamBattingDetails(team,dir=".",save=FALSE,odir=".") #' #' @param team #' The team for which batting details is required #' #' @param dir #' The source directory #' #' @param odir #' The output directory to store saved files #' #' @param save #' Whether the data frame needs to be saved as RData or not. It is recommended to set save=TRUE #' as the data can be used for a lot of analyses of batsmen #' #' @return battingDetails #' The dataframe with the batting details #' #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' @examples #' \dontrun{ #' a <- getTeamBattingDetails("India",dir="../data", save=TRUE) #' } #' #' @seealso #' \code{\link{getBatsmanDetails}}\cr #' \code{\link{getBowlerWicketDetails}}\cr #' \code{\link{batsmanDismissals}}\cr #' \code{\link{getTeamBowlingDetails}}\cr #' #' @export #' getTeamBattingDetails <- function(team,dir=".",save=FALSE,odir="."){ overs=batsman=NULL a <- paste(dir,"/","*",team,"*",sep="") # Gather team against all ooposition fl <- Sys.glob(a) battingDetails <- NULL for(i in 1:length(fl)){ # Add try-catch to handle issues tryCatch({ load(fl[i]) match <- overs details <- teamBattingPerfDetails(match,team,includeInfo=TRUE) # If the side has not batted details will be NULL. Skip in that case if(!is.null(dim(details))){ battingDetails <- rbind(battingDetails,details) }else { #print("Empty") next } }, error=function(e){cat("ERROR :",conditionMessage(e), "\n")}) } if(save==TRUE){ fl <-paste(odir,"/",team,"-BattingDetails.RData",sep="") save(battingDetails,file=fl) } battingDetails <- arrange(battingDetails,batsman,date) battingDetails }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/getTeamBattingDetails.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 2 May 2020 # Function: getTeamBowlingDetails # This function uses gets the bowling details of a team # ########################################################################################### #' @title #' Get the team bowling details #' #' @description #' This function gets the bowling details of a team in all matchs against all #' oppositions. This gets all the details of the bowlers for e.g deliveries, maidens, runs, #' wickets, venue, date, winner ec #' #' @usage #' getTeamBowlingDetails(team,dir=".",save=FALSE, odir=".") #' #' @param team #' The team for which detailed bowling info is required #' #' @param dir #' The source directory of RData files obtained with convertAllYaml2RDataframes() #' #' @param odir #' The output directory #' #' @param save #' Whether the data frame needs to be saved as RData or not. It is recommended to set save=TRUE #' as the data can be used for a lot of analyses of batsmen #' #' @return bowlingDetails #' The dataframe with the bowling details #' #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' @examples #' \dontrun{ #' a <- getTeamBowlingDetails("India",dir="../data",save=TRUE,odir=".") #' } #' #' @seealso #' \code{\link{getBatsmanDetails}}\cr #' \code{\link{getBowlerWicketDetails}}\cr #' \code{\link{batsmanDismissals}}\cr #' \code{\link{getTeamBattingDetails}}\cr #' #' @export #' getTeamBowlingDetails <- function(team,dir=".",save=FALSE,odir="."){ overs=bowler=NULL a <- paste(dir,"/","*",team,"*",sep="") # Gather team against all ooposition fl <- Sys.glob(a) bowlingDetails <- NULL for(i in 1:length(fl)){ # Add try-catch to handle issues tryCatch({ load(fl[i]) match <- overs details <- teamBowlingPerfDetails(match,team,includeInfo=TRUE) # If the side has not batted details will be NULL. Skip in that case if(!is.null(dim(details))){ bowlingDetails <- rbind(bowlingDetails,details) }else { #print("Empty") next } }, error=function(e){cat("ERROR :",conditionMessage(e), "\n")}) } if(save==TRUE){ fl <- paste(odir,"/",team,"-BowlingDetails.RData",sep="") save(bowlingDetails,file=fl) } bowlingDetails <- arrange(bowlingDetails,bowler,date) bowlingDetails }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/getTeamBowlingDetails.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 5 Jan 2021 # Function: getWBBBattingDetails # This function creates WBB batting details # ########################################################################################### #' @title #' Gets the WBB batting details #' #' @description #' This function creates a single datframe of all WBB batsmen #' @usage #' getWBBBattingDetails(dir='.',odir=".") #' #' @param dir #' The input directory #' #' @param odir #' The output directory #' #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' #' @seealso #' \code{\link{getIPLBattingDetails}}\cr #' \code{\link{getIPLBowlingDetails}}\cr #' \code{\link{getNTBBattingDetails}}\cr #' \code{\link{getNTBBowlingDetails}}\cr #' @export #' getWBBBattingDetails <- function(dir='.',odir=".") { currDir= getwd() teams <-c("Adelaide Strikers", "Brisbane Heat", "Hobart Hurricanes", "Melbourne Renegades", "Melbourne Stars", "Perth Scorchers", "Sydney Sixers", "Sydney Thunder") battingDetails=batsman=runs=strikeRate=matches=meanRuns=meanSR=battingDF=val=NULL details=df=NULL teams1 <- NULL for(team in teams){ print(team) tryCatch({ batting <- getTeamBattingDetails(team,dir=dir, save=TRUE,odir=odir) teams1 <- c(teams1,team) }, error = function(e) { print("No data") } ) } }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/getWBBBattingDerails.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 5 Jan 2021 # Function: getWBBBowlingDetails # This function creates WBB bowling details # ########################################################################################### #' @title #' Gets the WBB bowling details #' #' @description #' This function creates a single datframe of all WBB bowling #' @usage #' getWBBBowlingDetails(dir='.',odir=".") #' #' @param dir #' The input directory #' #' @param odir #' The output directory #' #' #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' #' @seealso #' \code{\link{getIPLBattingDetails}}\cr #' \code{\link{getIPLBowlingDetails}}\cr #' \code{\link{getNTBBattingDetails}}\cr #' \code{\link{getNTBBattingDetails}}\cr #' @export #' getWBBBowlingDetails <- function(dir='.',odir=".") { bowlingDetails=bowler=wickets=economyRate=matches=meanWickets=meanER=totalWickets=NULL currDir= getwd() teams <-c("Adelaide Strikers", "Brisbane Heat", "Hobart Hurricanes", "Melbourne Renegades", "Melbourne Stars", "Perth Scorchers", "Sydney Sixers", "Sydney Thunder") # Get all bowling details details=df=NULL teams1 <- NULL for(team in teams){ print(team) tryCatch({ bowling <- getTeamBowlingDetails(team,dir=dir, save=TRUE,odir=odir) teams1 <- c(teams1,team) }, error = function(e) { print("No data") } ) } }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/getWBBBowlingDetails.R
########################################################################################## ########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 25 Dec 2022 # Function: winProbabiltyRF # This function computes the ball by ball win probability using Random Forest model # ########################################################################################### #' @title #' globals.R #' #' @description #' quiets concerns of R CMD check re: the .'s that appear in pipelines #' #' @name globals if(getRversion() >= "2.15.1") utils::globalVariables(c("final_lr_model","final_model","dl_model","gan_model"))
/scratch/gouwar.j/cran-all/cranData/yorkr/R/globals.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 27 Jan 2021 # Function: helper # This function is a helper for computing batting details of team # ########################################################################################### #' @title #' Gets min,max date and min and max matches from dataframe #' #' @description #' This function gets min,max date and min and max matches from dataframe #' @usage #' helper(teamNames,dir=".",type="IPL") #' #' @param teamNames #' The team names #' #' @param dir #' The output directory #' #' @param type #' T20 format #' #' @return minDate,maxDate, minMatches, maxMatches #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' #' @seealso #' \code{\link{rankODIBowlers}}\cr #' \code{\link{rankODIBatsmen}}\cr #' \code{\link{rankT20Batsmen}}\cr #' \code{\link{rankT20Bowlers}}\cr #' @export #' helper<- function(teamNames,dir=".",type="IPL") { currDir= getwd() battingDetails=batsman=runs=strikeRate=matches=meanRuns=meanSR=battingDF=val=NULL year=NULL print("Helper") print(getwd()) setwd(dir) print(getwd()) teams = unlist(teamNames) battingDF<-NULL battingDetails <- paste(type,"-BattingDetails.RData",sep="") print(battingDetails) load(battingDetails) print(dim(battingDF)) print(names(battingDF)) cat("Dir helper =====",getwd(),"\n") maxDate= as.Date(max(battingDF$date)) minDate= as.Date(min(battingDF$date)) print(minDate,maxDate) df <- select(battingDF,batsman,runs,strikeRate) b=summarise(group_by(df,batsman),matches=n()) minMatches = min(b$matches) maxMatches = max(b$matches) setwd(currDir) cat("Helper **********************************************\n") return(list(minDate,maxDate,minMatches, maxMatches)) }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/helper.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 27 Jan 2021 # Function: helper1 # This function is a helper for computing batting details of team given the year # ########################################################################################### #' @title #' Gets min,max date and min and max matches from dataframe from the year #' #' @description #' This function gets min,max date and min and max matches from dataframe #' @usage #' helper1(teamNames,dateRange, dir=".",type="IPL") #' #' @param teamNames #' The team names #' #' @param dateRange #' Date interval to consider #' #' @param dir #' The input directory #' #' @param type #' T20 format #' #' @return minMatches, maxMatches #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' @seealso #' \code{\link{rankODIBowlers}}\cr #' \code{\link{rankODIBatsmen}}\cr #' \code{\link{rankT20Batsmen}}\cr #' \code{\link{rankT20Bowlers}}\cr #' @export #' helper1<- function(teamNames,dateRange, dir=".",type="IPL") { currDir= getwd() battingDetails=batsman=runs=strikeRate=matches=meanRuns=meanSR=battingDF=val=NULL setwd(dir) teams = unlist(teamNames) battingDetails <- paste(type,"-BattingDetails.RData",sep="") print(battingDetails) load(battingDetails) print(dim(battingDF)) print(names(battingDF)) maxDate= as.Date(max(battingDF$date)) minDate= as.Date(min(battingDF$date)) a=battingDF %>% filter(date >= dateRange[1] & date <= dateRange[2]) df <- select(a,batsman,runs,strikeRate) # Compute matches b=summarise(group_by(df,batsman),matches=n()) minMatches = min(b$matches) maxMatches = max(b$matches) setwd(currDir) return(list(minMatches, maxMatches)) }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/helper1.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 28 Jan 2021 # Function: helper2 # his function is a helper for computing batting details of team # ########################################################################################### #' #' @title #' Gets min,max date and min and max matches from dataframe #' #' #' @description #' This function gets min,max date and min and max matches from dataframe #' #' @usage #' helper2(teamNames,dir=".",type="IPL") #' #' #' @param teamNames #' The team names #' #' @param dir #' The output directory #' #' @param type #' T20 format #' #' #' @return minDate,maxDate, minMatches, maxMatches #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' #' @seealso #' \code{\link{rankODIBowlers}}\cr #' \code{\link{rankODIBatsmen}}\cr #' \code{\link{rankT20Batsmen}}\cr #' \code{\link{rankT20Bowlers}}\cr #' @export #' helper2<- function(teamNames,dir=".",type="IPL") { currDir= getwd() setwd(dir) year=bowler=NULL teams = unlist(teamNames) cat("Dir helper2=====",getwd(),"Dir=", dir, "\n") bowlingDF<-NULL bowlingDetails <- paste(type,"-BowlingDetails.RData",sep="") print(bowlingDetails) load(bowlingDetails) maxDate= as.Date(max(bowlingDF$date)) minDate= as.Date(min(bowlingDF$date)) print(minDate,maxDate) # Compute number of matches played a=bowlingDF %>% select(bowler,date) %>% unique() b=summarise(group_by(a,bowler),matches=n()) minMatches = min(b$matches) maxMatches = max(b$matches) setwd(currDir) #a=battingDF %>% filter(date > as.Date("2018-02-01")) return(list(minDate,maxDate,minMatches, maxMatches)) }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/helper2.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 28 Jan 2021 # Function: helper3 # This function is a helper for computing batting details of team given the year # ########################################################################################### #' @title #' Gets min,max date and min and max matches from dataframe for the year #' #' @description #' This function gets min,max date and min and max matches from dataframe #' @usage #' helper3(teamNames,dateRange, dir=".",type="IPL") #' #' @param teamNames #' The team names #' #' @param dateRange #' Date interval to consider #' #' @param dir #' The input directory #' #' @param type #' T20 format #' #' #' @return minMatches, maxMatches #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' #' @seealso #' \code{\link{rankODIBowlers}}\cr #' \code{\link{rankODIBatsmen}}\cr #' \code{\link{rankT20Batsmen}}\cr #' \code{\link{rankT20Bowlers}}\cr #' @export #' helper3<- function(teamNames,dateRange, dir=".",type="IPL") { currDir= getwd() setwd(dir) year=bowler=NULL teams = unlist(teamNames) bowlingDF<-NULL bowlingDetails <- paste(type,"-BowlingDetails.RData",sep="") print(bowlingDetails) load(bowlingDetails) maxDate= as.Date(max(bowlingDF$date)) minDate= as.Date(min(bowlingDF$date)) a=bowlingDF %>% filter(date >= dateRange[1] & date <= dateRange[2]) # Compute number of matches played b=a %>% select(bowler,date) %>% unique() c=summarise(group_by(b,bowler),matches=n()) minMatches = min(c$matches) maxMatches = max(c$matches) setwd(currDir) cat("max matxhes =", maxMatches) return(list(minMatches, maxMatches)) }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/helper3.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 15 Apr 2016 # Function: matchWormGraph # This function computes and plots the match worm chart # ########################################################################################### #' @title #' Plot the match worm graph #' #' @description #' This function plots the match worm graph between 2 teams in a match #' #' @usage #' matchWormGraph(match,t1,t2,plot=1) #' #' @param match #' The dataframe of the match #' #' @param t1 #' The 1st team of the match #' #' @param t2 #' the 2nd team in the match #' #' @param plot #' Plot=1 (static), Plot=2(interactive) #' #' @return none #' #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' @examples #' \dontrun{ #' #Get the match details #' a <- getMatchDetails("England","Pakistan","2006-09-05",dir="../temp") #' #' # Plot tne match worm plot #' matchWormGraph(a,'England',"Pakistan") #' } #' @seealso #' \code{\link{getBatsmanDetails}}\cr #' \code{\link{getBowlerWicketDetails}}\cr #' \code{\link{batsmanDismissals}}\cr #' \code{\link{getTeamBattingDetails}}\cr #' #' @export #' matchWormGraph <- function(match,t1,t2,plot=1) { team=ball=totalRuns=total=NULL ggplotly=NULL # Filter the performance of team1 a <-filter(match,team==t1) b <- select(a,ball,totalRuns) # Check for both possibilities if(grepl("1st",b$ball[1])){ c <-mutate(b,ball=gsub("1st\\.","",ball)) } else{ c <-mutate(b,ball=gsub("2nd\\.","",ball)) } # Compute cumulative sum vs balls bowled d <- mutate(c,total=cumsum(totalRuns)) # Filter performance of team2 a <-filter(match,team==t2) b1 <- select(a,ball,totalRuns) # Check for both possibilities if(grepl("2nd",b1$ball[1])){ c1 <-mutate(b1,ball=gsub("2nd\\.","",ball)) } else{ c1 <-mutate(b1,ball=gsub("1st\\.","",ball)) } # Compute cumulative sum vs balls bowled d1 <- mutate(c1,total=cumsum(totalRuns)) # Convert to numeric d$ball=as.numeric(d$ball) d1$ball=as.numeric(d1$ball) # Plot both lines if(plot ==1){ #ggplot2 ggplot() + geom_line(data = d, aes(x = ball, y = total, color = t1)) + geom_line(data = d1, aes(x = ball, y = total, color = t2))+ xlab("Overs") + ggtitle(bquote(atop(.("Worm chart of match"), atop(italic("Data source:http://cricsheet.org/"),"")))) }else { #ggplotly g <- ggplot() + geom_line(data = d, aes(x = ball, y = total, color = t1)) + geom_line(data = d1, aes(x = ball, y = total, color = t2))+ xlab("Overs") + ggtitle("Worm chart of match") ggplotly(g) } }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/matchWormChart.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 6 Nov 2021 # Function: matchWormWicketGraph # This function computes and plots the match worm wicket chart # ########################################################################################### #' @title #' Plot the match worm wicket graph #' #' @description #' This function plots the match worm wicket graph between 2 teams in a match #' #' @usage #' matchWormWicketGraph(match,t1,t2,plot=1) #' #' @param match #' The dataframe of the match #' #' @param t1 #' The 1st team of the match #' #' @param t2 #' the 2nd team in the match #' #' @param plot #' Plot=1 (static), Plot=2(interactive) #' #' @return none #' #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' @examples #' \dontrun{ #' #Get the match details #' a <- getMatchDetails("England","Pakistan","2006-09-05",dir="../temp") #' #' # Plot tne match worm plot #' matchWormWicketGraph(a,'England',"Pakistan") #' } #' @seealso #' \code{\link{getBatsmanDetails}}\cr #' \code{\link{getBowlerWicketDetails}}\cr #' \code{\link{batsmanDismissals}}\cr #' \code{\link{getTeamBattingDetails}}\cr #' #' @export #' matchWormWicketGraph <- function(match,t1,t2,plot=1) { team=ball=totalRuns=total=wicketPlayerOut=NULL ggplotly=NULL # Filter the performance of team1 a <-filter(match,team==t1) b <- select(a,ball,totalRuns,wicketPlayerOut) # Check for both possibilities if(grepl("1st",b$ball[1])){ c <-mutate(b,ball=gsub("1st\\.","",ball)) } else{ c <-mutate(b,ball=gsub("2nd\\.","",ball)) } # Compute cumulative sum vs balls bowled d <- mutate(c,total=cumsum(totalRuns)) # Filter performance of team2 a <-filter(match,team==t2) b1 <- select(a,ball,totalRuns,wicketPlayerOut) # Check for both possibilities if(grepl("2nd",b1$ball[1])){ c1 <-mutate(b1,ball=gsub("2nd\\.","",ball)) } else{ c1 <-mutate(b1,ball=gsub("1st\\.","",ball)) } # Compute cumulative sum vs balls bowled d1 <- mutate(c1,total=cumsum(totalRuns)) # Convert to numeric d$ball=as.numeric(d$ball) d1$ball=as.numeric(d1$ball) e= filter(d,wicketPlayerOut != "nobody") e1= filter(d1,wicketPlayerOut != "nobody") # Plot both lines if(plot ==1){ #ggplot2 ggplot() + geom_line(data = d, aes(x = ball, y = total, color = t1)) + geom_line(data = d1, aes(x = ball, y = total, color = t2))+ geom_point(data=e, aes(x=ball, y=total,color=t1),shape=0) + geom_text(data=e, aes(x=ball,y=total,label=wicketPlayerOut,color=t1),vjust=0.5) + geom_point(data=e1,aes(x=ball, y=total,color=t2),shape=2) + geom_text(data=e1, aes(x=ball,y=total,label=wicketPlayerOut,color=t2),vjust=0.5) + xlab("Overs") + ggtitle(bquote(atop(.("Worm chart of match"), atop(italic("Data source:http://cricsheet.org/"),"")))) }else { #ggplotly g <- ggplot() + geom_line(data = d, aes(x = ball, y = total, color = t1)) + geom_line(data = d1, aes(x = ball, y = total, color = t2))+ geom_point(data=e, aes(x=ball, y=total,color=t1),shape=0) + geom_text(data=e, aes(x=ball,y=total,label=wicketPlayerOut,color=t1),vjust=-0.5) + geom_point(data=e1,aes(x=ball, y=total,color=t2),shape=2) + geom_text(data=e1, aes(x=ball,y=total,label=wicketPlayerOut,color=t2),vjust=0.5) + xlab("Overs") + ggtitle("Worm chart of match") ggplotly(g) } }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/matchWormWicket.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 23 Nov 2021 # Function: overallRunsSRDeathOversPlotT20 # This function plots Runs vs SR in death overs Intl. T20 batsmen # # ########################################################################################### #' @title #' Plot the Runs vs SR in death overs of Intl. T20 batsmen #' #' @description #' Runs vs SR in middle death of Intl. T20 batsmen #' #' @usage #' overallRunsSRDeathOversPlotT20(dir=".", dateRange,type="IPL",plot=1) #' #' @param dir #' The input directory #' #' #' @param dateRange #' Date interval to consider #' #' @param type #' T20 league #' #' @param plot #' plot=1 (static),plot=2(interactive), plot=3 (table) #' #' @return The ranked T20 batsmen #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' @examples #' \dontrun{ #' overallRunsSRDeathOversPlotT20(dir=".", dateRange,type="IPL",plot=1) #' } #' #' @seealso #' \code{\link{rankODIBowlers}}\cr #' \code{\link{rankODIBatsmen}}\cr #' \code{\link{rankT20Bowlers}}\cr #' @export #' overallRunsSRDeathOversPlotT20 <- function(dir=".", dateRange,type="IPL",plot=1) { team=ball=totalRuns=total=t20MDF=str_extract=batsman=quantile=SRDeathOvers=quadrant=runs=NULL ggplotly=NULL fl <- paste(dir,"/",type,"-MatchesDataFrame.RData",sep="") load(fl) # Filter by date range df=t20MDF %>% filter(date >= dateRange[1] & date <= dateRange[2]) a1 <- df %>% filter(between(as.numeric(str_extract(ball, "\\d+(\\.\\d+)?$")), 16.1, 20.0)) a2 <- select(a1,ball,totalRuns,batsman,date) a3 <- a2 %>% group_by(batsman) %>% summarise(runs=sum(totalRuns),count=n(), SRDeathOvers=runs/count*100) x_lower <- quantile(a3$runs,p=0.66,na.rm = TRUE) y_lower <- quantile(a3$SRDeathOvers,p=0.66,na.rm = TRUE) plot.title <- paste("Overall Runs vs SR in Death overs in ",type,sep="") if(plot == 1){ #ggplot2 a3 %>% mutate(quadrant = case_when(runs > x_lower & SRDeathOvers > y_lower ~ "Q1", runs <= x_lower & SRDeathOvers > y_lower ~ "Q2", runs <= x_lower & SRDeathOvers <= y_lower ~ "Q3", TRUE ~ "Q4")) %>% ggplot(aes(runs,SRDeathOvers,color=quadrant)) + geom_text(aes(runs,SRDeathOvers,label=batsman,color=quadrant)) + geom_point() + xlab("Runs - Death overs") + ylab("Strike rate - Death overs") + geom_vline(xintercept = x_lower,linetype="dashed") + # plot vertical line geom_hline(yintercept = y_lower,linetype="dashed") + # plot horizontal line ggtitle(plot.title) } else if(plot == 2){ #ggplotly g <- a3 %>% mutate(quadrant = case_when(runs > x_lower & SRDeathOvers > y_lower ~ "Q1", runs <= x_lower & SRDeathOvers > y_lower ~ "Q2", runs <= x_lower & SRDeathOvers <= y_lower ~ "Q3", TRUE ~ "Q4")) %>% ggplot(aes(runs,SRDeathOvers,color=quadrant)) + geom_text(aes(runs,SRDeathOvers,label=batsman,color=quadrant)) + geom_point() + xlab("Runs - Death overs") + ylab("Strike rate - Death overs") + geom_vline(xintercept = x_lower,linetype="dashed") + # plot vertical line geom_hline(yintercept = y_lower,linetype="dashed") + # plot horizontal line ggtitle(plot.title) ggplotly(g) } }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/overallRunsSRDeathOversPlotT20.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 23 Nov 2021 # Function: overallRunsSRMiddleOversPlotT20 # This function plots Runs vs SR in middle overs Intl. T20 batsmen # # ########################################################################################### #' @title #' Plot the Runs vs SR in middle overs of Intl. T20 batsmen #' #' @description #' Runs vs SR in middle overs of Intl. T20 batsmen #' #' @usage #' overallRunsSRMiddleOversPlotT20(dir=".", dateRange,type="IPL",plot=1) #' #' @param dir #' The input directory #' #' #' #' @param dateRange #' Date interval to consider #' #' @param type #' T20 league #' #' @param plot #' plot=1 (static),plot=2(interactive), plot=3 (table) #' #' @return The ranked T20 batsmen #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' @examples #' \dontrun{ #' overallRunsSRMiddleOversPlotT20(dir=".", dateRange,type="IPL",plot=1) #' } #' #' @seealso #' \code{\link{rankODIBowlers}}\cr #' \code{\link{rankODIBatsmen}}\cr #' \code{\link{rankT20Bowlers}}\cr #' @export #' overallRunsSRMiddleOversPlotT20 <- function(dir=".",dateRange,type="IPL",plot=1) { team=ball=totalRuns=total=t20MDF=str_extract=batsman=quantile=SRMiddleOvers=quadrant=runs=NULL ggplotly=NULL fl <- paste(dir,"/",type,"-MatchesDataFrame.RData",sep="") load(fl) # Filter by date range df=t20MDF %>% filter(date >= dateRange[1] & date <= dateRange[2]) a1 <- df %>% filter(between(as.numeric(str_extract(ball, "\\d+(\\.\\d+)?$")), 6.1, 15.9)) a2 <- select(a1,ball,totalRuns,batsman,date) a3 <- a2 %>% group_by(batsman) %>% summarise(runs=sum(totalRuns),count=n(), SRMiddleOvers=runs/count*100) x_lower <- 1/3* min(a3$runs + max(a3$runs)) y_lower <- 1/3 * min(a3$SRMiddleOvers + max(a3$SRMiddleOvers)) plot.title <- paste("Overall Runs vs SR in Middle overs in ",type,sep="") if(plot == 1){ #ggplot2 a3 %>% mutate(quadrant = case_when(runs > x_lower & SRMiddleOvers > y_lower ~ "Q1", runs <= x_lower & SRMiddleOvers > y_lower ~ "Q2", runs <= x_lower & SRMiddleOvers <= y_lower ~ "Q3", TRUE ~ "Q4")) %>% ggplot(aes(runs,SRMiddleOvers,color=quadrant)) + geom_text(aes(runs,SRMiddleOvers,label=batsman,color=quadrant)) + geom_point() + xlab("Runs - Middle overs") + ylab("Strike rate - Middle overs") + geom_vline(xintercept = x_lower,linetype="dashed") + # plot vertical line geom_hline(yintercept = y_lower,linetype="dashed") + # plot horizontal line ggtitle(plot.title) } else if(plot == 2){ #ggplotly g <- a3 %>% mutate(quadrant = case_when(runs > x_lower & SRMiddleOvers > y_lower ~ "Q1", runs <= x_lower & SRMiddleOvers > y_lower ~ "Q2", runs <= x_lower & SRMiddleOvers <= y_lower ~ "Q3", TRUE ~ "Q4")) %>% ggplot(aes(runs,SRMiddleOvers,color=quadrant)) + geom_text(aes(runs,SRMiddleOvers,label=batsman,color=quadrant)) + geom_point() + xlab("Runs - Middle overs") + ylab("Strike rate - Middle overs") + geom_vline(xintercept = x_lower,linetype="dashed") + # plot vertical line geom_hline(yintercept = y_lower,linetype="dashed") + # plot horizontal line ggtitle(plot.title) ggplotly(g) } }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/overallRunsSRMiddleOversPlotT20.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 27 Nov 2021 # Function: overallRunsSRPPowerplayPlotT20 # This function plots Runs vs SR in power play of T20 batsmen # # ########################################################################################### #' @title #' Plot the Runs vs SR in power play of T20 batsmen #' #' @description #' Runs vs SR in power play of T20 batsmen #' #' @usage #' overallRunsSRPPowerplayPlotT20(dir=".", dateRange,type="IPL",plot=1) #' #' @param dir #' The input directory #' #' #' @param dateRange #' Date interval to consider #' #' @param type #' T20 league #' #' @param plot #' plot=1 (static),plot=2(interactive), plot=3 (table) #' #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' @examples #' \dontrun{ #' overallRunsSRPPowerplayPlotT20(dir=".", dateRange,type="IPL",plot=1) #' } #' #' @seealso #' \code{\link{rankODIBowlers}}\cr #' \code{\link{rankODIBatsmen}}\cr #' \code{\link{rankT20Bowlers}}\cr #' @export #' overallRunsSRPPowerplayPlotT20 <- function(dir=".", dateRange,type="IPL",plot=1){ team=ball=totalRuns=total=t20MDF=str_extract=batsman=quantile=SRPowerPlay=quadrant=runs=NULL ggplotly=NULL fl <- paste(dir,"/",type,"-MatchesDataFrame.RData",sep="") load(fl) # Filter by date range df=t20MDF %>% filter(date >= dateRange[1] & date <= dateRange[2]) a1 <- df%>% filter(between(as.numeric(str_extract(ball, "\\d+(\\.\\d+)?$")), 0.1, 5.9)) a2 <- select(a1,ball,totalRuns,batsman,date) a3 <- a2 %>% group_by(batsman) %>% summarise(runs=sum(totalRuns),count=n(), SRPowerPlay=runs/count*100) x_lower <- quantile(a3$runs,p=0.66,na.rm = TRUE) y_lower <- quantile(a3$SRPowerPlay,p=0.66,na.rm = TRUE) plot.title <- paste("Overall Runs vs SR in Power play in ",type,sep="") if(plot == 1){ #ggplot2 a3 %>% mutate(quadrant = case_when(runs > x_lower & SRPowerPlay > y_lower ~ "Q1", runs <= x_lower & SRPowerPlay > y_lower ~ "Q2", runs <= x_lower & SRPowerPlay <= y_lower ~ "Q3", TRUE ~ "Q4")) %>% ggplot(aes(runs,SRPowerPlay,color=quadrant)) + geom_text(aes(runs,SRPowerPlay,label=batsman,color=quadrant)) + geom_point() + xlab("Runs - Power play") + ylab("Strike rate - Power play") + geom_vline(xintercept = x_lower,linetype="dashed") + # plot vertical line geom_hline(yintercept = y_lower,linetype="dashed") + # plot horizontal line ggtitle(plot.title) } else if(plot == 2){ #ggplotly g <- a3 %>% mutate(quadrant = case_when(runs > x_lower & SRPowerPlay > y_lower ~ "Q1", runs <= x_lower & SRPowerPlay > y_lower ~ "Q2", runs <= x_lower & SRPowerPlay <= y_lower ~ "Q3", TRUE ~ "Q4")) %>% ggplot(aes(runs,SRPowerPlay,color=quadrant)) + geom_text(aes(runs,SRPowerPlay,label=batsman,color=quadrant)) + geom_point() + xlab("Runs - Power play") + ylab("Strike rate - Power play") + geom_vline(xintercept = x_lower,linetype="dashed") + # plot vertical line geom_hline(yintercept = y_lower,linetype="dashed") + # plot horizontal line ggtitle(plot.title) ggplotly(g) } }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/overallRunsSRPPowerplayPlotT20.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 23 Nov 2021 # Function: overallRunsSRPlotT20 # This function plots Runs vs SR of Intl. T20 batsmen # # ########################################################################################### #' @title #' Plot the Runs vs SR of Intl. T20 batsmen #' #' @description #' This function creates a single datframe of all T20 batsmen and then ranks them #' #' @usage #' overallRunsSRPlotT20(dir=".",minMatches, dateRange,type="IPL",plot=1) #' #' #' @param dir #' The input directory #' #' @param minMatches #' Minimum matches played #' #' @param dateRange #' Date interval to consider #' #' @param type #' T20 league #' #' @param plot #' plot=1 (static),plot=2(interactive), plot=3 (table) #' #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' @examples #' \dontrun{ #' overallRunsSRPlotT20(dir=".",minMatches, dateRange,type="IPL",plot=1) #' } #' #' @seealso #' \code{\link{rankODIBowlers}}\cr #' \code{\link{rankODIBatsmen}}\cr #' \code{\link{rankT20Bowlers}}\cr #' @export #' overallRunsSRPlotT20 <- function(dir=".",minMatches, dateRange,type="IPL",plot=1) { quantile=quadrant=ggplotly=NULL currDir= getwd() cat("T20batmandir=",currDir,"\n") battingDetails=batsman=runs=strikeRate=matches=meanRuns=meanSR=battingDF=val=year=NULL setwd(dir) battingDF<-NULL battingDetails <- paste(type,"-BattingDetails.RData",sep="") print(battingDetails) load(battingDetails) print(dim(battingDF)) print(dim(battingDF)) print(names(battingDF)) # Note: If the date Range is NULL setback to root directory tryCatch({ df=battingDF %>% filter(date >= dateRange[1] & date <= dateRange[2]) }, warning=function(war) { print(paste("NULL values: ", war)) }, error=function(err) { # Change to root directory on error setwd(currDir) cat("Back to root",getwd(),"\n") }) df1 <- select(df,batsman,runs,strikeRate) df1 <- distinct(df1) b=summarise(group_by(df1,batsman),matches=n(), meanRuns=mean(runs),meanSR=mean(strikeRate)) print(dim(b)) b[is.na(b)] <- 0 c <- filter(b,matches >= minMatches) # Reset to currDir setwd(currDir) x_lower <- quantile(c$meanRuns,p=0.66,na.rm = TRUE) y_lower <- quantile(c$meanSR,p=0.66,na.rm = TRUE) print("!!!!!!!!!!!!!!!!!!!!!!!!!") print(plot) print("!!!!!!!!!!!!!!!!!!!!!!!!!") plot.title <- paste("Overall Runs vs SR in ",type,sep="") if(plot == 1){ #ggplot2 c %>% mutate(quadrant = case_when(meanRuns > x_lower & meanSR > y_lower ~ "Q1", meanRuns <= x_lower & meanSR > y_lower ~ "Q2", meanRuns <= x_lower & meanSR <= y_lower ~ "Q3", TRUE ~ "Q4")) %>% ggplot(aes(meanRuns,meanSR,color=quadrant)) + geom_text(aes(meanRuns,meanSR,label=batsman,color=quadrant)) + geom_point() + xlab("Runs") + ylab("Strike rate") + geom_vline(xintercept = x_lower,linetype="dashed") + # plot vertical line geom_hline(yintercept = y_lower,linetype="dashed") + # plot horizontal line ggtitle(plot.title) } else if(plot == 2){ #ggplotly g <- c %>% mutate(quadrant = case_when(meanRuns > x_lower & meanSR > y_lower ~ "Q1", meanRuns <= x_lower & meanSR > y_lower ~ "Q2", meanRuns <= x_lower & meanSR <= y_lower ~ "Q3", TRUE ~ "Q4")) %>% ggplot(aes(meanRuns,meanSR,color=quadrant)) + geom_text(aes(meanRuns,meanSR,label=batsman,color=quadrant)) + geom_point() + xlab("Runs") + ylab("Strike rate") + geom_vline(xintercept = x_lower,linetype="dashed") + # plot vertical line geom_hline(yintercept = y_lower,linetype="dashed") + # plot horizontal line ggtitle(plot.title) ggplotly(g) } }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/overallRunsSRPlotT20.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 27 Nov 2021 # Function: overallWicketsERDeathOversPlotT20 # This function plots Wickets vs ER in Death overs of Intl. T20 batsmen # # ########################################################################################### #' @title #' Plot the Wickets vs ER in death overs of Intl. T20 batsmen #' #' @description #' Wickets vs ER in death overs of Intl. T20 batsmen #' #' @usage #' overallWicketsERDeathOversPlotT20(dir=".", dateRange,type="IPL",plot=1) #' #' @param dir #' The input directory #' #' #' @param dateRange #' Date interval to consider #' #' @param type #' T20 league #' #' @param plot #' plot=1 (static),plot=2(interactive), plot=3 (table) #' #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' @examples #' \dontrun{ #' overallWicketsERDeathOversPlotT20(dir=".", dateRange,type="IPL",plot=1) #' } #' #' @seealso #' \code{\link{rankODIBowlers}}\cr #' \code{\link{rankODIBatsmen}}\cr #' \code{\link{rankT20Bowlers}}\cr #' @export #' overallWicketsERDeathOversPlotT20 <- function(dir=".", dateRange,type="IPL",plot=1) { team=ball=totalRuns=total=wickets=wicketsPowerPlay=wicketsMiddleOvers=wicketsDeathOvers=bowler=str_extract=NULL ggplotly=wicketPlayerOut=quantile=quadrant=t20MDF=ERDeathOvers=NULL fl <- paste(dir,"/",type,"-MatchesDataFrame.RData",sep="") load(fl) # Filter by date range df=t20MDF %>% filter(date >= dateRange[1] & date <= dateRange[2]) # Death overs a1 <- df %>% filter(between(as.numeric(str_extract(ball, "\\d+(\\.\\d+)?$")), 16.1, 20.0)) a2 <- select(a1,date,bowler,wicketPlayerOut) a3 <- a2 %>% group_by(bowler,date) %>% filter(wicketPlayerOut != "nobody") %>% mutate(wickets =n()) a4 <- a3 %>% select(date,bowler,wickets) %>% distinct(date,bowler,wickets) %>% group_by(bowler) %>% summarise(wicketsDeathOvers=sum(wickets)) a21 <- select(a1,team,bowler,date,totalRuns) a31 <- a21 %>% group_by(bowler) %>% summarise(total=sum(totalRuns),count=n(), ERDeathOvers=total/count *6) a41 <- a31 %>% select(bowler,ERDeathOvers) a42=inner_join(a4,a41,by="bowler") x_lower <- quantile(a42$wicketsDeathOvers,p=0.66,na.rm = TRUE) y_lower <- quantile(a42$ERDeathOvers,p=0.66,na.rm = TRUE) plot.title <- paste("Overall Wickets vs ER in Death overs in ",type,sep="") if(plot == 1){ #ggplot2 a42 %>% mutate(quadrant = case_when(wicketsDeathOvers > x_lower & ERDeathOvers > y_lower ~ "Q1", wicketsDeathOvers <= x_lower & ERDeathOvers > y_lower ~ "Q2", wicketsDeathOvers <= x_lower & ERDeathOvers <= y_lower ~ "Q3", TRUE ~ "Q4")) %>% ggplot(aes(wicketsDeathOvers,ERDeathOvers,color=quadrant)) + geom_text(aes(wicketsDeathOvers,ERDeathOvers,label=bowler,color=quadrant)) + geom_point() + xlab("Wickets - Death overs") + ylab("Economy rate - Death overs") + geom_vline(xintercept = x_lower,linetype="dashed") + # plot vertical line geom_hline(yintercept = y_lower,linetype="dashed") + # plot horizontal line ggtitle(plot.title) } else if(plot == 2){ #ggplotly g <- a42 %>% mutate(quadrant = case_when(wicketsDeathOvers > x_lower & ERDeathOvers > y_lower ~ "Q1", wicketsDeathOvers <= x_lower & ERDeathOvers > y_lower ~ "Q2", wicketsDeathOvers <= x_lower & ERDeathOvers <= y_lower ~ "Q3", TRUE ~ "Q4")) %>% ggplot(aes(wicketsDeathOvers,ERDeathOvers,color=quadrant)) + geom_text(aes(wicketsDeathOvers,ERDeathOvers,label=bowler,color=quadrant)) + geom_point() + xlab("Wickets - Death overs") + ylab("Economy rate - Death overs") + geom_vline(xintercept = x_lower,linetype="dashed") + # plot vertical line geom_hline(yintercept = y_lower,linetype="dashed") + # plot horizontal line ggtitle(plot.title) ggplotly(g) } }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/overallWicketsERDeathOversPlotT20.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 27 Nov 2021 # Function: overallWicketsERMiddleOversPlotT20 # This function plots Wickets vs ER in power play of Intl. T20 batsmen # # ########################################################################################### #' @title #' Plot the Wickets vs ER in middle overs of Intl. T20 batsmen #' #' @description #' Wickets vs ER in middle overs of Intl. T20 batsmen #' #' @usage #' overallWicketsERMiddleOversPlotT20(dir=".", dateRange,type="IPL",plot=1) #' #' @param dir #' The input directory #' #' #' @param dateRange #' Date interval to consider #' #' @param type #' T20 league #' #' @param plot #' plot=1 (static),plot=2(interactive), plot=3 (table) #' #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' @examples #' \dontrun{ #' overallWicketsERMiddleOversPlotT20(dir=".", dateRange,type="IPL",plot=1) #' } #' #' @seealso #' \code{\link{rankODIBowlers}}\cr #' \code{\link{rankODIBatsmen}}\cr #' \code{\link{rankT20Bowlers}}\cr #' @export #' overallWicketsERMiddleOversPlotT20 <- function(dir=".", dateRange,type="IPL",plot=1) { team=ball=totalRuns=total=wickets=wicketsPowerPlay=wicketsMiddleOvers=wicketsDeathOvers=bowler=str_extract=NULL ggplotly=wicketPlayerOut=quantile=quadrant=t20MDF=ERMiddleOvers=NULL fl <- paste(dir,"/",type,"-MatchesDataFrame.RData",sep="") load(fl) # Filter by date range df=t20MDF %>% filter(date >= dateRange[1] & date <= dateRange[2]) # Middle overs a1 <- df %>% filter(between(as.numeric(str_extract(ball, "\\d+(\\.\\d+)?$")), 6.1, 15.9)) a2 <- select(a1,date,bowler,wicketPlayerOut) a3 <- a2 %>% group_by(bowler,date) %>% filter(wicketPlayerOut != "nobody") %>% mutate(wickets =n()) a4 <- a3 %>% select(date,bowler,wickets) %>% distinct(date,bowler,wickets) %>% group_by(bowler) %>% summarise(wicketsMiddleOvers=sum(wickets)) a21 <- select(a1,team,bowler,date,totalRuns) a31 <- a21 %>% group_by(bowler) %>% summarise(total=sum(totalRuns),count=n(), ERMiddleOvers=total/count *6) a41 <- a31 %>% select(bowler,ERMiddleOvers) a42=inner_join(a4,a41,by="bowler") x_lower <- 1/2 * min(a42$wicketsMiddleOvers + max(a42$wicketsMiddleOvers)) y_lower <- 1/2 * min(a42$ERMiddleOvers + max(a42$ERMiddleOvers)) plot.title <- paste("Overall Wickets vs ER in Middle overs in ",type,sep="") if(plot == 1){ #ggplot2 a42 %>% mutate(quadrant = case_when(wicketsMiddleOvers > x_lower & ERMiddleOvers > y_lower ~ "Q1", wicketsMiddleOvers <= x_lower & ERMiddleOvers > y_lower ~ "Q2", wicketsMiddleOvers <= x_lower & ERMiddleOvers <= y_lower ~ "Q3", TRUE ~ "Q4")) %>% ggplot(aes(wicketsMiddleOvers,ERMiddleOvers,color=quadrant)) + geom_text(aes(wicketsMiddleOvers,ERMiddleOvers,label=bowler,color=quadrant)) + geom_point() + xlab("Wickets - Middle overs") + ylab("Economy rate - Middle overs") + geom_vline(xintercept = x_lower,linetype="dashed") + # plot vertical line geom_hline(yintercept = y_lower,linetype="dashed") + # plot horizontal line ggtitle(plot.title) } else if(plot == 2){ #ggplotly g <- a42 %>% mutate(quadrant = case_when(wicketsMiddleOvers > x_lower & ERMiddleOvers > y_lower ~ "Q1", wicketsMiddleOvers <= x_lower & ERMiddleOvers > y_lower ~ "Q2", wicketsMiddleOvers <= x_lower & ERMiddleOvers <= y_lower ~ "Q3", TRUE ~ "Q4")) %>% ggplot(aes(wicketsMiddleOvers,ERMiddleOvers,color=quadrant)) + geom_text(aes(wicketsMiddleOvers,ERMiddleOvers,label=bowler,color=quadrant)) + geom_point() + xlab("Wickets - Middle overs") + ylab("Economy rate - Middle overs") + geom_vline(xintercept = x_lower,linetype="dashed") + # plot vertical line geom_hline(yintercept = y_lower,linetype="dashed") + # plot horizontal line ggtitle(plot.title) ggplotly(g) } }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/overallWicketsERMiddleOversPlotT20.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 26 Nov 2021 # Function: overallWicketsERPlotT20 # This function plots the overall wickets vs ER in T20 men # ########################################################################################### #' @title #' Ranks the T20 bowlers #' #' @description #' This function plots the overall wickets vs ER in T20 men #' #' @usage #' overallWicketsERPlotT20(dir=".",minMatches, dateRange,type="IPL",plot=1) #' #' #' @param dir #' The input directory #' #' @param minMatches #' Minimum matches played #' #' @param dateRange #' Date interval to consider #' #' @param type #' T20 league #' #' @param plot #' plot=1 (static),plot=2(interactive), plot=3 (table) #' #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' #'@examples #' \dontrun{ #' overallWicketsERPlotT20(dir=".",minMatches, dateRange,type="IPL",plot=1) #' } #' #' @seealso #' \code{\link{rankODIBowlers}}\cr #' \code{\link{rankODIBatsmen}}\cr #' \code{\link{rankT20Batsmen}}\cr #' \code{\link{rankT20Bowlers}}\cr #' @export #' overallWicketsERPlotT20 <- function(dir=".",minMatches, dateRange,type="IPL",plot=1) { bowlingDetails=bowler=wickets=economyRate=matches=meanWickets=meanER=totalWickets=year=NULL wicketPlayerOut=opposition=venue=quantile=quadrant=bowlingDF=ggplotly=NULL currDir= getwd() bowlingDF<-NULL setwd(dir) bowlingDF<-NULL bowlingDetails <- paste(type,"-BowlingDetails.RData",sep="") print(bowlingDetails) load(bowlingDetails) print(dim(bowlingDF)) # Note: If the date Range is NULL setback to root directory tryCatch({ df=bowlingDF %>% filter(date >= dateRange[1] & date <= dateRange[2]) }, warning=function(war) { print(paste("NULL values: ", war)) }, error=function(err) { # Change to root directory on error setwd(currDir) cat("Back to root",getwd(),"\n") }) # Compute number of matches played a=df %>% select(bowler,date) %>% unique() b=summarise(group_by(a,bowler),matches=n()) # Compute wickets c <- filter(df,wicketPlayerOut != "nobody") d <- select(c,bowler,wicketPlayerOut,economyRate,date,opposition,venue) e <- summarise(group_by(d,bowler,date,economyRate),wickets=length(unique(wicketPlayerOut))) f=summarise(group_by(e,bowler), totalWickets=sum(wickets),meanER=mean(economyRate)) # Join g=merge(b,f,by="bowler",all.x = TRUE) g[is.na(g)] <- 0 h <- filter(g,matches >= minMatches) setwd(currDir) x_lower <- quantile(h$totalWickets,p=0.66,na.rm = TRUE) y_lower <- quantile(h$meanER,p=0.66,na.rm = TRUE) plot.title <- paste("Overall Wickets vs ER in ",type,sep="") if(plot == 1){ #ggplot2 h %>% mutate(quadrant = case_when(totalWickets > x_lower & meanER > y_lower ~ "Q1", totalWickets <= x_lower & meanER > y_lower ~ "Q2", totalWickets <= x_lower & meanER <= y_lower ~ "Q3", TRUE ~ "Q4")) %>% ggplot(aes(totalWickets,meanER,color=quadrant)) + geom_text(aes(totalWickets,meanER,label=bowler,color=quadrant)) + geom_point() + xlab("Wickets") + ylab("Economy rate") + geom_vline(xintercept = x_lower,linetype="dashed") + # plot vertical line geom_hline(yintercept = y_lower,linetype="dashed") + # plot horizontal line ggtitle(plot.title) } else if(plot == 2){ #ggplotly g <- h %>% mutate(quadrant = case_when(totalWickets > x_lower & meanER > y_lower ~ "Q1", totalWickets <= x_lower & meanER > y_lower ~ "Q2", totalWickets <= x_lower & meanER <= y_lower ~ "Q3", TRUE ~ "Q4")) %>% ggplot(aes(totalWickets,meanER,color=quadrant)) + geom_text(aes(totalWickets,meanER,label=bowler,color=quadrant)) + geom_point() + xlab("Wickets") + ylab("Economy rate") + geom_vline(xintercept = x_lower,linetype="dashed") + # plot vertical line geom_hline(yintercept = y_lower,linetype="dashed") + # plot horizontal line ggtitle(plot.title) ggplotly(g) } }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/overallWicketsERPlotT20.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 27 Nov 2021 # Function: overallWicketsERPowerPlayPlotT20 # This function plots Wickets vs ER in power play of Intl. T20 batsmen # # ########################################################################################### #' @title #' Plot the Wickets vs ER in power play of Intl. T20 batsmen #' #' @description #' Wickets vs ER in power play of Intl. T20 batsmen #' #' @usage #' overallWicketsERPowerPlayPlotT20(dir=".", dateRange,type="IPL",plot=1) #' #' @param dir #' The input directory #' #' #' @param dateRange #' Date interval to consider #' #' @param type #' T20 league #' #' @param plot #' plot=1 (static),plot=2(interactive), plot=3 (table) #' #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' @examples #' \dontrun{ #' overallWicketsERPowerPlayPlotT20(dir=".", dateRange,type="IPL",plot=1) #' } #' #' @seealso #' \code{\link{rankODIBowlers}}\cr #' \code{\link{rankODIBatsmen}}\cr #' \code{\link{rankT20Bowlers}}\cr #' @export #' overallWicketsERPowerPlayPlotT20 <- function(dir=".", dateRange,type="IPL",plot=1) { team=ball=totalRuns=total=wickets=wicketsPowerPlay=bowler=str_extract=NULL ggplotly=wicketPlayerOut=t20MDF=ERPowerPlay=quantile=quadrant=t20MDF=ERMiddleOvers=NULL fl <- paste(dir,"/",type,"-MatchesDataFrame.RData",sep="") load(fl) df=t20MDF %>% filter(date >= dateRange[1] & date <= dateRange[2]) # Power play a1 <- df %>% filter(between(as.numeric(str_extract(ball, "\\d+(\\.\\d+)?$")), 0.1, 5.9)) a2 <- select(a1,date,bowler,wicketPlayerOut) a3 <- a2 %>% group_by(bowler,date) %>% filter(wicketPlayerOut != "nobody") %>% mutate(wickets =n()) a4 <- a3 %>% select(date,bowler,wickets) %>% distinct(date,bowler,wickets) %>% group_by(bowler) %>% summarise(wicketsPowerPlay=sum(wickets)) a21 <- select(a1,team,bowler,date,totalRuns) a31 <- a21 %>% group_by(bowler) %>% summarise(total=sum(totalRuns),count=n(), ERPowerPlay=total/count *6) a41 <- a31 %>% select(bowler,ERPowerPlay) a42=inner_join(a4,a41,by="bowler") x_lower <- 1/2 * min(a42$wicketsPowerPlay + max(a42$wicketsPowerPlay)) y_lower <- 1/2 * min(a42$ERPowerPlay + max(a42$ERPowerPlay)) plot.title <- paste("Overall Wickets vs ER in Power play in ",type,sep="") if(plot == 1){ #ggplot2 a42 %>% mutate(quadrant = case_when(wicketsPowerPlay > x_lower & ERPowerPlay > y_lower ~ "Q1", wicketsPowerPlay <= x_lower & ERPowerPlay > y_lower ~ "Q2", wicketsPowerPlay <= x_lower & ERPowerPlay <= y_lower ~ "Q3", TRUE ~ "Q4")) %>% ggplot(aes(wicketsPowerPlay,ERPowerPlay,color=quadrant)) + geom_text(aes(wicketsPowerPlay,ERPowerPlay,label=bowler,color=quadrant)) + geom_point() + xlab("Wickets - Power play") + ylab("Economy rate - Power play") + geom_vline(xintercept = x_lower,linetype="dashed") + # plot vertical line geom_hline(yintercept = y_lower,linetype="dashed") + # plot horizontal line ggtitle(plot.title) } else if(plot == 2){ #ggplotly g <- a42 %>% mutate(quadrant = case_when(wicketsPowerPlay > x_lower & ERPowerPlay > y_lower ~ "Q1", wicketsPowerPlay <= x_lower & ERPowerPlay > y_lower ~ "Q2", wicketsPowerPlay <= x_lower & ERPowerPlay <= y_lower ~ "Q3", TRUE ~ "Q4")) %>% ggplot(aes(wicketsPowerPlay,ERPowerPlay,color=quadrant)) + geom_text(aes(wicketsPowerPlay,ERPowerPlay,label=bowler,color=quadrant)) + geom_point() + xlab("Wickets - Power play") + ylab("Economy rate - Power play") + geom_vline(xintercept = x_lower,linetype="dashed") + # plot vertical line geom_hline(yintercept = y_lower,linetype="dashed") + # plot horizontal line ggtitle(plot.title) ggplotly(g) } }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/overallWicketsERPowerPlayPlotT20.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 2 May 2020 # Function: parseYamlOver # This function converts a given yaml file to a dataframe delivery by delivery. # ########################################################################################### #' @title #' Parse yaml file and convert to dataframe #' #' @description #' This function parses the yaml file and converts it into a data frame. This is an internal function and #' is used by convertAllYaml2RDataframes() & convertYaml2RDataframe() #' #' @usage #' parseYamlOver(match,s,ateam,delivery,meta) #' #' @param match #' The dataframe of the match #' #' @param s #' The string with the delivery #' #' @param ateam #' The team #' #' #' @param delivery #' The delivery of the over #' #' @param meta #' The meta information of the match #' #' @return overs #' The dataframe of overs #' #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' #' #' @author #' Tinniam V Ganesh #' #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' @examples #' \dontrun{ #' # Parse the yaml over #' } #' #' @seealso #' \code{\link{getBatsmanDetails}}\cr #' \code{\link{getBowlerWicketDetails}}\cr #' \code{\link{batsmanDismissals}}\cr #' \code{\link{getTeamBattingDetails}}\cr #' #' #' parseYamlOver <- function(match,s,ateam,delivery,meta) { team=ball=totalRuns=rnames=batsman=bowler=nonStriker=NULL byes=legbyes=noballs=wides=nonBoundary=penalty=runs=NULL extras=wicketFielder=wicketKind=wicketPlayerOut=NULL gt9=FALSE print("new code") # Create an empty data frame overs <- data.frame(ball=character(),team=character(),batsman=character(), bowler=character(),nonStriker=character(),byes=character(), legbyes=character(), noballs=character(), wides=character(), nonBoundary=character(), penalty=character(), runs=character(),extras=character(),totalRuns=character(), wicketFielder=character(), wicketKind=character(), wicketPlayerOut=character(),replacementIn=factor(), replacementOut=character(),replacementReason=character(),replacementTeam=character(), date=character(), matchType=character(), overs=character(),venue=character(),team1=character(),team2=character(), winner=character(),result=character()) # Loop through all deliveries one by one. for(i in 1:length(delivery)){ #cat("i=",i,"\n") # Debug # Filter rows based on the delivery(ball) as overset # Note if an over has more than 10 deliveries then the deliveries are # 1st.0,1.batsman, 1st.0.2.batsman,..., 1st.0.9.batsman, 1st.0.1.batsman.1, # 1st.0.1.batsman.2 and so on. #filter(match,grepl("1st.0.1.\\D*$",rnames)) #1 1st.0.1.batsman Shahzaib Hasan #2 1st.0.1.bowler JA Morkel #3 1st.0.1.non_striker Imran Farhat #4 1st.0.1.runs.batsman 1 #5 1st.0.1.runs.extras 0 #6 1st.0.1.runs.total 1 #filter(match,grepl("1st.0.1.\\D*.\\d{1}$",rnames)) #1 1st.0.1.batsman.1 Imran Farhat #2 1st.0.1.bowler.1 JA Morkel #3 1st.0.1.non_striker.1 Shahzaib Hasan #4 1st.0.1.runs.batsman.1 1 #5 1st.0.1.runs.extras.1 0 #6 1st.0.1.runs.total.1 1 # Assume in the worst case there are 15 deliveries # Compute delivery del <- i %% 15 # Assuming max of 15 deliveries # For deliveries 1-9 if((del >=1) && (del<= 9)){ pattern = paste(s[i],"\\D*$",sep="") } else if(del > 9){ # deliveries 10-15 # Find increment above 9 gt9=TRUE inc <- del -9 # Use pattern with suffix .1,.2,.3 etc pattern = paste(s[i],"\\D*.","[",inc,"]$",sep="") } overset <- filter(match,grepl(pattern,rnames)) #Transpose over <-as.data.frame(t(overset)) # Set column names from 1st row names(over) <- lapply(over[1, ], as.character) # Remove 1st row over <- over[-1, ] names(over)=gsub(s[i],"",names(over)) #If the over had more than 9 balls then the suffix *.1,*.2 have to be removed also if(gt9){ val = paste(".",inc,sep="") names(over)=gsub(val,"",names(over)) } #Check the number of deliveries in the over d <- dim(over) if(d[2] == 0){ next } else if(d[2] >=10){ print("Greater than equal to 10 cols!") #print(d) #print(names(over)) #break } #Replace extras. with "" for the extras before doing diff - Added 27 Oct 2021 names(over)=gsub("extras\\.","",names(over)) cols<-names(over) cols1=c("batsman","bowler","non_striker","byes","legbyes","noballs","wides","runs.non_boundary","penalty", "runs.batsman","runs.extras","runs.total","wicket.fielders","wicket.kind","wicket.player_out", "replacements.match.in", "replacements.match.out","replacements.match.team","replacements.match.reason") # Get the missing columns a <- setdiff(cols1,cols) if(length(a) != (length(cols1) - length(cols))){ print("New columns added") break } # Create a dataframe with the missing columns over1=data.frame(rbind(a)) # Set column names names(over1) <- lapply(over1[1, ], as.character) over1 <- over1[-1, ] over1 <- data.frame(lapply(over1, as.character), stringsAsFactors=FALSE) over1[1,] <- rep(0,times=length(a)) newover <- cbind(over,over1) newover$ball=gsub("\\\\.","",s[i]) newover$team = ateam newover <- cbind(newover,meta) # Convert all columns to character newover <- data.frame(lapply(newover, as.character), stringsAsFactors=FALSE) # Stack the overs overs <- rbind(overs,newover) } overs }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/parseYamlOver.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 24 Apr 2021 # Function: plotWinLossBetweenTeams # This function computes and plots number of wins for each team # ########################################################################################### #' @title #' Plot wins for each team #' #' @description #' This function computes and plots number of wins for each team in all their #' encounters. The plot includes the number of wins byteam1 each team and the matches #' with no result #' #' @usage #' plotWinLossBetweenTeams(team1,team2,dir=".",dateRange, plot=1) #' #' @param team1 #' The 1st team #' #' @param team2 #' The 2nd team #' #' @param dir #' The source directory of teh RData files #' #' @param dateRange #' Date Range #' #' @param plot #' plot=1 (static),plot=2(interactive) #' #' @return None #' #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' @examples #' \dontrun{ #' #' plotWinLossBetweenTeams(team1="India",team2="Australia",dir=pathToFile) #' batsmanDismissals(kohli,"Kohli") #' } #' @seealso #' \code{\link{batsmanFoursSixes}}\cr #' \code{\link{batsmanRunsVsDeliveries}}\cr #' \code{\link{batsmanRunsVsStrikeRate}}\cr #' #' #' @export #' plotWinLossBetweenTeams <- function(team1,team2,dir=".",dateRange,plot=1){ matches=NULL ggplotly=NULL venue=winner=result=date=NULL # Create 2 filenames with both combinations of team1 and team2 d1 <-paste(team1,"-",team2,"-allMatches.RData",sep="") fl1 <- paste(dir,"/",d1,sep="") load(fl1) # FIlter matches in date Range print(dim(matches)) print(as.Date(dateRange[1])) print(as.Date(dateRange[2])) matches=matches %>% filter(date >= dateRange[1] & date <= dateRange[2]) print("b") print(dim(matches)) a <- select(matches,date,venue,winner,result) b=distinct(a) #Get distinct rows winLoss <- summarise(group_by(b,winner),count=n()) x <- winLoss$winner=="NA" winLoss$winner <- as.character(winLoss$winner) if(sum(x) !=0) { winLoss[x,]$winner <-"NoResult" } plot.title <- paste("Number of wins in",team1," vs ",team2, " matches") if(plot == 1){ #ggplot2 ggplot(winLoss, aes(x=winner, y=count, fill=winner))+ geom_bar(stat = "identity",position="dodge") + xlab("Winner") + ylab("Numer of Wins") + ggtitle(bquote(atop(.(plot.title), atop(italic("Data source:http://cricsheet.org/"),"")))) } else if(plot == 2 || plot == 3){ g <- ggplot(winLoss, aes(x=winner, y=count, fill=winner))+ geom_bar(stat = "identity",position="dodge") + xlab("Winner") + ylab("Numer of Wins") + ggtitle(plot.title) ggplotly(g) } }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/plotWinLossBetweenTeams.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 24 Apr 2021 # Function: plotWinLossTeamVsAllTeams # This function computes and plots number of wins for each team # ########################################################################################### #' @title #' Plot wins for each team #' #' @description #' This function computes and plots number of wins for a team against all #' other teams. The plot includes the number of wins by team each team and the matches #' with no result #' #' @usage #' plotWinLossTeamVsAllTeams(team1,dir=".",dateRange, plot=1) #' #' @param team1 #' The 1st team #' #' #' @param dir #' The source directory of the RData files #' #' @param dateRange #' Date Range #' #' @param plot #' plot=1 (static), plot=2(interactive) #' #' @return None #' #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' @examples #' \dontrun{ #' #' plotWinLossBetweenTeams(team1="India",team2="Australia",dir=pathToFile) #' batsmanDismissals(kohli,"Kohli") #' } #' @seealso #' \code{\link{batsmanFoursSixes}}\cr #' \code{\link{batsmanRunsVsDeliveries}}\cr #' \code{\link{batsmanRunsVsStrikeRate}}\cr #' #' #' @export #' plotWinLossTeamVsAllTeams <- function(team1,dir=".",dateRange, plot=1){ matches=NULL venue=winner=result=date=NULL ggplotly=NULL # Create 2 filenames with both combinations of team1 and team2 d1 <-paste("allMatchesAllOpposition-",team1,".RData",sep="") fl1 <- paste(dir,"/",d1,sep="") load(fl1) # FIlter matches in date Range print(dim(matches)) print(as.Date(dateRange[1])) print(as.Date(dateRange[2])) matches=matches %>% filter(date >= dateRange[1] & date <= dateRange[2]) print("b") print(dim(matches)) a <- select(matches,date,venue,winner,result) b=distinct(a) #Get distinct rows print("xxxxxxxxxxxxxxxxx") print(b) winLoss <- summarise(group_by(b,winner),count=n()) print("xxxxxxxxxxxxxxxxx") print(winLoss) x <- winLoss$winner=="NA" winLoss$winner <- as.character(winLoss$winner) if(sum(x) !=0) { winLoss[x,]$winner <-"Tie" } plot.title <- paste("Number of wins of",team1,"against all teams in all matches") if(plot == 1){ #ggplot2 ggplot(winLoss, aes(x=winner, y=count, fill=winner))+ geom_bar(stat = "identity",position="dodge") + xlab("Winner") + ylab("Numer of Wins") + ggtitle(bquote(atop(.(plot.title), atop(italic("Data source:http://cricsheet.org/"),"")))) + theme(axis.text.x = element_text(angle = 90, hjust = 1)) } else if(plot == 2 || plot == 3){ #ggplotly g <- ggplot(winLoss, aes(x=winner, y=count, fill=winner))+ geom_bar(stat = "identity",position="dodge") + xlab("Winner") + ylab("Numer of Wins") + ggtitle(plot.title) + theme(axis.text.x = element_text(angle = 90, hjust = 1)) ggplotly(g) } }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/plotWinLossTeamVsAllTeams.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 05 Jan 2021 # Function: rankODIBatsmen # This function ranks the batsmen # ########################################################################################### #' @title #' Ranks the ODI batsmen #' #' @description #' This function creates a single datframe of all ODI batsmen and then ranks them #' @usage #' rankODIBatsmen(dir='.',odir=".",minMatches=50) #' #' @param dir #' The input directory #' #' @param odir #' The output directory #' #' @param minMatches #' Minimum matches #' #' @return The ranked ODI batsmen #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' @examples #' \dontrun{ #' odiBatsmanRank <- rankODIBatsmen() #' } #' #' @seealso #' \code{\link{rankODIBowlers}}\cr #' \code{\link{rankT20Batsmen}}\cr #' \code{\link{rankT20Bowlers}}\cr #' @export #' rankODIBatsmen <- function(dir='.',odir=".",minMatches=50) { # This needs to be done once. After it is done, we can use the RData files currDir= getwd() battingDetails=batsman=runs=strikeRate=matches=meanRuns=meanSR=battingDF=val=NULL teams <-c("Australia","India","Pakistan","West Indies", 'Sri Lanka', "England", "Bangladesh","Netherlands","Scotland", "Afghanistan", "Zimbabwe","Ireland","New Zealand","South Africa","Canada", "Bermuda","Kenya","Hong Kong","Nepal","Oman","Papua New Guinea", "United Arab Emirates","Namibia","Cayman Islands","Singapore", "United States of America","Bhutan","Maldives","Botswana","Nigeria", "Denmark","Germany","Jersey","Norway","Qatar","Malaysia","Vanuatu", "Thailand") #Change dir setwd(odir) battingDF<-NULL for(team in teams){ battingDetails <- NULL val <- paste(team,"-BattingDetails.RData",sep="") print(val) tryCatch(load(val), error = function(e) { print("No data1") setNext=TRUE } ) details <- battingDetails battingDF <- rbind(battingDF,details) } df <- select(battingDF,batsman,runs,strikeRate) b=summarise(group_by(df,batsman),matches=n(), meanRuns=mean(runs),meanSR=mean(strikeRate)) b[is.na(b)] <- 0 # Reset to currDir setwd(currDir) # Select only players based on minMatches c <- filter(b,matches >= minMatches) ODIBatsmenRank <- arrange(c,desc(meanRuns),desc(meanSR)) ODIBatsmenRank }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/rankODIBatsmen.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 05 Jan 2021 # Function: rankODIBowlers # This function ranks the bowlers # # ########################################################################################### #' @title #' Ranks the ODI bowlers #' #' @description #' This function creates a single datframe of all ODI bowlers and then ranks them #' @usage #' rankODIBowlers(dir=".",odir=".",minMatches=20) #' #' @param dir #' The input directory #' #' @param odir #' The output directory #' #' @param minMatches #' Minimum matches #' #' #' @return The ranked ODI bowlers #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' @examples #' \dontrun{ #' # #' odiBowlersRank <- rankODIBowlers() #' } #' #' @seealso #' \code{\link{rankODIBatsmen}}\cr #' \code{\link{rankT20Batsmen}}\cr #' @export #' rankODIBowlers <- function(dir='.',odir=".",minMatches=20) { bowlingDetails=bowler=wickets=economyRate=matches=meanWickets=meanER=totalWickets=NULL wicketPlayerOut=opposition=venue=NULL currDir= getwd() teams <-c("Australia","India","Pakistan","West Indies", 'Sri Lanka', "England", "Bangladesh","Netherlands","Scotland", "Afghanistan", "Zimbabwe","Ireland","New Zealand","South Africa","Canada", "Bermuda","Kenya","Hong Kong","Nepal","Oman","Papua New Guinea", "United Arab Emirates","Namibia","Cayman Islands","Singapore", "United States of America","Bhutan","Maldives","Botswana","Nigeria", "Denmark","Germany","Jersey","Norway","Qatar","Malaysia","Vanuatu", "Thailand") #Change dir setwd(odir) # Compute wickets by bowler in each team o <- data.frame(bowler=character(0),wickets=numeric(0),economyRate=numeric(0)) for(team1 in teams){ bowlingDetails <- NULL val <- paste(team1,"-BowlingDetails.RData",sep="") print(val) tryCatch(load(val), error = function(e) { print("No data1") setNext=TRUE } ) details <- bowlingDetails bowlingDF <- rbind(bowlingDF,details) } # Compute number of matches played a=bowlingDF %>% select(bowler,date) %>% unique() b=summarise(group_by(a,bowler),matches=n()) # Compute wickets c <- filter(bowlingDF,wicketPlayerOut != "nobody") d <- select(c,bowler,wicketPlayerOut,economyRate,date,opposition,venue) e <- summarise(group_by(d,bowler,date,economyRate),wickets=length(unique(wicketPlayerOut))) f=summarise(group_by(e,bowler), totalWickets=sum(wickets),meanER=mean(economyRate)) # Join g=merge(b,f,by="bowler",all.x = TRUE) g[is.na(g)] <- 0 h <- filter(g,matches >= minMatches) setwd(currDir) ODIBowlersRank <- arrange(h,desc(totalWickets),desc(meanER)) ODIBowlersRank <- distinct(ODIBowlersRank) ODIBowlersRank }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/rankODIBowlers.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 05 Jan 2021 # Function: rankT20Batsmen # This function ranks the T20 batsmen # # ########################################################################################### #' @title #' Ranks the T20 batsmen #' #' @description #' This function creates a single datframe of all T20 batsmen and then ranks them #' @usage #' rankT20Batsmen(dir=".",minMatches, dateRange, runsvsSR,type) #' #' #' @param dir #' The input directory #' #' @param minMatches #' Minimum matches played #' #' @param dateRange #' Date interval to consider #' #' @param runsvsSR #' Runs or Strike rate #' #' @param type #' T20 format #' #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' @examples #' \dontrun{ #' rankT20Batsmen(dir=".",minMatches, dateRange, runsvsSR,type) #' } #' #' @seealso #' \code{\link{rankODIBowlers}}\cr #' \code{\link{rankODIBatsmen}}\cr #' \code{\link{rankT20Bowlers}}\cr #' @export #' rankT20Batsmen <- function(dir=".",minMatches, dateRange, runsvsSR,type) { cat("Entering rank Batsmen1 \n") currDir= getwd() cat("T20batman dir=",currDir,"\n") battingDetails=batsman=runs=strikeRate=matches=meanRuns=meanSR=battingDF=val=year=NULL cat("dir=",dir) setwd(dir) battingDF<-NULL battingDetails <- paste(type,"-BattingDetails.RData",sep="") print(battingDetails) load(battingDetails) print(dim(battingDF)) print(names(battingDF)) # Note: If the date Range is NULL setback to root directory tryCatch({ df=battingDF %>% filter(date >= dateRange[1] & date <= dateRange[2]) }, warning=function(war) { print(paste("NULL values: ", war)) }, error=function(err) { # Change to root directory on error setwd(currDir) cat("Back to root",getwd(),"\n") }) df1 <- select(df,batsman,runs,strikeRate) df1 <- distinct(df1) b=summarise(group_by(df1,batsman),matches=n(), meanRuns=mean(runs),meanSR=mean(strikeRate)) print(dim(b)) b[is.na(b)] <- 0 c <- filter(b,matches >= minMatches) # Reset to currDir setwd(currDir) if(runsvsSR == "Runs over Strike rate"){ T20BatsmenRank <- arrange(c,desc(meanRuns),desc(meanSR)) } else if (runsvsSR == "Strike rate over Runs"){ T20BatsmenRank <- arrange(c,desc(meanSR),desc(meanRuns)) } T20BatsmenRank }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/rankT20Batsmen.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 28 Jan 2021 # Function: rankT20Bowlers # This function ranks the t20 bowlers # ########################################################################################### #' @title #' Ranks the T20 bowlers #' #' @description #' This function creates a single datframe of all T20 bowlers and then ranks them #' #' @usage #' rankT20Bowlers(dir=".",minMatches, dateRange, wicketsVsER,type) #' #' #' @param dir #' The directory #' #' @param minMatches #' Minimum matches played #' #' @param dateRange #' Date interval to consider #' #' @param wicketsVsER #' Wickets or economy rate #' #' @param type #' T20 format #' #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' #'@examples #' \dontrun{ #' rankT20Bowlers(dir=".",minMatches, dateRange, wicketsVsER,type) #' } #' #' @seealso #' \code{\link{rankODIBowlers}}\cr #' \code{\link{rankODIBatsmen}}\cr #' \code{\link{rankT20Batsmen}}\cr #' \code{\link{rankT20Bowlers}}\cr #' @export #' rankT20Bowlers <- function(dir=".",minMatches, dateRange, wicketsVsER,type) { bowlingDetails=bowler=wickets=economyRate=matches=meanWickets=meanER=totalWickets=year=NULL wicketPlayerOut=opposition=venue=NULL currDir= getwd() #Change dir setwd(dir) bowlingDF<-NULL print("*******") print(type) bowlingDetails <- paste(type,"-BowlingDetails.RData",sep="") print(bowlingDetails) load(bowlingDetails) print(dim(bowlingDF)) # Note: If the date Range is NULL setback to root directory tryCatch({ df=bowlingDF %>% filter(date >= dateRange[1] & date <= dateRange[2]) }, warning=function(war) { print(paste("NULL values: ", war)) }, error=function(err) { # Change to root directory on error setwd(currDir) cat("Back to root",getwd(),"\n") }) # Compute number of matches played a=df %>% select(bowler,date) %>% unique() b=summarise(group_by(a,bowler),matches=n()) # Compute wickets c <- filter(df,wicketPlayerOut != "nobody") d <- select(c,bowler,wicketPlayerOut,economyRate,date,opposition,venue) e <- summarise(group_by(d,bowler,date,economyRate),wickets=length(unique(wicketPlayerOut))) f=summarise(group_by(e,bowler), totalWickets=sum(wickets),meanER=mean(economyRate)) # Join g=merge(b,f,by="bowler",all.x = TRUE) g[is.na(g)] <- 0 h <- filter(g,matches >= minMatches) # Reset to currDir setwd(currDir) if(wicketsVsER == "Wickets over Economy rate"){ T20BowlersRank <- arrange(h,desc(totalWickets),desc(meanER)) } else if(wicketsVsER == "Economy rate over Wickets"){ T20BowlersRank <- arrange(h,meanER,desc(totalWickets)) } T20BowlersRank <- distinct(T20BowlersRank) T20BowlersRank }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/rankT20Bowlers.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 2 May 2020 # Function: saveAllMatchesAllOpposition # This function saves all matches between all opposition of a teams as a # single dataframe ################################################################################## #' @title #' Saves matches of all opposition as dataframe #' #' @description #' This function saves all matches agaist all opposition as a single dataframe in the #' current directory #' #' @param dir #' Input Directory #' #' @param odir #' Output Directory to store saved matches #' #' @usage #' saveAllMatchesAllOpposition(dir=".",odir=".") #' #' @return None #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' @examples #' \dontrun{ #' saveAllMatchesBetweenTeams(dir=".",odir=".") #' } #' @seealso #' \code{\link{batsmanDismissals}}\cr #' \code{\link{batsmanRunsVsDeliveries}}\cr #' \code{\link{batsmanRunsVsStrikeRate}}\cr #' \code{\link{getAllMatchesAllOpposition}}\cr #' \code{\link{getAllMatchesBetweenTeams}}\cr #' #' @export #' saveAllMatchesAllOpposition <- function(dir=".",odir=".") { teams <-c("Australia","India","Pakistan","West Indies", 'Sri Lanka', "England", "Bangladesh","Netherlands","Scotland", "Afghanistan", "Zimbabwe","Ireland","New Zealand","South Africa","Canada", "Bermuda","Kenya","Hong Kong","Nepal","Oman","Papua New Guinea", "United Arab Emirates","Namibia","Cayman Islands","Singapore", "United States of America","Bhutan","Maldives","Botswana","Nigeria", "Denmark","Germany","Jersey","Norway","Qatar","Malaysia","Vanuatu", "Thailand") matches <- NULL for(i in seq_along(teams)){ cat("Team1=",teams[i],"\n") tryCatch(matches <- getAllMatchesAllOpposition(teams[i],dir=dir,save=TRUE,odir=odir), error = function(e) { print("No matches") } ) matches <- NULL } }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/saveAllMatchesAllOpposition.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 11 May 2020 # Function: saveAllMatchesAllOppositionBBLT20 # This function saves all BBL matches between a team and all opposition as a # single dataframe ################################################################################## #' @title #' Saves matches against all BBL teams as dataframe for an BBL team #' #' @description #' This function saves all BBL matches agaist all opposition as a single dataframe in the #' output directory #' #' @usage #' saveAllMatchesAllOppositionBBLT20(dir=".",odir=".") #' #' @param dir #' Input Directory #' #' @param odir #' Output Directory #' #' @return None #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' @examples #' \dontrun{ #' saveAllMatchesAllOppositionT20 #' } #' @seealso #' \code{\link{batsmanDismissals}}\cr #' \code{\link{batsmanRunsVsDeliveries}}\cr #' \code{\link{batsmanRunsVsStrikeRate}}\cr #' \code{\link{getAllMatchesAllOpposition}}\cr #' \code{\link{getAllMatchesBetweenTeams}}\cr #' #' @export #' saveAllMatchesAllOppositionBBLT20 <- function(dir=".",odir=".") { teams <-c("Adelaide Strikers", "Brisbane Heat", "Hobart Hurricanes", "Melbourne Renegades", "Melbourne Stars", "Perth Scorchers", "Sydney Sixers", "Sydney Thunder") matches <- NULL for(i in seq_along(teams)){ cat("Team1=",teams[i],"\n") tryCatch(matches <- getAllMatchesAllOpposition(teams[i],dir=dir,save=TRUE,odir=odir), error = function(e) { print("No matches") } ) matches <- NULL } }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/saveAllMatchesAllOppositionBBLT20.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 26 Jan 2021 # Function: saveAllMatchesAllOppositionCPLT20 # This function saves all CPL matches between a team and all opposition as a # single dataframe ################################################################################## #' @title #' Saves matches against all CPL teams as dataframe for an CPL team #' #' @description #' This function saves all CPL matches agaist all opposition as a single dataframe in the #' output directory #' #' @usage #' saveAllMatchesAllOppositionCPLT20(dir=".",odir=".") #' #' @param dir #' Input Directory #' #' @param odir #' Output Directory #' #' @return None #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' @examples #' \dontrun{ #' saveAllMatchesAllOppositionT20 #' } #' @seealso #' \code{\link{batsmanDismissals}}\cr #' \code{\link{batsmanRunsVsDeliveries}}\cr #' \code{\link{batsmanRunsVsStrikeRate}}\cr #' \code{\link{getAllMatchesAllOpposition}}\cr #' \code{\link{getAllMatchesBetweenTeams}}\cr #' #' @export #' saveAllMatchesAllOppositionCPLT20 <- function(dir=".",odir=".") { teams <-c("Antigua Hawksbills","Barbados Tridents","Guyana Amazon Warriors","Jamaica Tallawahs", "St Kitts and Nevis Patriots","St Lucia Zouks","Trinbago Knight Riders") matches <- NULL for(i in seq_along(teams)){ cat("Team1=",teams[i],"\n") tryCatch(matches <- getAllMatchesAllOpposition(teams[i],dir=dir,save=TRUE,odir=odir), error = function(e) { print("No matches") } ) matches <- NULL } }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/saveAllMatchesAllOppositionCPLT20.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 2 May 2020 # Function: saveAllMatchesAllOppositionIPLT20 # This function saves all IPL matches between a team and all opposition as a # single dataframe ################################################################################## #' @title #' Saves matches against all IPL teams as dataframe for an IPL team #' #' @description #' This function saves all IPL matches agaist all opposition as a single dataframe in the #' output directory #' #' @usage #' saveAllMatchesAllOppositionIPLT20(dir=".",odir=".") #' #' @param dir #' Input Directory #' #' @param odir #' Output Directory #' #' @return None #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' @examples #' \dontrun{ #' saveAllMatchesAllOppositionT20 #' } #' @seealso #' \code{\link{batsmanDismissals}}\cr #' \code{\link{batsmanRunsVsDeliveries}}\cr #' \code{\link{batsmanRunsVsStrikeRate}}\cr #' \code{\link{getAllMatchesAllOpposition}}\cr #' \code{\link{getAllMatchesBetweenTeams}}\cr #' #' @export #' saveAllMatchesAllOppositionIPLT20 <- function(dir=".",odir=".") { teams <-c("Chennai Super Kings","Delhi Capitals","Deccan Chargers","Delhi Daredevils", "Kings XI Punjab","Punjab Kings", 'Kochi Tuskers Kerala',"Kolkata Knight Riders", "Mumbai Indians", "Pune Warriors","Rajasthan Royals", "Royal Challengers Bangalore","Sunrisers Hyderabad","Gujarat Lions", "Rising Pune Supergiants","Lucknow Super Giants","Gujarat Titans", "Royal Challengers Bengaluru") matches <- NULL for(i in seq_along(teams)){ cat("Team1=",teams[i],"\n") tryCatch(matches <- getAllMatchesAllOpposition(teams[i],dir=dir,save=TRUE,odir=odir), error = function(e) { print("No matches") } ) matches <- NULL } }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/saveAllMatchesAllOppositionIPLT20.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 11 May 2020 # Function: saveAllMatchesAllOppositionNTBT20 # This function saves all NTB matches between a team and all opposition as a # single dataframe ################################################################################## #' @title #' Saves matches against all NTB teams as dataframe for an NTB team #' #' @description #' This function saves all NTB matches agaist all opposition as a single dataframe in the #' output directory #' #' @usage #' saveAllMatchesAllOppositionNTBT20(dir=".",odir=".") #' #' @param dir #' Input Directory #' #' @param odir #' Output Directory #' #' @return None #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' @examples #' \dontrun{ #' saveAllMatchesAllOppositionT20 #' } #' @seealso #' \code{\link{batsmanDismissals}}\cr #' \code{\link{batsmanRunsVsDeliveries}}\cr #' \code{\link{batsmanRunsVsStrikeRate}}\cr #' \code{\link{getAllMatchesAllOpposition}}\cr #' \code{\link{getAllMatchesBetweenTeams}}\cr #' #' @export #' saveAllMatchesAllOppositionNTBT20 <- function(dir=".",odir=".") { teams <- c("Birmingham Bears","Derbyshire", "Durham", "Essex", "Glamorgan", "Gloucestershire", "Hampshire", "Kent","Lancashire", "Leicestershire", "Middlesex","Northamptonshire", "Nottinghamshire","Somerset","Surrey","Sussex","Warwickshire", "Worcestershire","Yorkshire") matches <- NULL for(i in seq_along(teams)){ cat("Team1=",teams[i],"\n") tryCatch(matches <- getAllMatchesAllOpposition(teams[i],dir=dir,save=TRUE,odir=odir), error = function(e) { print("No matches") } ) matches <- NULL } }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/saveAllMatchesAllOppositionNTBT20.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 11 May 2020 # Function: saveAllMatchesAllOppositionPSLT20 # This function saves all PSL matches between a team and all opposition as a # single dataframe ################################################################################## #' @title #' Saves matches against all PSL teams as dataframe for an PSL team #' #' @description #' This function saves all PSL matches agaist all opposition as a single dataframe in the #' output directory #' #' @usage #' saveAllMatchesAllOppositionPSLT20(dir=".",odir=".") #' #' @param dir #' Input Directory #' #' @param odir #' Output Directory #' #' @return None #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' @examples #' \dontrun{ #' saveAllMatchesAllOppositionT20 #' } #' @seealso #' \code{\link{batsmanDismissals}}\cr #' \code{\link{batsmanRunsVsDeliveries}}\cr #' \code{\link{batsmanRunsVsStrikeRate}}\cr #' \code{\link{getAllMatchesAllOpposition}}\cr #' \code{\link{getAllMatchesBetweenTeams}}\cr #' #' @export #' saveAllMatchesAllOppositionPSLT20 <- function(dir=".",odir=".") { teams <- c("Islamabad United","Karachi Kings", "Lahore Qalandars", "Multan Sultans", "Peshawar Zalmi", "Quetta Gladiators") matches <- NULL for(i in seq_along(teams)){ cat("Team1=",teams[i],"\n") tryCatch(matches <- getAllMatchesAllOpposition(teams[i],dir=dir,save=TRUE,odir=odir), error = function(e) { print("No matches") } ) matches <- NULL } }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/saveAllMatchesAllOppositionPSLT20.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 24 May 2021 # Function: saveAllMatchesAllOppositionSSMT20 # This function saves all SSM matches between a team and all opposition as a # single dataframe ################################################################################## #' @title #' Saves matches against all SSM teams as dataframe for an SSM team #' #' @description #' This function saves all SSM matches agaist all opposition as a single dataframe in the #' output directory #' #' @usage #' saveAllMatchesAllOppositionSSMT20(dir=".",odir=".") #' #' @param dir #' Input Directory #' #' @param odir #' Output Directory #' #' @return None #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' @examples #' \dontrun{ #' saveAllMatchesAllOppositionT20 #' } #' @seealso #' \code{\link{batsmanDismissals}}\cr #' \code{\link{batsmanRunsVsDeliveries}}\cr #' \code{\link{batsmanRunsVsStrikeRate}}\cr #' \code{\link{getAllMatchesAllOpposition}}\cr #' \code{\link{getAllMatchesBetweenTeams}}\cr #' #' @export #' saveAllMatchesAllOppositionSSMT20 <- function(dir=".",odir=".") { teams <-c("Auckland", "Canterbury", "Central Districts", "Northern Districts", "Otago", "Wellington") matches <- NULL for(i in seq_along(teams)){ cat("Team1=",teams[i],"\n") tryCatch(matches <- getAllMatchesAllOpposition(teams[i],dir=dir,save=TRUE,odir=odir), error = function(e) { print("No matches") } ) matches <- NULL } }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/saveAllMatchesAllOppositionSSMT20.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 11 May 2020 # Function: saveAllMatchesAllOppositionBBLT20 # This function saves all WBB matches between a team and all opposition as a # single dataframe ################################################################################## #' @title #' Saves matches against all WBB teams as dataframe for an WBB team #' #' @description #' This function saves all WBB matches agaist all opposition as a single dataframe in the #' output directory #' #' @usage #' saveAllMatchesAllOppositionWBBT20(dir=".",odir=".") #' #' @param dir #' Input Directory #' #' @param odir #' Output Directory #' #' @return None #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' @examples #' \dontrun{ #' saveAllMatchesAllOppositionT20 #' } #' @seealso #' \code{\link{batsmanDismissals}}\cr #' \code{\link{batsmanRunsVsDeliveries}}\cr #' \code{\link{batsmanRunsVsStrikeRate}}\cr #' \code{\link{getAllMatchesAllOpposition}}\cr #' \code{\link{getAllMatchesBetweenTeams}}\cr #' #' @export #' saveAllMatchesAllOppositionWBBT20 <- function(dir=".",odir=".") { teams <-c("Adelaide Strikers", "Brisbane Heat", "Hobart Hurricanes", "Melbourne Renegades", "Melbourne Stars", "Perth Scorchers", "Sydney Sixers", "Sydney Thunder") matches <- NULL for(i in seq_along(teams)){ cat("Team1=",teams[i],"\n") tryCatch(matches <- getAllMatchesAllOpposition(teams[i],dir=dir,save=TRUE,odir=odir), error = function(e) { print("No matches") } ) matches <- NULL } }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/saveAllMatchesAllOppositionWBBT20.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 11 May 2020 # Function: saveAllMatchesBetween2BBLTeams # This function saves all matches between 2 teams as a single dataframe ################################################################################## #' @title #' Saves all matches between 2 BBL teams as dataframe #' #' @description #' This function saves all matches between 2 BBL teams as a single dataframe in the #' current directory #' #' @usage #' saveAllMatchesBetween2BBLTeams(dir=".",odir=".") #' #' @param dir #' Input Directory #' #' @param odir #' Output Directory to store saved matches #' #' @return None #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' #' #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' @examples #' \dontrun{ #' saveAllMatchesBetween2BBLTeams(dir=".",odir=".") #' } #' @seealso #' \code{\link{batsmanDismissals}}\cr #' \code{\link{batsmanRunsVsDeliveries}}\cr #' \code{\link{batsmanRunsVsStrikeRate}}\cr #' \code{\link{getAllMatchesAllOpposition}}\cr #' \code{\link{getAllMatchesBetweenTeams}}\cr #' #' @export #' saveAllMatchesBetween2BBLTeams <- function(dir=".",odir="."){ teams <-c("Adelaide Strikers", "Brisbane Heat", "Hobart Hurricanes", "Melbourne Renegades", "Melbourne Stars", "Perth Scorchers", "Sydney Sixers", "Sydney Thunder") matches <- NULL #Create all combinations of teams for(i in seq_along(teams)){ for(j in seq_along(teams)){ if(teams[i] != teams[j]){ cat("Team1=",teams[i],"Team2=",teams[j],"\n") tryCatch(matches <- getAllMatchesBetweenTeams(teams[i],teams[j],dir=dir,save=TRUE,odir=odir), error = function(e) { print("No matches") } ) } } matches <- NULL } }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/saveAllMatchesBetween2BBLTeams.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 26 Jan 2021 # Function: saveAllMatchesBetween2CPLTeams # This function saves all matches between 2 teams as a single dataframe ################################################################################## #' @title #' Saves all matches between 2 CPL teams as dataframe #' #' @description #' This function saves all matches between 2 CPL teams as a single dataframe in the #' current directory #' #' @usage #' saveAllMatchesBetween2CPLTeams(dir=".",odir=".") #' #' @param dir #' Input Directory #' #' @param odir #' Output Directory to store saved matches #' #' @return None #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' #' #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' @examples #' \dontrun{ #' saveAllMatchesBetween2IPLTeams(dir=".",odir=".") #' } #' @seealso #' \code{\link{batsmanDismissals}}\cr #' \code{\link{batsmanRunsVsDeliveries}}\cr #' \code{\link{batsmanRunsVsStrikeRate}}\cr #' \code{\link{getAllMatchesAllOpposition}}\cr #' \code{\link{getAllMatchesBetweenTeams}}\cr #' #' @export #' saveAllMatchesBetween2CPLTeams <- function(dir=".",odir="."){ teams <-c("Antigua Hawksbills","Barbados Tridents","Guyana Amazon Warriors","Jamaica Tallawahs", "St Kitts and Nevis Patriots","St Lucia Zouks","Trinbago Knight Riders") matches <- NULL #Create all combinations of teams for(i in seq_along(teams)){ for(j in seq_along(teams)){ if(teams[i] != teams[j]){ cat("Team1=",teams[i],"Team2=",teams[j],"\n") tryCatch(matches <- getAllMatchesBetweenTeams(teams[i],teams[j],dir=dir,save=TRUE,odir=odir), error = function(e) { print("No matches") } ) } } matches <- NULL } }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/saveAllMatchesBetween2CPLTeams.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 2 May 2020 # Function: saveAllMatchesBetween2IPLTeams # This function saves all matches between 2 teams as a single dataframe ################################################################################## #' @title #' Saves all matches between 2 IPL teams as dataframe #' #' @description #' This function saves all matches between 2 IPL teams as a single dataframe in the #' current directory #' #' @usage #' saveAllMatchesBetween2IPLTeams(dir=".",odir=".") #' #' @param dir #' Input Directory #' #' @param odir #' Output Directory to store saved matches #' #' @return None #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' #' #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' @examples #' \dontrun{ #' saveAllMatchesBetween2IPLTeams(dir=".",odir=".") #' } #' @seealso #' \code{\link{batsmanDismissals}}\cr #' \code{\link{batsmanRunsVsDeliveries}}\cr #' \code{\link{batsmanRunsVsStrikeRate}}\cr #' \code{\link{getAllMatchesAllOpposition}}\cr #' \code{\link{getAllMatchesBetweenTeams}}\cr #' #' @export #' saveAllMatchesBetween2IPLTeams <- function(dir=".",odir="."){ teams <-c("Chennai Super Kings","Delhi Capitals","Deccan Chargers","Delhi Daredevils", "Kings XI Punjab","Punjab Kings", 'Kochi Tuskers Kerala',"Kolkata Knight Riders", "Mumbai Indians", "Pune Warriors","Rajasthan Royals", "Royal Challengers Bangalore","Sunrisers Hyderabad","Gujarat Lions", "Rising Pune Supergiants","Lucknow Super Giants","Gujarat Titans", "Royal Challengers Bengaluru") matches <- NULL #Create all combinations of teams for(i in seq_along(teams)){ for(j in seq_along(teams)){ if(teams[i] != teams[j]){ cat("Team1=",teams[i],"Team2=",teams[j],"\n") tryCatch(matches <- getAllMatchesBetweenTeams(teams[i],teams[j],dir=dir,save=TRUE,odir=odir), error = function(e) { print("No matches") } ) } } matches <- NULL } }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/saveAllMatchesBetween2IPLTeams.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 11 May 2020 # Function: saveAllMatchesBetween2NTBTeams # This function saves all matches between 2 teams as a single dataframe ################################################################################## #' @title #' Saves all matches between 2 NTB teams as dataframe #' #' @description #' This function saves all matches between 2 NTB teams as a single dataframe in the #' current directory #' #' @usage #' saveAllMatchesBetween2NTBTeams(dir=".",odir=".") #' #' @param dir #' Input Directory #' #' @param odir #' Output Directory to store saved matches #' #' @return None #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' #' #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' @examples #' \dontrun{ #' saveAllMatchesBetween2BBLTeams(dir=".",odir=".") #' } #' @seealso #' \code{\link{batsmanDismissals}}\cr #' \code{\link{batsmanRunsVsDeliveries}}\cr #' \code{\link{batsmanRunsVsStrikeRate}}\cr #' \code{\link{getAllMatchesAllOpposition}}\cr #' \code{\link{getAllMatchesBetweenTeams}}\cr #' #' @export #' saveAllMatchesBetween2NTBTeams <- function(dir=".",odir="."){ teams <- c("Birmingham Bears","Derbyshire", "Durham", "Essex", "Glamorgan", "Gloucestershire", "Hampshire", "Kent","Lancashire", "Leicestershire", "Middlesex","Northamptonshire", "Nottinghamshire","Somerset","Surrey","Sussex","Warwickshire", "Worcestershire","Yorkshire") matches <- NULL #Create all combinations of teams for(i in seq_along(teams)){ for(j in seq_along(teams)){ if(teams[i] != teams[j]){ cat("Team1=",teams[i],"Team2=",teams[j],"\n") tryCatch(matches <- getAllMatchesBetweenTeams(teams[i],teams[j],dir=dir,save=TRUE,odir=odir), error = function(e) { print("No matches") } ) } } matches <- NULL } }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/saveAllMatchesBetween2NTBTeams.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 11 May 2020 # Function: saveAllMatchesBetween2PSLTeams # This function saves all matches between 2 teams as a single dataframe ################################################################################## #' @title #' Saves all matches between 2 PSL teams as dataframe #' #' @description #' This function saves all matches between 2 PSL teams as a single dataframe in the #' current directory #' #' @usage #' saveAllMatchesBetween2PSLTeams(dir=".",odir=".") #' #' @param dir #' Input Directory #' #' @param odir #' Output Directory to store saved matches #' #' @return None #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' #' #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' @examples #' \dontrun{ #' saveAllMatchesBetween2BBLTeams(dir=".",odir=".") #' } #' @seealso #' \code{\link{batsmanDismissals}}\cr #' \code{\link{batsmanRunsVsDeliveries}}\cr #' \code{\link{batsmanRunsVsStrikeRate}}\cr #' \code{\link{getAllMatchesAllOpposition}}\cr #' \code{\link{getAllMatchesBetweenTeams}}\cr #' #' @export #' saveAllMatchesBetween2PSLTeams <- function(dir=".",odir="."){ teams <- c("Islamabad United","Karachi Kings", "Lahore Qalandars", "Multan Sultans", "Peshawar Zalmi", "Quetta Gladiators") matches <- NULL #Create all combinations of teams for(i in seq_along(teams)){ for(j in seq_along(teams)){ if(teams[i] != teams[j]){ cat("Team1=",teams[i],"Team2=",teams[j],"\n") tryCatch(matches <- getAllMatchesBetweenTeams(teams[i],teams[j],dir=dir,save=TRUE,odir=odir), error = function(e) { print("No matches") } ) } } matches <- NULL } }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/saveAllMatchesBetween2PSLTeams.R
########################################################################################## # Designed and developed by Tinniam V Ganesh # Date : 24 May 2021 # Function: saveAllMatchesBetween2SSMTeams # This function saves all matches between 2 SSM teams as a single dataframe ################################################################################## #' @title #' Saves all matches between 2 SSM teams as dataframe #' #' @description #' This function saves all matches between 2 SSM teams as a single dataframe in the #' current directory #' #' @usage #' saveAllMatchesBetween2SSMTeams(dir=".",odir=".") #' #' @param dir #' Input Directory #' #' @param odir #' Output Directory to store saved matches #' #' @return None #' @references #' \url{https://cricsheet.org/}\cr #' \url{https://gigadom.in/}\cr #' \url{https://github.com/tvganesh/yorkrData/} #' #' #' @author #' Tinniam V Ganesh #' @note #' Maintainer: Tinniam V Ganesh \email{[email protected]} #' #' @examples #' \dontrun{ #' saveAllMatchesBetween2SSMTeams(dir=".",odir=".") #' } #' @seealso #' \code{\link{batsmanDismissals}}\cr #' \code{\link{batsmanRunsVsDeliveries}}\cr #' \code{\link{batsmanRunsVsStrikeRate}}\cr #' \code{\link{getAllMatchesAllOpposition}}\cr #' \code{\link{getAllMatchesBetweenTeams}}\cr #' #' @export #' saveAllMatchesBetween2SSMTeams <- function(dir=".",odir="."){ teams <-c("Auckland", "Canterbury", "Central Districts", "Northern Districts", "Otago", "Wellington") matches <- NULL #Create all combinations of teams for(i in seq_along(teams)){ for(j in seq_along(teams)){ if(teams[i] != teams[j]){ cat("Team1=",teams[i],"Team2=",teams[j],"\n") tryCatch(matches <- getAllMatchesBetweenTeams(teams[i],teams[j],dir=dir,save=TRUE,odir=odir), error = function(e) { print("No matches") } ) } } matches <- NULL } }
/scratch/gouwar.j/cran-all/cranData/yorkr/R/saveAllMatchesBetween2SSMTeams.R