code
stringlengths
1
13.8M
st_read.DBIObject = function(dsn = NULL, layer = NULL, query = NULL, EWKB = TRUE, quiet = TRUE, as_tibble = FALSE, geometry_column = NULL, ...) { if (is.null(dsn)) stop("no connection provided") if (as_tibble && !requireNamespace("tibble", quietly = TRUE)) { stop("package tibble not available: install first?") } expe <- setdiff(names(list(...)), names(formals(st_sf))) if(length(expe) > 0) { suggest <- NULL if("table" %in% expe){ suggest <- c(suggest, "\nMaybe you should use `layer` rather than `table` ?") } pref <- if(length(expe) > 1) "\t *" else "" stop( "Unused arguments: ", if(length(expe) > 1) "\n" else "", paste(pref, expe, "=", list(...)[expe], collapse = "\n", sep = " "), suggest, "\nCheck arguments for `st_sf()` for details.", call. = FALSE ) } filter_warning <- function(expr, regexp) { wlist <- NULL warning_handler <- function(w) { wlist <<- c(wlist, list(w)) invokeRestart("muffleWarning") } msg <- function(x) x$message out <- withCallingHandlers(expr, warning = warning_handler) if(!all(grepl(regexp, wlist))) { lapply(vapply(wlist, msg, character(1)), warning, call. = FALSE) } return(out) } if (!is.null(layer)) { if (!is.null(query)) { warning("You provided both `layer` and `query` arguments,", " will only use `layer`.", call. = FALSE) } if (inherits(dsn, "PostgreSQLConnection")) { tbl <- filter_warning(dbReadTable(dsn, layer), "unrecognized PostgreSQL field type geometry") } else { tbl <- dbReadTable(dsn, layer) } } else if(is.null(query)) { stop("Provide either a `layer` or a `query`", call. = FALSE) } else { if (inherits(dsn, "PostgreSQLConnection")) { filter_warning(tbl <- dbGetQuery(dsn, query), "unrecognized PostgreSQL field type geometry") } else { tbl <- dbGetQuery(dsn, query) } } if (is.null(tbl)) { stop("Query `", query, "` returned no results.", call. = FALSE) } if (is.null(geometry_column)) { geometry_column = is_geometry_column(dsn, tbl) tbl[geometry_column] <- lapply(tbl[geometry_column], try_postgis_as_sfc, EWKB = EWKB, conn = dsn) } else { if (!all(geometry_column %in% names(tbl))) { nm <- names(tbl) prefix <- "" new_line <- "" if(length(nm) > 1) { prefix <- " *" new_line <- "\n" } stop("Could not find `geometry_column` (\"", paste(geometry_column, collapse = "\", \""), "\") ", "in column names. Available names are:", new_line, paste(prefix, nm, collapse = "\n", sep = " "), call. = FALSE) } tbl[geometry_column] <- lapply(tbl[geometry_column], postgis_as_sfc, EWKB = EWKB, conn = dsn) } if (! any(vapply(tbl, inherits, logical(1), "sfc"))) { blob_columns = vapply(tbl, inherits, logical(1), "blob") success = FALSE for (i in which(blob_columns)) { try(sfc <- st_as_sfc(tbl[[i]]), silent = TRUE) if (!inherits(sfc, "try-error")) { tbl[[i]] = sfc success = TRUE } } if (! success) { warning("Could not find a simple features geometry column. Will return a `data.frame`.") return(tbl) } } x <- st_sf(tbl, ...) if (!quiet) print(x, n = 0) if (as_tibble) { x <- tibble::new_tibble(x, nrow = nrow(x), class = "sf") } return(x) } st_read.Pool = function(dsn = NULL, layer = NULL, ...) { if (! requireNamespace("pool", quietly = TRUE)) stop("package pool required, please install it first") dsn = pool::poolCheckout(dsn) on.exit(pool::poolReturn(dsn)) st_read(dsn, layer = layer, ...) } st_read.PostgreSQLConnection <- function(...) { st_read.DBIObject(...) } postgis_as_sfc <- function(x, EWKB, conn) { geom <- st_as_sfc(as_wkb_(x), EWKB = EWKB) srid <- attr(geom, "srid") if (!is.null(srid)) { st_crs(geom) = db_find_srid(conn, srid = srid, validate = FALSE) attr(geom, "srid") = NULL warning("Could not find database srid (", srid, ") locally; using the remote database definition.") } return(geom) } try_postgis_as_sfc <- function(x, EWKB, conn) { tryCatch(postgis_as_sfc(x, EWKB, conn), error = function(...) return(x)) } schema_table <- function(conn, table, public = "public") { if (!is.character(table)) stop("table must be a character vector", call. = FALSE) if (length(table) == 1L) table = c(public, table) else if (length(table) > 2) stop("table cannot be longer than 2 (schema, table)", call. = FALSE) if (any(is.na(table))) stop("table and schema cannot be NA", call. = FALSE) return(table) } as_wkb_ <- function(x) { structure(x, class = "WKB") } get_possibly_new_srid <- function(conn, crs) { db_crs <- db_find_srid(conn, crs) if(!is.na(db_crs)) { return(db_crs) } db_crs <- db_find_srtext(conn, crs) if (!is.na(db_crs)) { return(db_crs) } db_insert_crs(conn, crs) } db_find_srid = function(conn, crs_local = st_crs(srid), srid = epsg(crs_local), validate = TRUE) { if (validate && is.na(crs_local)) return(st_crs(NA)) if (is.na(srid)) { return(st_crs(NA)) } query <- paste0("select srtext from spatial_ref_sys where srid = ", srid) db_crs <- dbGetQuery(conn, query) if (nrow(db_crs) < 1) { return(st_crs(NA)) } if (nrow(db_crs) > 1) { stop("SRID should be unique, but the database returned ", nrow(db_crs), " matching crs. \n", db_crs, call. = FALSE) } crs_found <- st_crs(db_crs[["srtext"]]) crs_found[["input"]] <- build_epsg(srid) if(validate && crs_found != crs_local & !is.na(crs_local)) { warning("Local crs different from database crs. You can inspect the ", "database crs using `dbReadtable(conn, \"spatial_ref_sys\")` ", "and compare it to `st_crs(", srid,")`.") } crs_found } db_find_srtext = function(conn, crs_local = st_crs(wkt), wkt = st_as_text(crs_local)) { if (is.na(crs_local)) return(st_crs(NA)) if (is.na(wkt)) { return(st_crs(NA)) } query <- paste0("select * from spatial_ref_sys where srtext = '", wkt, "'") db_spatial_ref <- DBI::dbGetQuery(conn, query) if (nrow(db_spatial_ref) < 1) { query <- "select * from spatial_ref_sys where srtext is not null and srtext != ''" db_spatial_ref <- DBI::dbGetQuery(conn, query) db_crs <- lapply(db_spatial_ref[["srtext"]], function(string) try(st_crs(string))) reject <- vapply(db_crs, function(x) inherits(x, "try-error"), logical(1)) eq <- vapply(db_crs[!reject], function(x) crs_local == x, logical(1)) db_spatial_ref <- db_spatial_ref[eq, ] } if (nrow(db_spatial_ref) > 1) { db_spatial_ref <- db_spatial_ref[seq_len(min(nrow(db_spatial_ref), 10)), ] message("Found multiple matching projections, will use srid = ", db_spatial_ref[["srid"]][[1]], ".\nOther database srid matching the projection WKT description: ", paste(db_spatial_ref[["srid"]][-1], collapse = ", "), "\n", "You can suppress this warning by setting the projection to `st_crs(", db_spatial_ref[["srid"]][[1]], ")`.") db_spatial_ref <- db_spatial_ref[1, ] } if (nrow(db_spatial_ref) < 1) { return(st_crs(NA)) } else { crs_found <- make_empty_crs(db_spatial_ref[["srid"]], db_spatial_ref[["srtext"]]) } if(crs_found != crs_local) { warning("Local crs different from database crs. You can inspect the ", "database crs using `dbReadtable(conn, \"spatial_ref_sys\")` ", "and compare it to `st_crs(\"", wkt,"\")`.") } crs_found } make_empty_crs <- function(epsg = NA, text = NA, wkt = NA) { if(!is.na(epsg)) { epsg <- build_epsg(epsg)[1] } if(is.na(wkt)) { wkt = st_as_text(st_crs(text)) } structure( list( input = epsg, wkt = wkt), class = "crs") } build_epsg <- function(auth_srid, auth_name = "EPSG") { paste0(auth_name, ":", auth_srid) } db_insert_crs <- function(conn, crs, srid = epsg(crs), auth_name = "sf", auth_srid = srid, wkt = st_as_text(crs), proj4text = proj4string(crs), update = FALSE, verbose = TRUE) { error_msg <- NULL if (update) { if (is.na(srid)) { error_msg <- c(error_msg, paste0( "You need to provide an `srid` to update a projection, but the `srid` is NA.", "\n Either: \n * provide an `srid` or \n * use `update = FALSE` to receive an srid", collapse = "" )) } } if (is.na(wkt)) { error_msg <- c(error_msg, "You need to provide a `wkt` to update the database `spatial_ref_sys`.") } if (!is.null(error_msg)) { n_errors <- length(error_msg) if (n_errors > 1) { error_msg <- c(paste0("We found ", n_errors, " errors:\n"), error_msg) } stop(paste(error_msg, collapse = "\n"), call. = FALSE) } if (is.na(srid)) { srid <- get_new_postgis_srid(conn) } if (is.na(auth_srid)) { auth_srid <- auth_srid } crs <- make_empty_crs(epsg = srid, text = wkt) q <- function(x) paste0("'", x, "'") if (update) { query <- paste("UPDATE spatial_ref_sys SET", "auth_name =", q(auth_name), ", ", "auth_srid =", auth_srid, ", ", "srtext =", q(wkt), ", ", "proj4text =", q(proj4string(crs)), "WHERE srid =", srid, ";") } else { query <- paste("INSERT INTO spatial_ref_sys (srid, auth_name, auth_srid, srtext, proj4text)", "VALUES (", paste( srid, q(auth_name), auth_srid, q(wkt), q(proj4string(crs)), sep = ", "), ");") } tryCatch(dbExecute(conn, query), error = function(err) { if(grepl("permission denied", err)) { stop("Write permission denied on table `spatial_ref_sys` because:", "\n * Local crs is not in the database; ", "\n * Write permission on table `spatial_ref_sys` is denied.", "\nEither: ", "\n * Change the crs locally using `st_transform()` on your `sf` object;", "\n * Set the crs to NA using `st_set_crs({your_sf}, NA)`.", "\n * Grant write access on `spatial_sys_ref`.", "\n * Ask the database administrator to add your projection with :", "\n ``` sql\n", query, "\n ```", call. = FALSE) } stop(err) }) if (verbose) { message("Inserted local crs: `", wkt, "` in database as srid:", srid, ".") } return(crs) } db_check_user_permission <- function(conn, table, permission, strict = FALSE) { q <- paste0("select has_table_privilege('", table, "', '", permission, "') as has") can <- try(dbReadTable(conn, q)[["has"]]) if (inherits(can, "try-error")){ if (strict) { return(FALSE) } return(TRUE) } return(can) } delete_postgis_crs <- function(conn, crs) { if (is.na(epsg(crs))) stop("Missing SRID") wkt <- st_as_text(crs) query <- paste0("DELETE FROM spatial_ref_sys ", "WHERE srid = '", epsg(crs), "' ", "AND srtext = '", wkt, "' ", "AND proj4text = '", proj4string(crs), "';") dbExecute(conn, query) } get_new_postgis_srid <- function(conn) { query = paste0("select srid + 1 as srid from spatial_ref_sys order by srid desc limit 1;") dbGetQuery(conn, query)[["srid"]] } setMethod("dbWriteTable", c("PostgreSQLConnection", "character", "sf"), function(conn, name, value, ..., row.names = FALSE, overwrite = FALSE, append = FALSE, field.types = NULL, binary = TRUE) { if (is.null(field.types)) field.types <- dbDataType(conn, value) tryCatch({ dbWriteTable(conn, name, to_postgis(conn, value, binary),..., row.names = row.names, overwrite = overwrite, append = append, field.types = field.types) }, warning=function(w) { stop(conditionMessage(w), call. = FALSE) }) } ) setMethod("dbWriteTable", c("DBIObject", "character", "sf"), function(conn, name, value, ..., row.names = FALSE, overwrite = FALSE, append = FALSE, field.types = NULL, binary = TRUE) { if (is.null(field.types)) field.types <- dbDataType(conn, value) if (append) field.types <- NULL dbWriteTable(conn, name, to_postgis(conn, value, binary),..., row.names = row.names, overwrite = overwrite, append = append, field.types = field.types) } ) to_postgis <- function(conn, x, binary) { geom_col <- vapply(x, inherits, TRUE, what = "sfc") x[geom_col] <- lapply(x[geom_col], sync_crs, conn = conn) if (binary) { x[geom_col] <- lapply(x[geom_col], db_binary) } else { x[geom_col] <- lapply(x[geom_col], st_as_text, EWKT = TRUE) } x <- as.data.frame(x) clean_columns(x, factorsAsCharacter = TRUE) } db_binary <- function(x) { st_as_binary(x, EWKB = TRUE, hex = TRUE, pureR = FALSE, srid = epsg(st_crs(x))) } sync_crs <- function(conn, geom) { crs <- st_crs(geom) srid <- epsg(crs) if (is.na(crs) || is.na(srid)) { if (is.na(st_as_text(crs))) crs <- st_crs(NA) else { crs <- get_possibly_new_srid(conn, crs) } } st_set_crs(geom, crs) } setMethod("dbDataType", c("PostgreSQLConnection", "sf"), function(dbObj, obj) { dtyp <- vapply(obj, RPostgreSQL::dbDataType, character(1), dbObj = dbObj) gtyp <- vapply(obj, inherits, TRUE, what = "sfc") dtyp[gtyp] <- "geometry" gtyp <- vapply(obj, inherits, TRUE, what = "units") dtyp[gtyp] <- "numeric" return(dtyp) }) setMethod("dbDataType", c("DBIObject", "sf"), function(dbObj, obj) { dtyp <- vapply(obj, DBI::dbDataType, character(1), dbObj = dbObj) gtyp <- vapply(obj, inherits, TRUE, what = "sfc") dtyp[gtyp] <- "geometry" gtyp <- vapply(obj, inherits, TRUE, what = "units") dtyp[gtyp] <- "numeric" return(dtyp) }) is_geometry_column <- function(con, x, classes = "") UseMethod("is_geometry_column") is_geometry_column.PqConnection <- function(con, x, classes = c("pq_geometry")) { vapply(x, inherits, logical(1), classes) } is_geometry_column.default <- function(con, x, classes = c("character")) { vapply(x, function(x) inherits(x, classes) && !all(is.na(x)), FUN.VALUE = logical(1)) } st_as_sfc.pq_geometry <- function(x, ..., EWKB = TRUE, spatialite = FALSE, pureR = FALSE, crs = NA_crs_) { st_as_sfc.WKB(x, ..., EWKB = EWKB, spatiallite = spatialite, pureR = pureR, crs = crs) }
is_scalar_na = function(x) { is.atomic(x) && length(x) == 1L && is.na(x) }
getColumnsOfBase <- function(base, strColumns){ colunas = vector() nomes = names(base) j=0 if( 1 <= length(names(base))) for(i in 1: length(names(base))) if (grepl(nomes[[i]], strColumns) > 0) colunas[[(j=j+1)]] = nomes[[i]] return(colunas) }
getMales <- function(males, numPairs, breedCount, random = FALSE) { maleIndex <- list() index <- which(breedCount < 1) if (length(index) > 0) { males <- males[-which(males %in% index)] } for (i in 1:numPairs) { if (length(males) < 1) { break } if (length(males) == 1) { maleIndex[[i]] <- males } else { if (random) { maleIndex[[i]] <- sample(males, 1) } else { maleIndex[[i]] <- sample(males, 1, prob = ranking(length(males))) } } breedCount[maleIndex[[i]]] <- breedCount[maleIndex[[i]]] - 1 if (breedCount[maleIndex[[i]]] < 1) { males <- males[males != maleIndex[[i]]] } } return(unlist(maleIndex)) } recombine <- function(hap1, hap2, recProb) { recPoints <- (runif(length(recProb)) < recProb) mask <- recMask(recPoints) hap1[mask] <- hap2[mask] return(hap1) } ranking <- function(n) { return(2 * (n - 1:n + 1) / (n * (n + 1))) } prepPed <- function(pedigree) { if (!is.data.frame(pedigree) || ncol(pedigree) < 3) { stop("Pedigree must be a data frame with at least three columns") } if (!(is.numeric(pedigree[, 1])) || !(is.numeric(pedigree[, 2])) || !(is.numeric(pedigree[, 3])) || any(pedigree[, 1:3] %% 1 != 0)) { stop("Pedigree IDs must be integers.") } if (sum(xor(pedigree[, 2] > 0, pedigree[, 3] > 0)) > 0) { stop("Individuals must have two parents or be from initial generation.") } for (i in 1:nrow(pedigree)) if (anyDuplicated(pedigree[i, 1:3]) && pedigree[i, 2] != 0) { stop("No IDs can be repeated within the same row.") } sire <- pedigree[, 2] sire <- sire[sire != 0] dam <- pedigree[, 3] dam <- dam[dam != 0] if (any(sire %in% dam) || any(dam %in% sire)) { stop("No individual can be both a sire and a dam") } males <- unique(match(sire, pedigree[, 1])) females <- unique(match(dam, pedigree[, 1])) sex <- rep("X", nrow(pedigree)) sex[males] <- "M" sex[females] <- "F" sexless <- which(sex == "X") sex[sexless] <- sample(c("M", "F"), length(sexless), replace = TRUE) pedigree <- pedigree[, 1:3] names(pedigree) <- c("ID", "Sire", "Dam") pedigree$Additive <- rep(0, length(pedigree$ID)) pedigree$Epistatic <- rep(0, length(pedigree$ID)) pedigree$Environmental <- rep(0, length(pedigree$ID)) pedigree$Phenotype <- rep(0, length(pedigree$ID)) pedigree$Sex <- sex return(pedigree) } prepPop <- function(pop, generations, selection, fitness, burnIn, truncSire, truncDam, roundsSire, roundsDam, litterDist, breedSire) { if (!is.numeric(generations) || length(generations) != 1 || generations%%1 != 0 || generations < 2) { stop("Number of generations must be an integer greater than 1") } pop$numGen <- generations pop$ranking <- (tolower(trimws(selection)) == "ranking") if (tolower(trimws(fitness)) == "tgv") { pop$select <- "TGV" pop$phenotype <- pop$ped$Additive + pop$ped$Epistatic } else if (tolower(trimws(fitness)) == "ebv") { pop$select <- "EBV" pop$phenotype <- pop$ped$EBV } else { pop$select <- "phenotypic" } if (length(burnIn) != 1 || !is.numeric(burnIn) || burnIn%%1 != 0 || burnIn < 0 || burnIn > pop$numGen) { stop("Burn-in length must be an integer between 0 and the number of generations to run") } pop$burnIn <- burnIn if (length(truncSire) != 1 || !is.numeric(truncDam) || truncSire > 1 || truncSire <= 0) { stop("Sire truncation rate incorrectly specified") } pop$truncMale <- truncSire if (length(truncDam) != 1 || !is.numeric(truncDam) || truncDam > 1 || truncDam <= 0) { stop("Dam truncation rate incorrectly specified") } pop$truncFemale <- truncDam if (length(roundsSire) != 1 || length(roundsDam) != 1 || !is.numeric(roundsSire) || !is.numeric(roundsDam) || roundsSire%%1 != 0 || roundsDam%%1 != 0 || roundsSire < 1 || roundsDam < 1 || roundsSire > pop$numGen || roundsDam > pop$numGen) { stop("Sire and dam rounds incorrectly specified") } pop$sireRounds <- roundsSire pop$damRounds <- roundsDam if (length(litterDist) < 2 || !is.numeric(litterDist) || any(litterDist < 0)) { stop("Invalid litter distribution") } pop$litterDist <- litterDist/sum(litterDist) if (length(breedSire) != 1 || !is.numeric(breedSire) || breedSire < 1) { stop("Sires must each have a maximum breeding rate of at least once per round") } pop$sireBreed <- breedSire pop$roundsCount <- rep(pop$damRounds, pop$popSize) pop$roundsCount[pop$isMale] <- pop$sireRounds pop$expectedOffspring <- (pop$numGen - 1) * 0.5 * pop$truncFemale * pop$popSize * sum(pop$litterDist * 0:(length(pop$litterDist) - 1)) zeroes <- rep(0, pop$popSize + pop$expectedOffspring) tempped <- data.frame(ID = zeroes, Sire = zeroes, Dam = zeroes, Additive = zeroes, Epistatic = zeroes, Environmental = zeroes, Phenotype = zeroes, EBV = zeroes, Sex = as.character(rep("X", pop$popSize + pop$expectedOffspring)), Round = zeroes, stringsAsFactors = FALSE) components <- getComponents(pop) components$Sex <- as.character(components$Sex) tempped[1:pop$popSize, ] <- components tempped$Round <- zeroes pop$ped <- tempped pop$ped$Round[1:pop$popSize] <- 1 pop$af <- matrix(0, pop$numGen, length(pop$alleleFreq)) return(pop) } sortPed <- function(ped) { indices <- which(ped[, 2] == 0) matings <- length(indices) indices2 <- which(ped[, 2] %in% ped[indices, 1] & ped[, 3] %in% ped[ indices, 1 ]) indices2 <- indices2[!(indices2 %in% indices)] while (length(indices2) > 0) { indices <- c(indices, indices2) matings <- c(matings, length(indices2)) indices2 <- which(ped[, 2] %in% ped[indices, 1] & ped[, 3] %in% ped[indices, 1]) indices2 <- indices2[!(indices2 %in% indices)] } retval <- list() retval$sort <- indices retval$matings <- matings return(retval) } cullIndices <- function(pop, ped, matings, gen) { index1 <- sum(matings[1:gen]) + 1 index2 <- nrow(ped) parents <- unique(c(ped$Sire[index1:index2], ped$Dam[index1:index2])) cull <- unique(which(!(pop$ID %in% parents))) return(cull) } getRecProb <- function(rp, map) { chr <- unique(map$chr) if (length(rp) != nrow(map) - length(chr)) { stop("Number of recombination probabilities must match number of possible recombination points") } if (any(rp < 0 | rp > 1)) { stop("Recombination probabilities must be between 0 and 1") } if (length(chr) <= 0) { stop("There must be at least 1 chromosome") } index <- 1 index2 <- 1 recProb <- numeric(nrow(map)) for (i in chr) { recProb[index] <- 0.5 numSNP <- sum(map$chr == i) recProb[(index + 1):(index + numSNP - 1)] <- rp[index2:(index2 + numSNP - 2)] index <- index + numSNP index2 <- index2 + numSNP - 1 } return(recProb) } getFilename <- function(pop, generation) { numwidth <- nchar(paste(pop$numGen)) filenumber <- formatC(generation, width = numwidth, format = "d", flag = "0") filename <- tools::file_path_sans_ext(pop$hapout) fileext <- tools::file_ext(pop$hapout) filename <- paste(filename, filenumber, sep = "-") return(paste(filename, fileext, sep = ".")) } getPheno <- function(pop, geno = NULL) { if (is.null(geno)) { geno <- (pop$hap[[1]] + pop$hap[[2]]) } genotrim <- geno[, pop$qtl] dimensions <- dim(geno) zeros <- rep(0, dimensions[1]) if (pop$h2 > 0 && !is.null(pop$additive)) { add <- (genotrim %*% matrix(pop$additive)) + pop$addOffset } else { add <- zeros } if (pop$h2 < pop$H2 && !is.null(pop$epiNet)) { epi <- getEpi(pop, geno = genotrim) * pop$epiScale + pop$epiOffset } else { epi <- zeros } if (pop$H2 < 1) { env <- rnorm(nrow(geno), sd = sqrt(pop$VarE)) } else { env <- zeros } tot <- add + epi + env ebv <- geno %*% matrix(pop$addEst) return(matrix(c(add, epi, env, tot, ebv), length(add), 5)) }
stat_binh <- function(mapping = NULL, data = NULL, geom = "barh", position = "stackv", ..., binwidth = NULL, bins = NULL, center = NULL, boundary = NULL, closed = c("right", "left"), pad = FALSE, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE) { layer( data = data, mapping = mapping, stat = StatBinh, geom = geom, position = position, show.legend = show.legend, inherit.aes = inherit.aes, params = list( binwidth = binwidth, bins = bins, center = center, boundary = boundary, closed = closed, pad = pad, na.rm = na.rm, ... ) ) } StatBinh <- ggproto("StatBinh", Stat, setup_params = function(data, params) { if (!is.null(data$x) || !is.null(params$x)) { stop("stat_bin() must not be used with a x aesthetic.", call. = FALSE) } if (is.integer(data$y)) { stop('StatBin requires a continuous y variable the y variable is discrete. Perhaps you want stat="count"?', call. = FALSE) } if (!is.null(params$drop)) { warning("`drop` is deprecated. Please use `pad` instead.", call. = FALSE) params$drop <- NULL } if (!is.null(params$origin)) { warning("`origin` is deprecated. Please use `boundary` instead.", call. = FALSE) params$boundary <- params$origin params$origin <- NULL } if (!is.null(params$right)) { warning("`right` is deprecated. Please use `closed` instead.", call. = FALSE) params$closed <- if (params$right) "right" else "left" params$right <- NULL } if (!is.null(params$width)) { stop("`width` is deprecated. Do you want `geom_barh()`?", call. = FALSE) } if (!is.null(params$boundary) && !is.null(params$center)) { stop("Only one of `boundary` and `center` may be specified.", call. = FALSE) } if (is.null(params$breaks) && is.null(params$binheight) && is.null(params$bins)) { message_wrap("`stat_bin()` using `bins = 30`. Pick better value with `binwidth`.") params$bins <- 30 } params }, compute_group = function(data, scales, binwidth = NULL, bins = NULL, center = NULL, boundary = NULL, closed = c("right", "left"), pad = FALSE, breaks = NULL, origin = NULL, right = NULL, drop = NULL, width = NULL) { if (!is.null(breaks)) { bins <- bin_breaks(breaks, closed) } else if (!is.null(binwidth)) { bins <- bin_breaks_width(scales$y$dimension(), binwidth, center = center, boundary = boundary, closed = closed) } else { bins <- bin_breaks_bins(scales$y$dimension(), bins, center = center, boundary = boundary, closed = closed) } data <- bin_vector(data$y, bins, weight = data$weight, pad = pad) flip_aes(data) }, default_aes = aes(x = ..count..), required_aes = c("y") ) bin_breaks <- generate("bin_breaks") bin_breaks_width <- generate("bin_breaks_width") bin_breaks_bins <- generate("bin_breaks_bins") bin_vector <- generate("bin_vector")
data(dietary_survey_IBS) dat = dietary_survey_IBS[, -ncol(dietary_survey_IBS)] X = center_scale(dat) context('plot_2d - silhouette plot - external_validation - center_scale - distance_matrix') testthat::test_that("in case that the data is not a matrix or a data frame, it returns an error", { tmp_x = list(X) clust = sample(1:2, nrow(X), replace = T) centr = matrix(runif(ncol(X) * 2), nrow = 2, ncol = ncol(X)) testthat::expect_error( plot_2d(tmp_x, clust, centr) ) }) testthat::test_that("in case that the data is not 2-dimensional, it returns an error", { clust = sample(1:2, nrow(X), replace = T) centr = data.frame(matrix(runif(ncol(X) * 2), nrow = 2, ncol = ncol(X))) testthat::expect_error( plot_2d(dat, clust, centr) ) }) testthat::test_that("in case that the unique levels of the clusters is greater than 26, it returns an error", { clust = sample(1:30, nrow(X), replace = T) centr = data.frame(matrix(runif(ncol(X) * length(unique(clust))), nrow = length(unique(clust)), ncol = ncol(X))) testthat::expect_error( plot_2d(dat, clust, centr) ) }) testthat::test_that("in case that the clusters parameter is not a numeric vector, it returns an error", { tmp_m = data.frame(1) centr = matrix(runif(ncol(X) * 2), nrow = 2, ncol = ncol(X)) testthat::expect_error( plot_2d(X, tmp_m, centr) ) }) testthat::test_that("in case that the centroids/medoids is not a matrix or data frame, it returns an error", { clust = sample(1:2, nrow(X), replace = T) centr = list(matrix(runif(ncol(X) * 2), nrow = 2, ncol = ncol(X))) testthat::expect_error( plot_2d(X, clust, centr) ) }) testthat::test_that("in case that the centroids/medoids rows do not equal the length of the unique levels of the clusters vector, it returns an error", { clust = sample(1:2, nrow(X), replace = T) centr = matrix(runif(ncol(X) * 3), nrow = 3, ncol = ncol(X)) testthat::expect_error( plot_2d(X, clust, centr) ) }) testthat::test_that("in case that the centroids/medoids columns do not equal the number of columns of the data, it returns an error", { clust = sample(1:2, nrow(X), replace = T) centr = matrix(runif((ncol(X) - 1) * 2), nrow = 2, ncol = ncol(X) - 1) testthat::expect_error( plot_2d(X, clust, centr) ) }) testthat::test_that("in case that the data includes NaN or Inf values, it returns an error", { tmp_dat = X tmp_dat[1,1] = Inf clust = sample(1:2, nrow(X), replace = T) centr = matrix(runif(ncol(X) * 2), nrow = 2, ncol = ncol(X)) testthat::expect_error( plot_2d(tmp_dat, clust, centr) ) }) testthat::test_that("the function returns a plot of class 'gg', 'ggplot' ", { pca_dat = stats::princomp(X)$scores[, 1:2] km = KMeans_rcpp(pca_dat, clusters = 2, num_init = 5, max_iters = 100) testthat::expect_true( inherits(plot_2d(pca_dat, km$clusters, km$centroids), c("gg", "ggplot")) ) }) testthat::test_that("in case that the true labels is not a numeric vector, it returns an error", { km = KMeans_rcpp(X, clusters = 2, num_init = 5, max_iters = 100, initializer = 'optimal_init') tmp_cl = list(dietary_survey_IBS$class) testthat::expect_error( external_validation(tmp_cl, km$clusters, method = "adjusted_rand_index") ) }) testthat::test_that("in case that the clusters is not a numeric vector, it returns an error", { km = KMeans_rcpp(X, clusters = 2, num_init = 5, max_iters = 100, initializer = 'optimal_init') tmp_cl = list(km$clusters) testthat::expect_error( external_validation(dietary_survey_IBS$class, tmp_cl, method = "adjusted_rand_index") ) }) testthat::test_that("in case that the clusters is not a numeric vector, it returns an error", { km = KMeans_rcpp(X, clusters = 2, num_init = 5, max_iters = 100, initializer = 'optimal_init') tmp_cl = sample(1:2, nrow(X) + 1, replace = T) testthat::expect_error( external_validation(dietary_survey_IBS$class, tmp_cl, method = "adjusted_rand_index") ) }) testthat::test_that("in case that the method is not valid, it returns an error", { km = KMeans_rcpp(X, clusters = 2, num_init = 5, max_iters = 100, initializer = 'optimal_init') testthat::expect_error( external_validation(dietary_survey_IBS$class, km$clusters, method = "invalid") ) }) testthat::test_that("in case that the true labels is an integer vector they will be converted to numeric", { km = KMeans_rcpp(X, clusters = 2, num_init = 5, max_iters = 100, initializer = 'optimal_init') tmp_cl = as.integer(dietary_survey_IBS$class) res = external_validation(tmp_cl, km$clusters, method = "adjusted_rand_index") testthat::expect_true( is.numeric(res) && length(res) == 1 ) }) testthat::test_that("in case that the clusters is an integer vector they will be converted to numeric", { km = KMeans_rcpp(X, clusters = 2, num_init = 5, max_iters = 100, initializer = 'optimal_init') tmp_cl = as.integer(km$clusters) res = external_validation(dietary_survey_IBS$class, tmp_cl, method = "adjusted_rand_index") testthat::expect_true( is.numeric(res) && length(res) == 1 ) }) testthat::test_that("the function for the different methods returns the correct output", { km = KMeans_rcpp(X, clusters = 2, num_init = 5, max_iters = 100, initializer = 'optimal_init') mth = c('rand_index', 'adjusted_rand_index', 'jaccard_index', 'fowlkes_mallows_index', 'mirkin_metric', 'purity', 'entropy', 'nmi', 'var_info', 'nvi') res = rep(NA, length(mth)) for (i in 1:length(mth)) { tmp_res = external_validation(dietary_survey_IBS$class, km$clusters, method = mth[i]) res[i] = (is.numeric(tmp_res) && length(tmp_res) == 1) } testthat::expect_true( sum(res) == length(mth) ) }) testthat::test_that("if summary_stats is TRUE the function returns output", { km = KMeans_rcpp(X, clusters = 2, num_init = 5, max_iters = 100, initializer = 'optimal_init') res = external_validation(dietary_survey_IBS$class, km$clusters, method = "adjusted_rand_index", summary_stats = T) testthat::expect_output( str(res), 'num' ) }) testthat::test_that("in case that the data is not a matrix or a data frame, it returns an error", { tmp_x = list(X) testthat::expect_error( center_scale(tmp_x, mean_center = TRUE, sd_scale = TRUE) ) }) testthat::test_that("in case that the mean_center parameter is not logical, it returns an error", { testthat::expect_error( center_scale(X, mean_center = 'TRUE', sd_scale = TRUE) ) }) testthat::test_that("in case that the sd_scale parameter is not logical, it returns an error", { testthat::expect_error( center_scale(X, mean_center = TRUE, sd_scale = 'TRUE') ) }) testthat::test_that("in case that the data includes NaN or Inf values, it returns an error", { tmp_dat = X tmp_dat[1,1] = Inf testthat::expect_error( center_scale(tmp_dat, mean_center = TRUE, sd_scale = TRUE) ) }) testthat::test_that("in case that the data is a matrix the function returns a matrix", { res = center_scale(X, mean_center = TRUE, sd_scale = TRUE) testthat::expect_true( is.matrix(res) && nrow(X) == nrow(res) && ncol(X) == ncol(res) ) }) testthat::test_that("in case that the data is a data frame the function returns a matrix", { res = center_scale(dat, mean_center = TRUE, sd_scale = TRUE) testthat::expect_true( is.matrix(res) && nrow(X) == nrow(res) && ncol(X) == ncol(res) ) }) testthat::test_that("in case that the data is a matrix and mean_center = TRUE and sd_scale = FALSE, the function returns a matrix", { res = center_scale(X, mean_center = TRUE, sd_scale = FALSE) testthat::expect_true( is.matrix(res) && nrow(X) == nrow(res) && ncol(X) == ncol(res) ) }) testthat::test_that("in case that the data is a matrix and mean_center = FALSE and sd_scale = TRUE, the function returns a matrix", { res = center_scale(X, mean_center = FALSE, sd_scale = TRUE) testthat::expect_true( is.matrix(res) && nrow(X) == nrow(res) && ncol(X) == ncol(res) ) }) testthat::test_that("in case that the data is a matrix and mean_center = FALSE and sd_scale = FALSE, the function returns a matrix", { res = center_scale(X, mean_center = FALSE, sd_scale = FALSE) testthat::expect_true( is.matrix(res) && nrow(X) == nrow(res) && ncol(X) == ncol(res) ) }) testthat::test_that("in case that the data is not a matrix or data frame, it returns an error", { tmp_x = list(X) testthat::expect_error( distance_matrix(tmp_x, method = 'euclidean', upper = TRUE, diagonal = TRUE) ) }) testthat::test_that("in case that the method parameter is invalid, it returns an error", { testthat::expect_error( distance_matrix(X, method = 'invalid', upper = TRUE, diagonal = TRUE) ) }) testthat::test_that("in case that the upper parameter is not logical, it returns an error", { testthat::expect_error( distance_matrix(X, method = 'euclidean', upper = 'TRUE', diagonal = TRUE) ) }) testthat::test_that("in case that the diagonal parameter is not logical, it returns an error", { testthat::expect_error( distance_matrix(X, method = 'euclidean', upper = TRUE, diagonal = 'TRUE') ) }) testthat::test_that("in case that the method parameter is minkowski and the minkowski_p parameter is 0.0, it returns an error", { testthat::expect_error( distance_matrix(X, method = 'minkowski', minkowski_p = 0.0) ) }) testthat::test_that("in case that the threads parameter is less than 1, it returns an error", { testthat::expect_error( distance_matrix(X, method = 'euclidean', threads = 0) ) }) testthat::test_that("in case that the data is a matrix the function returns a matrix", { res = distance_matrix(X, method = 'euclidean', upper = TRUE, diagonal = TRUE) testthat::expect_true( is.matrix(res) ) }) testthat::test_that("in case that the data is a data frame the function returns a matrix", { res = distance_matrix(dat, method = 'euclidean', upper = TRUE, diagonal = TRUE) testthat::expect_true( is.matrix(res) ) }) testthat::test_that("in case that the evaluation_object is invalid, it returns an error", { km = KMeans_arma(X, clusters = 2, n_iter = 10, "random_subset", verbose = F) testthat::expect_error( Silhouette_Dissimilarity_Plot(km, silhouette = TRUE) ) }) testthat::test_that("in case that the silhouette parameter is not logical, it returns an error", { cm = Cluster_Medoids(X, clusters = 2, distance_metric = 'euclidean') testthat::expect_error( Silhouette_Dissimilarity_Plot(cm, silhouette = 'TRUE') ) }) testthat::test_that("in case of 'Cluster_Medoids' function AND silhouette = TRUE, it returns TRUE", { cm = Cluster_Medoids(X, clusters = 4, distance_metric = 'euclidean') plt_sd = Silhouette_Dissimilarity_Plot(cm, silhouette = TRUE) testthat::expect_true( plt_sd ) }) testthat::test_that("in case of 'Cluster_Medoids' function AND silhouette = FALSE, it returns TRUE", { cm = Cluster_Medoids(X, clusters = 8, distance_metric = 'euclidean') plt_sd = Silhouette_Dissimilarity_Plot(cm, silhouette = FALSE) testthat::expect_true( plt_sd ) }) testthat::test_that("in case of 'Clara_Medoids' function AND silhouette = TRUE, it returns TRUE", { cm = Clara_Medoids(X, clusters = 8, samples = 5, sample_size = 0.2, swap_phase = TRUE, fuzzy = T) plt_sd = Silhouette_Dissimilarity_Plot(cm, silhouette = TRUE) testthat::expect_true( plt_sd ) }) testthat::test_that("in case of 'Clara_Medoids' function AND silhouette = FALSE, it returns TRUE", { cm = Clara_Medoids(X, clusters = 4, samples = 5, sample_size = 0.2, swap_phase = TRUE, fuzzy = T) plt_sd = Silhouette_Dissimilarity_Plot(cm, silhouette = FALSE) testthat::expect_true( plt_sd ) })
"print.summ.grouped" <- function(x, ...){ if(!inherits(x, "summ.grouped")) stop("Use only with 'summ.grouped' objects.\n") obj <- x$object dets <- obj$details cat("\nCall:\n", deparse(obj$call), "\n\n", sep = "") if(length(coefs <- x$coef)){ cat("Model Summary:\n") model.sum <- data.frame("log.Lik" = round(x$logLik,3), "AIC" = round(x$AIC,3), "BIC" = round(x$BIC,3), row.names = "") print(model.sum) cat("\nCoefficients:\n") coefs <- data.frame("Esimate" = coefs[, 1], "Std.error" = coefs[, 2], "t.value" = coefs[, 3], "p.value" = format.pval(coefs[, 4], digits = 2, eps = 1e-03)) if(nrow(coefs) == 1) row.names(coefs) <- "(Intercept)" print(coefs, digits = 3) cat("\nRandom-Effect:\n") distr <- dets$distr link.distr <- paste(dets$link, "-", distr, sep = "") distr <- if(distr == "t") paste(link.distr, "(df=", dets$df, ")", sep = "") else link.distr sigma <- data.frame("value" = x$sigma, "std.error" = x$se.sigma, "link-distribution" = distr, row.names = "sigma") print(sigma, digits = 3) } else cat("No coefficients\n") cat("\nOptimization:\n") cat("Convergence:", dets$conv, "\n") cat("max(|grad|):", format.pval(dets$max.sc, digits = 2, eps = 1e-06), "\n") cat(" Outer iter:", dets$k, "\n\n") invisible(x) }
mtukey.test<-function(Y,alpha=0.05,correction=0,Nboot=1000) { p.test<-function(data) { n.a<-nrow(data) n.b<-ncol(data) mu<-mean(data) r.effect<-apply(data,1,mean)-mu c.effect<-apply(data,2,mean)-mu exp<-matrix(mu+rep(r.effect,n.b)+rep(c.effect,each=n.a),n.a,n.b) err<-data-exp k<-sum(cbind(r.effect)%*%rbind(c.effect)*err)/sum(cbind(r.effect)^2%*%rbind(c.effect)^2) y<-data-mu-rep(c.effect,each=n.a) x<-matrix(1+k*rep(c.effect,each=n.a),n.a,n.b) a.new<-apply(x*y,1,sum)/apply(x^2,1,sum) y<-data-mu-rep(r.effect,n.b) x<-matrix(1+k*rep(r.effect,n.b),n.a,n.b) b.new<-apply(x*y,2,sum)/apply(x^2,2,sum) exp2<-matrix(mu+rep(a.new,n.b)+rep(b.new,each=n.a),n.a,n.b) err2<-data-exp2 k.new<-sum(cbind(a.new)%*%rbind(b.new)*err2)/sum(cbind(a.new)^2%*%rbind(b.new)^2) exp3<-matrix(mu+rep(a.new,n.b)+rep(b.new,each=n.a),n.a,n.b) + k.new*cbind(a.new)%*%rbind(b.new) err3<-data-exp3 rss0<-sum(err^2) rss<-sum(err3^2) s<-rss/(n.a*n.b-n.a-n.b) loglik.ratio<-rss0/rss stat<-(loglik.ratio-1)*(n.a*n.b-n.a-n.b)/qf(1-alpha,1,n.a*n.b-n.a-n.b) return(c(stat,rss,s,loglik.ratio,abs(k.new))) } n.a<-nrow(Y) n.b<-ncol(Y) mu<-mean(Y) r.effect<-apply(Y,1,mean)-mu c.effect<-apply(Y,2,mean)-mu exp<-matrix(mu+rep(r.effect,n.b)+rep(c.effect,each=n.a),n.a,n.b) err<-Y-exp ppp<-p.test(Y) if (correction==0) out<-list(result=ppp[1]>1,stat=ppp[1],critical.value=1,alpha=alpha,name="Modified Tukey test") if (correction==1) { boot<-replicate(Nboot,p.test(exp+sample(err,n.a*n.b, replace=FALSE))) B<-apply(boot,1,quantile,probs=1-alpha) out<-list(result=ppp[1]>B[1],stat=ppp[1],critical.value=B[1],alpha=alpha,name="Modified Tukey test (small sample size correction, type 1)") } if (correction==2) { boot<-replicate(Nboot,p.test(exp+rnorm(n.a*n.b,sd=sqrt(ppp[3])))) B<-apply(boot,1,quantile,probs=1-alpha) out<-list(result=ppp[1]>B[1],stat=ppp[1],critical.value=B[1],alpha=alpha,name="Modified Tukey test (small sample size correction, type 2)") } class(out)<-"aTest" return(out) }
"grch38"
print.submean <- function(x,...) { cat("\nsubmean object: Sub-sample mean estimate\n", sep="") if(x$call$fpc == FALSE) cat("Without ") else cat("With ") cat("finite population correction.") cat("\nUsing method: ", x$call$method, "\n", sep="") cat("\nMean estimate: ", round(x$mean,4), "\n", sep="") cat("Standard error: ", round(x$se,4), "\n", sep="") cat(100 * x$call$level,"% confidence interval: [",round(x$ci[1],4),",",round(x$ci[2],4),"]\n\n", sep="") invisible(x) }
user_followee_count <- function(id, url = get_default_url(), key = get_default_key(), as = "list", ...) { id <- as.ckan_user(id, url = url) res <- ckan_GET(url, 'user_followee_count', query = list(id = id$id), key = key, opts = list(...)) switch(as, json = res, list = jsl(res), table = jsd(res)) }
context("UNFv6: UNF Class Object") test_that("Object is 'UNF' class", { expect_equal(class(unf6(1)), "UNF") }) test_that("'UNF' class object prints", { u <- unf6(1) expect_equal(class(print(u)), "UNF", label = "print UNF") attr(u, "formatted") <- NULL expect_equal(class(print(u)), "UNF", label = "print UNF without 'formatted' attribute") attr(u, "version") <- NULL expect_equal(class(print(u)), "UNF", label = "print UNF without 'formatted' or 'version' attributes") u2 <- unf5(1) expect_equal(class(print(u2)), "UNF", label = "print UNF version < 6") }) test_that("Object slots", { expect_equal(names(unf6(1)), c("unf","hash","unflong","formatted"), label = "object names correct") expect_equal(class(unf6(1)$unf), "character", label = "unf is character") expect_equal(class(unf6(1)$hash), "raw", label = "hash is raw") expect_equal(class(unf6(1)$unflong), "character", label = "unflong is character") expect_equal(class(unf6(1)$formatted), "character", label = "formatted is character") }) test_that("Attributes", { expect_equal(attr(unf6(1), "class"), "UNF", label = "class") expect_equal(attr(unf6(1), "version"), 6, label = "version") expect_equal(attr(unf6(1), "digits"), 7, label = "digits") expect_equal(attr(unf6(1), "characters"), 128, label = "characters") expect_equal(attr(unf6(1), "truncation"), 128, label = "truncation") })
require(geometa, quietly = TRUE) require(testthat) context("ISOServiceIdentification") test_that("encoding",{ testthat::skip_on_cran() md <- ISOServiceIdentification$new() md$setAbstract("abstract") md$setPurpose("purpose") rp <- ISOResponsibleParty$new() rp$setIndividualName("someone") rp$setOrganisationName("somewhere") rp$setPositionName("someposition") rp$setRole("pointOfContact") contact <- ISOContact$new() phone <- ISOTelephone$new() phone$setVoice("myphonenumber") phone$setFacsimile("myfacsimile") contact$setPhone(phone) address <- ISOAddress$new() address$setDeliveryPoint("theaddress") address$setCity("thecity") address$setPostalCode("111") address$setCountry("France") address$setEmail("[email protected]") contact$setAddress(address) res <- ISOOnlineResource$new() res$setLinkage("http://www.somewhereovertheweb.org") res$setName("somename") contact$setOnlineResource(res) rp$setContactInfo(contact) md$addPointOfContact(rp) ct <- ISOCitation$new() ct$setTitle("sometitle") d <- ISODate$new() d$setDate(ISOdate(2015, 1, 1, 1)) d$setDateType("publication") ct$addDate(d) ct$setEdition("1.0") ct$setEditionDate(ISOdate(2015,1,1)) ct$addIdentifier(ISOMetaIdentifier$new(code = "identifier")) ct$addPresentationForm("mapDigital") ct$addCitedResponsibleParty(rp) md$setCitation(ct) go <- ISOBrowseGraphic$new( fileName = "http://wwww.somefile.org/png", fileDescription = "Map Overview", fileType = "image/png" ) md$setGraphicOverview(go) mi <- ISOMaintenanceInformation$new() mi$setMaintenanceFrequency("daily") md$setResourceMaintenance(mi) lc <- ISOLegalConstraints$new() lc$addUseLimitation("limitation1") lc$addUseLimitation("limitation2") lc$addUseLimitation("limitation3") lc$addAccessConstraint("copyright") lc$addAccessConstraint("license") lc$addUseConstraint("copyright") lc$addUseConstraint("license") expect_equal(length(lc$useLimitation), 3L) expect_equal(length(lc$accessConstraints), 2L) expect_equal(length(lc$useConstraints), 2L) md$setResourceConstraints(lc) xml <- md$encode() expect_is(xml, "XMLInternalNode") md2 <- ISOServiceIdentification$new(xml = xml) xml2 <- md2$encode() expect_true(ISOAbstractObject$compare(md, md2)) }) test_that("encoding - i18n",{ testthat::skip_on_cran() md <- ISOServiceIdentification$new() md$setAbstract( "abstract", locales = list( EN = "abstract", FR = "résumé", ES = "resumen", AR = "ملخص", RU = "резюме", ZH = "摘要" )) md$setPurpose( "purpose", locales = list( EN = "purpose", FR = "objectif", ES = "objetivo", AR = "غرض", RU = "цель", ZH = "目的" )) rp <- ISOResponsibleParty$new() rp$setIndividualName( "someone", locales = list( EN = "name in english", FR = "nom en français", ES = "Nombre en español", AR = "الاسم باللغة العربية", RU = "имя на русском", ZH = "中文名" )) rp$setOrganisationName( "organization", locales = list( EN = "organization", FR = "organisation", ES = "organización", AR = "منظمة", RU = "организация", ZH = "组织" )) rp$setPositionName( "someposition", locales = list( EN = "my position", FR = "mon poste", ES = "mi posición", AR = "موقعي", RU = "моя позиция", ZH = "我的位置" ) ) rp$setRole("pointOfContact") contact <- ISOContact$new() phone <- ISOTelephone$new() phone$setVoice( "myphonenumber", locales = list( EN = "myphonenumber in UK", FR = "mon numéro en France", ES = "mi número en España", AR = "رقم هاتفي في المملكة العربية السعودية", RU = "мой номер телефона в России", ZH = "我在中国的电话号码" ) ) phone$setFacsimile( "myfacsimile", locales = list( EN = "mi facsimile in UK", FR = "mon fax en France", ES = "mi fax en España", AR = "فاكس بلدي في المملكة العربية السعودية", RU = "мой факс в россии", ZH = "我在中国的传真" ) ) contact$setPhone(phone) address <- ISOAddress$new() address$setDeliveryPoint( "theaddress", locales = list( EN = "address in UK", FR = "adresse en France", ES = "dirección en España", AR = "العنوان في المملكة العربية السعودية", RU = "адрес в россии", ZH = "在中国的地址" )) address$setCity( "thecity", locales = list( EN = "thecity", FR="ville", ES="Ciudad", AR="مدينة", RU="город", ZH="城市" )) address$setPostalCode( "111", locales=list( EN="111_UK",FR="111_FR",ES="111_ES",AR="111_AR",RU="111_RU",ZH="111_ZH" ) ) address$setCountry( "United Kingdom", locales=list( EN="United Kingdom", FR="France", ES="España", AR="网站名称", RU="Россия", ZH = "Китай" ) ) address$setEmail( "[email protected]", locales = list( EN="[email protected]", FR="[email protected]", ES="[email protected]", AR="[email protected]", RU="[email protected]", ZH="[email protected]" ) ) contact$setAddress(address) res <- ISOOnlineResource$new() res$setLinkage("http://www.somewhereovertheweb.org") res$setName( "name", locales=list( EN="name of the website", FR="nom du site internet", ES="nombre del sitio web", AR="اسم الموقع", RU="название сайта", ZH="网站名称" )) res$setDescription( "description", locales = list( EN="description_EN", FR="description_FR", ES="description_ES", AR="description_AR", RU="description_RU", ZH="description_ZH" )) res$setProtocol( "protocol", locales=list( EN="protocol_EN", FR="protocol_FR", ES="protocol_ES", AR="protocol_AR", RU="protocol_RU", ZH="protocol_ZH" )) contact$setOnlineResource(res) rp$setContactInfo(contact) md$addPointOfContact(rp) ct <- ISOCitation$new() ct$setTitle( "sometitle", locales = list( EN = "title", FR = "titre", ES = "título", AR = "لقبان", RU = "название", ZH = "标题" ) ) d <- ISODate$new() d$setDate(ISOdate(2015, 1, 1, 1)) d$setDateType("publication") ct$addDate(d) ct$setEdition("1.0") ct$setEditionDate(ISOdate(2015,1,1)) ct$addIdentifier(ISOMetaIdentifier$new(code = "identifier")) ct$addPresentationForm("mapDigital") ct$addCitedResponsibleParty(rp) md$setCitation(ct) go <- ISOBrowseGraphic$new() go$setFileName("http://wwww.somefile.org/png") go$setFileDescription( "Map overview", locales = list( EN = "Map overview", FR = "Aperçu de carte", ES = "Vista general del mapa", AR = "نظرة عامة على الخريطة", RU = "Обзор карты", ZH = "地图概述" ) ) md$setGraphicOverview(go) mi <- ISOMaintenanceInformation$new() mi$setMaintenanceFrequency("daily") md$setResourceMaintenance(mi) lc <- ISOLegalConstraints$new() lc$addUseLimitation( "use limitation 1", locales= list( EN = "use limitation 1", FR = "limitation d'utilisation 1", ES = "limitación de uso 1", AR = "الحد من الاستخدام 1", RU = "предел использования 1", ZH = "使用限制1" )) lc$addUseLimitation( "use limitation 2", locales= list( EN = "use limitation 2", FR = "limitation d'utilisation 2", ES = "limitación de uso 2", AR = "2 الحد من الاستخدام ", RU = "предел использования 2", ZH = "使用限制2" )) lc$addAccessConstraint("copyright") lc$addAccessConstraint("license") lc$addUseConstraint("copyright") lc$addUseConstraint("license") expect_equal(length(lc$useLimitation), 2L) expect_equal(length(lc$accessConstraints), 2L) expect_equal(length(lc$useConstraints), 2L) md$setResourceConstraints(lc) xml <- md$encode() expect_is(xml, "XMLInternalNode") md2 <- ISOServiceIdentification$new(xml = xml) xml2 <- md2$encode() expect_true(ISOAbstractObject$compare(md, md2)) }) test_that("encoding",{ testthat::skip_on_cran() md <- ISOSRVServiceIdentification$new() md$setAbstract("abstract") md$setPurpose("purpose") rp <- ISOResponsibleParty$new() rp$setIndividualName("someone") rp$setOrganisationName("somewhere") rp$setPositionName("someposition") rp$setRole("pointOfContact") contact <- ISOContact$new() phone <- ISOTelephone$new() phone$setVoice("myphonenumber") phone$setFacsimile("myfacsimile") contact$setPhone(phone) address <- ISOAddress$new() address$setDeliveryPoint("theaddress") address$setCity("thecity") address$setPostalCode("111") address$setCountry("France") address$setEmail("[email protected]") contact$setAddress(address) res <- ISOOnlineResource$new() res$setLinkage("http://www.somewhereovertheweb.org") res$setName("somename") contact$setOnlineResource(res) rp$setContactInfo(contact) md$addPointOfContact(rp) ct <- ISOCitation$new() ct$setTitle("sometitle") d <- ISODate$new() d$setDate(ISOdate(2015, 1, 1, 1)) d$setDateType("publication") ct$addDate(d) ct$setEdition("1.0") ct$setEditionDate(ISOdate(2015,1,1)) ct$addIdentifier(ISOMetaIdentifier$new(code = "identifier")) ct$addPresentationForm("mapDigital") ct$addCitedResponsibleParty(rp) md$setCitation(ct) go <- ISOBrowseGraphic$new( fileName = "http://wwww.somefile.org/png", fileDescription = "Map Overview", fileType = "image/png" ) md$setGraphicOverview(go) mi <- ISOMaintenanceInformation$new() mi$setMaintenanceFrequency("daily") md$setResourceMaintenance(mi) lc <- ISOLegalConstraints$new() lc$addUseLimitation("limitation1") lc$addUseLimitation("limitation2") lc$addUseLimitation("limitation3") lc$addAccessConstraint("copyright") lc$addAccessConstraint("license") lc$addUseConstraint("copyright") lc$addUseConstraint("license") expect_equal(length(lc$useLimitation), 3L) expect_equal(length(lc$accessConstraints), 2L) expect_equal(length(lc$useConstraints), 2L) md$setResourceConstraints(lc) md$setServiceType("Fishery data harmonization process") md$addServiceTypeVersion("1.0") orderProcess <- ISOStandardOrderProcess$new() orderProcess$setFees("fees") orderProcess$setPlannedAvailableDateTime(ISOdate(2017,7,5,12,0,0)) orderProcess$setOrderingInstructions("instructions") orderProcess$setTurnaround("turnaround") md$setAccessProperties(orderProcess) md$setRestrictions(lc) kwds <- ISOKeywords$new() kwds$addKeyword("keyword1") kwds$addKeyword("keyword2") kwds$setKeywordType("theme") th <- ISOCitation$new() th$setTitle("General") th$addDate(d) kwds$setThesaurusName(th) md$addKeywords(kwds) extent <- ISOExtent$new() bbox <- ISOGeographicBoundingBox$new(minx = -180, miny = -90, maxx = 180, maxy = 90) extent$setGeographicElement(bbox) md$addExtent(extent) md$setCouplingType("tight") coupledDataset1 <- ISOCoupledResource$new() coupledDataset1$setOperationName("Rscript") coupledDataset1$setIdentifier("my-dataset-identifier") coupledDataset2 <- ISOCoupledResource$new() coupledDataset2$setOperationName("WPS:Execute") coupledDataset2$setIdentifier("my-dataset-identifier") md$addCoupledResource(coupledDataset1) md$addCoupledResource(coupledDataset2) scriptOp <- ISOOperationMetadata$new() scriptOp$setOperationName("Execute") scriptOp$addDCP("WebServices") scriptOp$setOperationDescription("WPS Execute") scriptOp$setInvocationName("identifier") for(i in 1:3){ param <- ISOParameter$new() param$setName(sprintf("name%s",i), "xs:string") param$setDirection("in") param$setDescription(sprintf("description%s",i)) param$setOptionality(FALSE) param$setRepeatability(FALSE) param$setValueType("xs:string") scriptOp$addParameter(param) } outParam <-ISOParameter$new() outParam$setName("outputname", "xs:string") outParam$setDirection("out") outParam$setDescription("outputdescription") outParam$setOptionality(FALSE) outParam$setRepeatability(FALSE) outParam$setValueType("xs:string") scriptOp$addParameter(outParam) or <- ISOOnlineResource$new() or$setLinkage("http://somelink/myrscript.R") or$setName("R script name") or$setDescription("R script description") or$setProtocol("protocol") scriptOp$addConnectPoint(or) md$addOperationMetadata(scriptOp) wpsOp <- ISOOperationMetadata$new() wpsOp$setOperationName("WPS:Execute") wpsOp$addDCP("WebServices") wpsOp$setOperationDescription("WPS Execute") invocationName <- "mywpsidentifier" wpsOp$setInvocationName(invocationName) for(i in 1:3){ param <- ISOParameter$new() param$setName(sprintf("name%s",i), "xs:string") param$setDirection("in") param$setDescription(sprintf("description%s",i)) param$setOptionality(FALSE) param$setRepeatability(FALSE) param$setValueType("xs:string") wpsOp$addParameter(param) } outParam <-ISOParameter$new() outParam$setName("outputname", "xs:string") outParam$setDirection("out") outParam$setDescription("outputdescription") outParam$setOptionality(FALSE) outParam$setRepeatability(FALSE) outParam$setValueType("xs:string") wpsOp$addParameter(outParam) or1 <- ISOOnlineResource$new() or1$setLinkage(sprintf("http://somelink/wps?request=Execute&version=1.0.0&Identifier=%s",invocationName)) or1$setName("WPS process name") or1$setDescription("WPS process description") or1$setProtocol("protocol") wpsOp$addConnectPoint(or1) or2 <- ISOOnlineResource$new() or2$setLinkage("http://somelink/myrscript.R") or2$setName("Source R script name") or2$setDescription("Source R script description") or2$setProtocol("protocol") wpsOp$addConnectPoint(or2) md$addOperationMetadata(wpsOp) xml <- md$encode() expect_is(xml, "XMLInternalNode") md2 <- ISOSRVServiceIdentification$new(xml = xml) xml2 <- md2$encode() expect_true(ISOAbstractObject$compare(md, md2)) }) test_that("encoding - i18n",{ testthat::skip_on_cran() md <- ISOSRVServiceIdentification$new() md$setAbstract( "abstract", locales = list( EN = "abstract", FR = "résumé", ES = "resumen", AR = "ملخص", RU = "резюме", ZH = "摘要" )) md$setPurpose( "purpose", locales = list( EN = "purpose", FR = "objectif", ES = "objetivo", AR = "غرض", RU = "цель", ZH = "目的" )) rp <- ISOResponsibleParty$new() rp$setIndividualName( "someone", locales = list( EN = "name in english", FR = "nom en français", ES = "Nombre en español", AR = "الاسم باللغة العربية", RU = "имя на русском", ZH = "中文名" )) rp$setOrganisationName( "organization", locales = list( EN = "organization", FR = "organisation", ES = "organización", AR = "منظمة", RU = "организация", ZH = "组织" )) rp$setPositionName( "someposition", locales = list( EN = "my position", FR = "mon poste", ES = "mi posición", AR = "موقعي", RU = "моя позиция", ZH = "我的位置" ) ) rp$setRole("pointOfContact") contact <- ISOContact$new() phone <- ISOTelephone$new() phone$setVoice( "myphonenumber", locales = list( EN = "myphonenumber in UK", FR = "mon numéro en France", ES = "mi número en España", AR = "رقم هاتفي في المملكة العربية السعودية", RU = "мой номер телефона в России", ZH = "我在中国的电话号码" ) ) phone$setFacsimile( "myfacsimile", locales = list( EN = "mi facsimile in UK", FR = "mon fax en France", ES = "mi fax en España", AR = "فاكس بلدي في المملكة العربية السعودية", RU = "мой факс в россии", ZH = "我在中国的传真" ) ) contact$setPhone(phone) address <- ISOAddress$new() address$setDeliveryPoint( "theaddress", locales = list( EN = "address in UK", FR = "adresse en France", ES = "dirección en España", AR = "العنوان في المملكة العربية السعودية", RU = "адрес в россии", ZH = "在中国的地址" )) address$setCity( "thecity", locales = list( EN = "thecity", FR="ville", ES="Ciudad", AR="مدينة", RU="город", ZH="城市" )) address$setPostalCode( "111", locales=list( EN="111_UK",FR="111_FR",ES="111_ES",AR="111_AR",RU="111_RU",ZH="111_ZH" ) ) address$setCountry( "United Kingdom", locales=list( EN="United Kingdom", FR="France", ES="España", AR="网站名称", RU="Россия", ZH = "Китай" ) ) address$setEmail( "[email protected]", locales = list( EN="[email protected]", FR="[email protected]", ES="[email protected]", AR="[email protected]", RU="[email protected]", ZH="[email protected]" ) ) contact$setAddress(address) res <- ISOOnlineResource$new() res$setLinkage("http://www.somewhereovertheweb.org") res$setName( "name", locales=list( EN="name of the website", FR="nom du site internet", ES="nombre del sitio web", AR="اسم الموقع", RU="название сайта", ZH="网站名称" )) res$setDescription( "description", locales = list( EN="description_EN", FR="description_FR", ES="description_ES", AR="description_AR", RU="description_RU", ZH="description_ZH" )) res$setProtocol( "protocol", locales=list( EN="protocol_EN", FR="protocol_FR", ES="protocol_ES", AR="protocol_AR", RU="protocol_RU", ZH="protocol_ZH" )) contact$setOnlineResource(res) rp$setContactInfo(contact) md$addPointOfContact(rp) ct <- ISOCitation$new() ct$setTitle( "sometitle", locales = list( EN = "title", FR = "titre", ES = "título", AR = "لقبان", RU = "название", ZH = "标题" ) ) d <- ISODate$new() d$setDate(ISOdate(2015, 1, 1, 1)) d$setDateType("publication") ct$addDate(d) ct$setEdition("1.0") ct$setEditionDate(ISOdate(2015,1,1)) ct$addIdentifier(ISOMetaIdentifier$new(code = "identifier")) ct$addPresentationForm("mapDigital") ct$addCitedResponsibleParty(rp) md$setCitation(ct) go <- ISOBrowseGraphic$new() go$setFileName("http://wwww.somefile.org/png") go$setFileDescription( "Map overview", locales = list( EN = "Map overview", FR = "Aperçu de carte", ES = "Vista general del mapa", AR = "نظرة عامة على الخريطة", RU = "Обзор карты", ZH = "地图概述" ) ) md$setGraphicOverview(go) mi <- ISOMaintenanceInformation$new() mi$setMaintenanceFrequency("daily") md$setResourceMaintenance(mi) lc <- ISOLegalConstraints$new() lc$addUseLimitation( "use limitation 1", locales= list( EN = "use limitation 1", FR = "limitation d'utilisation 1", ES = "limitación de uso 1", AR = "الحد من الاستخدام 1", RU = "предел использования 1", ZH = "使用限制1" )) lc$addUseLimitation( "use limitation 2", locales= list( EN = "use limitation 2", FR = "limitation d'utilisation 2", ES = "limitación de uso 2", AR = "2 الحد من الاستخدام ", RU = "предел использования 2", ZH = "使用限制2" )) lc$addAccessConstraint("copyright") lc$addAccessConstraint("license") lc$addUseConstraint("copyright") lc$addUseConstraint("license") expect_equal(length(lc$useLimitation), 2L) expect_equal(length(lc$accessConstraints), 2L) expect_equal(length(lc$useConstraints), 2L) md$setResourceConstraints(lc) md$setServiceType("Fishery data harmonization process") md$addServiceTypeVersion("1.0") orderProcess <- ISOStandardOrderProcess$new() orderProcess$setFees( "license fees", locales = list( EN = "license fees", FR = "frais de licence", ES = "derechos de licencia", AR = "رسوم الترخيص", RU = "лицензионные сборы", ZH = "许可费" )) orderProcess$setPlannedAvailableDateTime(ISOdate(2017,7,5,12,0,0)) orderProcess$setOrderingInstructions( "instructions", locales = list( EN = "instructions", FR = "instructions", ES = "instrucciones", AR = "تعليمات", RU = "инструкции", ZH = "说明" )) orderProcess$setTurnaround( "turnaround", locales = list( EN = "turnaround", FR = "revirement", ES = "inversión", AR = "انعكاس", RU = "реверс", ZH = "翻转" )) md$setAccessProperties(orderProcess) md$setRestrictions(lc) kwds <- ISOKeywords$new() kwds$addKeyword( "keyword1", locales = list( EN = "keyword 1", FR = "mot-clé 1", ES = "palabra clave 1", AR = "1 الكلمة", RU = "ключевое слово 1", ZH = "关键词 1" )) kwds$addKeyword( "keyword1", locales = list( EN = "keyword 2", FR = "mot-clé 2", ES = "palabra clave 2", AR = "2 الكلمة", RU = "ключевое слово 2", ZH = "关键词 2" )) kwds$setKeywordType("theme") th <- ISOCitation$new() th$setTitle( "General", locales =list( EN = "General", FR = "Général", ES = "General", AR = "جنرال لواء", RU = "генеральный", ZH = "一般" )) th$addDate(d) kwds$setThesaurusName(th) md$addKeywords(kwds) extent <- ISOExtent$new() bbox <- ISOGeographicBoundingBox$new(minx = -180, miny = -90, maxx = 180, maxy = 90) extent$setGeographicElement(bbox) md$addExtent(extent) md$setCouplingType("tight") coupledDataset1 <- ISOCoupledResource$new() coupledDataset1$setOperationName("Rscript") coupledDataset1$setIdentifier("my-dataset-identifier") coupledDataset2 <- ISOCoupledResource$new() coupledDataset2$setOperationName("WPS:Execute") coupledDataset2$setIdentifier("my-dataset-identifier") md$addCoupledResource(coupledDataset1) md$addCoupledResource(coupledDataset2) scriptOp <- ISOOperationMetadata$new() scriptOp$setOperationName("Execute") scriptOp$addDCP("WebServices") scriptOp$setOperationDescription("WPS Execute") scriptOp$setInvocationName("identifier") for(i in 1:3){ param <- ISOParameter$new() param$setName(sprintf("name%s",i), "xs:string") param$setDirection("in") param$setDescription(sprintf("description%s",i)) param$setOptionality(FALSE) param$setRepeatability(FALSE) param$setValueType("xs:string") scriptOp$addParameter(param) } outParam <-ISOParameter$new() outParam$setName("outputname", "xs:string") outParam$setDirection("out") outParam$setDescription("outputdescription") outParam$setOptionality(FALSE) outParam$setRepeatability(FALSE) outParam$setValueType("xs:string") scriptOp$addParameter(outParam) or <- ISOOnlineResource$new() or$setLinkage("http://somelink/myrscript.R") or$setName("R script name") or$setDescription("R script description") or$setProtocol("protocol") scriptOp$addConnectPoint(or) md$addOperationMetadata(scriptOp) wpsOp <- ISOOperationMetadata$new() wpsOp$setOperationName("WPS:Execute") wpsOp$addDCP("WebServices") wpsOp$setOperationDescription("WPS Execute") invocationName <- "mywpsidentifier" wpsOp$setInvocationName(invocationName) for(i in 1:3){ param <- ISOParameter$new() param$setName(sprintf("name%s",i), "xs:string") param$setDirection("in") param$setDescription(sprintf("description%s",i)) param$setOptionality(FALSE) param$setRepeatability(FALSE) param$setValueType("xs:string") wpsOp$addParameter(param) } outParam <-ISOParameter$new() outParam$setName("outputname", "xs:string") outParam$setDirection("out") outParam$setDescription("outputdescription") outParam$setOptionality(FALSE) outParam$setRepeatability(FALSE) outParam$setValueType("xs:string") wpsOp$addParameter(outParam) or1 <- ISOOnlineResource$new() or1$setLinkage(sprintf("http://somelink/wps?request=Execute&version=1.0.0&Identifier=%s",invocationName)) or1$setName("WPS process name") or1$setDescription("WPS process description") or1$setProtocol("protocol") wpsOp$addConnectPoint(or1) or2 <- ISOOnlineResource$new() or2$setLinkage("http://somelink/myrscript.R") or2$setName("Source R script name") or2$setDescription("Source R script description") or2$setProtocol("protocol") wpsOp$addConnectPoint(or2) md$addOperationMetadata(wpsOp) xml <- md$encode() expect_is(xml, "XMLInternalNode") md2 <- ISOSRVServiceIdentification$new(xml = xml) xml2 <- md2$encode() expect_true(ISOAbstractObject$compare(md, md2)) })
gts <- function(y, groups, gnames = rownames(groups), characters) { if (!is.ts(y)) { y <- stats::as.ts(y) } if (ncol(y) <= 1L) { stop("Argument y must be a multivariate time series.", call. = FALSE) } bnames <- colnames(y) nc.y <- ncol(y) if (missing(characters)) { if (missing(groups)) { groups <- matrix(c(rep(1L, nc.y), seq(1L, nc.y)), nrow = 2L, byrow = TRUE) } else if (!is.matrix(groups)) { stop("Argument groups must be a matrix.", call. = FALSE) } else if (!is.character(groups[1L, ])) { if (all(groups[1L, ] == 1L)) { groups <- groups[-1L, , drop = FALSE] } tmp.last <- nrow(groups) if (all(groups[tmp.last, ] == seq(1L, nc.y))) { groups <- groups[-tmp.last, , drop = FALSE] } } } else { if (length(characters) == 1L) { stop("The argument characters must have length greater than one.", call. = FALSE) } if (!all(nchar(bnames)[1L] == nchar(bnames)[-1L])) { stop("The bottom names must be of the same length.", call. = FALSE) } if (any(nchar(bnames) != sum(unlist(characters)))) { warning("The argument characters is not fully specified for the bottom names.") } groups <- CreateGmat(bnames, characters) } gmat <- GmatrixG(groups) nr.gmat <- nrow(gmat) if (nr.gmat == 2L) { name.list <- NULL } else if (is.null(gnames)) { message("Argument gnames is missing and the default labels are used.") gnames <- paste0("G", 1L:(nr.gmat - 2L)) } colnames(gmat) <- bnames rownames(gmat) <- c("Total", gnames, "Bottom") if (nr.gmat > 2L) { times <- Mlevel(groups) full.groups <- mapply(rep, as.list(gnames), times, SIMPLIFY = FALSE) subnames <- apply(groups, 1, unique) if (is.matrix(subnames)) { subnames <- split(subnames, rep(1L:ncol(subnames), each = nrow(subnames))) } name.list <- mapply(paste0, full.groups, "/", subnames, SIMPLIFY = FALSE) names(name.list) <- gnames } return(structure( list(bts = y, groups = gmat, labels = name.list), class = c("gts") )) } get_groups <- function(y) { if(all(is.hts(y) && is.gts(y))) stop("'y' must be grouped time series.", call. = FALSE) return(y$groups) } GmatrixG <- function(xmat) { if (is.character(xmat)) { gmat <- t(apply(xmat, 1, function(x) as.integer(factor(x, unique(x))))) } else { gmat <- xmat } nc.xmat <- ncol(xmat) gmat <- rbind( if (all(gmat[1,] == rep(1L, nc.xmat))) NULL else rep(1L, nc.xmat), gmat, if (all(gmat[NROW(gmat),] == seq(1L, nc.xmat))) NULL else seq(1L, nc.xmat) ) return(structure(gmat, class = "gmatrix")) } Mlevel <- function(xgroup) { m <- apply(xgroup, 1, function(x) length(unique(x))) return(m) } InvS4g <- function(xgroup) { mlevel <- Mlevel(xgroup) len <- length(mlevel) repcount <- mlevel[len]/mlevel inv.s <- 1/unlist(mapply(rep, repcount, mlevel, SIMPLIFY = FALSE)) return(inv.s) } CreateGmat <- function(bnames, characters) { total.len <- length(characters) sub.len <- c(0L, lapply(characters, length)) cs <- cumsum(unlist(sub.len)) int.char <- unlist(characters) end <- cumsum(int.char) start <- end - int.char + 1L tmp.token <- sapply(bnames, function(x) substring(x, start, end)) token <- vector(length = total.len, mode = "list") for (i in 1L:total.len) { token[[i]] <- matrix(, nrow = sub.len[[i + 1L]], ncol = ncol(tmp.token)) } for (i in 1L:total.len) { token[[i]][1L, ] <- tmp.token[cs[i] + 1L, ] if (sub.len[[i + 1L]] >= 2L) { for (j in 2L:sub.len[[i + 1L]]) { token[[i]][j, ] <- paste0(token[[i]][j - 1L, ], tmp.token[cs[i] + j, ]) } } } cn <- combn(1L:total.len, 2) ncl <- ncol(cn) groups <- vector(length = ncl, mode = "list") for (i in 1L:ncl) { bigroups <- list(token[[cn[, i][1L]]], token[[cn[, i][2L]]]) nr1 <- nrow(bigroups[[1L]]) nr2 <- nrow(bigroups[[2L]]) nr <- nr1 * nr2 tmp.groups <- vector(length = nr1, mode = "list") for (j in 1L:nr1) { tmp.groups[[j]] <- paste0(bigroups[[1L]][j, ], bigroups[[2L]][1L, ]) if (nr2 >= 2L) { for (k in 2L:nr2) { tmp.groups[[j]] <- rbind(tmp.groups[[j]], paste0(bigroups[[1L]][j, ], bigroups[[2L]][k, ])) } } } groups[[i]] <- tmp.groups[[1L]] if (nr1 >= 2L) { for (h in 2L:nr1) { groups[[i]] <- rbind(groups[[i]], tmp.groups[[h]]) } } } new.list <- c(token, groups) gmatrix <- new.list[[1L]] for (i in 2L:length(new.list)) { gmatrix <- rbind(gmatrix, new.list[[i]]) } gmatrix <- gmatrix[!duplicated(gmatrix), , drop = FALSE] check <- try(which(gmatrix == bnames, arr.ind = TRUE)[1L, 1L], silent = TRUE) if (class(check) != "try-error") { gmatrix <- gmatrix[-check, ] } return(gmatrix) } is.gts <- function(xts) { is.element("gts", class(xts)) } print.gts <- function(x, ...) { cat("Grouped Time Series \n") nlevels <- Mlevel(x$groups) cat(length(nlevels), "Levels \n") cat("Number of groups at each level:", nlevels, "\n") cat("Total number of series:", sum(nlevels), "\n") if (is.null(x$histy)) { cat("Number of observations per series:", nrow(x$bts), "\n") cat("Top level series: \n") } else { cat("Number of observations in each historical series:", nrow(x$histy), "\n") cat("Number of forecasts per series:", nrow(x$bts), "\n") cat("Top level series of forecasts: \n") } topts <- ts(rowSums(x$bts), start = stats::tsp(x$bts)[1L], frequency = stats::tsp(x$bts)[3L]) print(topts) } summary.gts <- function(object, ...) { print(object) if (is.null(object$histy)) { cat("\n") cat("Labels: \n") print(names(object$labels)) } else { method <- switch(object$method, comb = "Optimal combination forecasts", bu = "Bottom-up forecasts", mo = "Middle-out forecasts", tdgsa = "Top-down forecasts based on the average historical proportions", tdgsf = "Top-down forecasts based on the proportion of historical averages", tdfp = "Top-down forecasts using forecasts proportions") fmethod <- switch(object$fmethod, ets = "ETS", arima = "Arima", rw = "Random walk") cat("\n") cat(paste("Method:", method), "\n") cat(paste("Forecast method:", fmethod), "\n") if (!is.null(object$fitted)) { cat("In-sample error measures at the bottom level: \n") print(accuracy.gts(object)) } } }
read.blast <- function(file, sep = "\t"){ x <- read.table(file = file, header = FALSE, sep = sep, quote = "\"", dec = ".", fill = TRUE, comment.char = "", stringsAsFactors = FALSE) if(ncol(x) != 12) stop("Data in given file", basename(file), "has wrong dimension!") names(x) <- c("query.id", "subject.id", "identity", "alignment.length", "mismatches", "gap.opens", "q.start", "q.end", "s.start", "s.end", "evalue", "bit.score") if(!all(sid <- x[,"subject.id"] %in% x[,"query.id"])) warning("The following 'subject.id's do not occur as 'query.id's: ", paste(x[!sid,"subject.id"], collapse = ", "), "\nThis may lead to problems in subsequent analyses!") x }
leveneAndWilcoxResidualDistributions <- function(Y, predicted, E, verbose){ uniqueE <- unique(E) numUniqueE <- length(uniqueE) residuals <- Y - predicted pvalueWilcoxon <- 1 pvalueLevene <- levene.test(residuals, as.factor(E), location = "mean")$p.value for(e in 1:numUniqueE){ pvalueWilcoxon <- min(pvalueWilcoxon, wilcox.test( residuals[which(E == uniqueE[e])], residuals[which(E != uniqueE[e])] )$p.value) if(numUniqueE == 2) break } bonfAdjustment <- if(numUniqueE == 2) 1 else numUniqueE pvalueWilcoxon <- pvalueWilcoxon*bonfAdjustment pvalue <- 2*min(pvalueWilcoxon, pvalueLevene) if(verbose) cat(paste("\np-value: ", pvalue)) list(pvalue = pvalue) }
modSimulator<-function(datStart=NULL, datFinish=NULL, modelTag=NULL, parS=NULL, seed=NULL, file=NULL, IOmode="suppress" ){ argument_check_simulator(modelTag=modelTag,datStart=datStart,datFinish=datFinish,parS=parS) modelInfo=get.multi.model.info(modelTag=modelTag) modelTag=update.simPriority(modelInfo=modelInfo) simVar=sapply(X=modelInfo[modelTag],FUN=return.simVar,USE.NAMES=TRUE) dates=makeDates(datStart=datStart,datFinish=datFinish) datInd=mod.get.date.ind(obs=dates,modelTag=modelTag,modelInfo=modelInfo) set.seed(seed) for(mod in 1:length(modelTag)){ if(modelTag[mod]=="P-har-wgen"){ ar1ParMult=0.001 multRange=0.8 multiplierMean=1 sdJumpDistr=multRange/1.96*sqrt(1-ar1ParMult^2) X=arima.sim(n = datInd[[modelTag[mod]]]$nyr*12, list(ar =ar1ParMult),sd = sdJumpDistr) [email protected]+multiplierMean multSim=rep(NA,datInd[[modelTag[mod]]]$ndays) for(iy in 1:datInd[[modelTag[mod]]]$nyr){ for(im in 1:12){ ind=datInd[[modelTag[mod]]]$i.yy[[iy]][which(datInd[[modelTag[mod]]]$i.yy[[iy]]%in%datInd[[modelTag[mod]]]$i.mm[[im]])] multSim[ind]=X[(iy-1)*12+im] } } multSim<-pmax(multSim,0) modelInfo[[modelTag[mod]]]$ar1=multSim } else { modelInfo[[modelTag[mod]]]$ar1=NULL } } out=list() for(mod in 1:length(modelTag)){ randomVector <- runif(n=datInd[[modelTag[mod]]]$ndays) switch(simVar[mod], "P" = {wdStatus=NULL}, "Temp" = {if(modelInfo[[modelTag[mod]]]$WDcondition==TRUE){ wdStatus=out[["P"]]$sim }else{ wdStatus=NULL } }, {wdStatus=NULL} ) parSel=as.double(parS[[modelTag[mod]]]) write_model_env(envir = foreSIGHT_modelEnv, modelInfo = modelInfo[[modelTag[mod]]], modelTag = modelTag[mod], datInd = datInd[[modelTag[mod]]] ) out[[simVar[mod]]]=switch_simulator(type=modelInfo[[modelTag[mod]]]$simVar, parS=parSel, modelEnv = foreSIGHT_modelEnv, randomVector = randomVector, wdSeries=wdStatus, resid_ts=NULL, seed=seed) } simDat=makeOutputDataframe(data=out,dates=dates,simVar=simVar,modelTag=modelTag[1]) if(IOmode!="suppress"){ write.table(simDat,file=file,row.names=FALSE,quote = FALSE,sep=",") } return(simDat) } argument_check_simulator<-function(modelTag=NULL, datStart=NULL, datFinish=NULL, parS=NULL){ if (anyDuplicated(modelTag)!=0) {stop("There are multiple entries of the same model tag")} for(i in 1:length(modelTag)){ if(sum(modelTag[i] %in% modelTaglist)==0){ stop(paste0("modelTag ",i," unrecognised")) } } if(is.null(parS)){ stop("No model parameters specified via parS argument. Parameters are required for each modelTag.") } modelPar=ls(parS) for(i in 1:length(modelTag)){ if(sum(modelTag[i] %in% modelPar)==0){ stop(paste0("modelTag ",i,", parameters missing. No parameters supplied in 'pars' list")) } } modelInfo=get.multi.model.info(modelTag=modelTag) for(i in 1:length(modelTag)){ if(length(parS[[modelTag[i]]])!=modelInfo[[modelTag[i]]]$npars){ stop(paste0("Parameters missing for modelTag: ",modelTag[i],".\nMismatch in length of supplied parameter vector pars$",modelTag[i],".\nModel requires:", paste(modelInfo[[modelTag[i]]]$parNam,collapse=" "))) } } if(datStart>datFinish){ stop("Check supplied dates. datFinish must occur after datStart. Must use recognised date format: '1990-10-01', '01/10/1990', etc ") } }
`modelParameters.fitBMAgamma` <- function(fit, ...) { list(weights = fit$weights, popCoefs = fit$popCoefs, biasCoefs = fit$biasCoefs, varCoefs = fit$varCoefs, power = fit$power, model = "gamma") }
test_that("rmem works", { set.seed(1) pvec <- stats::runif(6) pvec <- pvec / sum(pvec) qvec <- stats::convolve(pvec, rev(pvec), type = "open") nvec <- round(100000000 * qvec) pest <- rmem(nvec = nvec, tol = 10^-6) expect_equal(pest, pvec, tolerance = 10^-4) }) test_that("hwelike works", { nvec <- c(421L, 390L, 159L, 27L, 3L, 0L, 0L, 0L, 0L) expect_error(hwelike(nvec = nvec), NA) nvec <- c(522L, 356L, 110L, 10L, 2L, 0L, 0L) expect_error(hwelike(nvec = nvec), NA) nvec <- c(48194L, 31292L, 14514L, 4696L, 1067L, 205L, 30L, 2L, 0L) expect_error(hwelike(nvec = nvec), NA) nvec <- c(25L, 0L, 0L, 0L, 0L) expect_error(rmlike(nvec = nvec), NA) }) test_that("hwenodr works", { nvec <- c(421L, 390L, 159L, 27L, 3L, 0L, 0L, 0L, 0L) expect_error(hwenodr(nvec = nvec), NA) nvec <- c(522L, 356L, 110L, 10L, 2L, 0L, 0L) expect_error(hwenodr(nvec = nvec), NA) nvec <- c(48194L, 31292L, 14514L, 4696L, 1067L, 205L, 30L, 2L, 0L) expect_error(hwenodr(nvec = nvec), NA) })
getcmat<-function(control,nats){ CON<-control; G<-nats Cmat<-matrix(rep(0,G*(G-1)),ncol=G) for (j in seq(G)){ if (j==CON) {Cmat[ ,j]<- 1} else if (j<CON) {Cmat[j,j]<--1} else if (j>CON) {Cmat[j-1,j]<--1} } return(Cmat) }
hMave <- function(x, y, censor, m0, B0 = NULL) { if (!is.matrix(x)) stop("x must be a matrix") if (!is.matrix(y)) stop("y must be a matrix") if (!is.matrix(censor)) stop("censor must be a matrix") censor = as.matrix(as.numeric(censor)) if (!all(censor %in% c(0,1))) stop("censor can only have two levels 0/1") n = nrow(x) p = ncol(x) onen = matrix(1, n, 1) x = scale(x, scale = FALSE) xeigen = eigen(t(x) %*% x /n) ss = xeigen$vectors[, rev(1:p), drop = FALSE] D = diag(rev(xeigen$values)) ss = (ss/repmat(matrix(sqrt(diag(D)), 1, p), p, 1)) x = x %*% ss if (!is.null(B0)) { if (!is.matrix(B0)) stop("B0 must be a matrix") if (nrow(B0) != ncol(x)) stop("Dimension of B0 is not correct") B0 = solve(ss) %*% B0 B = B0 m = ncol(B) }else{ m = p B = diag(p) } Ba = B BI = Ba B = B[, 1:m, drop = FALSE] noip0 = 0 noip1 = 1 iterstop = 0 Btmp = B rige = sd(y)*mean(apply(x, 2, sd)) y = scale(y) I = order(y) y = y[I, , drop = FALSE] x = x[I, , drop = FALSE] censor = censor[I, ,drop = FALSE] censor0 = censor niter = floor(p*3/2) yc = y ky2 = repmat(yc, 1, n) ky2 = (ky2-t(ky2))^2 censor = repmat(censor, 1, n) for (iter in 1:niter) { adj = p^(1/iter)*n^(1/(m0+4)-1/(m+4)) hy = sd(yc)/n^(1/5)*p^(1/(iter+1)) xB = x %*% Ba h = p^(1/(iter+1))*mean(apply(xB, 2, sd))/n^(1/(m+4)) h2 = 2*h*h*adj H = matrix(1, 1, n) for (i in 1:n) { xBi = (xB-repmat(xB[i, ,drop = FALSE], n, 1)) k = exp(-rowSums(xBi^2)/h2) kH = pnorm( (y[i] - y)/hy ) H[, i] = t(k) %*% kH/sum(k) } ky = censor*exp(-ky2/(2*hy*hy))/hy/repmat(H,n,1) n1 = ncol(ky) ABI = matrix(0, m, n*n) for (iiter in 1:max(1, (m < p)*floor(m/2))) { dd = matrix(0, m*p, m*p) dc = matrix(0, m*p, 1) for (j in 1:n) { xij = x - repmat(x[j, , drop = FALSE], n, 1) sxij = rowSums((xij %*% Ba)^2) + rowSums(xij^2)/1.5^iter ker = exp(-sxij/h2) rker = repmat(as.matrix(ker), 1, p+1) onexi = cbind(xij %*% B, onen) xk = t(onexi*rker[, 1:(m+1)]) abi = solve(xk %*% onexi + diag(1, m+1)/n) %*% (xk %*% ky) kxij = t(xij*rker[ , 1:p, drop = FALSE]) kxijy = kxij %*% (ky - repmat(abi[m+1, , drop = FALSE],n,1)) ddx = kxij %*% xij for (k1 in 1:m) { ka = ((k1-1)*p+1) : (k1*p) dc[ka,] = dc[ka,] + kxijy %*% t(abi[k1,,drop = FALSE]) } tmp = abi[1:m, , drop = FALSE] %*% t(abi[1:m, , drop = FALSE]) dd = dd + kronecker(tmp, ddx) ABI[, ((j-1)*n1+1):(j*n1)] = abi[1:m, , drop = FALSE] } B = solve(dd + rige* diag(1, length(dc))/n ) %*% dc B0 = matrix(B, p, m) %*% ABI B = eigen(B0 %*% t(B0))$vectors[, rev(1:p), drop = FALSE] B = B[, (p-m+1):p, drop = FALSE] Ba = B if (max(svd(B %*% t(B) - BI %*% t(BI))$d) < 0.001) break BI = B } mb = m ma = max(m-1,m0) m = ma B = B[ , (mb-m+1):mb, drop = FALSE] Ba = B if (max(svd(B %*% t(B) - BI %*% t(BI))$d) < 0.001 & iter > p+3 ) break BI = Ba if (iter == 1) B00 = B[, (ncol(B)-m0+1):ncol(B), drop = FALSE] } h2 = 2*n^(-2/(m0+3)) x = x[censor0 == 1, , drop = FALSE] y = y[censor0 == 1, , drop = FALSE] n = nrow(y) ky = scale(y) ky = exp(-(repmat(ky,1,n) - repmat(t(ky),n,1))^2/h2) kye = ky cv = 0 for (j in 1:n) { xij = x - repmat(x[j, , drop = FALSE], n, 1) sxij = rowSums((xij %*% Ba)^2) ker = as.matrix(exp(-sxij/h2)) ker[j] = 0 kye[j, ] = t(ker) %*% ky / sum(ker) } cv = sum((ky-kye)^2) B = ss %*% B apply(B, 2, function(x) x / sqrt(sum(x^2))) return(list("B" = B, "cv" = cv)) }
loglik_AtCtEt_epsp <- function(param, pheno_m, pheno_d, B_des_a_m, B_des_a_d, beta_a, D_a, B_des_c_m, B_des_c_d, beta_c, D_c, B_des_e_m, B_des_e_d, beta_e, D_e) { var_b_a <- param[1] var_b_c <- param[2] var_b_e <- param[3] nll <- .Call('loglik_AtCtEt_epsp_c', var_b_a, var_b_c, var_b_e, pheno_m, pheno_d, B_des_a_m, B_des_a_d, beta_a, D_a, B_des_c_m, B_des_c_d, beta_c, D_c, B_des_e_m, B_des_e_d, beta_e, D_e) return(nll) } loglik_AtCtEt_epsp_g <- function(param, pheno_m, pheno_d, B_des_a_m, B_des_a_d, B_des_c_m, B_des_c_d, B_des_e_m, B_des_e_d, var_b_a, var_b_c, var_b_e, D_a, D_c, D_e) { beta_a <- param[1:ncol(D_a)] beta_c <- param[(ncol(D_a)+1):(ncol(D_a)+ncol(D_c))] beta_e <- param[(ncol(D_a)+ncol(D_c)+1):(ncol(D_a)+ncol(D_c)+ncol(D_e))] nll <- .Call('loglik_AtCtEt_epsp_g_c', beta_a, beta_c, beta_e, pheno_m, pheno_d, B_des_a_m, B_des_a_d, B_des_c_m, B_des_c_d, B_des_e_m, B_des_e_d, var_b_a, var_b_c, var_b_e, D_a, D_c, D_e) return(nll) } gr_AtCtEt_epsp <- function(param, pheno_m, pheno_d, B_des_a_m, B_des_a_d, beta_a, D_a, B_des_c_m, B_des_c_d, beta_c, D_c, B_des_e_m, B_des_e_d, beta_e, D_e) { var_b_a <- param[1] var_b_c <- param[2] var_b_e <- param[3] d <- .Call('gr_AtCtEt_epsp_c', var_b_a, var_b_c, var_b_e, pheno_m, pheno_d, B_des_a_m, B_des_a_d, beta_a, D_a, B_des_c_m, B_des_c_d, beta_c, D_c, B_des_e_m, B_des_e_d, beta_e, D_e) return(d) } gr_AtCtEt_epsp_g <- function(param, pheno_m, pheno_d, B_des_a_m, B_des_a_d, B_des_c_m, B_des_c_d, B_des_e_m, B_des_e_d, var_b_a, var_b_c, var_b_e, D_a, D_c, D_e) { beta_a <- param[1:ncol(D_a)] beta_c <- param[(ncol(D_a)+1):(ncol(D_a)+ncol(D_c))] beta_e <- param[(ncol(D_a)+ncol(D_c)+1):(ncol(D_a)+ncol(D_c)+ncol(D_e))] d <- .Call('gr_AtCtEt_epsp_g_c', beta_a, beta_c, beta_e, pheno_m, pheno_d, B_des_a_m, B_des_a_d, B_des_c_m, B_des_c_d, B_des_e_m, B_des_e_d, var_b_a, var_b_c, var_b_e, D_a, D_c, D_e) return(d) }
example4_sv <- function(noBurnInIterations=2500, noIterations=7500, noParticles=500, initialTheta=c(0, 0.9, 0.2), syntheticData=FALSE) { set.seed(10) if (syntheticData) { y <- rnorm(10) } else { d <- Quandl::Quandl( "NASDAQOMX/OMXS30", start_date = "2012-01-02", end_date = "2014-01-02", type = "zoo" ) y <- as.numeric(100 * diff(log(d$"Index Value"))) } stepSize <- matrix( c( 0.137255431,-0.0016258103, 0.0015047492,-0.0016258103, 0.0004802053,-0.0009973058, 0.0015047492,-0.0009973058, 0.0031307062 ), ncol = 3, nrow = 3 ) stepSize <- 2.562^2 / 3 * stepSize res <- particleMetropolisHastingsSVmodel(y, initialTheta, noParticles, noIterations, stepSize) noIterationsToPlot <- min(c(1500, noIterations - noBurnInIterations)) iact <- makePlotsParticleMetropolisHastingsSVModel(y, res, noBurnInIterations, noIterations, noIterationsToPlot) resTh <- res$theta[noBurnInIterations:noIterations, ] resXh <- res$xHatFiltered[noBurnInIterations:noIterations, ] thhat <- colMeans(resTh) thhatSD <- apply(resTh, 2, sd) xhat <- colMeans(resXh) xhatSD <- apply(resXh, 2, sd) estCov <- var(resTh) list(thhat=thhat, xhat=xhat, thhatSD=thhatSD, xhatSD=xhatSD, iact=iact, estCov=estCov) }
linebreak <- function(breaks = "\n"){cat(breaks, colortext(paste(rep("-", getOption("width")), collapse = ""), defaults = "message"), "\n")} rm.lead.space <- function(word) { word <- bad.response(word) if(!is.na(word)) {word <- gsub("^[[:space:]]+|[[:space:]]+$", "", word)} return(word) } bad.response <- function (word, ...) { others <- unlist(list(...)) bad <- c(NA, "NA", "", " ", " ", others) if(length(word)==0) {word <- NA} for(i in 1:length(word)) { if(word[i] %in% bad) {word[i] <- NA} } return(word) } moniker <- function (word, misnom, spelling) { mis <- unlist(misnom) if(!is.na(match(word,mis))) { matched <- names(mis[match(word,mis)]) misnomed <- gsub("[[:digit:]]+","", matched) }else{ misnomed <- word } misnomed <- brit.us.conv(vec = misnomed, spelling = spelling, dictionary = FALSE) return(misnomed) } appropriate.answer <- function (answer, choices, default, dictionary = FALSE) { ret <- NA defaults <- paste(1:default) if(!dictionary) { qwert <- c(c("Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P")[1:(length(choices[-c(1:default)]))], "B", "H") app.ans <- c(defaults, qwert) first <- c(1:(length(defaults) + length(qwert))) names(app.ans) <- 1:length(app.ans) }else{ app.ans <- defaults names(app.ans) <- 1:(length(defaults)) } while(is.na(ret)) { if(toupper(answer) %in% app.ans) {ret <- toupper(answer) }else{ message("Inappropriate selection.") answer <- readline(prompt = "Please enter a new selection: ") } } ret <- as.numeric(names(which(ret == app.ans))) return(ret) } customMenu <- function (choices, title = NULL, default, dictionary = FALSE, help = FALSE) { if (!interactive()) {stop("menu() cannot be used non-interactively")} nc <- length(choices) if (length(title) && nzchar(title[1L])) {cat(title[1L], "\n")} if(!dictionary) { qwert <- c("Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P")[1:(length(choices[-c(1:default)]))] op <- paste0(format(c(seq_len(default),qwert)), ": ", choices) }else{op <- paste0(format(seq_len(default)), ": ", choices)} if (nc > default) { fop <- format(op) nw <- nchar(fop[1L], "w") + 2L ncol <- getOption("width")%/%nw if (ncol > 1L) if(default == 10 || default == 9) { word <- fop[1:5] word <- paste0(word, c(rep.int(" ", 4), "\n"), collapse = "") nw <- nchar(word) if(substr(word, nw-1, nw) != "\n") {word <- paste(substr(word, 1, nw-2), "\n")} string <- fop[6:default] opts <- ifelse(default == 9, 3, 4) string <- paste0(string, c(rep.int(" ", opts), "\n"), collapse = "") ns <- nchar(string) if(substr(string, ns-1, ns) != "\n") {string <- paste(substr(string, 1, ns-2), "\n")} }else{ def <- fop[1:default] def <- paste0(def, c(rep.int(" ", min(nc, ncol) - 1L), "\n"), collapse = "") n <- nchar(def) if(substr(def, n-1, n) != "\n") {def <- paste(substr(def, 1, n-2), "\n")} } resp <- fop[(default + 1):length(fop)] resp[1] <- paste0("\n", resp[1], collapse = "") resp.len <- length(resp) if(resp.len > ncol) { resp <- paste0(resp, c(rep.int(" ", min(nc, ncol) - 1L), "\n"), collapse = "") if((resp.len / ncol) %% 1 != 0) {resp <- paste0(paste0(resp, collapse = ""), "\n")} }else{resp <- paste0(paste0(resp, collapse = ""), "\n")} if(default == 10 || default == 9) { op <- paste0(styletext("Word options\n", defaults = "underline"), word, styletext("\nString options\n", defaults = "underline"), string, styletext("\nResponse options", defaults = "underline"), resp, collapse = "") }else if(default == 5) { op <- paste0(styletext("Word options\n", defaults = "underline"), def, styletext("\nResponse options", defaults = "underline"), resp, collapse = "") }else{stop("Error in customMenu")} }else{op <- c(op, "")} if(!help) {cat("", op, sep = "\n") }else{paste0("", resp, sep = "")} } error.fun <- function(result, SUB_FUN, FUN) { message(paste("\nAn error has occurred in the '", SUB_FUN, "' function of '", FUN, "':\n", sep ="")) cat(paste(result)) message("\nPlease open a new issue on GitHub (bug report): https://github.com/AlexChristensen/SemNetCleaner/issues/new/choose") OS <- as.character(Sys.info()["sysname"]) OSversion <- paste(as.character(Sys.info()[c("release", "version")]), collapse = " ") Rversion <- paste(R.version$major, R.version$minor, sep = ".") SNCversion <- paste(unlist(packageVersion("SemNetCleaner")), collapse = ".") SNDversion <- paste(unlist(packageVersion("SemNetDictionaries")), collapse = ".") message(paste("\nBe sure to provide the following information:\n")) message(styletext("To Reproduce:", defaults = "bold")) message(paste(" ", textsymbol("bullet"), " Function error occurred in: ", SUB_FUN, " function of ", FUN, sep = "")) message(styletext("\nR, SemNetCleaner, and SemNetDictionaries versions:", defaults = "bold")) message(paste(" ", textsymbol("bullet"), " R version: ", Rversion, sep = "")) message(paste(" ", textsymbol("bullet"), " SemNetCleaner version: ", SNCversion, sep = "")) message(paste(" ", textsymbol("bullet"), " SemNetDictionaries version: ", SNDversion, sep = "")) message(styletext("\nOperating System:", defaults = "bold")) message(paste(" ", textsymbol("bullet"), " OS: ", OS, sep = "")) message(paste(" ", textsymbol("bullet"), " Version: ", OSversion, sep = "")) } ql.dist <- function (wordA, wordB, allowPunctuations) { characters <- paste("([", paste(allowPunctuations, collapse = ""), "])|[[:punct:]]", sep = "", collapse = "") data <- apply(data, 2, function(y) gsub(characters, "\\1", y)) wordA <- stringi::stri_trans_general(wordA, "Latin-ASCII") wordA <- gsub("([-])|[[:punct:]]", "\\1", wordA) wordB <- stringi::stri_trans_general(wordB, "Latin-ASCII") wordB <- gsub("([-])|[[:punct:]]", "\\1", wordB) m <- structure(c(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 1, 1, 2, 2, 3, 4, 5, 6, 4, 5, 6, 7, 8, 3, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 1, 2, 1, 2, 1, 2, 2, 1, 1, 1, 1, 1, 1, 2, 2), .Dim = c(27L,2L), .Dimnames = list(c("q", "w", "e", "r", "t", "y", "u", "i","o", "p", "a", "z", "s", "x", "d", "c", "f", "b", "m", "j", "g", "h", "j", "k", "l", "v", "n"), c("x", "y"))) keyb <- sweep(m, 2, c(1, -1), "*") keyb <- rbind(keyb,c(4,-3),c(9,1),c(10,-1)) row.names(keyb)[28:30] <- c(" ","-","'") keys <- c(letters, " ", "-", "'") dvec <- numeric(2) if(nchar(wordA) != nchar(wordB)) { if(nchar(wordA) > nchar(wordB)) { wordC <- wordB wordB <- wordA wordA <- wordC } chardiff <- nchar(wordB) - nchar(wordA) while(chardiff != 0) { n <- nchar(wordA) res <- list() for(i in 1:n) {res[[i]] <- paste(substr(wordA, -1, (i-1)), keys, substr(wordA, i, n), sep = "")} res[[(i+1)]] <- paste(wordA, keys, sep = "") l.dist <- sapply(lapply(res, function(x){adist(x, wordB)}), rbind) min.dist <- unique(unlist(res)[which(l.dist == min(l.dist))])[1] target <- which.min(apply(l.dist,2,min)) if(target == 1) {before <- 0 }else{before <- sum(abs(keyb[substr(min.dist,(target-1),(target-1)),] - keyb[substr(min.dist, target, target),]))} if(target == nchar(min.dist)) {after <- 0 }else{after <- sum(abs(keyb[substr(min.dist,(target+1),(target+1)),] - keyb[substr(min.dist, target, target),]))} average <- mean(c(before,after)) penalty <- average / max(rowSums(sweep(keyb, 2, keyb[substr(min.dist, target, target),], "-"))) dvec[1] <- dvec[1] + penalty wordA <- min.dist chardiff <- nchar(wordB) - nchar(wordA) } } if(nchar(wordA) == nchar(wordB)) { if(wordA != wordB) { penalty <- numeric(nchar(wordA)) for(i in 1:nchar(wordA)) {penalty[i] <- sum(abs(keyb[substr(wordA,i,i),] - keyb[substr(wordB, i, i),])) / max(rowSums(sweep(keyb, 2, keyb[substr(wordA, i, i),], "-")))} dvec[2] <- sum(penalty) } } return(sum(dvec)) } permn<- function(x, fun = NULL, ...) { if(is.numeric(x) && length(x) == 1 && x > 0 && trunc(x) == x) x <- seq( x) n <- length(x) nofun <- is.null(fun) out <- vector("list", gamma(n + 1)) p <- ip <- seqn <- 1:n d <- rep(-1, n) d[1] <- 0 m <- n + 1 p <- c(m, p, m) i <- 1 use <- - c(1, n + 2) while(m != 1) { out[[i]] <- if(nofun) x[p[use]] else fun(x[p[use]], ...) i <- i + 1 m <- n chk <- (p[ip + d + 1] > seqn) m <- max(seqn[!chk]) if(m < n) d[(m + 1):n] <- - d[(m + 1):n] index1 <- ip[m] + 1 index2 <- p[index1] <- p[index1 + d[m]] p[index1 + d[m]] <- m tmp <- ip[index2] ip[index2] <- ip[m] ip[m] <- tmp } out } yes.no.menu <- function (title = NULL) { yes.no <- function (ans) { if(is.numeric(ans)){ return(NA) }else if(is.character(ans)){ ans <- tolower(ans) if(ans != "y" && ans != "yes" && ans != "n" && ans != "no"){ return(NA) }else{ return( switch(ans, "y" = 1, "yes" = 1, "n" = 2, "no" = 2 ) ) } }else{return(NA)} } title <- paste(title, "[Y/n]? ") ans <- readline(prompt = title) while(is.na(yes.no(ans))){ ans <- readline(prompt = "Inappropriate response. Try again [Y/n]. ") } return(yes.no(ans)) } obtain.id <- function (data) { named.id <- c("subject", "id", "participant", "part", "sub") if(any(named.id %in% tolower(colnames(data)))) {id.col <- na.omit(match(named.id, tolower(colnames(data)))) }else{ uniq.cols <- which(lapply(apply(data, 2, unique), length) == nrow(data)) if(length(uniq.cols)==1) {id.col <- uniq.cols} } if(exists("id.col", envir = environment())) { ids <- data[,id.col] message(paste("\nIDs refer to variable:", " '", colnames(data)[id.col], "'", sep = "")) data <- data[,-id.col] }else{ ids <- 1:nrow(data) message("\nIDs refer to row number") } res <- list() res$data <- data res$ids <- ids return(res) } convert.miss <- function (data, miss) { data <- as.matrix(data) data <- ifelse(data == paste(miss), NA, data) data <- apply(data, 2, bad.response) data <- ifelse(is.na(data), "", data) return(data) } prep.spellcheck.dictionary <- function (data, allowPunctuations, allowNumbers, lowercase) { if(all(allowPunctuations != "all")){ characters <- paste("([", paste(allowPunctuations, collapse = ""), "])|[[:punct:]]", sep = "", collapse = "") data <- apply(data, 2, function(y) gsub(characters, "\\1", y)) } if(!isTRUE(allowNumbers)){ data <- apply(data, 2, function(y) gsub("[[:digit:]]+", "", y)) } data <- apply(apply(data, 2, trimws), 1:2, rm.lead.space) if(isTRUE(lowercase)){ data <- apply(data, 2, tolower) } data <- apply(data, 2, function(y) gsub("[\n\r\t]", " ", y)) data <- apply(data, 2, strsplit, split = " ") data <- lapply(data, function(y){ lapply(y, function(y) gsub("[^\x20-\x7E]", "", y)) }) data <- lapply(data, function(y){ lapply(y, paste, sep = "", collapse = " ") }) data <- simplify2array(data, higher = FALSE) data <- apply(data, 1:2, function(y){ifelse(y == "NA", NA, unlist(y))}) data <- as.data.frame(data, stringsAsFactors = FALSE) return(data) } ind.word.check <- function (string, full.dict, dictionary, spelling) { string <- gsub("[^[:alnum:][:space:]]", "", string) spl <- unlist(strsplit(string," ")) spl <- na.omit(bad.response(spl)) guesses <- lapply(spl, best.guess, full.dictionary = full.dict, dictionary = dictionary, tolerance = 1) lengths <- unlist(lapply(guesses, length)) if(any(lengths > 1)) {guesses[which(lengths > 1)] <- spl[which(lengths > 1)]} resp <- paste(unlist(guesses), collapse = " ") if(any(dictionary %in% SemNetDictionaries::dictionaries(TRUE))) {resp <- moniker(word = resp, misnom = SemNetDictionaries::load.monikers(dictionary), spelling = spelling)} return(resp) } multiple.words <- function (vec, multi.min, full.dict, dictionary, spelling) { spl <- unlist(strsplit(vec, " ")) spl <- na.omit(bad.response(spl)) if(length(spl) >= multi.min) { misspl <- which(!spl %in% full.dict) for(i in misspl) { ind <- FALSE multi <- vector(length = 2) ind.guess <- best.guess(spl[i], full.dictionary = full.dict, dictionary = dictionary) if(length(ind.guess) == 1) { spl[i] <- ind.guess ind <- TRUE } if(i != 1) { spacing <- c(paste(spl[i-1], spl[i]), paste(spl[i-1], spl[i], sep = "")) spacing <- unique(unlist(lapply(spacing, moniker, dictionary, spelling = spelling))) if(sum(spacing %in% full.dict) == 1) {multi[1] <- spacing[which(spacing %in% full.dict)]} } if(i != length(spl)) { spacing <- c(paste(spl[i], spl[i+1]), paste(spl[i], spl[i+1], sep = "")) spacing <- unique(unlist(lapply(spacing, moniker, dictionary, spelling = spelling))) if(sum(spacing %in% full.dict) == 1) {multi[2] <- spacing[which(spacing %in% full.dict)]} } if(multi[1] %in% full.dict && !multi[2] %in% full.dict) { spl[i] <- multi[1] spl <- spl[-(i-1)] }else if(!multi[1] %in% full.dict && multi[2] %in% full.dict) { spl[i] <- multi[2] spl <- spl[-(i+1)] } } vec <- unlist(lapply(spl, moniker, misnom = SemNetDictionaries::load.monikers(dictionary), spelling = spelling)) }else if(length(spl) > 1) { guess <- best.guess(vec, full.dictionary = full.dict, dictionary = dictionary) if(length(guess) == 1) {vec <- guess} } res <- list() res$response <- unique(vec) res$correct <- unique(vec) %in% full.dict return(res) } response.splitter <- function (vec, full.dict) { if(length(vec) == 1) { spl <- unlist(strsplit(vec, " ")) spl <- na.omit(bad.response(spl)) if(length(spl) > 1) { if(vec %in% full.dict) {return(vec) }else if(all(spl %in% full.dict)) {return(spl) }else{return(vec)} }else{return(vec)} }else{return(vec)} } brit.us.conv.vector <- function (vec, spelling = c("UK", "US"), dictionary = FALSE) { if(toupper(spelling) == "UK"){ if(any(vec %in% names(SemNetDictionaries::brit2us))){ target.US <- which(!is.na(vec[match(names(SemNetDictionaries::brit2us), vec)])) spelling.GB <- unname(unlist(SemNetDictionaries::brit2us[target.US])) vec[na.omit(match(names(SemNetDictionaries::brit2us), vec))] <- spelling.GB } }else if(toupper(spelling) == "US"){ if(any(vec %in% SemNetDictionaries::brit2us)){ target.GB <- which(!is.na(vec[match(SemNetDictionaries::brit2us, vec)])) spelling.US <- names(unlist(SemNetDictionaries::brit2us[target.GB])) vec[na.omit(match(SemNetDictionaries::brit2us, vec))] <- spelling.US } } if(dictionary){ vec <- sort(unique(vec)) } return(vec) } brit.us.conv <- function (vec, spelling = c("UK", "US"), dictionary) { vec <- unlist(lapply(vec, strsplit, split = " "), recursive = FALSE) vec <- lapply(vec, function(x, spelling, dictionary){ converted <- brit.us.conv.vector(x, spelling = spelling) conv <- paste(converted, collapse = " ") return(conv) }, spelling = spelling, dictionary = dictionary) if(dictionary){ vec <- sort(unlist(vec)) } return(vec) } walk_through <- function(walkthrough) { do.it <- FALSE if(is.null(walkthrough)) { customMenu(choices = c("Yes", "No"), title = c(paste("\nBefore starting the manual spell-check, would you like to do a walkthrough?", colortext("\n(Recommended for first time users)", defaults = "message"))), default = 2, dictionary = TRUE) ans <- readline("Selection: ") ans <- appropriate.answer(ans, choices = 1:2, default = 2, dictionary = TRUE) if(ans == 1) {do.it <- TRUE }else{message("\nWalkthrough skipped.")} }else if(walkthrough) {do.it <- TRUE} if(do.it) { cat(colortext("\nWelcome to the manual spell-check walkthrough for `textcleaner`!", defaults = "message")) cat(colortext("\n\nThe manual spell-check process is designed to allow you to", defaults = "message")) cat(colortext("\nhave maximum control over the responses that need spell-checking.", defaults = "message")) cat(colortext("\nThis walkthrough will guide you through each response option", defaults = "message")) cat(colortext("\nin the manual spell-check menu by using examples of responses", defaults = "message")) cat(colortext("\nyou might encounter.", defaults = "message")) cat(colortext("\n\nThere are generally two types of responses you might encounter:", defaults = "message")) cat(colortext("\na single word or multiple word response. This latter type is a", defaults = "message")) cat(colortext("\nbit tricky because the response could be a single response or", defaults = "message")) cat(colortext("\nit could be multiple responses entered as though it were a", defaults = "message")) cat(colortext("\nsingle response.", defaults = "message")) cat(colortext("\n\nBecause `textcleaner` spell-checks each word individually, your", defaults = "message")) cat(colortext("\nintervention is necessary to determine how to properly split", defaults = "message")) cat(colortext("\nthese responses. By demonstrating how to correct this type of", defaults = "message")) cat(colortext("\nresponse, you'll be prepared to correct single responses as well.", defaults = "message")) cat(colortext("\n\nThis is because these multiple word responses can be checked", defaults = "message")) cat(colortext("\nindividually or across all words in the response. Therefore, all", defaults = "message")) cat(colortext("\nexplanation for how to use the manual spell-check options of", defaults = "message")) cat(colortext("\n`textcleaner` are discussed in this single example.", defaults = "message")) cat(colortext("\n\nThese multiple word responses are where the `textcleaner`", defaults = "message")) cat(colortext("\nfunction starts and our walkthrough begins.\n\n", defaults = "message")) readline("Press ENTER to continue...") cat(colortext("\nThe multiple word response we will use for our example was given", defaults = "message")) cat(colortext("\nby an actual participant:", defaults = "message")) cat("\n\n'turtle catdog elephant fish bird squiral rabbit fox deer monkey giraff'\n") cat(colortext("\nWhen this multiple word response was passed through the automated", defaults = "message")) cat(colortext("\nspell-check, it was changed to:", defaults = "message")) cat("\n\n'turtle' 'catdog' 'elephant' 'fish' 'bird' 'squirrel' 'rabbit' 'fox' 'deer' 'monkey' 'giraffe'\n") cat(colortext("\nThe automated spell-check handled a few errors in the original", defaults = "message")) cat(colortext("\nresponse. First, the words in the response were separated into", defaults = "message")) cat(colortext("\nindividual responses. Second, the responses 'squiral' and 'giraff'", defaults = "message")) cat(colortext("\nwere automatically corrected to 'squirrel' and 'giraffe',", defaults = "message")) cat(colortext("\nrespectively. The word 'catdog', however, was not successfully", defaults = "message")) cat(colortext("\nseparated and is passed on to you to be manually spell-checked.\n\n", defaults = "message")) readline("Press ENTER to continue...") cat(colortext("\nBelow is the interactive menu that will appear when manually spell-checking responses:\n", defaults = "message")) Sys.sleep(5) original <- paste("turtle catdog elephant fish bird squiral rabbit fox deer monkey giraff") context <- paste("turtle", "catdog", "elephant", "fish", "bird", "squirrel", "rabbit", "fox", "deer", "monkey", "giraffe") context <- unlist(strsplit(context, split = " ")) check <- 2 title <- paste(paste("\nOriginal response: ", "'", original, "'", sep = ""), paste("Auto-corrected response: ", paste("'", context, "'", sep = "", collapse = " "), sep = ""), paste("Response to manually spell-check: ", paste("'", colortext(context[check], defaults = "highlight"), "'", sep = ""), sep = ""), sep = "\n\n") word <- c("SKIP WORD", "ADD WORD TO DICTIONARY", "TYPE MY OWN WORD", "GOOGLE WORD", "BAD WORD") string <- c("KEEP ORIGINAL", "KEEP AUTO-CORRECT", "TYPE MY OWN STRING", "GOOGLE STRING", "BAD STRING") resp <- best.guess(word = "catdog", full.dictionary = SemNetDictionaries::animals.dictionary, dictionary = "animals") choices <- c(word, string, resp) customMenu(choices = choices, title = title, default = 10) message("Press 'B' to GO BACK or 'esc' to STOP.\n") cat("Response option (accepts lowercase):\n\n") readline("Press ENTER to continue...\n(make sure to expand R's Console vertically to see the full menu)") cat(paste(colortext("\nAs you can see, the interactive menu contains", defaults = "message"), colortext(styletext("a lot", "italics"), defaults = "message"), colortext("of information.", defaults = "message")) ) cat(colortext("\nThe purpose of this walkthrough is to get familiar with this menu", defaults = "message")) cat(colortext("\nby breaking it down into digestible pieces. We'll start with the", defaults = "message")) cat(colortext("\nfirst three lines:\n", defaults = "message")) cat(title) linebreak() cat(paste("\n", "Original response:\n", colortext(paste(" ", textsymbol("bullet"), " Refers to the original response that the participant typed", sep = ""), defaults = "message"), "\n", sep = "") ) cat(paste("\n", "Auto-corrected response:\n", colortext(paste(" ", textsymbol("bullet"), " Refers to the response that the automated spell-check corrected to", sep = ""), defaults = "message"), "\n", sep = "") ) cat(paste("\n", "Response to manually spell-check: '", colortext("catdog", defaults = "highlight"), "'\n", paste( colortext(paste(" ", textsymbol("bullet"), " Refers to the ", sep = ""), defaults = "message"), styletext(colortext("target", defaults = "message"), defaults = "italics"), colortext(paste(" response to be manually spell-checked", sep = ""), defaults = "message"), sep = "" ), "\n\n", sep = "") ) readline("Press ENTER to continue...") cat(colortext("\nThese first three lines provide you with the full context of the", defaults = "message")) cat(colortext("\nparticipant's response to help you make a more informed decision.", defaults = "message")) cat(paste(colortext("\nThe ", defaults = "message"), "Auto-corrected response:", colortext(" is the current state of the response.", defaults = "message"), sep = "") ) cat(colortext("\nThat is, if you do nothing to manually spell-check the response,", defaults = "message")) cat(colortext("\nthen these are the responses that will be retained. In our example,", defaults = "message")) cat(paste(colortext("\nwe want to change to target response: ", defaults = "message"), "'", colortext("catdog", defaults = "highlight"), "'", colortext(".", defaults = "message"), sep = "") ) cat(colortext("\n\nNext, we'll move on to the possible options we have to", defaults = "message")) cat(colortext("\ncorrect this response.\n\n", defaults = "message")) readline("Press ENTER to continue...") cat(colortext("\nThe first set of options (i.e., ", defaults = "message"), styletext("Word options", defaults = "underline"), colortext(") we have are", defaults = "message"), sep = "" ) cat(colortext("\nto correct the target word:", defaults = "message"), paste("'", colortext("catdog", defaults = "highlight"), "'", colortext(". These options allow", defaults = "message"), sep = "") ) cat(colortext("\nyou to make a decision about how to handle this single", defaults = "message")) cat(colortext("\nword in the response -- that is, these options will", defaults = "message"), colortext(styletext("\nonly", "italics"), defaults = "message"), colortext("affect the target word. There are five options:", defaults = "message") ) word.set <- paste(1:5, ": ", word, sep = "") cat(paste(styletext("\n\nWord options\n", defaults = "underline"), paste0(word.set, c(rep.int(" ", min(20, 5) - 1L)), sep = "", collapse = ""))) linebreak() cat(paste("\n", "1: SKIP WORD\n", colortext(paste(" ", textsymbol("bullet"), ' Keeps word "as is" and moves on to next word to be spell-checked', sep = ""), defaults = "message"), "\n", sep = "") ) cat(paste("\n", "2: ADD WORD TO DICTIONARY\n", colortext(paste(" ", textsymbol("bullet"), " Adds word to dictionary for future spell-checking", sep = ""), defaults = "message"), "\n", sep = "") ) cat(paste("\n", "3: TYPE MY OWN WORD\n", colortext(paste(" ", textsymbol("bullet"), " Allows you to type your own correction for the word", sep = ""), defaults = "message"), "\n", sep = "") ) cat(paste("\n", "4: GOOGLE WORD\n", colortext(paste(" ", textsymbol("bullet"), ' Opens your default browser and "Googles" the word', sep = ""), defaults = "message"), "\n", sep = "") ) cat(paste("\n", "5: BAD WORD\n", colortext(paste(" ", textsymbol("bullet"), " Marks the word as an inappropriate response (NA)", sep = ""), defaults = "message"), "\n\n", sep = "") ) readline("Press ENTER to continue...") cat(colortext("\nThese options only affect the target word. But what if you want", defaults = "message")) cat(colortext("\nto change multiple words or the", defaults = "message"), colortext(styletext("entire", defaults = "italics"), defaults = "message"), colortext("string of responses? We", defaults = "message")) cat(colortext("\nmove to those options next.\n\n", defaults = "message")) readline("Press ENTER to continue...") cat(colortext("\nThe next set of options (i.e., ", defaults = "message"), styletext("String options", defaults = "underline"), colortext(") are able to", defaults = "message"), sep = "") cat(colortext("\ncorrect the entire string of responses. These options will", defaults = "message")) cat(colortext("\naffect the entire string rather than just the target word.", defaults = "message")) cat(colortext("\nThere are also five options:", defaults = "message")) string.set <- paste(6:10, ": ", string, sep = "") cat(paste(styletext("\n\nString options\n", defaults = "underline"), paste0(string.set, c(rep.int(" ", min(20, 5) - 1L)), sep = "", collapse = ""))) linebreak() cat(paste("\n", "6: KEEP ORIGINAL\n", paste(colortext(paste(" ", textsymbol("bullet"), " Reverts the string back to the", sep = ""), defaults = "message"), "Original response:", colortext("the participant provided.", defaults = "message")), "\n", sep = "" ) ) cat(paste("\n", "7: KEEP AUTO-CORRECT\n", paste(colortext(paste(" ", textsymbol("bullet"), " Keeps the string 'as is' with the", sep = ""), defaults = "message"), "Auto-correct response:", colortext("provided by the automated spell-check.", defaults = "message")), "\n", sep = "" ) ) cat(paste("\n", "8: TYPE MY OWN STRING\n", paste(colortext(paste(" ", textsymbol("bullet"), " Allows you to type your own correction for the", sep = ""), defaults = "message"), "Original response:", colortext("the participant provided.", defaults = "message")), "\n", sep = "" ) ) cat(paste("\n", "9: GOOGLE STRING\n", paste(colortext(paste(" ", textsymbol("bullet"), " Opens your default browser and 'Googles' the", sep = ""), defaults = "message"), "Original response:", colortext("the participant provided.", defaults = "message")), "\n", sep = "" ) ) cat(paste("\n", "10: BAD STRING\n", colortext(paste(" ", textsymbol("bullet"), " Marks the entire string as an inappropriate response (NA)", sep = ""), defaults = "message"), "\n\n", sep = "" ) ) readline("Press ENTER to continue...") cat(colortext("\nThese options only affect the entire string. They allow you to", defaults = "message")) cat(colortext("\nlook beyond the target word and to make a decision about the", defaults = "message")) cat(colortext("\nwhole string. These options are most useful when considering", defaults = "message")) cat(colortext("\na multiple word response as a single response (rather than", defaults = "message")) cat(colortext("\nmultiple individual responses).\n\n", defaults = "message")) readline("Press ENTER to continue...") cat(colortext("\nThe final set of options (i.e., ", defaults = "message"), styletext("Response options", defaults = "underline"), colortext(") only affect the", defaults = "message"), sep = "") cat(colortext("\ntarget word. These options are `textcleaner`'s best guess for", defaults = "message")) cat(colortext("\nwhat the response nmight be. These response options offer quick", defaults = "message")) cat(colortext("\ncorrections or potential directions for what the user meant to", defaults = "message")) cat(colortext("\nBelow the", defaults = "message"), styletext("Response options", defaults = "underline"), colortext("are two convenience options and an ", defaults = "message") ) cat(colortext("\ninput for your selection.", defaults = "message")) resp.set <- paste(c("Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P"), ": ", resp, sep = "") cat(paste(styletext("\n\nResponse options\n", defaults = "underline"), paste0(resp.set, c(rep.int(" ", min(20, 5) - 1L)), sep = "", collapse = ""))) cat(colortext("\n\nPress 'B' to GO BACK, 'H' for HELP, or 'esc' to STOP.\n", defaults = "message")) cat("\nSelection (accepts lowercase): ") linebreak() cat(paste(styletext("\nResponse options\n", defaults = "underline"), paste(colortext(paste(" ", textsymbol("bullet"), " Potential options based on `textcleaner`'s best guess (letters correspond to the response)", sep = ""), defaults = "message")), "\n", sep = "" ) ) cat(paste("\n'B'\n", paste(colortext(paste(" ", textsymbol("bullet"), " Takes you back to the previous response (use if you make a mistake or just want to go back)", sep = ""), defaults = "message")), "\n", sep = "" ) ) cat(paste("\n'H'\n", paste(colortext(paste(" ", textsymbol("bullet"), " Takes you to the documentation of `textcleaner`", sep = ""), defaults = "message")), "\n", sep = "" ) ) cat(paste("\n'esc'\n", paste(colortext(paste(" ", textsymbol("bullet"), " Exits textcleaner completely but saves your output", sep = ""), defaults = "message")), "\n", sep = "" ) ) cat(paste("\nSelection (accepts lowercase): \n", paste(colortext(paste(" ", textsymbol("bullet"), " Where you input the option you select", sep = ""), defaults = "message")), "\n\n", sep = "" ) ) readline("Press ENTER to continue...") cat(colortext("\nThese make up all the options you'll use in `textcleaner`. They", defaults = "message")) cat(colortext("\nenable total control over correcting the response(s). When there", defaults = "message")) cat(colortext("\nis only a single word response, then the 'String options' will", defaults = "message")) cat(colortext("\nnot be available (because they are no longer necessary).", defaults = "message")) cat(colortext("\n\nThis concludes the walkthrough of the manual spell-check process", defaults = "message")) cat(colortext("\nin `textcleaner`. You're now prepared to work through your data.\n", defaults = "message")) } cat("\n") readline("Press ENTER to start manual spell-check...") } textcleaner_help <- function(check, context, original, possible) { linebreak(breaks = "\n\n") help_art <- c(" _ _ _ _ _ ", "| |_ _____ _| |_ ___| | ___ __ _ _ __ ___ _ __ | |__ ___| |_ __ ", "| __/ _ \\ \\/ / __/ __| |/ _ \\/ _` | '_ \\ / _ \\ '__| | '_ \\ / _ \\ | '_ \\ ", "| || __/> <| || (__| | __/ (_| | | | | __/ | | | | | __/ | |_) | ", " \\__\\___/_/\\_\\\\__\\___|_|\\___|\\__,_|_| |_|\\___|_| |_| |_|\\___|_| .__/ ", " |_| ") cat(help_art, sep = "\n") linebreak(breaks = "") Sys.sleep(2) if(!is.null(context)) { cat(paste("\n", "Original string:\n\n", paste("'", original, "'", sep = ""), "\n\n", colortext(paste(" ", textsymbol("bullet"), " Refers to the original string that the participant typed", sep = ""), defaults = "message"), "\n", sep = "") ) cat(paste("\n", "Auto-corrected string:\n\n", paste("'", context, "'", sep = "", collapse = " "), "\n\n", colortext(paste(" ", textsymbol("bullet"), " Refers to the auto-corrected string that the automated spell-check derived", sep = ""), defaults = "message"), "\n", sep = "") ) word <- c("SKIP WORD", "ADD WORD TO DICTIONARY", "TYPE MY OWN WORD", "GOOGLE WORD", "BAD WORD") string <- c("KEEP ORIGINAL", "KEEP AUTO-CORRECT", "TYPE MY OWN STRING", "GOOGLE STRING", "BAD STRING") choices <- c(word, string, possible) check <- context[check] }else{ choices <- c("SKIP", "ADD TO DICTIONARY", "TYPE MY OWN", "GOOGLE IT", "BAD WORD", possible) } cat(paste("\n", "Target word: '", colortext(check, defaults = "highlight"), "'\n", paste( colortext(paste(" ", textsymbol("bullet"), " Refers to the ", sep = ""), defaults = "message"), colortext("target", defaults = "message"), colortext(paste(" word to be manually spell-checked", sep = ""), defaults = "message"), sep = "" ), sep = "") ) linebreak(breaks = "\n\n") cat(paste("\n", "1: SKIP WORD\n", colortext(paste(" ", textsymbol("bullet"), " Keeps the target word 'as is' and moves on to next word to be spell-checked", sep = ""), defaults = "message"), "\n", sep = "") ) cat(paste("\n", "2: ADD WORD TO DICTIONARY\n", colortext(paste(" ", textsymbol("bullet"), " Adds the target word to dictionary for future spell-checking", sep = ""), defaults = "message"), "\n", sep = "") ) cat(paste("\n", "3: TYPE MY OWN WORD\n", colortext(paste(" ", textsymbol("bullet"), " Allows you to type your own correction for the target word", sep = ""), defaults = "message"), "\n", sep = "") ) cat(paste("\n", "4: GOOGLE WORD\n", colortext(paste(" ", textsymbol("bullet"), " Opens your default browser and 'Googles' the target word", sep = ""), defaults = "message"), "\n", sep = "") ) cat(paste("\n", "5: BAD WORD\n", colortext(paste(" ", textsymbol("bullet"), " Marks the target word as an inappropriate response (NA)", sep = ""), defaults = "message"), sep = "") ) linebreak(breaks = "\n\n") if(!is.null(context)) { cat(paste("\n", "6: KEEP ORIGINAL\n", paste(colortext(paste(" ", textsymbol("bullet"), " Reverts the string back to the", sep = ""), defaults = "message"), "Original string:", colortext("the participant provided", defaults = "message")), "\n", sep = "" ) ) cat(paste("\n", "7: KEEP AUTO-CORRECT\n", paste(colortext(paste(" ", textsymbol("bullet"), " Keeps the string 'as is' with the", sep = ""), defaults = "message"), "Auto-correct string:", colortext("provided by the automated spell-check", defaults = "message")), "\n", sep = "" ) ) cat(paste("\n", "8: TYPE MY OWN STRING\n", paste(colortext(paste(" ", textsymbol("bullet"), " Allows you to type your own correction for the", sep = ""), defaults = "message"), "Original string:", colortext("the participant provided", defaults = "message")), "\n", sep = "" ) ) cat(paste("\n", "9: GOOGLE STRING\n", paste(colortext(paste(" ", textsymbol("bullet"), " Opens your default browser and 'Googles' the", sep = ""), defaults = "message"), "Original string:", colortext("the participant provided", defaults = "message")), "\n", sep = "" ) ) cat(paste("\n", "10: BAD STRING\n", colortext(paste(" ", textsymbol("bullet"), " Marks the entire string as an inappropriate response (NA)", sep = ""), defaults = "message"), sep = "" ) ) linebreak(breaks = "\n\n") cat(paste("\n", styletext("Response options\n", defaults = "underline"), customMenu(choices = choices, title = NULL, default = 10, help = TRUE), "\n", paste(colortext(paste(" ", textsymbol("bullet"), " Potential options based on `textcleaner`'s best guess for the target word (letters correspond to the response)", sep = ""), defaults = "message")), "\n", sep = "" ) ) }else{ cat(paste("\n", styletext("Response options\n", defaults = "underline"), customMenu(choices = choices, title = NULL, default = 5, help = TRUE), "\n", paste(colortext(paste(" ", textsymbol("bullet"), " Potential options based on `textcleaner`'s best guess for the target word (letters correspond to the response)", sep = ""), defaults = "message")), "\n", sep = "" ) ) } cat(paste("\n'B'\n", paste(colortext(paste(" ", textsymbol("bullet"), " Takes you back to the previous response (use if you make a mistake or just want to go back)", sep = ""), defaults = "message")), "\n", sep = "" ) ) cat(paste("\n'H'\n", paste(colortext(paste(" ", textsymbol("bullet"), " Outputs the information you see here. For other help information, see `?textcleaner`", sep = ""), defaults = "message")), "\n", sep = "" ) ) cat(paste("\n'X'\n", paste(colortext(paste(" ", textsymbol("bullet"), " Exits textcleaner completely but saves your output", sep = ""), defaults = "message")), "\n", sep = "" ) ) cat(paste("\nSelection (accepts lowercase): \n", paste(colortext(paste(" ", textsymbol("bullet"), " Where you input the option you select", sep = ""), defaults = "message")), "\n\n", sep = "" ) ) readline("Press ENTER to get back to manual spell-check...") } SemNetCleanerEdit <- function() { shiny::runApp(appDir = system.file("Shiny", package="SemNetCleaner")) } auto.spellcheck <- function(check, full.dict, dictionary, spelling, keepStrings) { names(check) <- formatC(1:length(check), width = nchar(as.character(length(check))), format = "d", flag = "0") full.names <- names(check) orig <- check message("\nIdentifying correctly spelled responses...", appendLF = FALSE) targets <- match(unlist(check),full.dict) if(all(is.na(targets))){ check <- orig auto.spell <- names(check) }else if(all(!is.na(targets))){ ind <- 1:length(check) names.ind <- names(check)[ind] message("\n\nAll words passed automated spell-check. Ending spell-check...") res <- list() res$manual <- as.numeric() auto <- matrix("", nrow = 0, ncol = 2) colnames(auto) <- c("from", "to_1") res$auto <- auto res$to <- orig return(res) }else{ ind <- which(!is.na(targets)) names.ind <- names(check)[ind] check <- orig[-as.numeric(names.ind)] auto.spell <- names(check) } Sys.sleep(0.50) message(paste("done.\n(", length(check), " of ", length(orig), " unique responses still need to be corrected)", sep = "")) message("\nSingularizing responses...", appendLF = FALSE) sing <- lapply(check, singularize) targets <- match(unlist(sing),full.dict) if(all(is.na(targets))){ sing <- check auto.spell <- names(sing) }else if(all(!is.na(targets))){ ind2 <- which(!is.na(targets)) orig[names(sing)[ind2]] <- sing[ind2] message("\n\nAll words passed automated spell-check. Ending spell-check...") res <- list() res$manual <- as.numeric() res$auto <- setdiff(as.numeric(names(check)), res$manual) res$to <- orig return(res) }else{ ind2 <- which(!is.na(targets)) orig[names(sing)[ind2]] <- sing[ind2] names.ind <- sort(c(names.ind, names(sing)[ind2])) sing <- orig[-as.numeric(names.ind)] } Sys.sleep(0.50) message(paste("done.\n(", length(sing), " unique responses still need to be corrected)", sep = "")) if(all(dictionary == "general")){ mons2 <- sing }else{ if(any(dictionary %in% SemNetDictionaries::dictionaries(TRUE))) { message("\nAuto-correcting common misspellings and monikers...", appendLF = FALSE) monik <- SemNetDictionaries::load.monikers(dictionary) if(length(monik)!=0) { mons <- unlist(lapply(sing, moniker, monik, spelling = spelling), recursive = FALSE) targets <- match(unlist(mons),full.dict) if(all(is.na(targets))){ mons <- sing auto.spell <- names(mons) }else if(all(!is.na(targets))){ ind3 <- which(!is.na(targets)) orig[names(mons)[ind3]] <- mons[ind3] message("\n\nAll words passed automated spell-check. Ending spell-check...") res <- list() res$manual <- as.numeric() res$auto <- setdiff(as.numeric(names(sing)), res$manual) res$to <- orig return(res) }else{ ind3 <- which(!is.na(targets)) orig[names(mons)[ind3]] <- mons[ind3] names.ind <- sort(c(names.ind, names(mons)[ind3])) mons <- orig[-as.numeric(names.ind)] } mons2 <- unlist(lapply(mons, function(x, monik, spelling){moniker(singularize(x, dictionary = FALSE), monik, spelling)}, monik, spelling = spelling), recursive = FALSE) targets <- match(unlist(mons2),full.dict) if(all(is.na(targets))){ mons2 <- mons auto.spell <- names(mons2) }else if(all(!is.na(targets))){ ind4 <- which(!is.na(targets)) orig[names(mons2)[ind4]] <- mons2[ind4] message("\n\nAll words passed automated spell-check. Ending spell-check...") res <- list() res$manual <- as.numeric() res$auto <- setdiff(as.numeric(names(mons2)), res$manual) res$to <- orig return(res) }else{ ind4 <- which(!is.na(targets)) orig[names(mons2)[ind4]] <- mons2[ind4] names.ind <- sort(c(names.ind, names(mons2)[ind4])) mons2 <- orig[-as.numeric(names.ind)] } } Sys.sleep(0.50) message("done.") }else{ mons2 <- sing } } message(paste("\nAttempting to auto-correct the remaining", length(mons2),"responses individually..."), appendLF = FALSE) ind.check <- unlist(lapply(mons2, ind.word.check, full.dict = full.dict, dictionary = dictionary, spelling = spelling), recursive = FALSE) targets <- match(unlist(ind.check), full.dict) if(all(is.na(targets))){ ind.check <- mons2 auto.spell <- names(ind.check) }else if(all(!is.na(targets))){ ind5 <- which(!is.na(targets)) orig[names(ind.check)[ind5]] <- ind.check[ind5] message("\n\nAll words passed automated spell-check. Ending spell-check...") res <- list() res$manual <- as.numeric() res$auto <- setdiff(as.numeric(names(ind.check)), res$manual) res$to <- orig return(res) }else{ ind5 <- which(!is.na(targets)) orig[names(ind.check)[ind5]] <- ind.check[ind5] names.ind <- sort(c(names.ind, names(ind.check)[ind5])) ind.check <- orig[-as.numeric(names.ind)] } message(paste("done.\n(", length(ind.check), " unique responses still need to be corrected)", sep = "")) message("\nParsing multi-word responses...", appendLF = FALSE) dict.lens <- unlist(lapply(full.dict, function(x){length(unlist(strsplit(x, " ")))})) multi.min <- ceiling(median(dict.lens) + 2 * sd(dict.lens)) if(multi.min == 1){ multi.min <- 2 } multi.word <- lapply(ind.check, multiple.words, multi.min = multi.min, full.dict = full.dict, dictionary = dictionary, spelling = spelling) changed <- unlist(lapply(multi.word, function(x) { if(any(x$correct)) {return(TRUE) }else{return(FALSE)} })) responses <- unlist(multi.word, recursive = FALSE)[grep("response", names(unlist(multi.word, recursive = FALSE)))] if(!keepStrings){ if(length(responses[changed]) != 0){ orig[names(multi.word)[changed]] <- responses[changed] } } ind6 <- unlist(lapply(multi.word, function(x) { if(all(x$correct)) {return(TRUE) }else{return(FALSE)} })) if(length(names(multi.word)[ind6]) != 0){ names.ind <- sort(c(names.ind, names(multi.word)[ind6])) multi.word <- orig[-as.numeric(names.ind)] } multi.word <- lapply(multi.word, response.splitter, full.dict = full.dict) ind7 <- unlist(lapply(multi.word, function(x) { if(all(x %in% full.dict)) {return(TRUE) }else{return(FALSE)} })) if(length(multi.word[ind7]) != 0){ orig[names(multi.word)[ind7]] <- multi.word[ind7] names.ind <- sort(c(names.ind, names(multi.word)[ind7])) multi.word <- orig[-as.numeric(names.ind)] } message("done") if(length(multi.word) != 0){ message(paste("\nAutomated spell-checking complete.\nAbout ",length(multi.word)," responses still need to be manually spell-checked", sep = "")) }else{ message("\nAll words passed automaed spell-check. Ending spell-check...") } res <- list() res$manual <- as.numeric(names(multi.word)) res$auto <- setdiff(as.numeric(names(check)), res$manual) res$to <- orig return(res) } change.format <- function (change.list, change.matrix, current.index) { if(is.null(names(change.list))) { change.list <- list(change.list) names(change.list) <- paste(current.index) } n.list <- ncol(change.list[[paste(current.index)]]) n.matrix <- ncol(change.matrix) r.list <- nrow(change.list[[paste(current.index)]]) if(!is.null(n.list)) { if(n.list < n.matrix) { new.matrix <- matrix(NA, nrow = r.list + 1, ncol = n.matrix) colnames(new.matrix) <- colnames(change.matrix) for(i in 1:r.list) { row.target <- as.vector(change.list[[paste(current.index)]][i,]) new.matrix[i,length(row.target)] <- row.target } new.matrix <- rbind(new.matrix, change.matrix) change.list[[paste(current.index)]] <- new.matrix row.names(change.list[[paste(current.index)]]) <- NULL }else if(n.list > n.matrix) { diff.cols <- n.list - n.matrix change.matrix <- c(as.vector(change.matrix), rep(NA, diff.cols)) change.list[[paste(current.index)]] <- rbind(change.list[[paste(current.index)]], change.matrix) row.names(change.list[[paste(current.index)]]) <- NULL }else{ change.list[[paste(current.index)]] <- rbind(change.list[[paste(current.index)]], change.matrix) row.names(change.list[[paste(current.index)]]) <- NULL } }else{change.list[[paste(current.index)]] <- change.matrix} return(change.list) } spellcheck.menu <- function (check, context = NULL, possible, original, current.index, changes, full.dictionary, category, dictionary, keepStrings, go.back.count) { ans <- 30 go.back <- FALSE if(!is.null(context)){ dict.check <- context[check] }else{dict.check <- check} if(dict.check %in% full.dictionary){ if(!is.null(context)){ message(paste("\nResponse '", styletext(dict.check, defaults = "bold"), "' in '", styletext(paste(context, collapse = " "), defaults = "bold"), "' was KEPT AS IS based on a previous manual spell-check decision", sep = "")) }else{ message(paste("\nResponse '", styletext(dict.check, defaults = "bold"), "' was KEPT AS IS based on a previous manual spell-check decision", sep = "")) } res <- list() res$go.back <- go.back res$target <- ifelse(is.null(context), dict.check, context) res$changes <- changes res$full.dictionary <- full.dictionary res$end <- if(is.null(context)){NULL}else{FALSE} res$go.back.count <- go.back.count + 1 if(!"general" %in% dictionary){ Sys.sleep(1) } return(res) } if(!is.null(context)){ end <- FALSE while(ans == 30) { if(keepStrings){ title <- paste(paste("\nOriginal string: ", "'", original, "'", sep = ""), paste("Target word: ", paste("'", colortext(context[check], defaults = "highlight"), "'", sep = ""), sep = ""), sep = "\n\n") }else{ title <- paste(paste("\nOriginal string: ", "'", original, "'", sep = ""), paste("Auto-corrected string: ", paste("'", context, "'", sep = "", collapse = " "), sep = ""), paste("Target word: ", paste("'", colortext(context[check], defaults = "highlight"), "'", sep = ""), sep = ""), sep = "\n\n") } word <- c("SKIP WORD", "ADD WORD TO DICTIONARY", "TYPE MY OWN WORD", "GOOGLE WORD", "BAD WORD") if(keepStrings){ string <- c("KEEP ORIGINAL", "TYPE MY OWN STRING", "GOOGLE STRING", "BAD STRING") }else{ string <- c("KEEP ORIGINAL", "KEEP AUTO-CORRECT", "TYPE MY OWN STRING", "GOOGLE STRING", "BAD STRING") } choices <- c(word, string, possible) default <- length(c(word, string)) customMenu(choices = choices, title = title, default = default) message("Press 'B' to GO BACK, 'H' for HELP, or 'X' to EXIT.\n") ans <- readline(prompt = "Selection (accepts lowercase): ") if(tolower(ans) == "x" || ans == "") {return("STOP")} ans <- appropriate.answer(answer = ans, choices = choices, default = default) if(keepStrings){ if(ans >= 7 && ans <= length(choices)){ ans <- ans + 1 } } if(ans == 1) { if(keepStrings){ if(check == 1){ message(paste("\nResponse was SKIPPED: '", styletext(context[check], defaults = "bold"), " ", paste(context[-check], collapse = " "), "'", sep = "", collapse = " ")) }else if(check == length(unlist(strsplit(context, split = " ")))){ message(paste("\nResponse was SKIPPED: '", paste(context[-check], collapse = " "), " ", styletext(context[check], defaults = "bold"), "'", sep = "", collapse = " ")) }else{ word.num <- which(context[check] == unlist(strsplit(context, split = " "))) message(paste("\nResponse was SKIPPED: '", paste(context[1:(word.num - 1)], collapse = " "), " ", styletext(context[word.num], defaults = "bold"), " ", paste(context[(word.num + 1):length(unlist(strsplit(context, split = " ")))], collapse = " "), "'", sep = "", collapse = " ")) } }else{ message(paste("\nResponse was SKIPPED:", paste("'", context[check], "'", sep = ""))) } }else if(ans == 2) { full.dictionary <- SemNetDictionaries::append.dictionary(context[check], full.dictionary, dictionary.name = "full", save.location = "envir", textcleaner = TRUE) if(keepStrings){ if(check == 1){ message(paste("\nResponse was KEPT AS: '", styletext(context[check], defaults = "bold"), " ", paste(context[-check], collapse = " "), "'", sep = "", collapse = " ")) }else if(check == length(unlist(strsplit(context, split = " ")))){ message(paste("\nResponse was KEPT AS: '", paste(context[-check], collapse = " "), " ", styletext(context[check], defaults = "bold"), "'", sep = "", collapse = " ")) }else{ word.num <- which(context[check] == unlist(strsplit(context, split = " "))) message(paste("\nResponse was KEPT AS: '", paste(context[1:(word.num - 1)], collapse = " "), " ", styletext(context[word.num], defaults = "bold"), " ", paste(context[(word.num + 1):length(unlist(strsplit(context, split = " ")))], collapse = " "), "'", sep = "", collapse = " ")) } } }else if(ans == 3) { message("\nType '30' (no quotations) to go back to the other response options\n") tmo <- readline(prompt = "Use commas for multiple words (dog, fish, etc.): ") if(tmo != "30") { tmo.split <- trimws(unlist(strsplit(tmo, split = ","))) change.mat <- t(as.matrix(c(context[check], tmo.split))) colnames(change.mat) <- c("from", paste("to", 1:(ncol(change.mat)-1), sep = "_")) changes <- change.format(change.list = changes, change.matrix = change.mat, current.index = current.index) if(!all(tmo.split %in% full.dictionary)) { non.dict <- which(!tmo.split %in% full.dictionary) for(i in 1:length(non.dict)) { message(paste("\n'", tmo.split[non.dict[i]], "'", sep = ""), " was not found in the dictionary.\n") dict.ans <- yes.no.menu( paste("Should ", paste("'", tmo.split[non.dict[i]], "'", sep = ""), " be added to the dictionary", sep = "") ) if(dict.ans == 1) { full.dictionary <- SemNetDictionaries::append.dictionary(tmo.split[non.dict[i]], full.dictionary, dictionary.name = "full", save.location = "envir", textcleaner = TRUE) } } } if(keepStrings){ if(check == 1){ message(paste("\nResponse was CHANGED TO: '", styletext(paste(tmo.split, collapse = " "), defaults = "bold"), " ", paste(context[-check], collapse = " "), "'", sep = "", collapse = " ")) }else if(check == length(unlist(strsplit(context, split = " ")))){ message(paste("\nResponse was CHANGED TO: '", paste(context[-check], collapse = " "), " ", styletext(paste(tmo.split, collapse = " "), defaults = "bold"), "'", sep = "", collapse = " ")) }else{ word.num <- which(context[check] == unlist(strsplit(context, split = " "))) message(paste("\nResponse was CHANGED TO: '", paste(context[1:(word.num - 1)], collapse = " "), " ", styletext(paste(tmo.split, collapse = " "), defaults = "bold"), " ", paste(context[(word.num + 1):length(unlist(strsplit(context, split = " ")))], collapse = " "), "'", sep = "", collapse = " ")) } }else{ message(paste("\nResponse was CHANGED TO:", paste("'", tmo.split, "'", sep = "", collapse = " "))) } context.change <- as.list(context) context.change[[check]] <- tmo.split context <- unlist(context.change) }else{ans <- 30} }else if(ans == 4) { searcher::search_site(paste(category, " '", context[check], "'", sep = "", collpase = ""), site = "google", rlang = FALSE) ans <- 30 }else if(ans == 5) { change.mat <- t(as.matrix(c(context[check], NA))) colnames(change.mat) <- c("from", paste("to", 1:(ncol(change.mat)-1), sep = "_")) changes <- change.format(change.list = changes, change.matrix = change.mat, current.index = current.index) if(keepStrings){ if(check == 1){ message(paste("\nResponse was CHANGED TO: '", styletext(NA, defaults = "bold"), " ", paste(context[-check], collapse = " "), "'", sep = "", collapse = " ")) }else if(check == length(unlist(strsplit(context, split = " ")))){ message(paste("\nResponse was CHANGED TO: '", paste(context[-check], collapse = " "), " ", styletext(NA, defaults = "bold"), "'", sep = "", collapse = " ")) }else{ word.num <- which(context[check] == unlist(strsplit(context, split = " "))) message(paste("\nResponse was CHANGED TO: '", paste(context[1:(word.num - 1)], collapse = " "), " ", styletext(NA, defaults = "bold"), " ", paste(context[(word.num + 1):length(unlist(strsplit(context, split = " ")))], collapse = " "), "'", sep = "", collapse = " ")) } }else{ message(paste("\nResponse was CHANGED TO:", paste(NA, sep = "", collapse = " "))) } context.change <- as.list(context) context.change[[check]] <- "NA" context <- unlist(context.change) }else if(ans == 6) { message(paste("\nString was REVERTED TO ORIGINAL:", paste("'", original, "'", sep = ""))) context <- original end <- TRUE if(!original %in% full.dictionary) { message(paste("\n'", original, "'", sep = ""), " was not found in the dictionary.\n") dict.ans <- yes.no.menu( paste("Should ", paste("'", original, "'", sep = ""), " be added to the dictionary", sep = "") ) if(dict.ans == 1) { full.dictionary <- SemNetDictionaries::append.dictionary(original, full.dictionary, dictionary.name = "full", save.location = "envir", textcleaner = TRUE) } } }else if(ans == 7) { message(paste("\nString was KEPT AS AUTO-CORRECT:", paste("'", context, "'", sep = "", collapse = " "))) context <- context end <- TRUE }else if(ans == 8) { message("\nType '30' (no quotations) to go back to the other response options\n") ams <- readline(prompt = "Use commas for multiple words (dog, fish, etc.): ") if(ams != "30") { ams.split <- trimws(unlist(strsplit(ams, split = ","))) change.mat <- t(as.matrix(c(paste(context, collapse = " "), ams.split))) colnames(change.mat) <- c("from", paste("to", 1:(ncol(change.mat)-1), sep = "_")) changes <- change.format(change.list = changes, change.matrix = change.mat, current.index = current.index) if(!all(ams.split %in% full.dictionary)) { non.dict <- which(!ams.split %in% full.dictionary) for(i in 1:length(non.dict)) { message(paste("\n'", ams.split[non.dict[i]], "'", sep = ""), " was not found in the dictionary.\n") dict.ans <- yes.no.menu( paste("Should ", paste("'", ams.split[non.dict[i]], "'", sep = ""), " be added to the dictionary", sep = "") ) if(dict.ans == 1) { full.dictionary <- SemNetDictionaries::append.dictionary(ams.split[non.dict[i]], full.dictionary, dictionary.name = "full", save.location = "envir", textcleaner = TRUE) } } } message(paste("\nString was CHANGED TO:", paste("'", ams.split, "'", sep = "", collapse = " "))) context <- ams.split end <- TRUE }else{ans <- 30} }else if(ans == 9) { searcher::search_site(paste(category, " '", original, "'", sep = "", collpase = ""), site = "google", rlang = FALSE) ans <- 30 }else if(ans == 10) { change.mat <- cbind(context, rep(NA, length(context))) colnames(change.mat) <- c("from", paste("to", 1:(ncol(change.mat)-1), sep = "_")) changes <- change.format(change.list = changes, change.matrix = change.mat, current.index = current.index) message(paste("\nALL responses were CHANGED TO:", paste(NA, sep = "", collapse = " "))) context <- rep("NA", length(context)) }else if(ans == length(choices) + 1) {go.back <- TRUE }else if(ans == length(choices) + 2) { textcleaner_help(check, context, original, possible) ans <- 30 }else{ change.mat <- t(as.matrix(c(context[check], possible[ans-10]))) colnames(change.mat) <- c("from", paste("to",1:(ncol(change.mat)-1), sep = "_")) changes <- change.format(change.list = changes, change.matrix = change.mat, current.index = current.index) if(keepStrings){ if(check == 1){ message(paste("\nResponse was CHANGED TO: '", styletext(possible[ans-10], defaults = "bold"), " ", paste(context[-check], collapse = " "), "'", sep = "", collapse = " ")) }else if(check == length(unlist(strsplit(context, split = " ")))){ message(paste("\nResponse was CHANGED TO: '", paste(context[-check], collapse = " "), " ", styletext(possible[ans-10], defaults = "bold"), "'", sep = "", collapse = " ")) }else{ word.num <- which(context[check] == unlist(strsplit(context, split = " "))) message(paste("\nResponse was CHANGED TO: '", paste(context[1:(word.num - 1)], collapse = " "), " ", styletext(possible[ans-10], defaults = "bold"), " ", paste(context[(word.num + 1):length(unlist(strsplit(context, split = " ")))], collapse = " "), "'", sep = "", collapse = " ")) } }else{ message(paste("\nResponse was CHANGED TO:", paste("'", possible[ans-10], "'", sep = ""))) } context[check] <- possible[ans-10] } } res <- list() res$go.back <- go.back res$target <- context res$changes <- changes res$full.dictionary <- full.dictionary res$end <- end res$go.back.count <- go.back.count if(!"general" %in% dictionary){ Sys.sleep(1) } return(res) }else{ while(ans == 30) { title <- paste(paste("\nTarget word: ", paste("'", colortext(check, defaults = "highlight"), "'", sep = ""), sep = "")) choices <- c("SKIP", "ADD TO DICTIONARY", "TYPE MY OWN", "GOOGLE IT", "BAD WORD", possible) customMenu(choices = choices, title = title, default = 5) message("Press 'B' to GO BACK, 'H' for HELP, or 'X' to EXIT.\n") ans <- readline(prompt = "Selection (accepts lowercase): ") if(tolower(ans) == "x" || ans == "") {return("STOP")} ans <- appropriate.answer(answer = ans, choices = choices, default = 5) if(ans == 1) { message(paste("\nResponse was SKIPPED:", paste("'", check, "'", sep = ""))) }else if(ans == 2) { full.dictionary <- SemNetDictionaries::append.dictionary(check, full.dictionary, dictionary.name = "full", save.location = "envir", textcleaner = TRUE) }else if(ans == 3) { message("\nType '30' (no quotations) to go back to the other response options\n") tmo <- readline(prompt = "Use commas for multiple words (dog, fish, etc.): ") if(tmo != "30") { tmo.split <- trimws(unlist(strsplit(tmo, split = ","))) change.mat <- t(as.matrix(c(check, tmo.split))) colnames(change.mat) <- c("from", paste("to", 1:(ncol(change.mat)-1), sep = "_")) changes <- change.format(change.list = changes, change.matrix = change.mat, current.index = current.index) if(!all(tmo.split %in% full.dictionary)) { non.dict <- which(!tmo.split %in% full.dictionary) for(i in 1:length(non.dict)) { message(paste("\n'", tmo.split[non.dict[i]], "'", sep = ""), " was not found in the dictionary.\n") dict.ans <- yes.no.menu( paste("Should ", paste("'", tmo.split[non.dict[i]], "'", sep = ""), " be added to the dictionary", sep = "") ) if(dict.ans == 1) { full.dictionary <- SemNetDictionaries::append.dictionary(tmo.split[non.dict[i]], full.dictionary, dictionary.name = "full", save.location = "envir", textcleaner = TRUE) } } } message(paste("\nResponse was CHANGED TO:", paste("'", tmo.split, "'", sep = "", collapse = " "))) check <- tmo.split }else{ans <- 30} }else if(ans == 4) { searcher::search_site(paste(category, " '", check, "'", sep = "", collpase = ""), site = "google", rlang = FALSE) ans <- 30 }else if(ans == 5) { change.mat <- t(as.matrix(c(check, NA))) colnames(change.mat) <- c("from", paste("to", 1:(ncol(change.mat)-1), sep = "_")) changes <- change.format(change.list = changes, change.matrix = change.mat, current.index = current.index) message(paste("\nResponse was CHANGED TO:", paste(NA, sep = "", collapse = " "))) check <- "NA" }else if(ans == length(choices) + 1) {go.back <- TRUE }else if(ans == length(choices) + 2) { textcleaner_help(check, context, original, possible) ans <- 30 }else{ change.mat <- t(as.matrix(c(check, possible[ans-5]))) colnames(change.mat) <- c("from", paste("to",1:(ncol(change.mat)-1), sep = "_")) changes <- change.format(change.list = changes, change.matrix = change.mat, current.index = current.index) message(paste("\nResponse was CHANGED TO:", paste("'", possible[ans-5], "'", sep = ""))) check <- possible[ans-5] } } res <- list() res$go.back <- go.back res$target <- check res$changes <- changes res$full.dictionary <- full.dictionary res$go.back.count <- go.back.count if(!"general" %in% dictionary){ Sys.sleep(1) } return(res) } } spellcheck.dictionary <- function (uniq.resp = NULL, dictionary = NULL, spelling = NULL, add.path = NULL, keepStrings = NULL, data = NULL, continue = NULL ) { if(is.null(continue)) { categories <- SemNetDictionaries::dictionaries(TRUE) if(any(dictionary %in% categories)) { target <- dictionary[na.omit(match(categories, dictionary))] if("general" %in% target) {category <- "dictionary" }else if("fruits" %in% target && "vegetables" %in% target) {category <- "food" }else if("fruits" %in% target && !"vegetables" %in% target) {category <- "fruits" }else if(!"fruits" %in% target && "vegetables" %in% target) {category <- "vegetables" }else if("jobs" %in% target) {category <- "jobs" }else if("hot" %in% target || "good" %in% target) {category <- "synonym" }else if("animals" %in% target) {category <- "animals" }else{category <- "general"} }else{category <- "general"} full.dictionary <- SemNetDictionaries::load.dictionaries(dictionary, add.path = add.path) message(paste("\nConverting dictionary to '", spelling, "' spelling...", sep = ""), appendLF = FALSE) full.dictionary <- brit.us.conv.vector(full.dictionary, spelling = spelling, dictionary = TRUE) message("done") orig.dictionary <- full.dictionary from <- as.list(uniq.resp) to <- from initial <- try( auto.spellcheck(check = from, full.dict = full.dictionary, dictionary = dictionary, spelling = spelling, keepStrings = keepStrings), silent = TRUE ) if(any(class(initial) == "try-error")) { error.fun(initial, "auto.spellcheck", "textcleaner") res <- list() res$stop <- TRUE } Sys.sleep(2) ind <- initial$manual to <- initial$to initial.to <- to if(keepStrings){ multi.ind <- which(lapply(to[ind], function(x){ length(unlist(strsplit(x, split = " "))) }) >= 2) }else{ multi.ind <- which(lapply(to[ind], length) >= 2) } single.ind <- setdiff(ind, as.numeric(names(multi.ind))) ind <- c(as.numeric(names(multi.ind)), single.ind) changes <- list() main.count <- 1 go.back.count <- 1 go.back.reset <- FALSE }else{ dictionary <- continue$dictionary full.dictionary <- continue$full.dictionary orig.dictionary <- continue$orig.dictionary spelling <- continue$spelling category <- continue$category from <- continue$from to <- continue$to initial <- continue$initial initial.to <- continue$initial.to ind <- continue$ind changes <- continue$changes main.count <- continue$main.count go.back.count <- continue$go.back.count go.back.reset <- continue$go.back.reset if(!is.null(continue$multi.count)) {multi.count <- continue$multi.count} keepStrings <- continue$keepStrings data <- continue$data } if(length(ind) != 0){ walk_through(FALSE) if(Sys.info()["sysname"] == "Windows") { pb <- tcltk::tkProgressBar(title = "R progress bar", label = "Spell-check progress", min = 0, max = length(ind), initial = 0, width = 300) invisible(tcltk::getTkProgressBar(pb)) }else{pb <- txtProgressBar(min = 0, max = length(ind), style = 3)} linebreak() } while(main.count != (length(ind) + 1)) { i <- ind[main.count] target <- to[[i]] if(keepStrings){ target <- unlist(strsplit(target, split = " ")) } if(length(target) > 1) { target.punct <- gsub("[^[:alnum:][:space:]]", "", target) check.words <- target[which(!target.punct %in% full.dictionary)] if(is.null(continue$multi.count)) {multi.count <- 1 }else{continue$multi.count <- NULL} if(length(check.words) == 0){ result$go.back.count <- go.back.count + 1 if(keepStrings){ message(paste("\nResponse '", styletext(paste(target, collapse = " "), defaults = "bold"), "' was KEPT AS IS based on a previous manual spell-check decision", sep = "")) }else{ message(paste("\nResponse '", styletext(target, defaults = "bold"), "' was KEPT AS IS based on a previous manual spell-check decision", sep = "")) } if(result$go.back.count == go.back.count){ if(go.back.reset){ go.back.count <- 1 }else{ go.back.reset <- TRUE } }else{ go.back.count <- result$go.back.count go.back.reset <- FALSE } linebreak() } while(multi.count != (length(check.words) + 1)){ result <- try( spellcheck.menu(check = which(check.words[multi.count] == target), context = target, possible = best.guess(target[which(check.words[multi.count] == target)], full.dictionary = full.dictionary, dictionary = dictionary), original = ifelse(keepStrings, paste(target, collapse = " "), from[[i]]), current.index = i, changes = changes, full.dictionary = full.dictionary, category = category, dictionary = dictionary, keepStrings = keepStrings, go.back.count = go.back.count), silent = TRUE ) linebreak() if("STOP" %in% result) { message("\nUser stopped. Saving progress...\n") res <- list() res$dictionary <- dictionary res$full.dictionary <- full.dictionary res$orig.dictionary <- orig.dictionary res$spelling <- spelling res$category <- category res$from <- from res$to <- to res$initial <- initial res$initial.to <- initial.to res$ind <- ind res$changes <- changes res$main.count <- main.count res$go.back.count <- go.back.count res$go.back.reset <- go.back.reset if(exists("multi.count")) {res$multi.count <- multi.count} res$data <- data res$keepStrings <- keepStrings res$stop <- TRUE class(res) <- "textcleaner" close(pb) Sys.sleep(2) return(res) }else if(any(class(result) == "try-error")) { error.fun(result, "spellcheck.menu", "textcleaner") res <- list() res$dictionary <- dictionary res$full.dictionary <- full.dictionary res$orig.dictionary <- orig.dictionary res$spelling <- spelling res$category <- category res$from <- from res$to <- to res$initial <- initial res$initial.to <- initial.to res$ind <- ind res$changes <- changes res$main.count <- main.count res$go.back.count <- go.back.count res$go.back.reset <- go.back.reset if(exists("multi.count")) {res$multi.count <- multi.count} res$keepStrings <- keepStrings res$data <- data res$stop <- TRUE class(res) <- "textcleaner" close(pb) message("\nSaving progress...\n") Sys.sleep(2) return(res) } if(result$go.back.count == go.back.count){ if(go.back.reset){ go.back.count <- 1 }else{ go.back.reset <- TRUE } }else{ go.back.count <- result$go.back.count go.back.reset <- FALSE } if(result$go.back) { if(multi.count == 1) { if(main.count != 1) { to[[i]] <- initial.to[[i]] prev.resp <- initial.to[[ind[main.count-go.back.count]]] prev.resp.split <- unlist(strsplit(prev.resp, split = " ")) if(any(!prev.resp.split %in% full.dictionary == prev.resp.split %in% orig.dictionary)){ target.rms <- which(!prev.resp.split %in% full.dictionary == prev.resp.split %in% orig.dictionary) ind.rms <- match(prev.resp.split[target.rms], full.dictionary) full.dictionary <- full.dictionary[-ind.rms] } to[[ind[main.count-go.back.count]]] <- prev.resp changes <- changes[-which(names(changes) == paste(ind[main.count-go.back.count]))] main.count <- main.count - (go.back.count + 1) go.back.count <- 1 break }else{ message("\nThis is the first response. 'GO BACK' is not available.") linebreak() Sys.sleep(0.5) } }else{ target <- prev.target if(any(prev.target %in% full.dictionary & !prev.target %in% orig.dictionary)) { target.rms <- which(prev.target %in% full.dictionary & !prev.target %in% orig.dictionary) ind.rms <- match(prev.target[target.rms], full.dictionary) full.dictionary <- full.dictionary[-ind.rms] } changes <- changes[[which(names(changes) == paste(ind[main.count]))]][-(multi.count - 1),] multi.count <- multi.count - 1 } }else{ prev.target <- target target <- result$target changes <- result$changes full.dictionary <- result$full.dictionary if(all(target == "NA")){ result$end <- TRUE } if(result$end){ multi.count <- length(check.words) + 1 }else{multi.count <- multi.count + 1} } } if(keepStrings){ target <- paste(target, collapse = " ") } to[[i]] <- target }else{ result <- try( spellcheck.menu(check = target, context = NULL, possible = best.guess(target, full.dictionary = full.dictionary, dictionary), original = from[[i]], current.index = i, changes = changes, full.dictionary = full.dictionary, category = category, dictionary = dictionary, keepStrings = keepStrings, go.back.count = go.back.count), silent = TRUE ) linebreak() if("STOP" %in% result) { message("\nUser stopped. Saving progress...\n") res <- list() res$dictionary <- dictionary res$full.dictionary <- full.dictionary res$orig.dictionary <- orig.dictionary res$spelling <- spelling res$category <- category res$from <- from res$to <- to res$initial <- initial res$initial.to <- initial.to res$ind <- ind res$changes <- changes res$main.count <- main.count res$go.back.count <- go.back.count res$go.back.reset <- go.back.reset if(exists("multi.count")) {res$multi.count <- multi.count} res$keepStrings <- keepStrings res$data <- data res$stop <- TRUE class(res) <- "textcleaner" close(pb) Sys.sleep(2) return(res) }else if(any(class(result) == "try-error")) { error.fun(result, "spellcheck.menu", "textcleaner") res <- list() res$dictionary <- dictionary res$full.dictionary <- full.dictionary res$orig.dictionary <- orig.dictionary res$spelling <- spelling res$category <- category res$from <- from res$to <- to res$initial <- initial res$initial.to <- initial.to res$ind <- ind res$changes <- changes res$main.count <- main.count res$go.back.count <- go.back.count res$go.back.reset <- go.back.reset if(exists("multi.count")) {res$multi.count <- multi.count} res$keepStrings <- keepStrings res$data <- data res$stop <- TRUE res$target <- target class(res) <- "textcleaner" close(pb) message("\nSaving progress...\n") Sys.sleep(2) return(res) } if(result$go.back.count == go.back.count){ if(go.back.reset){ go.back.count <- 1 }else{ go.back.reset <- TRUE } }else{ go.back.count <- result$go.back.count go.back.reset <- FALSE } if(result$go.back) { if(main.count != 1) { to[[i]] <- initial.to[[i]] prev.resp <- initial.to[[ind[main.count-go.back.count]]] prev.resp.split <- unlist(strsplit(prev.resp, split = " ")) if(any(!prev.resp.split %in% full.dictionary == prev.resp.split %in% orig.dictionary)){ target.rms <- which(!prev.resp.split %in% full.dictionary == prev.resp.split %in% orig.dictionary) ind.rms <- match(prev.resp.split[target.rms], full.dictionary) full.dictionary <- full.dictionary[-ind.rms] } to[[ind[main.count-go.back.count]]] <- prev.resp changes <- changes[-which(names(changes) == paste(ind[main.count-go.back.count]))] main.count <- main.count - (go.back.count + 1) go.back.count <- 1 }else{ message("This is the first response. 'GO BACK' is not available.") linebreak() Sys.sleep(0.5) } }else{ to[[i]] <- result$target changes <- result$changes full.dictionary <- result$full.dictionary } } if(Sys.info()["sysname"] == "Windows") { percent <- floor((main.count/length(ind))*100) info <- suppressWarnings(sprintf(paste(main.count, "of", length(ind), "responses done"), percent)) tcltk::setTkProgressBar(pb, main.count, sprintf("Spell-check Progress (%s)", info), info) }else{ cat("\n") setTxtProgressBar(pb, main.count) Sys.sleep(0.10) cat("\n") } main.count <- main.count + 1 } if(main.count != 1){ close(pb) } final.res <- list() if(length(orig.dictionary) != length(full.dictionary)) { choices <- c("In my results", "In my working directory", "I'd like to choose the directory", "Don't save it") title <- "\nWhere would you like to save your additional dictionary entries?" customMenu(choices = choices, title = title, default = 4, dictionary = TRUE) ans <- readline(prompt = "Selection: ") ans <- appropriate.answer(answer = ans, choices = choices, default = 4, dictionary = TRUE) if(ans == 1) { final.res$dictionary <- full.dictionary message("\nDictionary saved to your output object under '$dictionary'") }else if(ans == 2) { dictionary.name <- readline(prompt = "Name for the dictionary: ") dictionary.name <- gsub(".dictionary", "", dictionary.name) SemNetDictionaries::append.dictionary(full.dictionary, dictionary.name = dictionary.name, save.location = "wd", textcleaner = TRUE) message(paste("\nDictionary saved to your working directory: '", getwd(), "'", sep = "")) }else if(ans == 3) { dictionary.name <- readline(prompt = "Name for the dictionary: ") dictionary.name <- gsub(".dictionary", "", dictionary.name) SemNetDictionaries::append.dictionary(full.dictionary, dictionary.name = dictionary.name, save.location = "choose", textcleaner = TRUE) }else{message("\nDictionary was not saved")} } if(main.count != 1){ if(any(dictionary %in% SemNetDictionaries::dictionaries(TRUE)[-which(SemNetDictionaries::dictionaries(TRUE) == "general")])) { message("\nRunning ad hoc check for common misspellings and monikers...", appendLF = FALSE) target <- dictionary[na.omit(match(SemNetDictionaries::dictionaries(TRUE), dictionary))] for(i in 1:length(to)) for(j in 1:length(to[[i]])){ to[[i]][j] <- unlist(moniker(to[[i]][j], SemNetDictionaries::load.monikers(target), spelling = spelling)) } message("done") } } final.res$from <- from final.res$to <- to final.res$manual <- initial$manual final.res$auto <- initial$auto final.res$data <- data final.res$stop <- FALSE class(final.res) <- "textcleaner" return(final.res) } correspondence.matrix <- function (from, to) { n <- length(from) to_width <- max(unlist(lapply(to, length))) corr.mat <- matrix(NA, nrow = n, ncol = (to_width + 1)) colnames(corr.mat) <- c("from", paste("to_", 1:to_width, sep = "")) for(i in 1:n) { insert <- c(from[[i]], to[[i]]) corr.mat[i,1:length(insert)] <- insert } return(corr.mat) } correct.data <- function (data, corr.mat) { n <- nrow(data) data.max <- max(rowSums(apply(data, 2, function(x){!is.na(x)}))) correct.mat <- matrix(NA, nrow = n, ncol = 2 * data.max) behav.mat <- matrix(0, nrow = n, ncol = 2) colnames(behav.mat) <- c("Perseverations", "Intrusions") row.names(behav.mat) <- row.names(data) for(i in 1:n) { ind <- match(data[i,!is.na(data[i,])], corr.mat[,"from"]) corr <- corr.mat[ind,-1] if(!is.matrix(corr)) {corr <- as.matrix(corr)} correct.ord <- na.omit(as.vector(t(corr))) if(length(correct.ord) > 0) { behav.mat[i,"Intrusions"] <- sum(correct.ord == "NA") behav.mat[i,"Perseverations"] <- length(correct.ord[-which(correct.ord == "NA")]) - length(unique(correct.ord[-which(correct.ord == "NA")])) correct.mat[i,1:length(correct.ord)] <- correct.ord }else{ behav.mat[i,"Intrusions"] <- 0 behav.mat[i,"Perseverations"] <- 0 } } correct.mat <- correct.mat[,-which(apply(correct.mat, 2, function(x){all(is.na(x))}))] row.names(correct.mat) <- row.names(data) colnames(correct.mat) <- paste("Response_", formatC(1:ncol(correct.mat), digits = nchar(ncol(correct.mat)) - 1, flag = "0"), sep = "") res <- list() res$behavioral <- behav.mat res$corrected <- correct.mat return(res) } update.monikers <- function (word, monikers, monk.list) { obj.name <- as.character(substitute(monk.list)) if(word %in% names(monk.list)) { monk.list[[word]] <- sort(unique(c(monk.list[[word]], monikers))) }else{ monk.list[[paste(word)]] <- sort(unique(monikers)) monk.list <- monk.list[order(names(monk.list))] } assign(obj.name, monk.list, envir = environment()) path <- "D:/R Packages/SemNetDictionaries/data" data.path <- paste(path, "/", obj.name, ".Rdata", sep = "") return(monk.list) } colortext <- function(text, number = NULL, defaults = NULL) { sys.check <- system.check() if(sys.check$TEXT) { if(is.null(number) || number < 0 || number > 231) {number <- 15} if(!is.null(defaults)) { if(defaults == "highlight") { if(sys.check$RSTUDIO) { if(rstudioapi::getThemeInfo()$dark) {number <- 226 }else{number <- 208} }else{number <- 208} }else{ number <- switch(defaults, message = 204, red = 9, orange = 208, yellow = 11, "light green" = 10, green = 34, cyan = 14, blue = 12, magenta = 13, pink = 211, ) } } return(paste("\033[38;5;", number, "m", text, "\033[0m", sep = "")) }else{return(text)} } styletext <- function(text, defaults = c("bold", "italics", "highlight", "underline", "strikethrough")) { sys.check <- system.check() if(sys.check$TEXT) { if(missing(defaults)) {number <- 0 }else{ number <- switch(defaults, bold = 1, italics = 3, underline = 4, highlight = 7, strikethrough = 9 ) } return(paste("\033[", number, ";m", text, "\033[0m", sep = "")) }else{return(text)} } textsymbol <- function(symbol = c("alpha", "beta", "chi", "delta", "eta", "gamma", "lambda", "omega", "phi", "pi", "rho", "sigma", "tau", "theta", "square root", "infinity", "check mark", "x", "bullet") ) { sym <- switch(symbol, alpha = "\u03B1", beta = "\u03B2", chi = "\u03C7", delta = "\u03B4", eta = "\u03B7", gamma = "\u03B3", lambda = "\u03BB,", omega = "\u03C9", phi = "\u03C6", pi = "\u03C0", rho = "\u03C1", sigma = "\u03C3", tau = "\u03C4", theta = "\u03B8", "square root" = "\u221A", infinity = "\u221E", "check mark" = "\u2713", x = "\u2717", bullet = "\u2022" ) return(sym) } system.check <- function (...) { OS <- unname(tolower(Sys.info()["sysname"])) RSTUDIO <- ifelse(Sys.getenv("RSTUDIO") == "1", TRUE, FALSE) TEXT <- TRUE if(!RSTUDIO){if(OS != "linux"){TEXT <- FALSE}} res <- list() res$OS <- OS res$RSTUDIO <- RSTUDIO res$TEXT <- TEXT return(res) }
hr<- function(object, var, timevalue, scenario) UseMethod("hr") "hr.thregIcure" <- function (object,var,timevalue,scenario) { para <- match.call(expand.dots = FALSE) indx <- match(c("object", "var", "timevalue", "scenario"), names(para), nomatch=0) if (indx[1] ==0) stop("An object argument is required") if (indx[2] ==0) stop("A var argument is required") if (!inherits(object, 'thregIcure')) stop("Primary argument must be a thregIcure object") m_timevalue<-match(c("timevalue"), names(para), 0) if (!m_timevalue) timevalue<- model.extract(object$mf, "response")[,1] if(!is.numeric(timevalue)) { stop(paste("'timevalue' option must specify a numerical value!")) } m_scenario<-match(c("scenario"), names(para), 0) m_hr<-match(c("var"), names(para), 0) scenario_value<-NULL scenario_covariate<-NULL if(m_scenario!=0) { cur_scenario_string<-para[[m_scenario]] while(length(cur_scenario_string)>=2) { if(length(cur_scenario_string)==3) { current_scenario_covariate_string<-cur_scenario_string[[3]] if(length(current_scenario_covariate_string)==2) { current_scenario_covariate<-current_scenario_covariate_string[[1]] current_covariate_value<-current_scenario_covariate_string[[2]] scenario_covariate<-c(current_scenario_covariate,scenario_covariate) scenario_value<-c(current_covariate_value,scenario_value) } else { stop("wrong scenario specification") } cur_scenario_string<-cur_scenario_string[[2]] } else if(length(cur_scenario_string)==2) { current_scenario_covariate_string<-cur_scenario_string current_scenario_covariate<-current_scenario_covariate_string[[1]] current_covariate_value<-current_scenario_covariate_string[[2]] scenario_covariate<-c(current_scenario_covariate,scenario_covariate) scenario_value<-c(current_covariate_value,scenario_value) current_scenario_covariate_string<-NULL cur_scenario_string<-NULL current_scenario_covariate<-NULL current_covariate_value<-NULL } } } scenario_covariate<-c("(Intercept)",scenario_covariate) scenario_value<-c(1,scenario_value) names(scenario_value)<-scenario_covariate m_hr<-match(c("var"), names(para), 0) hr_var<-as.character(para[[m_hr]]) if (!is.factor(object$mf[[hr_var]])) stop("The variable for the hazard ratio calculation should be a factor variable") if (length(levels(object$mf[[hr_var]]))<2) stop("The variable for the hazard ratio calculation should have more than one level") if (!any(names(object$mf)==hr_var)) stop("The variable ",as.character(para[[m_hr]]) , " for the hazard ratio calculation should be included in the model") scenario_value_hr<-rbind(rep(0,length(levels(object$mf[[hr_var]]))-1),diag(rep(1,length(levels(object$mf[[hr_var]]))-1))) colnames(scenario_value_hr) <- paste(hr_var,levels(object$mf[[hr_var]])[-1],sep="") if (any(matrix(rep(names(scenario_value),times=length(dimnames(scenario_value_hr)[[2]])),nrow=length(dimnames(scenario_value_hr)[[2]]),byrow=TRUE)==dimnames(scenario_value_hr)[[2]])) stop("Don't specify the scenario value of the dummy variable for the hazard ratio calculation!") scenario_value<-matrix(rep(scenario_value,times=length(levels(object$mf[[hr_var]]))),nrow=length(levels(object$mf[[hr_var]])),byrow=TRUE) dimnames(scenario_value)[[2]] <- as.list(scenario_covariate) scenario_value<-cbind(scenario_value,scenario_value_hr) judgematrix_lny0<-matrix(rep(object$lny0,times=dim(scenario_value)[2]),ncol=dim(scenario_value)[2])==matrix(rep(dimnames(scenario_value)[[2]],times=length(object$lny0)),nrow=length(object$lny0),byrow=TRUE) if (any(!apply(judgematrix_lny0,1,any))) stop(paste("scenario value for", object$lny0[!apply(judgematrix_lny0,1,any)][1], "is required!")) positionpick_lny0=judgematrix_lny0%*%c(1:dim(scenario_value)[2]) lny0<-scenario_value[,positionpick_lny0]%*%object$coef[1:length(object$lny0)] y0<-exp(lny0) judgematrix_mu<-matrix(rep(object$mu,times=dim(scenario_value)[2]),ncol=dim(scenario_value)[2])==matrix(rep(dimnames(scenario_value)[[2]],times=length(object$mu)),nrow=length(object$mu),byrow=TRUE) if (any(!apply(judgematrix_mu,1,any))) stop(paste("scenario value for", object$mu[!apply(judgematrix_mu,1,any)][1], "is required!")) positionpick_mu=judgematrix_mu%*%c(1:dim(scenario_value)[2]) mu<-scenario_value[,positionpick_mu]%*%object$coef[(length(object$lny0)+1):(length(object$lny0)+length(object$mu))] judgematrix_lamda<-matrix(rep(object$lamda,times=dim(scenario_value)[2]),ncol=dim(scenario_value)[2])==matrix(rep(dimnames(scenario_value)[[2]],times=length(object$lamda)),nrow=length(object$lamda),byrow=TRUE) if (any(!apply(judgematrix_lamda,1,any))) stop(paste("scenario value for", object$lamda[!apply(judgematrix_lamda,1,any)][1], "is required!")) positionpick_lamda=judgematrix_lamda%*%c(1:dim(scenario_value)[2]) lamda<-scenario_value[,positionpick_lamda]%*%object$coef[(length(object$lny0)+length(object$mu)+1):(length(object$lny0)+length(object$mu)+length(object$lamda))] p<-exp(lamda)/(1+exp(lamda)) dim(y0)<-NULL dim(lny0)<-NULL dim(mu)<-NULL dim(lamda)<-NULL dim(p)<-NULL y0<-c(rep(y0,length(timevalue))) lny0<-c(rep(lny0,length(timevalue))) mu<-c(rep(mu,length(timevalue))) lamda<-c(rep(lamda,length(timevalue))) p<-c(rep(p,length(timevalue))) lenth_timevalue<-length(timevalue) timevalue_rep<-rep(timevalue,each=length(dimnames(scenario_value_hr)[[2]])+1) f<-p*exp((lny0-.5*(log(2*pi*(timevalue_rep^3))+(y0+mu*timevalue_rep)^2/timevalue_rep))) S<-p*exp(log(pnorm((mu*timevalue_rep+y0)/sqrt(timevalue_rep))-exp(-2*y0*mu)*pnorm((mu*timevalue_rep-y0)/sqrt(timevalue_rep))))+(1-p) h<-f/S dim(h)<-c(length(dimnames(scenario_value_hr)[[2]])+1,lenth_timevalue) if (dim(h)[[1]]>2) { hr<-t(h[-1,]/h[1,]) } else if (dim(h)[[1]]==2) { hr<-cbind(h[-1,]/h[1,]) } colnames(hr)<-dimnames(scenario_value_hr)[[2]] hr<-cbind(timevalue,hr) hr }
coin <- hijack(r_sample_binary_factor, name = "Coin", x = c("Tails", "Heads") )
depthf.simplicialBand <- function(objectsf, dataf, modified = TRUE, J = NULL, range = NULL, d = 101){ if (length(objectsf) < 1){ stop("Number of functions for which the depth should be computed is < 1.") } p <- ifelse(is.null(dim(objectsf[[1]]$vals)), 1, dim(objectsf[[1]]$vals)[2]) J <- p + 1 if (length(dataf) < J){ stop("Number of functions w.r.t. which the depth should be computed is < dimension + 1.") } m <- length(objectsf) n <- length(dataf) objArgs <- unique(unlist(lapply(objectsf, function(x){return(x$args)}))) datArgs <- unique(unlist(lapply(dataf, function(x){return(x$args)}))) if (length(objArgs) != length(datArgs) || sum(objArgs == datArgs) != length(objArgs)){ stop("Not the same arguments for 'objectsf' and 'dataf'.") } l <- length(objArgs) numObjArgs <- unlist(lapply(objectsf, function(x){return(length(x$args))})) if (sum(numObjArgs == length(objArgs)) != m){ stop("Not the same arguments for all functions in 'objectsf'.") } numDatArgs <- unlist(lapply(dataf, function(x){return(length(x$args))})) if (sum(numDatArgs == length(datArgs)) != n){ stop("Not the same arguments for all functions in 'dataf'.") } if (p == 1){ numObjVals <- unlist(lapply(objectsf, function(x){return(length(x$vals))})) numDatVals <- unlist(lapply(dataf, function(x){return(length(x$vals))})) }else{ numObjVals <- unlist(lapply(objectsf, function(x){return(nrow(x$vals))})) numDatVals <- unlist(lapply(dataf, function(x){return(nrow(x$vals))})) } if (sum(numObjVals == numObjArgs) != m){ stop("Number of arguments and values for (some) functions in 'objectsf' differ.") } if (sum(numDatVals == numDatArgs) != n){ stop("Number of arguments and values for (some) functions in 'dataf' differ.") } A <- dataf2rawfd(objectsf, range = range, d = d) B <- dataf2rawfd(dataf, range = range, d = d) At <- apply(A, 1, function(x) t(x)) Bt <- apply(B, 1, function(x) t(x)) fArgs <- approx(dataf[[1]]$args, n = d)$x ds <- .C("SimplicialBandDepthF", as.double(At), as.double(Bt), as.double(fArgs), as.integer(m), as.integer(n), as.integer(d), as.integer(p), as.integer(modified), as.integer(J), depths = double(m))$depths return(ds) }
library(lgcp) n <- 3 m <- 3 temporal.fitted <- c(1,2,3) SpatialOnlyMode <- FALSE M <- 5 N <- 5 Y <- list() for(i in 1:n){ Y[[i]] <- list() for (j in 1:m){ Y[[i]][[j]] <- matrix(runif(25),5,5) } } fun1 <- function(Y){ return(Y) } fun2 <- function(Y){ return(Y^2) } mca <- MonteCarloAverage(list("fun1","fun2")) GAinitialise(mca) oldtags <- list() for(i in 1:n){ oldtags$Y <- Y[[i]] GAupdate(mca) } GAfinalise(mca) ret <- GAreturnvalue(mca) Ymean <- as.list(rep(0,m)) Ymean2 <- as.list(rep(0,m)) for(i in 1:n){ for (j in 1:m){ Ymean[[j]] <- Ymean[[j]] + Y[[i]][[j]] Ymean2[[j]] <- Ymean2[[j]] + Y[[i]][[j]]^2 } } for (j in 1:m){ Ymean[[j]] <- Ymean[[j]]/n Ymean2[[j]] <- Ymean2[[j]]/n } for (j in 1:m){ print(all(ret$return[[1]][[j]]==Ymean[[j]])) print(all(ret$return[[2]][[j]]==Ymean2[[j]])) }
subcopemc <- function(mat.xy, m = nrow(mat.xy), display = FALSE){ n <- nrow(mat.xy) if (!(m %in% (1:n))){ error.msg <- paste("Order m must be an integer value in 1:n, n =", n) stop(error.msg) } else{ mensaje <- character(0) X <- mat.xy[ , 1] Y <- mat.xy[ , 2] if ((length(unique(X)) < n) | (length(unique(Y)) < n)){ mensaje <- "Presence of repeated values, jittering has been applied" ind.X <- which(duplicated(X)) ind.Y <- which(duplicated(Y)) if (length(ind.X) > 0) X[ind.X] <- jitter(X[ind.X]) if (length(ind.Y) > 0) Y[ind.Y] <- jitter(Y[ind.Y]) mat.xy <- cbind(X, Y) } r.xy <- apply(mat.xy, 2, rank) kparticion <- round(seq(0, n, length = (m + 1)), 0) r.ordx <- r.xy[order(r.xy[ , 1]) , ] contar.aux <- function(kx, ky) sum(r.ordx[1:kx, 2] <= ky) contar <- function(kx, ky) mapply(contar.aux, kx, ky) subcopula <- matrix(0, nrow = (m + 1), ncol = (m + 1)) subcopula[2:(m + 1), 2:(m + 1)] <- (1/n)*outer(kparticion[2:(m + 1)], kparticion[2:(m + 1)], contar) particion <- kparticion/n muestra.std <- r.xy/n M <- function(u, v) (u + v - abs(u - v))/2 W <- function(u, v) (u + v - 1 + abs(u + v - 1))/2 P <- function(u, v) u*v subcopM <- outer(particion, particion, M) subcopW <- outer(particion, particion, W) subcopP <- outer(particion, particion, P) dsgn <- function(A, B) max(A - B) - max(B - A) dsup <- function(A, B) max(abs(A - B)) Msgn <- dsgn(subcopM, subcopP) Wsgn <- dsgn(subcopW, subcopP) d <- dsgn(subcopula, subcopP) depMon <- (d >= 0)*d/Msgn - (d < 0)*d/Wsgn depMonNonSTD <- c(4*Wsgn, 4*d, 4*Msgn) names(depMonNonSTD) <- c("min", "value", "max") Msup <- dsup(subcopM, subcopP) Wsup <- dsup(subcopW, subcopP) supBound <- max(Msup, Wsup) depSup <- dsup(subcopula, subcopP)/supBound depSupNonSTD <- c(0, 4*supBound*depSup, 4*supBound) names(depSupNonSTD) <- c("min", "value", "max") SC <- list(depMon = depMon, depMonNonSTD = depMonNonSTD, depSup = depSup, depSupNonSTD = depSupNonSTD, matrix = subcopula, part1 = particion, part2 = particion, sample.size = n, order = m, std.sample = muestra.std, sample = mat.xy) if (length(mensaje) > 0) warning(mensaje) if (display == TRUE){ message("monotone dependence = [ -1 , ", round(depMon, 8), " , 1 ]") message("non-std interval = [ ", round(depMonNonSTD[1], 8), " , ", round(depMonNonSTD[2], 8), " , ", round(depMonNonSTD[3], 8), " ]") message("supremum dependence = [ 0 , ", round(depSup, 8), " , 1 ]") message("non-std interval = [ ", round(depSupNonSTD[1], 8), " , ", round(depSupNonSTD[2], 8), " , ", round(depSupNonSTD[3], 8), " ]") dev.new(); par(mfcol = c(2, 3)) hist(mat.xy[ , 1], main = "histogram", xlab = "X") hist(mat.xy[ , 2], main = "histogram", xlab = "Y") plot(mat.xy, main = "sample", xlab = "X", ylab = "Y") plot(c(0, 1), c(0, 1), type = "n", main = "standardized sample", ylab = "", xlab = paste("monotone dependence =", round(depMon, 3))) points(muestra.std) contour(particion, particion, subcopula, nlevels = 20, main = "subcopula", ylab = "", xlab = "") image(particion, particion, subcopula, col = heat.colors(20), main = "subcopula", ylab = "", xlab = paste("supremum dependence =", round(depSup, 3))) } return(SC) } }
facet_chart <- function( data, cd_method = "aggregate", facet_order = NULL, subradius = 0, file_name = "none", size = 1, font = "sans", rotate_radians = 0, rotate_degrees = 0, file_width = 10, file_height = 10, zoom_x = NULL, zoom_y = NULL, dpi = 500, color = " fade = 85, tick = 0, rotate_tick_label = 0, cor_labels = TRUE, dist_test_label = 2 / 3, rotate_test_label_radians = 0, rotate_test_label_degrees = 0, title = NULL, size_title = 1, size_cor_labels = 1, size_test_label = 1, size_facet_labels = 1, width_axes = 1, width_circles = 1, width_tick = 1, size_tick_label = 1){ coord <- coord_facets( data = data, cd_method = cd_method, facet_order = facet_order, subradius = subradius, tick = tick, rotate_tick_label, rotate_radians = rotate_radians, rotate_degrees = rotate_degrees, dist_test_label = dist_test_label, rotate_test_label_radians =rotate_test_label_radians, rotate_test_label_degrees = rotate_test_label_degrees) myipv <- plot_facets( coord = coord, title = title, size = size, file_name = file_name, file_width = file_width, file_height = file_height, zoom_x = zoom_x, zoom_y = zoom_y, dpi = dpi, color = color, fade = fade, font = font, cor_labels = cor_labels, size_cor_labels = size_cor_labels, size_title = size_title, size_test_label = size_test_label, size_facet_labels = size_facet_labels, width_axes = width_axes, width_circles = width_circles, width_tick = width_tick, size_tick_label = size_tick_label) return(myipv) } plot_facets <- function( coord, title = NULL, size = 1, file_name = "none", file_width = 10, file_height = 10, zoom_x = NULL, zoom_y = NULL, dpi = 500, color = "black", fade = 85, font = "sans", cor_labels = TRUE, size_title = 1, size_cor_labels = 1, size_test_label = 1, size_facet_labels = 1, width_axes = 1, width_circles = 1, width_tick = 1, size_tick_label = 1){ if (cor_labels == TRUE) { cors <- coord$cors } else cors <- NULL facet_labels <- row.names(coord$c_circs) tick <- signif(sqrt((coord$axis_tick$x ^ 2) + (coord$axis_tick$y ^ 2)), 1) tick_label_label <- as.character(formatC(tick, format = "fg")) tick_label_x <- coord$axis_tick$x + 0.03 * size * size_tick_label * cos(coord$axis_tick$phi) * coord$p_circs[1, "radius"] tick_label_y <- coord$axis_tick$y + 0.03 * size * size_tick_label * sin(coord$axis_tick$phi) * coord$p_circs[1, "radius"] if(!is.null(zoom_x) & !is.null(zoom_y)) { asp <- diff(zoom_y) / diff(zoom_x) file_height <- asp * file_width } myipv <- ggplot2::ggplot(coord$c_circs) + ggplot2::coord_fixed() + ggplot2::theme( axis.line = ggplot2::element_blank(), axis.text.x = ggplot2::element_blank(), axis.text.y = ggplot2::element_blank(), axis.ticks = ggplot2::element_blank(), axis.title.x = ggplot2::element_blank(), axis.title.y = ggplot2::element_blank(), legend.position = "none", panel.background = ggplot2::element_blank(), panel.border = ggplot2::element_blank(), panel.grid.major = ggplot2::element_blank(), panel.grid.minor = ggplot2::element_blank(), plot.background = ggplot2::element_blank(), text = ggplot2::element_text(size = 16, family = font), plot.margin = ggplot2::margin(0, 0, 0, 0, "in"), plot.title = ggplot2::element_text( hjust = .5, vjust = -3, size = 16 * size * size_title)) + ggplot2::aes() + ggplot2::geom_point( ggplot2::aes(x = 0, y = 0), size = 3 * size * width_axes) + ggforce::geom_circle( ggplot2::aes(x0 = 0, y0 = 0, r = tick), linetype = "dotted", size = .5 * min(size, 1) * width_tick) + ggforce::geom_circle( data = coord$c_circs[-1, ], ggplot2::aes_string(x0 = "x", y0 = "y", r = "radius"), size = .5 * size * width_circles, color = color, fill = "white") + ggplot2::geom_segment( data = coord$c_axes, ggplot2::aes_string(x = "x2", y = "y2", xend = "x3", yend = "y3"), size = .5 * size * width_axes, color = paste("gray", fade, sep = "")) + ggplot2::geom_text( data = coord$axis_tick, ggplot2::aes(x = tick_label_x, y = tick_label_y, label = tick_label_label), angle = (coord$axis_tick$phi - pi / 48 - pi / 2) * 180 / pi, family = font, size = 4 * size * size_tick_label) + ggforce::geom_circle( data = coord$c_circs[1, ], ggplot2::aes_string(x0 = "x", y0 = "y", r = "radius"), size = .5 * size * width_axes, color = paste("gray", fade, sep = "")) + ggforce::geom_circle( data = coord$c_circs[-1, ], ggplot2::aes_string(x0 = "x", y0 = "y", r = "radius"), size = .6 * size * width_circles, color = color) + ggplot2::geom_text( ggplot2::aes_string(x = "x", y = "y", label = "facet_labels"), family = font, size = 6 * size * size_facet_labels) + ggplot2::geom_segment( data = coord$c_axes, ggplot2::aes_string(x = "x0", y = "y0", xend = "x1", yend = "y1"), size = 1.5 * size * width_axes, color = "black") + ggplot2::geom_text( data = coord$test_label, ggplot2::aes_string(x = "x", y = "y", label = "label"), family = font, size = 8 * size * size_test_label, fontface = "bold", color = "black") if (!is.null(cors)) { myipv <- myipv + ggplot2::geom_text( data = cors, ggplot2::aes_string(x = "x", y = "y", label = "label"), family = font, size = 4 * size * size_cor_labels) } if (!is.null(title)) { myipv <- myipv + ggplot2::ggtitle(label = title) } if (!is.null(c(zoom_x, zoom_y))) { myipv <- myipv + ggplot2::coord_cartesian(xlim = zoom_x, ylim = zoom_y, expand = FALSE) if(!is.null(zoom_x) & !is.null(zoom_y) & file_name != "none") { message(paste( "file_height was set to ", signif(asp, 4), " times the file_width, to retain the aspect ratio.", sep = "")) } } if (substring(file_name, nchar(file_name)-3+1) == "pdf") { ggplot2::ggsave(file_name, myipv, width = file_width, height = file_height, units = "in", dpi = dpi) } if (substring(file_name, nchar(file_name)-3+1) == "png") { ggplot2::ggsave(file_name, myipv, width = file_width, height = file_height, units = "in", dpi = dpi) } if (substring(file_name, nchar(file_name)-3+1) == "peg") { ggplot2::ggsave(file_name, myipv, width = file_width, height = file_height, units = "in", dpi = dpi) } return(myipv) }
order.group<-function(trt, means, N, MSerror, Tprob, std.err, parameter = 1) { N <- rep(1/mean(1/N), length(N)) n <- length(means) letras<-letters if(n>26) { l<-floor(n/26) for(i in 1:l) letras<-c(letras,paste(letters,i,sep='')) } z <- data.frame(trt, means, N, std.err) w <- z[order(z[, 2], decreasing = TRUE), ] M <- rep("", n) k <- 1 j <- 1 k <- 1 cambio <- n cambio1 <- 0 chequeo = 0 M[1] <- letras[k] while (j < n) { chequeo <- chequeo + 1 if (chequeo > n) break for (i in j:n) { minimo <- Tprob * sqrt(parameter * MSerror * (1/N[i] + 1/N[j])) s <- abs(w[i, 2] - w[j, 2]) <= minimo if (s) { if (lastC(M[i]) != letras[k]) M[i] <- paste(M[i], letras[k], sep = "") } else { k <- k + 1 cambio <- i cambio1 <- 0 ja <- j for (jj in cambio:n) M[jj] <- paste(M[jj], " ", sep = "") M[cambio] <- paste(M[cambio], letras[k], sep = "") for (v in ja:cambio) { if (abs(w[v, 2] - w[cambio, 2]) > minimo) { j <- j + 1 cambio1 <- 1 } else break } break } } if (cambio1 == 0) j <- j + 1 } w <- data.frame(w, stat = M) trt <- as.character(w$trt) means <- as.numeric(w$means) N <- as.numeric(w$N) std.err <- as.numeric(w$std.err) for (i in 1:n) { cat(M[i], "\t", trt[i], "\t", means[i], "\n") } output <- data.frame(trt, means, M, N, std.err) return(output) }
clipsvg <- function(object, xmin = -Inf, xmax = +Inf, ymin = -Inf, ymax = +Inf, by.entity = TRUE) { if(!(by.entity == TRUE | by.entity == FALSE)){ stop("The by.entity parameter should be TRUE or FALSE") } if(by.entity){ out <- subset(object, object$x > xmax | object$x < xmin | object$y > ymax | object$y < ymin) l <- unique(out$id) res <- subset(object,!(object$id %in% l)) } else { res <- subset(object, object$x <= xmax & object$x >= xmin & object$y <= ymax & object$y >= ymin) } return(res) }
fdPar <- function(fdobj=NULL, Lfdobj=NULL, lambda=0, estimate=TRUE, penmat=NULL){ if(!inherits(fdobj, 'fd')) { if (is.null(fdobj)) { fdobj = fd() } else { if (inherits(fdobj, "basisfd")) { nbasis <- fdobj$nbasis dropind <- fdobj$dropind nbasis <- nbasis - length(dropind) coefs <- matrix(0,nbasis,nbasis) fdnames <- list('time', 'reps 1', 'values') if(!is.null(fdobj$names)){ basisnames <- { if(length(dropind)>0) fdobj$names[-dropind] else fdobj$names } dimnames(coefs) <- list(basisnames, NULL) fdnames[[1]] <- basisnames } fdobj <- fd(coefs, fdobj, fdnames) } else if(is.numeric(fdobj))fdobj <- fd(fdobj) else stop("First argument is neither a functional data object ", "nor a basis object.") } } else { nbasis <- fdobj$basis$nbasis } { if (is.null(Lfdobj)) { if(fdobj$basis$type=='fourier'){ rng <- fdobj$basis$rangeval Lfdobj <- vec2Lfd(c(0,(2*pi/diff(rng))^2,0), rng) } else { norder <- { if (fdobj$basis$type=='bspline') norder.bspline(fdobj$basis) else 2 } Lfdobj <- int2Lfd(max(0, norder-2)) } } else Lfdobj <- int2Lfd(Lfdobj) } if (!inherits(Lfdobj, "Lfd")) stop("'Lfdobj' is not a linear differential operator object.") if (!is.numeric(lambda)) stop("Class of LAMBDA is not numeric.") if (lambda < 0) stop("LAMBDA is negative.") if (!is.logical(estimate)) stop("Class of ESTIMATE is not logical.") if (!is.null(penmat)) { if (!is.numeric(penmat)) stop("PENMAT is not numeric.") penmatsize <- dim(penmat) if (any(penmatsize != nbasis)) stop("Dimensions of PENMAT are not correct.") } fdParobj <- list(fd=fdobj, Lfd=Lfdobj, lambda=lambda, estimate=estimate, penmat=penmat) oldClass(fdParobj) <- "fdPar" fdParobj } print.fdPar <- function(x, ...) { object <- x cat("Functional parameter object:\n\n") print("Functional data object:") print.fd(object$fd) print("Linear differential operator object:") print.Lfd(object$Lfd) cat(paste("\nSmoothing parameter =",object$lambda,"\n")) cat(paste("\nEstimation status =",object$estimate,"\n")) if (!is.null(object$penmat)) { print("Penalty matrix:") print(object$penmat) } } summary.fdPar <- function(object, ...) { cat("Functional parameter object:\n\n") print("Functional data object:") summary.fd(object$fd) print("Linear differential operator object:") summary.Lfd(object$Lfd) cat(paste("\nSmoothing parameter =",object$lambda,"\n")) cat(paste("\nEstimation status =",object$estimate,"\n")) if (!is.null(object$penmat)) print(paste("Penalty matrix dimensions:",dim(object$penmat))) }
vmd.cnapath <- function(x, pdb, out.prefix = "vmd.cnapath", spline = FALSE, colors = c("blue", "red"), launch = FALSE, exefile=NULL, mag=1.0, ...) { if(!inherits(x, "cnapath")) { if(is.list(x) && inherits(x[[1]], "cnapath")) { if(length(x)==1) { x <- x[[1]] } else { x2 <- do.call(mapply, c(list("c"), x, list(SIMPLIFY=FALSE))) x2$grp <- rep(1:length(x), times=sapply(x, function(x) length(x$path))) class(x2) <- "cnapath" x <- x2 } } else { stop("Input x is not a (or a list of) 'cnapath' object(s)") } } if(is.character(colors)) { cols <- colors } else { if(length(colors) == 1 && is.numeric(colors)) cols <- vmd_colors()[colors + 1] else stop("colors should be a character vector or an integer indicating a VMD color ID") } if(!is.null(x$grp)) { if(length(cols) != max(x$grp)) { stop("Color length does not match input x") } cols <- lapply(cols, colorRamp) } else { cols <- colorRamp(cols) } file = paste(out.prefix, ".vmd", sep="") pdbfile = paste(out.prefix, ".pdb", sep="") res <- unique(unlist(x$path)) ind.source <- match(x$path[[1]][1], res) ind.sink <- match(x$path[[1]][length(x$path[[1]])], res) ca.inds <- atom.select(pdb, elety="CA", verbose = FALSE) res.pdb <- pdb$atom[ca.inds$atom[res], "resno"] chain.pdb <- pdb$atom[ca.inds$atom[res], "chain"] names(res.pdb) <- chain.pdb .vmd.atomselect <- function(res) { if(any(is.na(names(res)))) return(paste("resid", paste(res, collapse=" "))) else { res <- res[order(names(res))] inds <- bounds(names(res), dup.inds=TRUE) string <- NULL for(i in 1:nrow(inds)) { string <- c(string, paste("chain", names(res)[inds[i, "start"]], "and resid", paste(res[inds[i, "start"]:inds[i, "end"]], collapse=" "))) } return(paste(string, collapse=" or ")) } } cat("mol new ", pdbfile, " type pdb first 0 last -1 step 1 filebonds 1 autobonds 1 waitfor all mol delrep 0 top mol representation NewCartoon 0.300000 10.000000 4.100000 0 mol color colorID 8 mol selection {all} mol material Opaque mol addrep top mol representation Licorice 0.300000 10.000000 10.000000 mol color name mol selection {(", .vmd.atomselect(res.pdb[c(ind.source, ind.sink)]), ")} mol material Opaque mol addrep top mol representation VDW 0.4 10 mol color colorID 2 mol selection {(", .vmd.atomselect(res.pdb), ") and name CA} mol material Opaque mol addrep top ", file=file) cat("\n rad <- function(r, rmin, rmax, radmin = 0.01, radmax = 0.5) { (rmax - r) / (rmax - rmin) * (radmax - radmin) + radmin } rmin <- min(x$dist) rmax <- max(x$dist) cat("display update off\n", file=file, append=TRUE) cat("set color_start [colorinfo num]\n", file=file, append=TRUE) if(!spline) { col.mat <- array(list(), dim=c(length(res), length(res))) conn <- matrix(0, length(res), length(res)) rr <- conn for(j in 1:length(x$path)) { y = x$path[[j]] for(i in 1:(length(y)-1)) { i1 = match(y[i], res) i2 = match(y[i+1], res) if(conn[i1, i2] == 0) conn[i1, i2] = conn[i2, i1] = 1 r = rad(x$dist[j], rmin, rmax, radmax = 0.5*mag) ic = (rmax - x$dist[j]) / (rmax - rmin) if(is.list(cols)) { col = list(cols[[x$grp[j]]](ic)[1:3]) } else { col = list(cols(ic)[1:3]) } if(r > rr[i1, i2]) { rr[i1, i2] = rr[i2, i1] = r col.mat[i1, i2] = col.mat[i2, i1] = col } } } rownames(conn) <- res colnames(conn) <- res rownames(rr) <- res colnames(rr) <- res k = 0 for(i in 1:(nrow(conn)-1)) { for(j in (i+1):ncol(conn)) { if(conn[i, j] == 1) { if(!is.numeric(colors)) { col = unlist(col.mat[i, j]) / 255 cat("color change rgb [expr ", k, " + $color_start] ", paste(col, collapse=" "), "\n", sep="", file=file, append=TRUE) cat("graphics top color [expr ", k, " + $color_start]\n", sep="", file=file, append=TRUE) } else { cat("graphics top color ", colors, "\n", sep="", file=file, append=TRUE) } cat("draw cylinder {", pdb$xyz[atom2xyz(ca.inds$atom[res[i]])], "} {", pdb$xyz[atom2xyz(ca.inds$atom[res[j]])], "} radius", rr[i, j], " resolution 6 filled 0\n", sep=" ", file=file, append=TRUE) k = k + 1 } } } } else { k = 0 for(j in 1:length(x$path)) { xyz = matrix(pdb$xyz[atom2xyz(ca.inds$atom[x$path[[j]]])], nrow=3) spline.x = spline(xyz[1, ], n = ncol(xyz)+(ncol(xyz)-1)*10)$y spline.y = spline(xyz[2, ], n = ncol(xyz)+(ncol(xyz)-1)*10)$y spline.z = spline(xyz[3, ], n = ncol(xyz)+(ncol(xyz)-1)*10)$y r = rad(x$dist[j], rmin, rmax, radmax=0.5*mag) ic = (rmax - x$dist[j]) / (rmax - rmin) if(is.list(cols)) { col = cols[[x$grp[j]]](ic)[1:3] / 255 } else { col = cols(ic)[1:3] / 255 } if(!is.numeric(colors)) { cat("color change rgb [expr ", k, " + $color_start] ", paste(col, collapse=" "), "\n", sep="", file=file, append=TRUE) cat("graphics top color [expr ", k, " + $color_start]\n", sep="", file=file, append=TRUE) } else { cat("graphics top color ", colors, "\n", sep="", file=file, append=TRUE) } for(i in 1:(length(spline.x) - 1)) { cat("draw cylinder {", spline.x[i], spline.y[i], spline.z[i], "} {", spline.x[i+1], spline.y[i+1], spline.z[i+1], "} radius", r, " resolution 6 filled 0\n", sep=" ", file=file, append=TRUE) } k = k + 1 } } cat("display update on\n", file=file, append=TRUE) write.pdb(pdb, file=pdbfile) if(launch) { if(is.null(exefile)) { exefile <- 'vmd' if(nchar(Sys.which(exefile)) == 0) { os1 <- Sys.info()["sysname"] exefile <- switch(os1, Windows = 'vmd.exe', Darwin = '/Applications/VMD\\ 1.9.*app/Contents/MacOS/startup.command', 'vmd' ) } } if(nchar(Sys.which(exefile)) == 0) stop(paste("Launching external program failed\n", " make sure '", exefile, "' is in your search path", sep="")) cmd <- paste(exefile, "-e", file) os1 <- .Platform$OS.type if (os1 == "windows") { shell(shQuote(cmd)) } else{ system(cmd) } } } vmd.ecnapath <- function(x, ...) { if(!inherits(x, "ecnapath")) { stop("The input 'x' must be an object of class 'ecnapath'.") } vmd.cnapath(x, ...) }
.dt_data_key <- "_data" dt_data_get <- function(data) { dt__get(data, .dt_data_key) } dt_data_set <- function(data, data_tbl) { dt__set(data, .dt_data_key, data_tbl %>% dplyr::as_tibble()) } dt_data_init <- function(data, data_tbl, rownames_to_column = NA) { if (!is.na(rownames_to_column)) { data_rownames <- rownames(data_tbl) if (rownames_to_column %in% colnames(data_tbl)) { stop("Reserved column name `", rownames_to_column, "` was detected in ", "the data; please rename this column", call. = FALSE) } data_tbl <- data_tbl %>% dplyr::mutate(!!sym(rownames_to_column) := data_rownames) %>% dplyr::select(!!sym(rownames_to_column), dplyr::everything()) } dt_data_set(data = data, data_tbl = data_tbl) }
context("SP_LIN_REG") N <- 73 M <- 230 x <- matrix(rnorm(N * M, mean = 100, sd = 5), N) y <- rnorm(N) covar0 <- matrix(rnorm(N * 3), N) lcovar <- list(NULL, covar0) test_that("equality with biglasso with all data", { for (t in TEST.TYPES) { X <- `if`(t == "raw", asFBMcode(x), big_copy(x, type = t)) for (covar in lcovar) { X2 <- bigmemory::as.big.matrix(cbind(X[], covar), type = "double", shared = FALSE) m <- runif(ncol(X2), min = 0.5, max = 2) alpha <- runif(1) lambda.min <- runif(1, min = 0.01, max = 0.5) mod.bigstatsr <- big_spLinReg(X, y, covar.train = covar, alpha = alpha, lambda.min = lambda.min, penalty.factor = m) mod.biglasso <- biglasso::biglasso(X2, y, family = "gaussian", alpha = alpha, penalty = "enet", lambda.min = lambda.min, penalty.factor = m) expect_equal(mod.bigstatsr$lambda, mod.biglasso$lambda) expect_equivalent(mod.bigstatsr$beta@x, mod.biglasso$beta[-1, ]@x) expect_equal(mod.bigstatsr$intercept, mod.biglasso$beta[1, ]) } } }) test_that("equality with biglasso with only half the data", { ind <- sample(N, N / 2) for (t in TEST.TYPES) { X <- `if`(t == "raw", asFBMcode(x), big_copy(x, type = t)) for (covar in lcovar) { X2 <- bigmemory::as.big.matrix(cbind(X[], covar), type = "double", shared = FALSE) m <- runif(ncol(X2), min = 0.5, max = 2) alpha <- runif(1) lambda.min <- runif(1, min = 0.01, max = 0.5) mod.bigstatsr <- big_spLinReg(X, y[ind], ind.train = ind, covar.train = covar[ind, ], alpha = alpha, lambda.min = lambda.min, penalty.factor = m) mod.biglasso <- biglasso::biglasso(X2, y, family = "gaussian", row.idx = ind, alpha = alpha, penalty = "enet", lambda.min = lambda.min, penalty.factor = m) expect_equal(mod.bigstatsr$lambda, mod.biglasso$lambda) expect_equivalent(mod.bigstatsr$beta@x, mod.biglasso$beta[-1, ]@x) expect_equal(mod.bigstatsr$intercept, mod.biglasso$beta[1, ]) } } })
NMisNumeric <- function(x,na.strings=".",each=FALSE){ is.timestamp <- function(x){ inherits(x, "POSIXct") || inherits(x, "POSIXlt") || inherits(x, "POSIXt") || inherits(x, "Date") } ok <- rep(TRUE,length(x)) if(is.logical(x) || is.timestamp(x)) { ok[] <- FALSE } else if(!is.numeric(x)){ ok[!is.na(x)&!as.character(x)%in%na.strings] <- suppressWarnings(!is.na(as.numeric(as.character(x)[!is.na(x)&!as.character(x)%in%na.strings]))) } if(!each) ok <- !any(!ok) ok }
library(tidyverse) library(dynbenchmark) dataset_preprocessing("real/gold/psc-astrocyte-maturation") txt_location <- download_dataset_source_file( "GSE99951_all_data_htseq_out.csv", "https://www.ncbi.nlm.nih.gov/geo/download/?acc=GSE99951&format=file&file=GSE99951%5Fall%5Fdata%5Fhtseq%5Fout%2Ecsv%2Egz" ) geo <- GEOquery::getGEO("GSE99951", destdir = dataset_source_file(""), GSElimits = c(1,1), GSEMatrix = FALSE, getGPL = FALSE, AnnotGPL = FALSE) cell_info_all <- dynutils::list_as_tibble(geo@gsms %>% map(~.@header)) %>% rowwise() %>% filter(length(characteristics_ch1) >= 7) %>% mutate( cell_id = gsub("([^ ]*).*", "X\\1", title), milestone_id = characteristics_ch1[[4]], group = characteristics_ch1[[6]] ) %>% ungroup() %>% select(cell_id, milestone_id, group) %>% mutate_all(funs(as.character)) counts_all <- read.table(txt_location, TRUE, " ", stringsAsFactors = FALSE) %>% as.matrix() %>% t settings <- list( list( id = "real/gold/psc-astrocyte-maturation-neuron_sloan", group_id = "cell type: neuron" ), list( id = "real/gold/psc-astrocyte-maturation-glia_sloan", group_id = "cell type: glia" ) ) milestone_network <- tribble( ~from, ~to, ~length, ~directed, "age: Day 100", "age: Day 130", 30, TRUE, "age: Day 130", "age: Day 175", 45, TRUE, "age: Day 175", "age: Day 450", 275, TRUE ) milestone_ids <- unique(c(milestone_network$from, milestone_network$to)) for (setting in settings) { cell_info <- cell_info_all %>% slice(match(rownames(counts_all), cell_id)) %>% filter(group == setting$group_id, milestone_id %in% milestone_ids) counts <- counts_all[cell_info$cell_id, ] grouping <- cell_info %>% select(cell_id, milestone_id) %>% deframe() save_raw_dataset(lst(milestone_network, cell_info, grouping, counts), setting$id) }
test.TwoAssetCorrelationOption = function() { TwoAssetCorrelationOption(TypeFlag = "c", S1 = 52, S2 = 65, X1 = 50, X2 = 70, Time = 0.5, r = 0.10, b1 = 0.10, b2 = 0.10, sigma1 = 0.2, sigma2 = 0.3, rho = 0.75) return() } test.EuropeanExchangeOption = function() { EuropeanExchangeOption(S1 = 22, S2 = 0.20, Q1 = 1, Q2 = 1, Time = 0.1, r = 0.1, b1 = 0.04, b2 = 0.06, sigma1 = 0.2, sigma2 = 0.25, rho = -0.5) return() } test.AmericanExchangeOption = function() { AmericanExchangeOption(S1 = 22, S2 = 0.20, Q1 = 1, Q2 = 1, Time = 0.1, r = 0.1, b1 = 0.04, b2 = 0.06, sigma1 = 0.2, sigma2 = 0.25, rho = -0.5) return() } test.ExchangeOnExchangeOption = function() { for (flag in 1:4) print( ExchangeOnExchangeOption(TypeFlag = as.character(flag), S1 = 105, S2 = 100, Q = 0.1, time1 = 0.75, Time2 = 1.0, r = 0.1, b1 = 0.10, b2 = 0.10, sigma1 = 0.20, sigma2 = 0.25, rho = -0.5)) return() } test.TwoRiskyAssetsOption = function() { TwoRiskyAssetsOption(TypeFlag = "cmax", S1 = 100, S2 = 105, X = 98, Time = 0.5, r = 0.05, b1 = -0.01, b2 = -0.04, sigma1 = 0.11, sigma2 = 0.16, rho = 0.63) TwoRiskyAssetsOption(TypeFlag = "pmax", S1 = 100, S2 = 105, X = 98, Time = 0.5, r = 0.05, b1 = -0.01, b2 = -0.04, sigma1 = 0.11, sigma2 = 0.16, rho = 0.63) return() } test.SpreadApproxOption = function() { SpreadApproxOption(TypeFlag = "c", S1 = 28, S2 = 20, X = 7, Time = 0.25, r = 0.05, sigma1 = 0.29, sigma2 = 0.36, rho = 0.42) return() }
tasknoise <- function(act.image, sigma, type=c("gaussian","rician"), vee=1){ if(missing(act.image)){ stop("An activation array is required.") } if(missing(type)){ type <- "gaussian" } dim <- dim(act.image) if(length(dim)>4){ stop("The activation array has more than 4 dimensions") } if(length(dim)==0){ if(type=="gaussian"){ noise <-rnorm(length(act.image), 0, sigma) } else { noise <- rrice(length(act.image), vee, sigma) } } else { if(type=="gaussian"){ noise <- array(rnorm(prod(dim), 0, sigma), dim=dim) } else { noise <- array(rrice(prod(dim), vee, sigma), dim=dim) } } ix <- which(zapsmall(act.image)!=0) noise[-ix] <- 0 noise <- noise*sigma/sd(noise) return(noise) }
oscorespls.fit <- function(X, Y, ncomp, center = TRUE, stripped = FALSE, tol = .Machine$double.eps^0.5, maxit = 100, ...) { Y <- as.matrix(Y) if (!stripped) { dnX <- dimnames(X) dnY <- dimnames(Y) } dimnames(X) <- dimnames(Y) <- NULL nobj <- dim(X)[1] npred <- dim(X)[2] nresp <- dim(Y)[2] W <- P <- matrix(0, nrow = npred, ncol = ncomp) tQ <- matrix(0, nrow = ncomp, ncol = nresp) B <- array(0, dim = c(npred, nresp, ncomp)) if (!stripped) { TT <- U <- matrix(0, nrow = nobj, ncol = ncomp) tsqs <- numeric(ncomp) fitted <- residuals <- array(0, dim = c(nobj, nresp, ncomp)) } if (center) { Xmeans <- colMeans(X) X <- X - rep(Xmeans, each = nobj) Ymeans <- colMeans(Y) Y <- Y - rep(Ymeans, each = nobj) } else { Xmeans <- rep_len(0, npred) Ymeans <- rep_len(0, nresp) } if (!stripped) Xtotvar <- sum(X * X) for (a in 1:ncomp) { if (nresp == 1) { u.a <- Y } else { u.a <- Y[,which.max(colSums(Y * Y))] t.a.old <- 0 } nit <- 0 repeat { nit <- nit + 1 w.a <- crossprod(X, u.a) w.a <- w.a / sqrt(c(crossprod(w.a))) t.a <- X %*% w.a tsq <- c(crossprod(t.a)) t.tt <- t.a / tsq q.a <- crossprod(Y, t.tt) if (nresp == 1) break if (sum(abs((t.a - t.a.old) / t.a), na.rm = TRUE) < tol) break else { u.a <- Y %*% q.a / c(crossprod(q.a)) t.a.old <- t.a } if (nit >= maxit) { warning("No convergence in ", maxit, " iterations\n") break } } p.a <- crossprod(X, t.tt) X <- X - t.a %*% t(p.a) Y <- Y - t.a %*% t(q.a) W[,a] <- w.a P[,a] <- p.a tQ[a,] <- q.a if (!stripped) { TT[,a] <- t.a U[,a] <- u.a tsqs[a] <- tsq fitted[,,a] <- TT[,1:a] %*% tQ[1:a,, drop=FALSE] residuals[,,a] <- Y } } if (ncomp == 1) { R <- W } else { PW <- crossprod(P, W) if (nresp == 1) { PWinv <- diag(ncomp) bidiag <- - PW[row(PW) == col(PW)-1] for (a in 1:(ncomp - 1)) PWinv[a,(a+1):ncomp] <- cumprod(bidiag[a:(ncomp-1)]) } else { PWinv <- backsolve(PW, diag(ncomp)) } R <- W %*% PWinv } for (a in 1:ncomp) { B[,,a] <- R[,1:a, drop=FALSE] %*% tQ[1:a,, drop=FALSE] } if (stripped) { list(coefficients = B, Xmeans = Xmeans, Ymeans = Ymeans) } else { fitted <- fitted + rep(Ymeans, each = nobj) objnames <- dnX[[1]] if (is.null(objnames)) objnames <- dnY[[1]] prednames <- dnX[[2]] respnames <- dnY[[2]] compnames <- paste("Comp", 1:ncomp) nCompnames <- paste(1:ncomp, "comps") dimnames(TT) <- dimnames(U) <- list(objnames, compnames) dimnames(R) <- dimnames(W) <- dimnames(P) <- list(prednames, compnames) dimnames(tQ) <- list(compnames, respnames) dimnames(B) <- list(prednames, respnames, nCompnames) dimnames(fitted) <- dimnames(residuals) <- list(objnames, respnames, nCompnames) class(TT) <- class(U) <- "scores" class(P) <- class(W) <- class(tQ) <- "loadings" list(coefficients = B, scores = TT, loadings = P, loading.weights = W, Yscores = U, Yloadings = t(tQ), projection = R, Xmeans = Xmeans, Ymeans = Ymeans, fitted.values = fitted, residuals = residuals, Xvar = colSums(P * P) * tsqs, Xtotvar = Xtotvar) } }
fetch_body_int <- function(self, msg_id, use_uid, mime_level, peek, partial, write_to_disk, keep_in_mem, mute, retries) { if (isFALSE(keep_in_mem)) { warning('"keep_in_mem = FALSE" will not alow you to use list_attachments() or get_attachments() after fetching.') } if (!is.null(mime_level)) { assertthat::assert_that( is.integer(mime_level), msg='"mime_level" must be an integer.') } check_args(msg_id = msg_id, use_uid = use_uid, peek = peek, partial = partial, write_to_disk = write_to_disk, keep_in_mem = keep_in_mem, mute = mute, retries = retries) if (isTRUE(peek)) { body_string = " BODY.PEEK[MIME.level]" } else { body_string = " BODY[MIME.level]" } if (!is.null(mime_level)) { body_string <- gsub('MIME.level', mime_level, body_string) } else { body_string <- gsub('MIME.level', '', body_string) } if (!is.null(partial)) { partial_string = paste0("<", partial, ">") } else { partial_string = NULL } if (isTRUE(use_uid)) { use_uid_string = "UID " } else { use_uid_string = NULL } fetch_request <- paste0(use_uid_string, "FETCH ", " fetch_type = "body" msg_list <- execute_fetch_loop(self = self, msg_id = msg_id, fetch_request = fetch_request, use_uid = use_uid, write_to_disk = write_to_disk, keep_in_mem = keep_in_mem, retries = retries, fetch_type = fetch_type) if (isFALSE(keep_in_mem)) { rm(msg_list) if (!mute) { cat(paste0("\n::mRpostman: the fetch operation is complete.\n")) } return(TRUE) } else { return(msg_list) } }
vus <- function(method = "full", T, Dvec, V, rhoEst = NULL, piEst = NULL, ci = TRUE, ci.level = ifelse(ci, 0.95, NULL), BOOT = FALSE, nR = ifelse(ci, 250, NULL), parallel = FALSE, ncpus = ifelse(parallel, detectCores()/2, NULL), trace = TRUE){ call <- match.call() methodtemp <- substitute(me, list(me = method)) okMethod <- c("full", "fi", "msi", "ipw", "spe", "knn") if(length(methodtemp) > 1) stop(gettextf("Please, choose one method from %s", paste(sQuote(okMethod), collapse = ", ")), domain = NA) if (!is.character(methodtemp)) methodtemp <- deparse(methodtemp) if (!is.element(methodtemp, okMethod)){ stop(gettextf("the required method \"%s\" is not available; it should be one of %s", methodtemp, paste(sQuote(okMethod), collapse = ", ")), domain = NA) } if(missing(T)) stop("argument \"T\" is missing \n") if(!inherits(T, "numeric") | any(is.na(T))) stop("variable \"T\" must be a numeric vector and not include NA values") name_diagnostic <- substitute(T) if (!is.character(name_diagnostic)) { name_diagnostic <- deparse(name_diagnostic) } name_diagnostic <- unlist(strsplit(name_diagnostic, NULL)) if(any(name_diagnostic %in% c("$"))){ id.name <- which(name_diagnostic %in% c("$")) name_diagnostic <- paste(name_diagnostic[(id.name[1] + 1) : length(name_diagnostic)], collapse = "") } else name_diagnostic <- paste(name_diagnostic, collapse = "") method_name <- toupper(method) if(missing(Dvec)) stop("argument \"Dvec\" is missing \n") if(!inherits(Dvec, "matrix") | ncol(Dvec) != 3 | !all(is.element(na.omit(Dvec), c(0,1)))) stop("variable \"Dvec\" must be a binary matrix with 3 columns") if(length(T) != nrow(Dvec)) stop(gettextf("arguments imply differing number of observation: %d", length(T)), gettextf(", %d", nrow(Dvec)), domain = NA) Dvec.flag <- any(is.na(Dvec)) if(!is.null(rhoEst)){ if(!is.element(class(rhoEst), c("prob_dise", "prob_dise_knn"))) stop("\"rhoEst\" not a result of rhoMlogit or rhoKNN \n") if(is.element(class(rhoEst), c("prob_dise_knn"))){ if(is.null(rhoEst$K)) stop("The \"rhoEst\" is a list and contains results of rhoKNN corresponding to many K! \n Please, choose one result of them \n") } } if(!is.null(piEst)){ if(!is.element(class(piEst), c("prob_veri"))) stop("\"piEst\" not a result of psglm \n") } if(missing(V)){ if(methodtemp != "full" | Dvec.flag) stop("argument \"V\" is missing, in addition, the method is not \"full\" or argument \"Dvec\" includes NA") if(trace){ cat("Hmm, look likes the full data.\n") cat("The verification status is not available.\n") cat("You are working on FULL or Complete Case approach.\n") cat("Number of observation:", length(T), "\n") cat("The diagnostic test:", name_diagnostic, "\n") cat("Processing .... \n") flush.console() } V <- NULL } else{ if(all(V == 0) | !all(is.element(V, c(0,1))) ) stop("There are mistakes in \"V\". Please, check your input and see whether it is correct or not") if(nrow(Dvec) != length(V) | length(T) != length(V)) stop(gettextf("arguments imply differing number of observation: %d", nrow(Dvec)), gettextf(", %d", length(T)), gettextf(", %d", length(V)), domain = NA) if(all(V == 1)){ if(methodtemp != "full" | Dvec.flag) stop("Please, check your inputs and see whether they are correct or not.\n If you want to estimate Complete Case approach, please, remove the missing values in the \n data set and try again with the option of \"full\" method.") if(trace){ cat("Hmm, look likes the full data\n") cat("Number of observation:", length(T), "\n") cat("All subjects underwent the verification process\n") cat("You are working on FULL or Complete Case approach\n") cat("The diagnostic test:", name_diagnostic, "\n") cat("Processing .... \n") flush.console() } } else{ rv <- mean(V) if(!Dvec.flag){ if(trace){ cat("Warning: There are no NA values in variable Dvec, while", paste(round(rv*100), "%", sep = ""), "of the subjects receive disease verification. \n") cat("BE CAREFULL OF YOUR INPUT AND RESULTS \n") cat("Number of observation:", length(T), "\n") cat("You required estimate VUS using", method_name, "approach \n") cat("The diagnostic test:", name_diagnostic, "\n") cat("Processing .... \n") flush.console() } } else{ if(trace){ cat("Hmm, look likes the incomplete data\n") cat("Number of observation:", length(T), "\n") cat(paste(round(rv*100), "%", sep = ""), "of the subjects receive disease verification. \n") cat("You required estimate VUS using", method_name, "approach \n") cat("The diagnostic test:", name_diagnostic, "\n") cat("Processing .... \n") flush.console() } } } } if(methodtemp == "full"){ if(Dvec.flag){ cat("Opp! Look likes wrong method \n") ques <- readline("Do you want use Complete Case (CC) approach? [y/n]: ") if(ques %in% c("y", "n")){ if(ques == "y"){ if(trace){ cat("Number of observation:", length(T), "\n") cat("We are estimating VUS by using CC method \n") cat("BE CAREFULL OF THE RESULTS. THIS CAN MAKE THE DISTORTED INFERENCE IN VUS \n") cat("Processing .... \n") flush.console() } Dvec <- Dvec[V == 1,] T <- T[V == 1] ans <- vusC(T, Dvec) } else if(ques == "n") stop("Sorry! The FULL method can not compute with NA value(s) of disease status Dvec.") } else stop("The answer was wrong. Please, choose y for Yes, or n for No!") } ans <- vusC(T, Dvec) } else if(methodtemp == "fi"){ if(is.null(rhoEst)) stop("The input of argument \"rhoEst\" is needed for ", method_name, " estimator") if(length(T) != nrow(rhoEst$values)) stop(gettextf("arguments imply differing number of observation: %d", length(T), ", %d", nrow(rhoEst$values)), domain = NA) ans <- vusC(T, rhoEst$values) } else if(methodtemp %in% c("msi", "knn")){ if(is.null(rhoEst)) stop("argument \"rhoEst\" is needed for", method_name, "estimator") Dvectemp <- Dvec if(Dvec.flag) Dvectemp[is.na(Dvec)] <- 99 Dmsi <- Dvectemp*V + (1 - V)*rhoEst$values ans <- vusC(T, Dmsi) } else if(methodtemp == "ipw"){ if(is.null(piEst)) stop("argument \"piEst\" is needed for", method_name, "estimator") Dvectemp <- Dvec if(Dvec.flag) Dvectemp[is.na(Dvec)] <- 99 Dipw <- Dvectemp*V/piEst$values ans <- vusC(T, Dipw) } else{ if(is.null(rhoEst) | is.null(piEst)) stop("arguments \"rhoEst\" and \"pi.est\" are needed for", method_name, "estimator") Dvectemp <- Dvec if(Dvec.flag) Dvectemp[is.na(Dvec)] <- 99 Dspe <- Dvectemp*V/piEst$values - (V/piEst$values - 1)*rhoEst$values ans <- vusC(T, Dspe) } attr(ans, "name") <- method_name res <- list(vus.fit = ans, call = call) class(res) <- "vus" if(ci){ var.ans <- asyVarVUS(res, T = T, Dvec = Dvec, V = V, rhoEst = rhoEst, piEst = piEst, BOOT = BOOT, nR = nR, parallel = parallel, ncpus = ncpus) cf.ans <- ans + c(-1, 1)*qnorm((1 + ci.level)/2)*sqrt(var.ans) sd.log <- sqrt(var.ans)/(ans*(1 - ans)) log.cf <- log(ans/(1 - ans)) + c(-1, 1)*qnorm((1 + ci.level)/2)*sd.log cf.ans.tran <- exp(log.cf)/(1 + exp(log.cf)) W <- (ans - 1/6)/sqrt(var.ans) p.val_norm <- 1 - pnorm(W) res <- list(vus.fit = ans, std = sqrt(var.ans), t.stat = W, p.val_norm = p.val_norm, ci.norm = cf.ans, ci.logit = cf.ans.tran, call = call, ci.level = ci.level, BOOT = BOOT, nR = nR) class(res) <- "vus" } if(trace) cat("DONE\n") res } print.vus <- function(x, digits = max(3L, getOption("digits") - 3L), ...){ cat("\n") cat("CALL: ", paste(deparse(x$call), sep = "\n", collapse = "\n"), "\n \n", sep = "") if(!is.null(x$std)){ res.tab <- c(x$ci.level*100, x$ci.norm, x$ci.logit) res.tab <- format(round(res.tab, digits = digits)) res.tab[1L] <- paste("\n",x$ci.level*100,"% ",sep = "") res.tab[2*(1L:2L)] <- paste(" (",res.tab[2*(1L:2L)],",",sep = "") res.tab[2*(1L:2L) + 1L] <- paste(res.tab[2*(1L:2L) + 1L],") ") p.val <- x$p.val_norm stat <- x$t.stat test.tab <- cbind(stat, p.val) colnames(test.tab) <- c("Test Statistic", "P-value") rownames(test.tab) <- "Normal-test" ci.name <- c(" Normal ", " Logit ") cat("Estimate of VUS:", format(round(x$vus.fit, digits = digits)), "\n") cat("Standard error:", format(round(x$std, digits = digits)), "\n") cat("\nIntervals:") cat("\nLevel", ci.name) cat(res.tab) if(attr(x$vus, "name") %in% c("FULL", "KNN")){ if(x$BOOT) cat("\nEstimation of Standard Error and Intervals are based on Bootstrap with", x$nR, "replicates\n") else cat("\nEstimation of Standard Error and Intervals are based on Jackknife approach \n") } else{ cat("\nEstimation of Standard Error and Intervals are based on Asymptotic Theory \n") } cat("\n") cat("Testing the null hypothesis H0: VUS = 1/6 \n") printCoefmat(test.tab, has.Pvalue = TRUE) } else{ cat("Estimate of VUS:", round(x$vus.fit, digits = digits), "\n") } invisible(x) }
expected <- eval(parse(text="TRUE")); test(id=0, code={ argv <- eval(parse(text="list(structure(c(4.17, 5.58, 5.18, 6.11, 4.5, 4.61, 5.17, 4.53, 5.33, 5.14, 4.81, 4.17, 4.41, 3.59, 5.87, 3.83, 6.03, 4.89, 4.32, 4.69, 17.3889, 31.1364, 26.8324, 37.3321, 20.25, 21.2521, 26.7289, 20.5209, 28.4089, 26.4196, 23.1361, 17.3889, 19.4481, 12.8881, 34.4569, 14.6689, 36.3609, 23.9121, 18.6624, 21.9961), .Dim = c(20L, 2L), .Dimnames = list(NULL, c(\"w\", \"w2\"))))")); do.call(`is.numeric`, argv); }, o=expected);
fitQmapQUANT <- function(obs,mod,...) UseMethod("fitQmapQUANT") fitQmapQUANT.default <- function(obs,mod,wet.day=TRUE,qstep=0.01, nboot = 1,...){ ys <- na.omit(obs) xs <- na.omit(mod) if(length(xs)!=length(ys)){ hn <- min(length(xs),length(ys)) ys <- quantile(ys,seq(0,1,length.out=hn),type=8) xs <- quantile(xs,seq(0,1,length.out=hn),type=8) } else { xs <- sort(xs) ys <- sort(ys) } if(is.numeric(wet.day)){ q0 <- ys>=wet.day ys <- ys[q0] xs <- xs[q0] } else if(is.logical(wet.day)){ if(wet.day){ q0 <- ys>0 ys <- ys[q0] xs <- xs[q0] wet.day <- xs[1] names(wet.day) <- NULL } else { wet.day <- NULL } } else { stop("'wet.day' should be 'numeric' or 'logical'") } nn <- length(ys) newx <- quantile(xs, probs=seq(0,1,by=qstep),type=8) fit <- array(NA, dim=c(length(newx),2,nboot)) if(nboot > 1){ booty <- replicate(nboot,sample(ys,size=nn,replace=FALSE)) booty <- apply(booty,2,quantile, probs=seq(0,1,by=qstep),type=8) booty <- rowMeans(booty,na.rm=TRUE) } else { booty <- quantile(ys,probs=seq(0,1,by=qstep),type=8) } ppar <- list(modq=matrix(newx,ncol=1), fitq=matrix(booty,ncol=1)) op <- list(par=ppar, wet.day=wet.day) class(op) <- "fitQmapQUANT" return(op) } fitQmapQUANT.matrix <- function(obs,mod,...){ if(ncol(mod)!=ncol(obs)) stop("'mod' and 'obs' need the same number of columns") NN <- ncol(mod) hind <- 1:NN names(hind) <- colnames(mod) xx <- lapply(hind,function(i){ tr <- try(fitQmapQUANT.default(obs=obs[,i],mod=mod[,i],...), silent=TRUE) if(any(class(tr)=="try-error")){ warning("model identification for ",names(hind)[i], " failed\n NA's produced.") NULL } else{ tr } }) xx.NULL <- sapply(xx,is.null) modq <- lapply(xx,function(x)x$par$modq) fitq <- lapply(xx,function(x)x$par$fitq) nq <- nrow(xx[!xx.NULL][[1]]$par$modq) nq <- matrix(NA,nrow=nq) modq[xx.NULL] <- list(nq) fitq[xx.NULL] <- list(nq) modq <- do.call(cbind,modq) fitq <- do.call(cbind,fitq) colnames(modq) <- names(xx) colnames(fitq) <- names(xx) wday <- lapply(xx,function(x)x$wet.day) wday[xx.NULL] <- NA wday <- do.call(c,wday) xx <- list(par=list(modq=modq,fitq=fitq), wet.day=wday) class(xx) <- c("fitQmapQUANT") return(xx) } fitQmapQUANT.data.frame <- function(obs,mod,...){ obs <- as.matrix(obs) mod <- as.matrix(mod) fitQmapQUANT.matrix(obs,mod,...) }
testMutationalPatternBinom <- function (x, y, PRINT=FALSE) { xy.tmp <- cbind (x, y) xy.tmp.nona <- xy.tmp[which (!is.na (x) & !is.na (y)),] x <- xy.tmp.nona[,1] y <- xy.tmp.nona[,2] p.x <- c(sum (x==0), sum(x==1), sum(x==2)) / length (x) p.y <- c(sum (y==0), sum(y==1), sum(y==2)) / length (y) xy <- c(sum (x==0 & y==0), sum (x==1 & y==0), sum(x==2 & y==0), sum (x==0 & y==1), sum (x==1 & y==1), sum(x==2 & y==1), sum (x==0 & y==2), sum (x==1 & y==2), sum(x==2 & y==2)) if (PRINT) { print (matrix (xy, ncol=3)) print (p.x %*% t(p.y) * length (x)) } xy.LL.binom <- binom.test (x=xy[1], n=length (x), p=p.x[1]*p.y[1], alternative="greater") xy.GL.binom <- binom.test (x=xy[3], n=length (x), p=p.x[3]*p.y[1], alternative="greater") xy.LG.binom <- binom.test (x=xy[7], n=length (x), p=p.x[1]*p.y[3], alternative="greater") xy.GG.binom <- binom.test (x=xy[9], n=length (x), p=p.x[3]*p.y[3], alternative="greater") xy.ME.binom <- binom.test (x=sum (xy[c(2,4,6,8)], na.rm=TRUE), n=length (x), p=(p.x[1]+p.x[3])*(1-p.y[1]-p.y[3]) + (p.y[1]+p.y[3])*(1-p.x[1]-p.x[3]), alternative="greater") return (c(xy.LL.binom$p.value, xy.GL.binom$p.value, xy.LG.binom$p.value, xy.GG.binom$p.value, xy.ME.binom$p.value)) }
context("covOrd") kcat <- covOrd(ordered = 8:12, k1Fun1 = k1Fun1Cos, warpFun = "norm", hasGrad = TRUE, cov = "homo") object <- kcat C1 <- object@covLevels(object@par, lowerSQRT = FALSE, compGrad = FALSE) C2 <- object@covLevMat C3 <- covMat(kcat) attr(C3, "gradient") <- NULL dfu <- data.frame(u = as.ordered(8:12)) dfux <- data.frame(u = as.ordered(8:12), x = rep(0, 5)) C4 <- covMat(kcat, X = dfu) C5 <- covMat(kcat, X = dfux) attr(C4, "gradient") <- attr(C5, "gradient") <- NULL test_that(desc = "covMat code", expect_lt(max(abs(C1 - C2)), 1e-8)) test_that(desc = "covMat 'X' missing", expect_lt(max(abs(C1 - C3)), 1e-8)) test_that(desc = "covMat 'X' one column", expect_lt(max(abs(C1 - C4)), 1e-8)) test_that(desc = "covMat 'X' two columns", expect_lt(max(abs(C1 - C5)), 1e-8))
Estep.MSAR <- function( data,theta,smth=FALSE,verbose=FALSE, covar.emis=covar.emis,covar.trans=covar.trans ) { go <- Sys.time() if (verbose) { message('Starting LWS_pfilt') } att.theta = attributes(theta) label <- att.theta$label p <- att.theta$order if (verbose) print(theta) M <- att.theta$NbRegimes d <- att.theta$NbComp if(is.null(d) || is.na(d)){d=1} n_par <- att.theta$n_par order = att.theta$order data <- as.array(data) T = dim(data)[1] if (is.null(T)) {T = length(data)} if (abs(length(data)/T-trunc(length(data)/T)) >1e-5) {stop('error : size of data should be nxT.sample with n integer')} N.samples = dim(data)[2] if(is.null(N.samples) || is.na(N.samples)){N.samples <- 1} data <- array(data,c(T,N.samples,d)) gamma <- array(0,c(N.samples,T-p,M)) xi = array(0,c(M,M,T-(p+1),N.samples)) loglik = 0 if(substr(label,2,2) == 'N'){ ncov.emis = dim(covar.emis)[3] if(is.null(ncov.emis) || is.na(ncov.emis)){ncov.emis=1} covar.emis=array(covar.emis,c(T,N.samples,ncov.emis)) } if (substr(label,1,1) == 'H') { tmat = as.matrix(theta$transmat) prior = as.matrix(theta$prior) for (ex in 1:N.samples) { if (verbose) { print(ex) } g <- emisprob.MSAR(data[,ex,],theta=theta,covar=covar.emis[,ex,]) FB = forwards_backwards(prior, tmat, g) gamma[ex,,] = t(FB$gamma) xi[,,,ex] = FB$xi loglik = loglik + FB$loglik } } else { if(missing(covar.trans)){stop("error : covariable is missing")} if (length(covar.trans)==1) { Lag = covar.trans+1 covar.trans = array(data[(1):(T-Lag+1),,],c(T-Lag+1,N.samples,d)) data = array(data[Lag:T,,],c(T-Lag+1,N.samples,d)) } ncov.trans = dim(covar.trans)[3] if(is.null(ncov.trans) || is.na(ncov.trans)){ncov.trans=1} ct = array(0,c(T,N.samples,ncov.trans)) ct[1:min(dim(ct)[1],dim(covar.trans)[1]),,] = covar.trans[1:min(dim(ct)[1],dim(covar.trans)[1]),,] covar.trans=ct for (ex in 1:N.samples) { if (verbose) { print(ex) } g <- emisprob.MSAR(data[,ex,],theta=theta,covar=covar.emis[,ex,]) transmat = theta$transmat par.trans = theta$par.trans nh_transition = attributes(theta)$nh.transitions inp = covar.trans[(order+1):T,ex,] transmat.t = nh_transition(array(inp,c((T-order),1,ncov.trans)),par.trans,transmat) FB = nhforwards_backwards(theta$prior, transmat.t, g) gamma[ex,,] = t(FB$gamma) xi[,,,ex] = FB$xi loglik = loglik + FB$loglik } } list(loglik=loglik,probS=gamma,probSS=xi,M=FB$M) }
require(OpenMx) data(myRegDataRaw) SimpleDataRaw <- myRegDataRaw[,c("x","y")] dataRaw <- mxData( observed=SimpleDataRaw, type="raw" ) matrA <- mxMatrix( type="Full", nrow=2, ncol=2, free=c(F,F,T,F), values=c(0,0,1,0), labels=c(NA,NA,"beta1",NA), byrow=TRUE, name="A" ) matrS <- mxMatrix( type="Symm", nrow=2, ncol=2, free=c(T,F,F,T), values=c(1,0,0,1), labels=c("varx",NA,NA,"residual"), byrow=TRUE, name="S" ) matrF <- mxMatrix( type="Iden", nrow=2, ncol=2, name="F" ) matrM <- mxMatrix( type="Full", nrow=1, ncol=2, free=c(T,T), values=c(0,0), labels=c("meanx","beta0"), name="M") expRAM <- mxExpectationRAM("A","S","F","M", dimnames=c("x","y")) funML <- mxFitFunctionML() uniRegModel <- mxModel("Simple Regression Matrix Specification", dataRaw, matrA, matrS, matrF, matrM, expRAM, funML) uniRegFit<-mxRun(uniRegModel) summary(uniRegFit) uniRegFit$output omxCheckCloseEnough(coef(uniRegFit)[["beta0"]], 2.5478, 0.001) omxCheckCloseEnough(coef(uniRegFit)[["beta1"]], 0.4831, 0.001) omxCheckCloseEnough(coef(uniRegFit)[["residual"]], 0.6652, 0.001) omxCheckCloseEnough(coef(uniRegFit)[["meanx"]], 0.0542, 0.001) omxCheckCloseEnough(coef(uniRegFit)[["varx"]], 1.1053, 0.001)
heddle <- function(data, pattern, ..., strip.whitespace = FALSE) { UseMethod("heddle") } heddle.default <- function(data, pattern, ..., strip.whitespace = FALSE) { stopifnot(is.logical(strip.whitespace)) stopifnot(length(strip.whitespace) == 1) dots <- list(...) if (length(pattern) != 1 & length(pattern) != length(data)) { stop("Argument pattern must be an atomic vector or have the same number of elements as your data.") } if (length(dots) > 1) { dots <- paste0(unlist(dots), collapse = "|") } if (!is.null(names(dots))) { warning("heddle ignores the names of '...' when passed a vector.") } if (strip.whitespace) { data <- gsub("[[:space:]]", "", data) } if (length(pattern) == 1) { if (is.na(dots)) { rep(pattern, length(data)) } else if (!grepl(dots, pattern)) { warning("Placeholder keyword not found in pattern.") } else { vapply( data, function(x) gsub(dots, x, pattern), FUN.VALUE = character(1) ) } } else { if ( any( vapply( pattern, function(x) grepl(dots, x), logical(1) ) ) == FALSE) { warning("Placeholder keyword not found in pattern.") } mapply(function(x, y) gsub(dots, x, y), x = data, y = pattern, SIMPLIFY = FALSE ) } } heddle.data.frame <- function(data, pattern, ..., strip.whitespace = FALSE) { dots <- rlang::enquos(...) if (any(names(dots) == "") || any(is.null(names(dots)))) { stop("All variables passed to '...' must have names matching the keyword they're replacing.") } if (!is.logical(strip.whitespace) || length(strip.whitespace) != 1) { stop("strip.whitespace must be either TRUE or FALSE") } return <- rep(pattern, nrow(data)) vars <- as.list(rlang::set_names(seq_along(data), names(data))) for (j in seq_along(dots)) { if (strip.whitespace) { data[, rlang::eval_tidy(dots[[j]], vars)] <- as.character(data[, rlang::eval_tidy(dots[[j]], vars)]) data[, rlang::eval_tidy(dots[[j]], vars)] <- gsub("[[:space:]]", "", data[, rlang::eval_tidy(dots[[j]], vars)]) } for (i in seq_len(nrow(data))) { if (!grepl(names(dots)[[j]], return[[i]])) warning(paste(names(dots)[[j]], "not found in pattern.")) return[[i]] <- paste(gsub(names(dots)[[j]], data[[i, rlang::eval_tidy(dots[[j]], vars)]], return[[i]]), sep = "", collapse = "") } } return }
test_that("minimal.Rmd", { ast = parse_rmd(system.file("minimal.Rmd", package = "parsermd")) expected_ast = create_ast( create_yaml( 'title: "Minimal"', 'author: "Colin Rundel"', 'date: "7/21/2020"', 'output: html_document' ), create_heading("Setup", 1), create_chunk( name = "setup", options = list(include = "FALSE"), code = "knitr::opts_chunk$set(echo = TRUE)" ), create_heading("Content", 1), create_heading("R Markdown", 2), create_markdown( 'This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, ', 'PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.', '', 'When you click the **Knit** button a document will be generated that includes both content as well ', 'as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:', '' ), create_chunk( name = "cars", code = "summary(cars)" ), create_chunk( code = "knitr::knit_patterns$get()" ), create_heading("Including Plots", 2), create_markdown("You can also embed plots, for example:", ""), create_chunk( name = "pressure", options = list(echo = "FALSE"), code = "plot(pressure)" ), create_markdown( "Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code ", "that generated the plot." ) ) expect_identical(ast, expected_ast) }) test_that("knitr examples", { files = dir( system.file("tests/testthat/knitr-examples/", package = "parsermd"), pattern = utils::glob2rx("*.Rmd"), full.names = TRUE ) for(file in files) { if (grepl("065-rmd-chunk\\.Rmd", file)) next label = paste("Parsing", basename(file)) expect_error(parse_rmd(!!file, allow_incomplete = FALSE), regexp = NA, label = label) } }) test_that("Found issues", { expect_equal( parse_rmd("```{r}\n1+1\n```"), create_ast(create_yaml(), create_chunk(code = "1+1")) ) })
pkg_ref_cache.web_url <- function(x, name, ...) { UseMethod("pkg_ref_cache.web_url") } pkg_ref_cache.web_url.pkg_cran_remote <- function(x, name, ...) { sprintf("%s/web/packages/%s", x$repo_base_url, x$name) } pkg_ref_cache.web_url.pkg_bioc_remote <- function(x, name, ...) { sprintf("%s/html/%s.html", x$repo_base_url, x$name) }
context("test-sas_to_disk.frame") test_that("testing sas_to_disk.frame", { expect_equal(2L, 2L) })
summary_meta <- function(meta, summarize = "integrate", ci = .95, rel.tol = .Machine$double.eps^.3) { summarize <- match.arg(summarize, c("integrate", "stan")) estimates <- NULL if (summarize == "integrate") { if (meta$model == "fixed") { estimates <- rbind("d" = summary_integrate(meta$posterior_d, rel.tol = rel.tol, ci = ci )) } else if (meta$model == "random") { estimates <- rbind( "d" = summary_integrate(meta$posterior_d, rel.tol = rel.tol, ci = ci ), "tau" = summary_integrate(meta$posterior_tau, rel.tol = rel.tol, ci = ci ) ) } else { warning( "summarize = 'integrate' not supported for model: ", meta$model, "\n (summary of MCMC/Stan samples is reported instead)" ) } } if (is.null(estimates)) { if (is.null(meta$stanfit)) { warning( "summarize = 'stan' not supported for model: ", meta$model, "\n (MCMC/Stan samples are missing)" ) } else { estimates <- summary_stanfit(meta$stanfit, ci = ci) idx <- grep("beta", rownames(estimates)) if (length(idx) > 0) { X <- add_jzs(meta$data, meta$jzs)$X rownames(estimates)[idx] <- paste0("beta_", colnames(X)) } } } estimates } summary_samples <- function(x, ci = .95) { probs <- c((1 - ci) / 2, .5, 1 - (1 - ci) / 2) s <- c(mean(x), sd(x), quantile(x, probs)) names(s) <- c("mean", "sd", paste0(round(probs * 100, digits = 1), "%")) hpd <- c(HPDinterval(mcmc(x), ci)) names(hpd) <- paste0("hpd", round(ci * 100, 2), c("_lower", "_upper")) c(s, hpd, "n_eff" = NA, "Rhat" = NA) } summary_stanfit <- function(stanfit, ci = .95) { samples <- As.mcmc.list(stanfit) mcmc <- do.call("rbind", samples) summ <- t(apply(mcmc, 2, summary_samples, ci = ci)) sel <- rownames(summ) != "lp__" & !grepl("g[", rownames(summ), fixed = TRUE) summ[sel, "n_eff"] <- round(summary(stanfit)$summary[sel, "n_eff"], 1) summ[sel, "Rhat"] <- round(summary(stanfit)$summary[sel, "Rhat"], 3) summ[sel, , drop = FALSE] } summary_integrate <- function(density, lb = NULL, ub = NULL, ci = .95, rel.tol = .Machine$double.eps^0.8) { if (class(density) %in% c("prior", "posterior")) { lb <- attr(density, "lower") ub <- attr(density, "upper") } if (lb == ub) { return(NULL) } mean <- NA try(mean <- integrate(function(x) x * density(x), lb, ub, rel.tol = rel.tol )$value, silent = TRUE) SD <- NA try( { variance <- integrate(function(x) (x - mean)^2 * density(x), lb, ub, rel.tol = rel.tol )$value SD <- sqrt(variance) }, silent = TRUE ) probs <- c((1 - ci) / 2, .50, 1 - (1 - ci) / 2) qq <- rep(NA, 3) try( { tmp <- function(q, p) { p - integrate(density, lb, q, rel.tol = rel.tol)$value } for (i in c(3, 5, 10, 20, 100, 500, 1000, 5000, 10000)) { interval <- c( max(lb + 1e-30, mean - i * SD), min(mean + i * SD, ub - 1e-30) ) q.diff <- sapply(interval, tmp, p = probs) if (all(q.diff[, 1] > 0) && all(q.diff[, 2] < 0)) { break } } qq <- sapply(probs, function(pp) uniroot(tmp, interval, p = pp)$root) }, silent = TRUE ) hpd <- c("hpd95_lower" = NA, "hpd95_upper" = NA) try( { xx <- seq(max(lb, qq[1] - i * SD), min(ub, qq[3] + i * SD), length.out = 201) dx <- sapply(xx, density) * diff(xx[1:2]) px <- cumsum(dx) qdens <- splinefun(px, xx, method = "monoH.FC", ties = "mean") length.interval <- function(start) { qdens(start + ci) - qdens(start) } oo <- optim((1 - ci) / 2, length.interval, method = "L-BFGS-B", lower = min(px), upper = max(px) - ci ) hpd <- c( "hpd95_lower" = qdens(oo$par), "hpd95_upper" = qdens(oo$par + ci) ) names(hpd) <- paste0("hpd", round(ci * 100, 2), c("_lower", "_upper")) }, silent = TRUE ) warn <- paste( "Some posterior statistics (mean, SD, etc) could not be computed\n", " for parameter", attr(density, "label"), "using numerical integration.\n", " Estimates based on MCMC/Stan samples will be shown instead\n", "(for high precision, refit the models with: iter=10000,warmup=500)" ) if (any(is.na(c(mean, qq, SD, hpd)))) { warning(warn) } names(qq) <- paste0(round(probs * 100, digits = 1), "%") c("mean" = mean, "sd" = SD, qq, hpd, "n_eff" = NA, "Rhat" = NA) }
NULL setClass( "dateRange", contains = getClass("Interval", where = "lubridate"), prototype = prototype( as.numeric(as.POSIXct(Sys.Date() - 2L)) - as.numeric(as.POSIXct(Sys.Date() - 8L)), start = as.POSIXct(Sys.Date() - 8L), tzone = "UTC" ), validity = function(object) { validations <- list( validate_that(all(int_length(object) >= 0), msg = "End date cannot be before start date."), validate_that( noNA(object), all(object@start >= as.POSIXct(kGaDateOrigin)) ) ) invalids <- !sapply(validations, function(x) {is.logical(x) && length(x) == 1L && !is.na(x) && x}) if(any(invalids)) as.character(validations[invalids]) } ) setClass( "gaCohort", contains = "dateRange", slots = c( type = "character" ), prototype = prototype( type = "FIRST_VISIT_DATE" ), validity = function(object) { validate_that( all(type %in% c("FIRST_VISIT_DATE")) ) } ) setClass( "gaPivot", slots = c( dimensions = "gaDimensions", dimensionFilters = "gaDimFilter", metrics = "gaMetrics", startGroup = "integer", maxGroupCount = "integer" ), prototype = prototype( dimensions = new("gaDimensions", list()), dimensionFilters = new("gaDimFilter"), metrics = new("gaMetrics", list()), startGroup = 1L, maxGroupCount = 5L ) ) setClass( "viewId", contains = "character", validity = function(object) { if (all(str_detect(object, "^ga:[0-9]+$"))) { TRUE } else { "viewId must be an string of digits preceded by 'ga:'" } } ) setClass( "gaReportRequest", slots = c( dimensions = "gaDimensions", metrics = "gaMetrics", sortBy = "gaSortBy", pivot = "gaPivot", tableFilter = "gaFilter" ) ) setClass( "gaReportRequests", contains = "list", slots = c( viewId = "viewId", creds = "list", dateRanges = "dateRange", samplingLevel = "character", segments = "gaSegmentList", cohorts = "gaCohort" ), prototype = prototype( creds = list(), dateRanges = new("dateRange"), samplingLevel = "DEFAULT" ), validity = function(object) { all_inherit(object, "gaReportRequest") } ) setClass("ga4_req") setClass( ".query", slots = c( viewId = "viewId", metrics = ".metrics", dimensions = ".dimensions", sortBy = ".sortBy", filters = ".tableFilter", maxResults = "integer", creds = "list" ), prototype = prototype( maxResults = kGaMaxResults, creds = list() ), validity = function(object) { valid <- validate_that( length(object@maxResults) == 1L, object@maxResults >= 1L, length(object@metrics) >= 1L ) if (valid == TRUE) { if (object@maxResults > kGaMaxRows) { "maxResults cannot be greater than 1,000,000" } else if (!all(object@sortBy %in% union(object@metrics, object@dimensions))) { "sortBy must contain varNames also used as metrics and/or dimensions" } else TRUE } else valid } ) setClass( ".standardQuery", slots = c( dateRange = "dateRange", samplingLevel = "character" ), prototype = prototype( dateRange = new("dateRange"), samplingLevel = "DEFAULT" ), contains = ".query", validity = function(object) { valid <- validate_that(length(object@samplingLevel) == 1L) if (valid == TRUE) { if (!(object@samplingLevel %in% samplingLevel_levels)) { paste("samplingLevel must be one of:", paste(samplingLevel_levels, collapse = ", ")) } else TRUE } else valid } ) setClass( "gaQuery", slots = c( metrics = "gaMetrics", dimensions = "gaDimensions", sortBy = "gaSortBy", filters = "gaFilter", segments = "gaSegmentList", buckets = "numeric", lifetimeValue = "logical" ), prototype = prototype( metrics = new("gaMetrics"), dimensions = new("gaDimensions"), sortBy = new("gaSortBy"), lifetimeValue = FALSE ), contains = ".standardQuery", validity = function(object) { validate_that( length(object@lifetimeValue) == 1L, object@lifetimeValue %in% c(TRUE, FALSE) ) } ) setClass( "mcfQuery", slots = c( metrics = "mcfMetrics", dimensions = "mcfDimensions", sortBy = "mcfSortBy", filters = "mcfFilter" ), prototype = prototype( metrics = new("mcfMetrics"), dimensions = new("mcfDimensions"), sortBy = new("mcfSortBy") ), contains = ".standardQuery" ) setClass( "rtQuery", slots = c( metrics = "rtMetrics", dimensions = "rtDimensions", sortBy = "rtSortBy", filters = "rtFilter" ), prototype = prototype( metrics = new("rtMetrics"), dimensions = new("rtDimensions"), sortBy = new("rtSortBy") ), contains = ".query" )
source("test.prolog.R") library(earth) options(warn=1) printh <- function(caption) cat("===", caption, "\n", sep="") CAPTION <- NULL multifigure <- function(caption, nrow=3, ncol=3) { CAPTION <<- caption printh(caption) par(mfrow=c(nrow, ncol)) par(cex = 0.8) par(mar = c(3, 3, 5, 0.5)) par(mgp = c(1.6, 0.6, 0)) oma <- par("oma") oma[3] <- 2 par(oma=oma) } do.caption <- function() mtext(CAPTION, outer=TRUE, font=2, line=1, cex=1) multifigure("test predict.earth with pints", 2, 2) set.seed(2) earth.trees <- earth(Volume~Girth, data=trees, nfold=3, ncross=3, varmod.method="earth") old.environment <- attr(earth.trees$varmod, ".Environment") stopifnot(is.environment(old.environment)) attr(earth.trees$varmod, ".Environment") <- NULL printh("print.default(earth.trees$varmod)") print.default(earth.trees$varmod) attr(earth.trees$varmod, ".Environment") <- old.environment printh("summary(earth.trees)") print(summary(earth.trees)) expect.err(try(predict(earth.trees, interval="se", level=.8))) printh("predict(earth.trees, interval=\"se\")") stderrs <- predict(earth.trees, interval="se") print(stderrs) expect.err(try(predict(earth.trees, interval="abs.res", level=.8))) printh("predict(earth.trees, interval=\"abs.residual\")") stderrs <- predict(earth.trees, interval="abs.residual") print(stderrs) expect.err(try(predict(earth.trees, newdata=trees, interval="cint"))) printh("predict(earth.trees, interval=\"cint\")") cints <- predict(earth.trees, interval="cint") print(cints) printh("predict(earth.trees, interval=\"pin\", level=.80)") news <- predict(earth.trees, interval="pin", level=.80) print(news) expect.err(try(predict(earth.trees, interval="none", level=.80)), "predict.earth: level=0.8 was specified but interval=\"none\"") expect.err(try(predict(earth.trees, interval="pin", type="class")), "predict.earth: the interval argument is not allowed with type=\"class\"") expect.err(try(predict(earth.trees, interval="pin", type="cl")), "predict.earth: the interval argument is not allowed with type=\"class\"") expect.err(try(predict(earth.trees, interval="pin", type="ter")), "predict.earth: the interval argument is not allowed with type=\"terms\"") printh("print.default(earth.trees$varmod$residmod)") earth.trees$varmod$residmod$terms <- NULL print.default(earth.trees$varmod$residmod) remove(earth.trees) multifigure("test example for varmod help page", 2, 2) data(ozone1) set.seed(1) a <- earth(O3~temp, data=ozone1, nfold=10, ncross=3, varmod.method="earth") print(summary(a)) old.mfrow <- par(mfrow=c(2,2)) plotmo(a, do.par=FALSE, col.response=1, level=.95, main="earth model: O3~temp") plot(a, which=1) plot(a, which=3, level=.95) plot(a, which=3, level=.95, standardize=TRUE) par(par=old.mfrow) plot(a$varmod) multifigure("test example for plot.varmod help page", 2, 2) data(ozone1) set.seed(1) mod.temp.vh.doy <- earth(O3~temp+vh+vis+doy, data=ozone1, nfold=5, ncross=3, varmod.method="x.earth") print(summary(mod.temp.vh.doy)) plot(mod.temp.vh.doy, level=.95) plot(mod.temp.vh.doy$varmod) plot(mod.temp.vh.doy, versus="", level=.9, caption="plot.earth versus=\"\"") plot(mod.temp.vh.doy, versus="v", level=.9, caption="plot.earth versus=\"v\" and versus=\"temp\"", do.par=2) plot(mod.temp.vh.doy, versus="temp", level=.9, caption="", main="temp on same page") plot(mod.temp.vh.doy, which=1:9, versus="v", info=T, caption='which=c(3,5) versus="v" info=T') par(org.par) plot(mod.temp.vh.doy, versus="b:", level=.9, caption="plot.earth versus=\"b:\"") plot(mod.temp.vh.doy, versus="b:", level=.8, info=TRUE, caption="plot.earth versus=\"b:\" with info") multifigure("versus=1:4", 3, 3) plot(mod.temp.vh.doy, versus=1, caption="", do.par=FALSE, which=3) do.caption() plot(mod.temp.vh.doy, versus=2, caption="", do.par=FALSE) plot(mod.temp.vh.doy, versus=3, caption="", do.par=FALSE) plot(mod.temp.vh.doy, versus=1, info=TRUE, caption="", do.par=FALSE, which=3) plot(mod.temp.vh.doy, versus=2, info=TRUE, caption="", do.par=FALSE) plot(mod.temp.vh.doy, versus=3, info=TRUE, caption="", do.par=FALSE) plot(mod.temp.vh.doy, versus=1, info=TRUE, caption="", do.par=FALSE, level=.8, which=3) plot(mod.temp.vh.doy, versus=2, info=TRUE, caption="", do.par=FALSE, level=.8) plot(mod.temp.vh.doy, versus=3, info=TRUE, caption="", do.par=FALSE, level=.8) expect.err(try(plot(mod.temp.vh.doy, versus=9))) expect.err(try(plot(mod.temp.vh.doy, versus=1.2))) expect.err(try(plot(mod.temp.vh.doy, versus=2:3))) plot(mod.temp.vh.doy, versus="b:doy", level=.9, caption="plot.earth versus=\"b:doy\"") plot(mod.temp.vh.doy, which=1, versus="b:doy") multifigure("test example in (very old) earth vignette", 2, 2) data(ozone1) x <- ozone1$temp y <- ozone1$O3 set.seed(1) earth.mod <- earth(y~x, nfold=10, ncross=3, varmod.method="earth", trace=.1) predict <- predict(earth.mod, interval="pint") cat("\npredict(earth.mod, interval=\"pint\")\n") print(head(predict)) order <- order(x) x <- x[order] y <- y[order] predict <- predict[order,] inconf <- y >= predict$lwr & y <= predict$upr plot(x, y, pch=20, col=ifelse(inconf, 1, 2), main=sprint( "Prediction intervals\n%.0f%% of the points are in the estimated band", 100 * sum(inconf) / length(y))) do.caption() lines(x, predict$fit) lines(x, predict$lwr, lty=2) lines(x, predict$upr, lty=2) plot(earth.mod, which=3, level=.95) plot(earth.mod$varmod, do.par=F, which=1:2) cat('head(residuals(earth.mod))\n') print(head(residuals(earth.mod))) cat('head(residuals(earth.mod, type="standardize"))\n') print(head(residuals(earth.mod, type="standardize"))) multifigure("plot.earth varmod options", 2, 2) plot(earth.mod, which=3, level=.95, level.shade=0, main="plot.earth varmod options") do.caption() plot(earth.mod, which=3, level.shade="orange", level.shade2="darkgray", level=.99) plot(earth.mod, which=3, level=.95, level.shade=0, level.shade2="mistyrose4") multifigure("plot.earth delever and standardize", 2, 2) set.seed(4) earth.mod1 <- earth(O3~temp, data=ozone1, nfold=5, ncross=3, varmod.method="lm", keepxy=T, trace=.5) plot(earth.mod1, which=3, ylim=c(-16,20), info=TRUE, level=.95) do.caption() plot(earth.mod1, which=3, ylim=c(-16,20), delever=TRUE, level=.95) plot(earth.mod1, which=3, standardize=TRUE, info=TRUE, level=.95) expect.err(try(plot(earth.mod1, which=3, standardize=TRUE, delever=TRUE, level=.95))) multifigure("plot.earth which=5 and which=6", 2, 3) plot(earth.mod1, which=5, info=T, main="which=5, info=T") plot(earth.mod1, which=5, standardize=T, info=T, main="which=5, standardize=T, info=T") plot(earth.mod1, which=5, standardize=T, main="which=5, standardize=T") do.caption() plot(earth.mod1, which=6, info=T, main="which=6, info=T") plot(earth.mod1, which=6, standardize=T, info=T, main="which=6, standardize=T, info=T") plot(earth.mod1, which=6, standardize=T, main="which=6, standardize=T") multifigure("plot.earth which=7", 2, 3) plot(earth.mod1, which=7, info=T, main="which=7, info=T") plot(earth.mod1, which=7, standardize=T, info=T, main="which=7, standardize=T, info=T") plot(earth.mod1, which=7, standardize=T, main="which=7, standardize=T") do.caption() multifigure("plot.earth which=8 and which=9", 2, 3) plot(earth.mod1, which=8, info=T, main="which=8, info=T") plot(earth.mod1, which=8, standardize=T, info=T, main="which=8, standardize=T, info=T") plot(earth.mod1, which=8, standardize=T, main="which=8, standardize=T") do.caption() plot(earth.mod1, which=9, info=T, main="which=9, info=T") plot(earth.mod1, which=9, standardize=T, info=T, main="which=9, standardize=T, info=T") plot(earth.mod1, which=9, standardize=T, main="which=9, standardize=T") multifigure("plot.earth versus=4, which=3 and which=5", 2, 3) plot(earth.mod1, versus=4, which=3, main="versus=4, which=3") plot(earth.mod1, versus=4, which=3, standardize=T, info=T, main="versus=4, which=3, standardize=T, info=T") plot(earth.mod1, versus=4, which=3, standardize=T, main="versus=4, which=3, standardize=T") do.caption() plot(earth.mod1, versus=4, which=5, main="versus=4, which=5") plot(earth.mod1, versus=4, which=5, standardize=T, info=T, main="versus=4, which=5, standardize=T, info=T") plot(earth.mod1, versus=4, which=5, standardize=T, main="versus=4, which=5, standardize=T") cat("summary(earth.mod1, newdata=ozone1)\n") print(summary(earth.mod1, newdata=ozone1)) cat("summary(earth.mod1, newdata=ozone1[1:100,]:)\n") print(summary(earth.mod1, newdata=ozone1[1:100,])) expect.err(try(summary(earth.mod1, newdata=c(1,2,3))), "plotmo_response: newdata must be a matrix or data.frame") expect.err(try(summary(earth.mod1, newdata=ozone1[1:100,1:3])), "response with newdata object 'temp' not found") O3 <- ozone1$O3 temper <- ozone1$temp set.seed(4) earth.default <- earth(temper, O3, nfold=5, ncross=3, varmod.method="lm") cat("summary(earth.default)\n") print(summary(earth.default)) expect.err(try(summary(earth.default, newdata=ozone1[1:100,])), "model.matrix.earth could not interpret the data") newdata_temper <- matrix(c(O3[1:100], temper[1:100]), ncol=2) expect.err(try(summary(earth.default, newdata=newdata_temper)), "cannot get response from newdata because newdata has no column names") colnames(newdata_temper) <- c("O3", "temper") cat("summary(earth.default, newdata=newdata_temper)\n") print(summary(earth.default, newdata=newdata_temper)) plot(earth.default, level=.80, caption="earth.default") options(warn=2) expect.err(try(plotmo(earth.default, level=.80, col.response=3)), "Cannot determine which variables to plot (use all1=TRUE?)") plotmo(earth.default, all1=TRUE, level=.80, col.response=3, caption="earth.default\nlevel = .80") options(warn=1) multifigure("plot(earth.mod2)", 2, 2) set.seed(5) earth.mod2 <- earth(y~x, nfold=10, ncross=5, varmod.method="earth") plot(earth.mod2, caption="plot(earth.mod2)", level=.95) do.caption() multifigure("plot(earth.mod2) with standardize=TRUE", 2, 2) plot(earth.mod2, standardize=TRUE, level=.95, caption="plot(earth.mod2, standardize=TRUE, level=.95)") do.caption() multifigure("plot.varmod by calling plot(earth.mod2$varmod)", 2, 2) plot(earth.mod2$varmod) multifigure("embedded earth model by calling plot(earth.mod2$varmod$residmod)", 2, 2) plot(earth.mod2$varmod$residmod, caption="embedded earth model") do.caption() cat("test varmod.conv=50%\n") set.seed(1) (earth(Volume~Girth, data=trees, nfold=3, ncross=3, varmod.method="lm", trace=.3, varmod.conv=50)) cat("test varmod.conv=-5\n") set.seed(1) (earth(Volume~Girth, data=trees, nfold=3, ncross=3, varmod.method="lm", trace=.3, varmod.conv=-5)) cat("test varmod.clamp\n") set.seed(1) a.noclamp <- earth(Volume~Girth, data=trees, nfold=3, ncross=3, varmod.method="lm") plot(a.noclamp$varmod, which=1:2, caption="a.noclamp and a.clamp", do.par=FALSE) set.seed(1) a.clamp <- earth(Volume~Girth, data=trees, nfold=3, ncross=3, varmod.method="lm", varmod.clamp=.6) plot(a.clamp$varmod, which=1:2, caption="", do.par=FALSE) cat("test varmod.minspan=-5\n") set.seed(1) a.varmod.minspan.minus5 <- earth(Volume~Girth, data=trees, nfold=3, ncross=3, varmod.method="earth", trace=.3, varmod.minspan=-5) print(coef(a.varmod.minspan.minus5$varmod)) cat("test varmod.minspan=1\n") set.seed(1) a.varmod.minspan1 <- earth(Volume~Girth, data=trees, nfold=3, ncross=3, varmod.method="earth", trace=.3, varmod.minspan=1) print(coef(a.varmod.minspan1$varmod)) use.mgcv.package <- FALSE for(varmod.method in c(earth:::VARMOD.METHODS, "gam", "x.gam")) { multifigure(sprint("varmod.method=\"%s\"", varmod.method), 2, 3) par(mar = c(3, 3, 2, 3)) if(varmod.method %in% c("gam", "x.gam")) { if(use.mgcv.package) { cat("skipping mgcv tests\n") next cat("library(mgcv)\n") library(mgcv) } else library(gam) } set.seed(2019) if(varmod.method %in% c("gam", "x.gam")) options(warn=1) earth.mod <- earth(Volume~Girth, data=trees, nfold=3, ncross=3, varmod.method=varmod.method, trace=if(varmod.method %in% c("const", "lm", "power")) .3 else 0) printh(sprint("varmod.method %s: summary(earth.mod)", varmod.method)) printh("summary(earth.mod)") print(summary(earth.mod)) if(use.mgcv.package && (varmod.method == "x.gam" || varmod.method == "gam")) { printh("skipping summary(mgcv::gam) etc.\n") } else { printh("earth.mod$varmod") print(earth.mod$varmod, style="unit") printh("summary(earth.mod$varmod)") print(summary(earth.mod$varmod)) printh("summary(earth.mod$varmod$residmod)") print(summary(earth.mod$varmod$residmod)) } printh(sprint("varmod.method %s: predict(earth.mod, interval=\"pint\")", varmod.method)) pints <- predict(earth.mod, interval="pint") print(pints) plotmo(earth.mod$varmod, do.par=FALSE, col.response=2, clip=FALSE, main="plotmo residual model", xlab="x", ylab="varmod residuals") plotmo(earth.mod, level=.90, do.par=FALSE, col.response=1, clip=FALSE, main="main model plotmo Girth") do.caption() plot(earth.mod, which=3, do.par=FALSE, level=.95) plot(earth.mod$varmod, do.par=FALSE, which=1:3, info=(varmod.method=="earth")) if(varmod.method == "x.gam" && !use.mgcv.package) { use.mgcv.package <- TRUE cat("detach(\"package:gam\", unload=TRUE)\n") detach("package:gam", unload=TRUE) } } set.seed(6) earth.exponent <- earth(Volume~Girth, data=trees, nfold=3, ncross=3, varmod.method="lm", varmod.exponent=.5) printh("summary(earth.exponent)") print(summary(earth.exponent)) par(org.par) source("test.epilog.R")
pmpv <- function(Y, X, W = NULL, type, B = 100, fold.num = 10, perm.num = 1000) { p <- ncol(X) p.noise <- matrix(rep(NA, perm.num*p), ncol = p) for (i in 1:perm.num) { Y_perm <- sample(Y) p.noise[i,] <- highdim.p(Y = Y_perm, X = X, W = W, type = type, B = B, fold.num = fold.num)$p.hmp } return(p.noise) }
covmve<-function(x){ val<-cov.mve(x) list(center=val$center,cov=val$cov) }
ObjEst = function(vPara) { b0 = exp(vPara - e$alpha) vPara = b0/(b0 + 1)*(e$UB - e$LB) + e$LB return(e$Obj(vPara)) } ObjDef = function(vPara) { Fi = e$Fx(vPara[1:e$nTheta]) Ri = e$Y - Fi e$Fi = Fi if (e$Error == "A") { Ci = rep(vPara[e$SGindex], e$nRec) } else if (e$Error == "POIS") { Ci = vPara[e$SGindex]*Fi Ci[Fi == 0] = 1 Ri[Fi == 0] = 0 } else if (e$Error == "P") { Ci = vPara[e$SGindex]*Fi*Fi Ci[Fi == 0] = 1 Ri[Fi == 0] = 0 } else if (e$Error == "C") { Ci = rep(vPara[e$SGindex[1]], e$nRec) + vPara[e$SGindex[2]]*Fi*Fi } else if (e$Error == "S") { Si = e$Sx(vPara[1:e$nTheta]) Ci = vPara[e$SGindex]*Si Ci[Si == 0] = 1 Ri[Si == 0] = 0 } return(sum(log(Ci) + Ri*Ri/Ci)) } ObjLS = function(vPara) { Fi = e$Fx(vPara) Ri = e$Y - Fi if (e$Error == "POIS") { Ri[Fi != 0] = Ri[Fi != 0] / sqrt(Fi[Fi != 0]) Ri[Fi == 0] = 0 } else if (e$Error == "P") { Ri[Fi != 0] = Ri[Fi != 0] / Fi[Fi != 0] Ri[Fi == 0] = 0 } return(sum(Ri*Ri)) }
eblupFH1 <- function (formula, vardir, method = "REML", data) { namevar <- deparse(substitute(vardir)) if (!missing(data)) { formuladata <- model.frame(formula, na.action = na.omit, data) X <- model.matrix(formula, data) vardir <- data[, namevar] } else { formuladata <- model.frame(formula, na.action = na.omit) X <- model.matrix(formula) } if (attr(attributes(formuladata)$terms, "response") == 1) textformula <- paste(formula[2], formula[1], formula[3]) else textformula <- paste(formula[1], formula[2]) if (length(na.action(formuladata)) > 0) stop("Argument formula=", textformula, " contains NA values.") if (any(is.na(vardir))) stop("Argument vardir=", namevar, " contains NA values.") y <- formuladata[, 1] m <- length(y) direct <- y I<-diag(1,m) p<-dim(X)[2] logl=function(delta){ area=m psi=matrix(c(vardir),area,1) Y=matrix(c(direct),area,1) Z.area=diag(1,area) sigma.u<-delta[1] V<-sigma.u*Z.area%*%t(Z.area)+I*psi[,1] Vi<-solve(V) Xt<-t(X) XVi<-Xt%*%Vi Q<-solve(XVi%*%X) P<-Vi-(Vi%*%X%*%Q%*%XVi) b.s<-Q%*%XVi%*%Y ee<-eigen(V) -(area/2)*log(2*pi)-0.5*sum(log(ee$value))-(0.5)*log(det(t(X)%*%Vi%*%X))-(0.5)*t(Y)%*%P%*%Y } opt<-optimize(logl,c(0.001,100),maximum = TRUE) estsigma2u<-opt$maximum Xt <-t(X) D=diag(1,m) V<-estsigma2u*D%*%t(D)+I*vardir Vi<-solve(V) Q<-solve(Xt%*%Vi%*%X) Beta.hat<-Q%*%Xt%*%Vi%*%direct res<-direct-X%*%Beta.hat Sigma.u=estsigma2u*I u.hat=Sigma.u%*%t(D)%*%Vi%*%res EBLUP.Mean<-X%*%Beta.hat+D%*%u.hat zvalue <- Beta.hat/sqrt(diag(Q)) pvalue <- 2 * pnorm(abs(zvalue), lower.tail = FALSE) coef <- data.frame(beta = Beta.hat, std.error = sqrt(diag(Q)),tvalue = zvalue, pvalue) g1<-NULL Ga<-Sigma.u-Sigma.u%*%Vi%*%Sigma.u for (i in 1:m) { g1[i]<-Ga[i,i] } g2<-NULL Gb<-Sigma.u%*%Vi%*%X Xa<-matrix(0,1,p) for (i in 1:m) { Xa[1,]<-X[i,]-Gb[i,] g2[i]<-Xa%*%Q%*%t(Xa) } g3<-NULL Deriv1=solve((estsigma2u*I)+ diag(c(vardir),m)) II<-((1/2)*sum(diag(Deriv1%*%Deriv1)))^(-1) for (i in 1:m) { g3[i]=(vardir[i]^2)*(vardir[i]+estsigma2u)^(-3)*II } EBLUP.MSE.PR<-c(g1+g2+g3) areacode=1:m FH.SE=round(sqrt(EBLUP.MSE.PR),2) FH.CV=round(100*(sqrt(EBLUP.MSE.PR)/EBLUP.Mean),2) result1= cbind(areacode,EBLUP.Mean, EBLUP.MSE.PR,FH.SE,FH.CV) colnames(result1)=c("area","EBLUP","EBLUP.MSE","EBLUP.SE","EBLUP.CV") result <- list(eblup = NA, mse = NA, sample = NA,fit = list(estcoef = NA, refvar = NA)) result$fit$estcoef <- coef result$fit$refvar <- estsigma2u result$fit$randomeffect <- u.hat result$eblup <- EBLUP.Mean result$mse <- EBLUP.MSE.PR result$sample <- result1 return(result) }
tam_linking_irf_discrepancy <- function(probs1, probs2, wgt, type, pow_rob_hae=1, eps_rob_hae=1e-4) { K <- min( dim(probs1)[3], dim(probs2)[3]) crit <- 0 if (type %in% c("Hae","RobHae") ){ for (kk in 1:K){ irf_diff <- probs1[,,kk,drop=FALSE] - probs2[,,kk,drop=FALSE] irf_loss <- tam_linking_function_haebara_loss(x=irf_diff, type=type, pow_rob_hae=pow_rob_hae, eps=eps_rob_hae) crit <- crit + sum( irf_loss * wgt ) } } if (type=="SL"){ vcrit <- 0 for (kk in 1:K){ vcrit <- vcrit + (kk-1)*( probs1[,,kk,drop=FALSE] - probs2[,,kk,drop=FALSE] ) } vcrit <- rowSums( vcrit ) crit <- sum( vcrit^2 * wgt ) } return(crit) }
library(MixSIAR) mix.filename <- system.file("extdata", "cladocera_consumer.csv", package = "MixSIAR") mix <- load_mix_data(filename=mix.filename, iso_names=c("c14.0","c16.0","c16.1w9","c16.1w7","c16.2w4", "c16.3w3","c16.4w3","c17.0","c18.0","c18.1w9", "c18.1w7","c18.2w6","c18.3w6","c18.3w3","c18.4w3", "c18.5w3","c20.0","c22.0","c20.4w6","c20.5w3", "c22.6w3","BrFA"), factors="id", fac_random=FALSE, fac_nested=FALSE, cont_effects=NULL) source.filename <- system.file("extdata", "cladocera_sources.csv", package = "MixSIAR") source <- load_source_data(filename=source.filename, source_factors=NULL, conc_dep=FALSE, data_type="means", mix) discr.filename <- system.file("extdata", "cladocera_discrimination.csv", package = "MixSIAR") discr <- load_discr_data(filename=discr.filename, mix)
p_wind <- function(data_wind, ws.int=0.5, angle=45, grid.line=10, type="default", breaks=5, offset=5, paddle=FALSE, key.position = "right"){ coln <- colnames(data_wind) ws <- coln[5] wd <- coln[4] openair::windRose(mydata=data_wind, ws = ws, wd = wd, ws2 = NA, wd2 = NA, ws.int = ws.int, angle = angle, type = type, bias.corr = TRUE, cols = "default", grid.line = grid.line, width = 1, seg = NULL, auto.text = TRUE, breaks = breaks, offset = offset, normalise = FALSE, max.freq = NULL, paddle = paddle, key.header = NULL, key.footer = "(m/s)", key.position = key.position, key = TRUE, dig.lab = 5, statistic = "prop.count", pollutant = NULL, annotate = FALSE, angle.scale = 315, border = NA) return() }
range_checker <- function(orig_data, newdata) { newdata <- na.omit(newdata) numerics <- sapply(newdata, FUN = is.numeric) newdata <- newdata[, numerics] varnames <- colnames(newdata) conds <- sapply(varnames, simplify = FALSE, FUN = function(x) return(sapply(newdata[[x]], FUN = function(y, x) return(y > min(orig_data[[x]]) & y < max(orig_data[[x]])), x = x))) conds <- data.frame(conds, row.names = row.names(newdata)) if (all(unlist(conds))) { result <- NULL } else { outlier_combs <- apply(conds, 1, function(x) return(!all(x))) %>% which() %>% names() result <- outlier_combs } return(result) } bad_range_warning <- function(outlier_combs) { if (length(outlier_combs) == 1) paste("Prediction", outlier_combs, "has covariate combinations", "\nwhich are out of the original data's range") else if (length(outlier_combs) > 1) paste("Predictions", paste(outlier_combs, collapse = ", "), "have", "covariate combinations", "\nwhich are out of the original data's range") }
plot_var <- function(resclv,K=NULL,axeh=1,axev=2,label=FALSE,cex.lab=1,v_colors=NULL,v_symbol=FALSE,beside=FALSE) { if (!inherits(resclv, c("clv","lclv"))) stop("non convenient objects") X<-resclv$param$X if (sum(is.na(X))>0) { valmq=TRUE stop(cat("This function cannot be apply if the data set contains missing values. \nUse the imputation approach based on clv result (see imput_clv() function) and perform again CLV on the imputed data set.")) } if(is.null(resclv$param$K)) { if (is.null(K)) {K<- as.numeric(readline("Please, give the number of groups : "))} clusters<-resclv[[K]]$clusters[2,] } else { clusters<-resclv$clusters[2,] K<-resclv$param$K } X<- scale(X, center=TRUE, scale=resclv$param$sX) p <- dim(X)[2] n <- dim(X)[1] if (is.null(v_colors)) {v_colors <- c("blue","red","green","black", "purple","orange","yellow","tomato","pink", "gold","cyan","turquoise","violet","green", "khaki","maroon","chocolate","burlywood")} if(v_symbol) {v_colors<-rep("black",20)} A<-max(axeh,axev) if (n<p) { reseig<-eigen(X%*%t(X)/n) valp<-100*reseig$values[1:A]/sum(reseig$values) coordvar<-t(X)%*%reseig$vectors[,1:A]/sqrt(n) coordind<-reseig$vectors[,1:A]%*%diag(sqrt(reseig$values[1:A])) } else { reseig<-eigen(t(X)%*%X/(n)) valp<-100*reseig$values[1:A]/sum(reseig$values) coordvar<-reseig$vectors[,1:A]%*%diag(sqrt(reseig$values[1:A])) coordind<-X%*%reseig$vectors[,1:A]/sqrt(n) } for (a in 1:A) { if (sign(mean(coordvar[,a]))==(-1)) { coordvar[,a]=coordvar[,a]*(-1) coordind[,a]=coordind[,a]*(-1) } } par(pty="s") if (resclv$param$sX) { xmin=-1 xmax=1 ymin=-1 ymax=1 } else { xmin=min(min(coordvar[,axeh]),-max(coordvar[,axeh])) xmax=max(max(coordvar[,axeh]),-min(coordvar[,axeh])) ymin=min(min(coordvar[,axev]),-max(coordvar[,axev])) ymax=max(max(coordvar[,axev]),-min(coordvar[,axev])) } clean_var<-NULL if(resclv$param$strategy=="kplusone") clean_var<-which(clusters==0) if(resclv$param$strategy=="sparselv"){ names0=c() sloading = resclv$sloading for(k in 1:K) names0 = c(names0,dimnames(sloading[[k]])[[1]]) names1 = names0[which(unlist(sloading)==0)] names2= dimnames(resclv$clusters)[[2]] clean_var = sort(match(names1,names2)) names(clean_var) = colnames(X)[clean_var] } colpart<-NULL symbpart<-NULL symbpart<-20 for (j in 1:p) { if (j %in% clean_var) { colpart[j]<-"gray" if(v_symbol) symbpart[j]="." }else{ colpart[j]<-v_colors[clusters[j]] if(v_symbol) symbpart[j]=clusters[j] } } if (beside==FALSE) { plot(coordvar[,c(axeh,axev)],col=colpart,pch=symbpart,cex.axis=0.7,cex.lab=0.7, xlab=paste("Dim ",axeh," (",round(valp[axeh],2),"%)"), ylab=paste("Dim ",axev," (",round(valp[axev],2),"%)"), xlim=c(xmin,xmax), ylim=c(ymin,ymax)) arrows(rep(0,p), rep(0,p), coordvar[,axeh], coordvar[,axev], col= colpart, angle=0) if(label) { for (j in 1:p) { if(coordvar[j,axev]>0) text(coordvar[j,axeh], coordvar[j,axev],colnames(X)[j],pos=3,cex=cex.lab,col=colpart[j]) if(coordvar[j,axev]<0) text(coordvar[j,axeh], coordvar[j,axev],colnames(X)[j],pos=1,cex=cex.lab,col=colpart[j]) } } abline(h=0,v=0) if (resclv$param$sX) symbols(0, 0, circles = 1, inches = FALSE, add = TRUE) ncol=ceiling(K/4) if(v_symbol) { legend("topleft",paste("G",1:K,sep=""),col=v_colors[1:K],title="Groups", lty="solid", pch=1:K, seg.len=0.6,cex=0.7,ncol=ncol) } else { legend("topleft",paste("G",1:K,sep=""),col=v_colors[1:K],title="Groups", lty="solid", seg.len=0.6,cex=0.7,ncol=ncol) } } if (beside==TRUE) { if (length(clean_var)==0) KK=K if (length(clean_var)>0) KK=K+1 NL=ceiling(KK/3) par(mfrow=c(NL,3)) case=levels(as.factor(colpart)) for(k in 1:K) { who=which(clusters==k) plot(coordvar[who,c(axeh,axev)],col=colpart[who],pch=symbpart[who],cex.axis=0.7,cex.lab=0.7, xlab=paste("Dim ",axeh," (",round(valp[axeh],2),"%)"), ylab=paste("Dim ",axev," (",round(valp[axev],2),"%)"), xlim=c(xmin,xmax), ylim=c(ymin,ymax)) arrows(rep(0,p), rep(0,p), coordvar[who,axeh], coordvar[who,axev], col= colpart[who], angle=0) if(label) { for (j in who) { if(coordvar[j,axev]>0) text(coordvar[j,axeh], coordvar[j,axev],colnames(X)[j],pos=3,cex=cex.lab,col=colpart[j]) if(coordvar[j,axev]<0) text(coordvar[j,axeh], coordvar[j,axev],colnames(X)[j],pos=1,cex=cex.lab,col=colpart[j]) } } abline(h=0,v=0) if (resclv$param$sX) symbols(0, 0, circles = 1, inches = FALSE, add = TRUE) if(v_symbol) { legend("topleft",paste("G",k,sep=""),col=v_colors[k], lty="solid", pch=k, seg.len=0.6,cex=1) } else { legend("topleft",paste("G",k,sep=""),col=v_colors[k], lty="solid", seg.len=0.6,cex=1) } } if (length(clean_var)>0) { who=clean_var plot(coordvar[who,c(axeh,axev)],col=colpart[who],pch=symbpart[who],cex.axis=0.7,cex.lab=0.7, xlab=paste("Dim ",axeh," (",round(valp[axeh],2),"%)"), ylab=paste("Dim ",axev," (",round(valp[axev],2),"%)"), xlim=c(xmin,xmax), ylim=c(ymin,ymax)) arrows(rep(0,p), rep(0,p), coordvar[who,axeh], coordvar[who,axev], col= colpart[who], angle=0) if(label) { for (j in who) { if(coordvar[j,axev]>0) text(coordvar[j,axeh], coordvar[j,axev],colnames(X)[j],pos=3,cex=cex.lab,col=colpart[j]) if(coordvar[j,axev]<0) text(coordvar[j,axeh], coordvar[j,axev],colnames(X)[j],pos=1,cex=cex.lab,col=colpart[j]) } } abline(h=0,v=0) if (resclv$param$sX) symbols(0, 0, circles = 1, inches = FALSE, add = TRUE) if(v_symbol) { legend("topleft","others",col="gray", lty="solid", pch=k, seg.len=0.6,cex=1) } else { legend("topleft","others",col="gray", lty="solid", seg.len=0.6,cex=1) } } } par(mfrow=c(1,1)) par(pty="m") }
exceptionalScores <- function(dat, items=NULL, exception=.025, totalOnly=TRUE, append=TRUE, both=TRUE, silent=FALSE, suffix = "_isExceptional", totalVarName = "exceptionalScores") { if (is.data.frame(dat)) { if (is.null(items)) { items <- names(dat); if (!silent) { cat("No items specified: extracting all variable names in dataframe.\n"); } } exceptionalScores <- dat[, items]; } else { exceptionalScores <- data.frame(dat); names(exceptionalScores) <- deparse(substitute(dat)); } originalCols <- ncol(exceptionalScores); exceptionalScores <- data.frame(exceptionalScores[, unlist(lapply(exceptionalScores, is.numeric))]); if ((originalCols > ncol(exceptionalScores) & !silent)) { cat0("Note: ", originalCols - ncol(exceptionalScores), " variables ", "were not numeric and will not be checked for exceptional values.\n"); } namesToUse <- paste0(colnames(exceptionalScores), suffix); exceptionalScores <- apply(exceptionalScores, 2, exceptionalScore, prob = exception, both=both, silent=silent); colnames(exceptionalScores) <- namesToUse; if (totalOnly) { totalTrues <- rowSums(exceptionalScores, na.rm=TRUE); if (append) { dat[, totalVarName] <- totalTrues; return(dat); } else { return(totalTrues); } } else { if (append) { return(data.frame(dat, exceptionalScores)); } else { return(exceptionalScores); } } }
NULL NULL pointdensity <- function(df, lat_col, lon_col, date_col = NULL, grid_size, radius){ calc_density <- function (lati, loni, grid_size, radius, count, sumDate){ lat.vec <- seq(lati - radius * grid_size, lati + radius * grid_size, grid_size) lat.vec.t <- acos(cos(radius*grid_size)/cos(lat.vec - lati)) lat.vec.t <- lat.vec.t/cos(lat.vec * 2 * pi/360) lat.vec.t <- round(lat.vec.t/grid_size,0)*grid_size lon.vec <- seq(loni - radius * grid_size, loni + radius * grid_size, grid_size) lon.mat <- matrix(lon.vec,nrow = length(lon.vec),ncol = length(lon.vec)) tlon.mat <- abs(lon.mat - loni) tlon.mat <- t(tlon.mat) temp <- lat.vec.t - tlon.mat temp[temp < (grid_size-(1E-6))] <- 0 temp[temp > 0] <- 1 temp2 <- temp*t(lon.mat) lat.mat <- matrix(rev(lat.vec),nrow = length(lat.vec),ncol = length(lat.vec)) lat.vec <- c(lat.mat) lon.vec <- c(temp2) count.vec <- rep(count,length(lat.vec)) sumDate.vec <- rep(sumDate,length(lat.vec)) return.mat <- cbind(lat.vec,lon.vec,count.vec,sumDate.vec) row_sub = apply(return.mat, 1, function(x) all(x[1]*x[2] !=0 )) return.mat <- return.mat[row_sub,] return(return.mat) } lat_c<-lon_c<-cat_r<-count<-sumDate<-ind<-NULL grid_size <- round(grid_size/111.2, digits = 3) rad_km <- radius rad_dg <- rad_km/111.2 rad_steps <- round(rad_dg/grid_size) rad_km <- rad_steps * grid_size * 111.2 cat("\nThe radius was adjusted to ",rad_km,"km in order to accomodate the grid size\n\n") cat("\nThe grid size is ",grid_size," measured in degrees\n\n") radius <- rad_steps lat_data <- unlist(df[,lat_col]) lat <- lat_data * (1/grid_size) lat <- round(lat, 0) lat <- lat * (grid_size) lat <- round(lat,3) lon_data <- unlist(df[,lon_col]) lon <- lon_data * (1/grid_size) lon <- round(lon, 0) lon <- lon * (grid_size) lon <- round(lon,3) if (is.null(date_col)) { date <- rep(0, length(lon)) } if (!is.null(date_col)) { date <- as.Date(df[, date_col]) date <- as.numeric(date) } olat_olon <- paste(lat_data,lon_data,sep = "_") rlat_rlon <- paste(lat,lon,sep = "_") o_DT <- data.table(lat_c = lat, lon_c = lon, date = date, lat_o = lat_data, lon_o = lon_data, cat_o = olat_olon, cat_r = rlat_rlon, ind = rep(1,length(lon_data))) o_DT <- o_DT[order(o_DT$cat_r),] yy <- o_DT[,list(lat_c = max(lat_c), lon_c = max(lon_c), sumDate=sum(date), count=length(date)), by="cat_r"] yy <- yy[order(yy$cat_r),] yy_orig <- yy yy[,cat_r:=NULL] idxs <- seq(1,length(yy$lat_c),1) yy <- cbind(yy, ind = idxs) total_measures <- length(yy$lat_c)*(2*radius +1)*(2*radius +1) cat("There are ", length(yy$lat_c)," unique grids that require ", total_measures, " measurements...\n\n") pb <- utils::txtProgressBar(title="point density calculation progress", label="0% done", min=0, max=100, initial=0, style = 3) inventory.mat <- matrix(nrow = 1E6, ncol = 4) inventory = 0 temp_inventory = 0 inventory.dt <- data.table(lat_c = numeric(0), lon_c = numeric(0), count = numeric(0), sumDate = numeric(0)) for(i in 1:length(yy$lat_c)){ temp3 <- calc_density(lati = yy$lat_c[i], loni = yy$lon_c[i], grid_size = grid_size, radius = radius, count = yy$count[i], sumDate = yy$sumDate[i]) inventory <- inventory + length(temp3[,1]) temp_inventory <- temp_inventory +1 if(temp_inventory == 100){ info <- sprintf("%d%% done", round((i/length(yy$lat_c))*100)) utils::setTxtProgressBar(pb, i/(length(yy$lat_c))*100, label=info) temp_inventory = 0 } if(inventory > 1E6){ inventory.mat <- inventory.mat[(1:(inventory - length(temp3[,1]))),] temp.dt <- data.table(lat_c = inventory.mat[,1], lon_c = inventory.mat[,2], count = inventory.mat[,3], sumDate = inventory.mat[,4]) temp.dt <- temp.dt[,list(count = sum(count),sumDate = sum(sumDate)), by = "lat_c,lon_c"] inventory.dt <- rbind(inventory.dt, temp.dt) inventory.mat <- matrix(nrow = 1E6, ncol = 4) inventory.mat[1:length(temp3[,1]),] <- temp3 inventory = 0 } else{ inventory.mat[(inventory - length(temp3[,1])+1):inventory,] <- temp3 } } inventory.mat <- inventory.mat[(1:inventory),] temp.dt <- data.table(lat_c = inventory.mat[,1], lon_c = inventory.mat[,2], count = inventory.mat[,3], sumDate = inventory.mat[,4]) temp.dt <- temp.dt[,list(count = sum(count),sumDate = sum(sumDate)), by = "lat_c,lon_c"] inventory.dt <- rbind(inventory.dt, temp.dt) yy_ind <- data.table(lat_c = yy$lat_c, lon_c = yy$lon_c, count = rep(0,length(yy$lat_c)), sumDate = rep(0,length(yy$lat_c)), ind = yy$ind) inventory.dt_ind <- data.table(lat_c = inventory.dt$lat_c, lon_c = inventory.dt$lon_c, count = inventory.dt$count, sumDate = inventory.dt$sumDate, ind = rep(0,length(inventory.dt$lat_c))) inventory2.dt_ind <- data.table(lat_c = round(inventory.dt_ind$lat_c,3), lon_c = round(inventory.dt_ind$lon_c,3), count = inventory.dt_ind$count, sumDate = inventory.dt_ind$sumDate, ind = inventory.dt_ind$ind) inventory.dt_ind <- inventory2.dt_ind inventory.dt <- rbind(inventory.dt_ind, yy_ind) inventory.dt<-inventory.dt[order(inventory.dt$lat_c, inventory.dt$lon_c),] inventory3.dt <- inventory.dt[,list(sumDate = sum(sumDate), count = sum(count), ind = sum(ind)), by = "lat_c,lon_c"] final_inventory.dt <- inventory3.dt[inventory3.dt$ind > 0,] date_avg = final_inventory.dt$sumDate / final_inventory.dt$count final<-data.table(lat=final_inventory.dt$lat_c,lon=final_inventory.dt$lon_c,count=final_inventory.dt$count,dateavg = date_avg, ind = final_inventory.dt$ind) final<-final[order(final$ind),] final.1 <- cbind(final,yy_count = yy_orig$count) nfinal <- final.1[rep(seq(1,nrow(final.1)), final.1$yy_count)] o_DT.check <- cbind(o_DT,nfinal) o_final <- data.table(lat = o_DT$lat_o, lon = o_DT$lon_o, count = nfinal$count, dateavg = nfinal$dateavg) o_final<-o_final[order(o_final$count),] cat("done...\n\n") return(o_final) }
check_class <- function(argument, target, arg_name){ if( !is.null(argument) ){ class_eval <- class(argument)[1] guess <- match(x = class_eval, table = target) is_na <- sum(guess) if( is.na(is_na) ){ error_message <- paste0('Oops...please check for ', arg_name, ' argument. Allowed classes are: ', paste(target, collapse = ', '), '.') stop( error_message, call. = FALSE ) } } }
context("dfRowToList") test_that("dfRowToList", { ps = makeParamSet( makeDiscreteParam("x", values = list(a = iris, b = 123)), makeNumericParam("y", lower = 1, upper = 2), makeNumericVectorParam("z", len = 2, lower = 10, upper = 20) ) des = generateDesign(10, par.set = ps) vals = dfRowsToList(des, ps) expect_true(is.list(vals) && length(vals) == nrow(des)) for (i in seq_row(des)) { v = vals[[i]] expect_true(is.list(v) && length(v) == 3 && all(names(v) == c("x", "y", "z"))) expect_true(identical(v$x, iris) || identical(v$x, 123)) expect_true(is.numeric(v$y) && length(v$y) == 1 && v$y >= 1 && v$y <= 2) expect_true(is.numeric(v$z) && length(v$z) == 2 && all(v$z >= 10 & v$z <= 20)) } }) test_that("requires works", { ps = makeParamSet( makeDiscreteParam("x", values = c("a", "b")), makeNumericParam("y", lower = 1, upper = 2, requires = quote(x == "a")), makeNumericVectorParam("z", len = 2, lower = 10, upper = 20, requires = quote(x == "b")) ) des = generateDesign(10, par.set = ps) mycheck = function(vals) { expect_true(is.list(vals) && length(vals) == nrow(des)) for (i in seq_row(des)) { v = vals[[i]] expect_true(is.list(v) && length(v) == 3L && all(names(v) %in% c("x", "y", "z"))) expect_true(is.character(v$x) && length(v$x) == 1 && v$x %in% c("a", "b")) if (v$x == "a") { expect_true(is.numeric(v$y) && length(v$y) == 1 && v$y >= 1 && v$y <= 2) expect_true(isScalarNA(v$z)) } else if (v$x == "b") { expect_true(isScalarNA(v$y)) expect_true(is.numeric(v$z) && length(v$z) == 2 && all(v$z >= 10 & v$z <= 20)) } } } vals = dfRowsToList(des, ps) mycheck(vals) }) test_that("ints in data frame work", { df = data.frame(x = 1:3, y = as.numeric(1:3)) ps = makeParamSet( makeIntegerParam("x"), makeIntegerParam("y") ) xs = dfRowsToList(df, ps) expect_equal(xs[[1]], list(x = 1L, y = 1L)) }) test_that("enforce.col.types works", { df = data.frame(u = c(NA, NA), x = 1:2, y = as.numeric(1:2), z = c("TRUE", "FALSE")) ps = makeParamSet( makeNumericParam("u"), makeIntegerParam("x"), makeIntegerParam("y"), makeLogicalParam("z") ) x = dfRowToList(df, ps, 1L, enforce.col.types = TRUE) expect_equal(x, list(u = NA, x = 1L, y = 1L, z = TRUE)) })
corm <- function(x,n){ typeofvar <- sapply(x,class) ha <- names(typeofvar[typeofvar == "numeric" | typeofvar == "integer" | typeofvar == "double"]) x <- x[,c(ha)] cormatirx <-data.frame(round(cor(x, use = "na.or.complete"), n)) corrank <- data.frame(sort(cor(x,use = "na.or.complete")[,1],decreasing = T)) return(cormatirx) return(corrank) }
source("ESEUR_config.r") library("lme4") library("reshape2") MAX_BREW=8 brew_col=rainbow(MAX_BREW) tests=read.csv(paste0(ESEUR_dir, "reliability/19860020075-10.csv.xz"), as.is=TRUE) tests$F20=NULL T1=subset(tests, tests$Task == 1) T1$Task=NULL T3=subset(tests, tests$Task == 3) T3$Task=NULL T3$F3=NULL T3$F4=NULL T3$F7=NULL T1_sort=data.frame(apply(T1[ , 2:9], 1, sort, na.last=TRUE)) T1_sort$failures=1:nrow(T1_sort) T1_vec=melt(T1_sort, id.vars="failures", variable.name="replication", value.name="input_count") f_mod=glmer(input_count ~ failures+ (1+failures | replication), data=T1_vec, family=poisson) print(summary(f_mod))
library(ape) library(adephylo) library(phylobase) library(phylosignal) data(carni19) tre <- read.tree(text = carni19$tre) dat <- data.frame(carni19$bm) dat$random <- rnorm(dim(dat)[1], sd = 10) dat$bm <- rTraitCont(tre) p4d <- phylo4d(tre, dat) barplot(p4d) dotplot(p4d) gridplot(p4d) dotplot(p4d, tree.type = "cladogram") gridplot(p4d, tree.type = "fan", tip.cex = 0.6, show.trait = FALSE) barplot(p4d, tree.ratio = 0.5) barplot(p4d, trait = c("bm", "carni19.bm")) mat.e <- matrix(abs(rnorm(19 * 3, 0, 0.5)), ncol = 3, dimnames = list(tipLabels(p4d), names(tdata(p4d)))) barplot(p4d, error.bar.sup = mat.e, error.bar.inf = mat.e) barplot(p4d, tree.type = "fan", tip.cex = 0.6, tree.open.angle = 160, trait.cex = 0.6) barplot(p4d, bar.col = rainbow(19)) mat.col <- ifelse(tdata(p4d, "tip") < 0, "red", "grey35") barplot(p4d, center = FALSE, bar.col = mat.col) barplot(p4d, trait.bg.col = c(" gridplot(p4d, tree.type = "fan", tree.ratio = 0.5, show.trait = FALSE, show.tip = FALSE, cell.col = terrain.colors(100)) tip.col <- rep(1, nTips(p4d)) tip.col[(mat.col[, 2] == "red") | (mat.col[, 3] == "red")] <- 2 barplot(p4d, center = FALSE, trait.bg.col = c(" bar.col = mat.col, tip.col = tip.col, trait.font = c(1, 2, 2)) barplot(p4d) focusTree() add.scale.bar() barplot(p4d) focusTraits(2) abline(v = 1, col = 2) barplot(p4d) focusTips() rect(xleft = 0, ybottom = 0.5, xright = 0.95, ytop = 3.5, col = "
print.lba.ls.fe <- function(x, digits = 3L, ...) { cat("\nCall:\n", paste(deparse(x$call), sep = "\n", collapse = "\n"), "\n") an <- round(x$A, digits) bn <- round(x$B, digits) cat("\nIdentified mixing parameters:\n\n") print.default(an, ...) cat("\nIdentified latent budget:\n\n") print.default(bn, ...) cat("\nBudget proportions:\n") pkk <- round(x$pk, digits) rownames(pkk) <- c('') print.default(pkk, ...) }
tmp <- function(a, ...) { c(as.list(environment()), list(...)) } tmp(2, b = 3, c = 3:4) tmp(2)
library(BRETIGEA, quietly = TRUE) library(knitr) str(aba_marker_expression, list.len = 5) str(aba_pheno_data, list.len = 5) ct_res = brainCells(aba_marker_expression, nMarker = 50) kable(head(ct_res)) cor_mic = cor.test(ct_res[, "mic"], as.numeric(aba_pheno_data$ihc_iba1_ffpe), method = "spearman") print(cor_mic) cor_ast = cor.test(ct_res[, "ast"], as.numeric(aba_pheno_data$ihc_gfap_ffpe), method = "spearman") print(cor_ast) ct_res = brainCells(aba_marker_expression, nMarker = 50, species = "combined", method = "PCA") kable(head(ct_res)) ct_res = brainCells(aba_marker_expression, nMarker = 50, species = "combined", celltypes = c("ast", "neu", "oli")) kable(head(ct_res)) ct_res = brainCells(aba_marker_expression, nMarker = 50, data_set = "kelley") kable(head(ct_res)) ct_res_mckenzie = brainCells(aba_marker_expression, nMarker = 50, data_set = "mckenzie", species = "human") ct_res_kelley = brainCells(aba_marker_expression, nMarker = 50, data_set = "kelley") cell_types_compare = colnames(ct_res_kelley) for(i in 1:length(cell_types_compare)){ cor_res = cor.test(ct_res_mckenzie[ , cell_types_compare[i]], ct_res_kelley[ , cell_types_compare[i]], method = "spearman") df_compare_cor = data.frame(Cell = cell_types_compare[i], Rho = cor_res$estimate, PVal = cor_res$p.value) if(i ==1) df_compare_cor_tot = df_compare_cor if(i > 1) df_compare_cor_tot = rbind(df_compare_cor_tot, df_compare_cor)} kable(df_compare_cor_tot) print(unique(unlist(lapply(strsplit(unique(kelley_df_brain$cell)[-c(1, 2, 3, 4)], "_"), "[[", 1)))) str(markers_df_brain) ct_res = findCells(aba_marker_expression, markers = markers_df_brain, nMarker = 50) kable(head(ct_res)) brain_cells_adjusted = adjustBrainCells(aba_marker_expression, nMarker = 50, species = "combined") expression_data_adj = brain_cells_adjusted$expression cor.test(as.numeric(aba_marker_expression["AIF1", ]), as.numeric(aba_pheno_data$ihc_iba1_ffpe), method = "spearman") cor.test(expression_data_adj["AIF1", ], as.numeric(aba_pheno_data$ihc_iba1_ffpe), method = "spearman") cor.test(as.numeric(aba_marker_expression["GFAP", ]), as.numeric(aba_pheno_data$ihc_gfap_ffpe), method = "spearman") cor.test(expression_data_adj["GFAP", ], as.numeric(aba_pheno_data$ihc_gfap_ffpe), method = "spearman")
FixVerbs <- function(texts,Context){ preper <- c("\u0627\u0645", "\u0627\u06CC", "\u0627\u0633\u062A", "\u0627\u06CC\u0645", "\u0627\u06CC\u062F", "\u0627\u0646\u062F") pasper <- c("\u0628\u0648\u062F\u0645", "\u0628\u0648\u062F\u06CC", "\u0628\u0648\u062F", "\u0628\u0648\u062F\u06CC\u0645", "\u0628\u0648\u062F\u06CC\u062F", "\u0628\u0648\u062F\u0646\u062F") passub <- c("\u0628\u0627\u0634\u0645", "\u0628\u0627\u0634\u06CC", "\u0628\u0627\u0634\u062F", "\u0628\u0627\u0634\u06CC\u0645", "\u0628\u0627\u0634\u06CC\u062F", "\u0628\u0627\u0634\u0646\u062F") sup <- c("\u0634\u062F\u0647", "\u0628\u0648\u062F\u0647") paslist <- c(preper, pasper, paste('\u0646\u0645\u06CC',pasper,sep=""), paste('\u0645\u06CC',pasper,sep=""), paste('\u0646',pasper,sep=""), passub, paste('\u0646\u0645\u06CC',passub,sep=""), paste('\u0645\u06CC',passub,sep=""), paste('\u0646',passub,sep=""), sup, paste('\u0646\u0645\u06CC',sup,sep=""), paste('\u0645\u06CC',sup,sep=""), paste('\u0646',sup,sep="")) paslistneg <- c(paste('\u0646\u0645\u06CC',pasper,sep=""), paste('\u0646',pasper,sep=""), paste('\u0646\u0645\u06CC',passub,sep=""), paste('\u0646',passub,sep=""), paste('\u0646\u0645\u06CC',sup,sep=""), paste('\u0646',sup,sep="")) paspersupnegpro <- c(paste('\u0646\u0645\u06CC',pasper,sep=""), paste('\u0646\u0645\u06CC',sup,sep="")) futurepossin <- c("\u062E\u0648\u0627\u0647\u0645", "\u062E\u0648\u0627\u0647\u06CC", "\u062E\u0648\u0627\u0647\u062F") futureposplu <- c("\u062E\u0648\u0627\u0647\u06CC\u0645", "\u062E\u0648\u0627\u0647\u06CC\u062F", "\u062E\u0648\u0627\u0647\u0646\u062F") futurepos <- c(futurepossin,futureposplu) futureneg <- paste('\u0646',futurepos,sep="") future <- c(futurepos,futureneg) futureposprogsin <- paste('\u0645\u06CC',futurepossin,sep="") futureposprogplu <- paste('\u0645\u06CC',futureposplu,sep="") futureposprog <- paste('\u0645\u06CC',futurepos,sep="") futurenegprogsin <- paste('\u0646',futureposprogsin,sep="") futurenegprogplu <- paste('\u0646',futureposprogplu,sep="") futurenegprog <- paste('\u0646',futureposprog,sep="") futureprog <- c(futureposprog,futurenegprog) pressinsuf <- c("\u0645","\u06CC","\u062F") presplusuf <- c("\u06CC\u0645","\u06CC\u062F","\u0646\u062F") simprepasspos <- c("\u0634\u0648\u0645", "\u0634\u0648\u06CC", "\u0634\u0648\u062F", "\u0634\u0648\u06CC\u0645", "\u0634\u0648\u06CC\u062F", "\u0634\u0648\u0646\u062F") simprepassneg <- paste('\u0646',simprepasspos,sep="") simprepass <- c(simprepasspos,simprepassneg) proprepasspos <- paste('\u0645\u06CC',simprepasspos,sep="") proprepassneg <- paste('\u0646',proprepasspos,sep="") proprepass <- c(proprepasspos,proprepassneg) simpaspasspos <- c("\u0634\u062F\u0645", "\u0634\u062F\u06CC", "\u0634\u062F", "\u0634\u062F\u06CC\u0645", "\u0634\u062F\u06CC\u062F", "\u0634\u062F\u0646\u062F") simpaspassneg <- paste('\u0646',simpaspasspos,sep="") simpaspass <- c(simpaspasspos,simpaspassneg) propaspasspos <- paste('\u0645\u06CC',simpaspasspos,sep="") propaspassneg <- paste('\u0646',propaspasspos,sep="") propaspass <- c(propaspasspos,propaspassneg) pass <- c(simprepass,proprepass,simpaspass,propaspass) suppresinpro <- c("\u062F\u0627\u0631\u0645", "\u062F\u0627\u0631\u06CC", "\u062F\u0627\u0631\u062F") suppreplupro <- c("\u062F\u0627\u0631\u06CC\u0645", "\u062F\u0627\u0631\u06CC\u062F", "\u062F\u0627\u0631\u0646\u062F") supprepro <- c(suppresinpro, suppreplupro) suppassinpro <- c("\u062F\u0627\u0634\u062A\u0645", "\u062F\u0627\u0634\u062A\u06CC", "\u062F\u0627\u0634\u062A") suppasplupro <- c("\u062F\u0627\u0634\u062A\u06CC\u0645", "\u062F\u0627\u0634\u062A\u06CC\u062F", "\u062F\u0627\u0634\u062A\u0646\u062F") suppaspro <- c(suppassinpro, suppasplupro) NoStemVerb <- c('\u0647\u0645\u0647', '\u0639\u062F\u0647', '\u0646\u0627\u0645\u0647', '\u0645\u06CC\u0644\u0627\u062F\u06CC') textsSplit <- strsplit(texts," ")[[1]] for(i in 1:length(textsSplit)){ if(textsSplit[i] == '\u0646\u0645\u06CC'){ textsSplit[i] <- "" textsSplit[i+1] <- paste('\u0646\u0645\u06CC', textsSplit[i+1], sep="")} if(textsSplit[i] == '\u0645\u06CC'){ textsSplit[i] <- "" textsSplit[i+1] <- paste('\u0645\u06CC', textsSplit[i+1], sep="")} } texts <- paste(textsSplit, collapse=" ") texts <- trim(gsub(" {2,}"," ", texts)) textsSplit <- strsplit(texts," ")[[1]] for(i in 1:length(textsSplit)){ word1 <- textsSplit[i] word2 <- textsSplit[i+1] word3 <- textsSplit[i+2] word4 <- textsSplit[i+3] word1str <- strsplit(word1,"")[[1]] word2str <- strsplit(word2,"")[[1]] word3str <- strsplit(word3,"")[[1]] if (!(word1 %in% NoStemVerb) & (word4 %in% paslist) & (word3 %in% paslist) & (word2 %in% paslist)){ if(length(word1str) >= 3){ if(word1str[length(word1str)] == '\u0647'){ word1str[length(word1str)] <- "" if(paste(word1str[1:3],collapse="") == '\u0646\u0645\u06CC'){word1str[2:3] <- ""} if(paste(word1str[1:2],collapse="") == '\u0645\u06CC'){word1str[1:2] <- ""} Test <- paste0("^(|\u0646\u0645\u06CC|\u0645\u06CC|\u0646)",paste0(word1str,collapse=""),"(|\u0646|\u0645|\u06CC|\u06CC\u0645|\u06CC\u062F|\u0646\u062F)$") PWord <- paste0(word1str,collapse="") PWord <- paste(PWord,"\u0030",sep="") if((word2 %in% paslistneg) | (word3 %in% paslistneg)){PWord <- paste("\u0646",PWord,sep="")} if(Context){if(TRUE %in% grepl(Test, textsSplit)){textsSplit[i] <- PWord}} if(!Context){textsSplit[i] <- PWord} textsSplit[i+1] <- "" textsSplit[i+2] <- "" textsSplit[i+3] <- "" next } } } if (!(word1 %in% NoStemVerb) & (word3 %in% paslist) & (word2 %in% paslist)){ if(length(word1str) >= 3){ if(word1str[length(word1str)] == '\u0647'){ word1str[length(word1str)] <- "" if(paste(word1str[1:3],collapse="") == '\u0646\u0645\u06CC'){word1str[2:3] <- ""} if(paste(word1str[1:2],collapse="") == '\u0645\u06CC'){word1str[1:2] <- ""} Test <- paste0("^(|\u0646\u0645\u06CC|\u0645\u06CC|\u0646)",paste0(word1str,collapse=""),"(|\u0646|\u0645|\u06CC|\u06CC\u0645|\u06CC\u062F|\u0646\u062F)$") PWord <- paste0(word1str,collapse="") PWord <- paste(PWord,"\u0030",sep="") if((word2 %in% paslistneg) | (word3 %in% paslistneg)){PWord <- paste("\u0646",PWord,sep="")} if(Context){if(TRUE %in% grepl(Test, textsSplit)){textsSplit[i] <- PWord}} if(!Context){textsSplit[i] <- PWord} textsSplit[i+1] <- "" textsSplit[i+2] <- "" next } } } if (!(word1 %in% NoStemVerb) & (word3 %in% c("\u0634\u062F", "\u0646\u0634\u062F")) & (word2 %in% future)){ if(length(word1str) >= 3){ if(word1str[length(word1str)] == '\u0647'){ word1str[length(word1str)] <- "" Test <- paste0("^(|\u0646\u0645\u06CC|\u0645\u06CC|\u0646)",paste0(word1str,collapse=""),"(|\u0646|\u0645|\u06CC|\u06CC\u0645|\u06CC\u062F|\u0646\u062F)$") PWord <- paste0(word1str,collapse="") PWord <- paste(PWord,"\u0030",sep="") if((word2 %in% futureneg) | (word3 == "\u0646\u0634\u062F")){PWord <- paste("\u0646",PWord,sep="")} if(Context){if(TRUE %in% grepl(Test, textsSplit)){textsSplit[i] <- PWord}} if(!Context){textsSplit[i] <- PWord} textsSplit[i+1] <- "" textsSplit[i+2] <- "" next } } } if (!(word2 %in% NoStemVerb) & (word1 %in% c(supprepro,suppaspro)) & (word3 %in% c(proprepass, propaspass))){ if(length(word2str) >= 3){ if(word2str[length(word2str)] == '\u0647'){ word2str[length(word2str)] <- "" Test <- paste0("^(|\u0646\u0645\u06CC|\u0645\u06CC|\u0646)",paste0(word2str,collapse=""),"(|\u0646|\u0645|\u06CC|\u06CC\u0645|\u06CC\u062F|\u0646\u062F)$") PWord <- paste0(word2str,collapse="") PWord <- paste(PWord,"\u0030",sep="") if(word3 %in% c(proprepassneg,propaspassneg)){PWord <- paste("\u0646",PWord,sep="")} if(Context){if(TRUE %in% grepl(Test, textsSplit)){textsSplit[i+1] <- PWord}} if(!Context){textsSplit[i+1] <- PWord} textsSplit[i] <- "" textsSplit[i+2] <- "" next } } } if (word1 %in% supprepro){ if((paste(word2str[1:2],collapse="") == '\u0645\u06CC')|(paste(word2str[1:3],collapse="") == '\u0646\u0645\u06CC')){ pre <- word2str[1] if(paste(word2str[1:3],collapse="") == '\u0646\u0645\u06CC'){word2str[1:3] <- ""} if(paste(word2str[1:2],collapse="") == '\u0645\u06CC'){word2str[1:2] <- ""} if (word1 %in% suppresinpro){word2str[length(word2str)]<-""} if (word1 %in% suppreplupro){word2str[(length(word2str)-1):length(word2str)] <-""} textsSplit[i] <- "" textsSplit[i+1] <- paste(word2str,collapse="") if(pre=="\u0646"){textsSplit[i+1] <- paste("\u0646",textsSplit[i+1],sep="")} textsSplit[i+1] <- paste(textsSplit[i+1],"\u0031",sep="") next } } if (word1 %in% suppaspro){ if((paste(word2str[1:2],collapse="") == '\u0645\u06CC')|(paste(word2str[1:3],collapse="") == '\u0646\u0645\u06CC')){ pre <- word2str[1] if(paste(word2str[1:3],collapse="") == '\u0646\u0645\u06CC'){word2str[1:3] <- ""} if(paste(word2str[1:2],collapse="") == '\u0645\u06CC'){word2str[1:2] <- ""} if ((word1 %in% suppassinpro) & (word1 != "\u062F\u0627\u0634\u062A")){word2str[length(word2str)]<-""} if (word1 %in% suppasplupro){word2str[(length(word2str)-1):length(word2str)] <-""} textsSplit[i] <- "" textsSplit[i+1] <- paste(word2str,collapse="") if(pre=="\u0646"){textsSplit[i+1] <- paste("\u0646",textsSplit[i+1],sep="")} textsSplit[i+1] <- paste(textsSplit[i+1],"\u0030",sep="") next } } if (!(word1 %in% NoStemVerb) & (word2 %in% paslist)){ if(length(word1str) >= 3){ if(word1str[length(word1str)] == '\u0647'){ word1str[length(word1str)] <- "" if(paste(word1str[1:3],collapse="") == '\u0646\u0645\u06CC'){word1str[2:3] <- ""} if(paste(word1str[1:2],collapse="") == '\u0645\u06CC'){word1str[1:2] <- ""} Test <- paste0("^(|\u0646\u0645\u06CC|\u0645\u06CC|\u0646)",paste0(word1str,collapse=""),"(|\u0646|\u0645|\u06CC|\u06CC\u0645|\u06CC\u062F|\u0646\u062F)$") PWord <- paste0(word1str,collapse="") PWord <- paste(PWord,"\u0030",sep="") if(word2 %in% paslistneg){PWord <- paste("\u0646",PWord,sep="")} if(Context){if(TRUE %in% grepl(Test, textsSplit)){textsSplit[i] <- PWord}} if(!Context){textsSplit[i] <- PWord} textsSplit[i+1] <- "" next } } } if (!(word1 %in% NoStemVerb) & (word2 %in% pass)){ if(length(word1str) >= 3){ if(word1str[length(word1str)] == '\u0647'){ word1str[length(word1str)] <- "" if(paste(word1str[1:3],collapse="") == '\u0646\u0645\u06CC'){word1str[2:3] <- ""} if(paste(word1str[1:2],collapse="") == '\u0645\u06CC'){word1str[1:2] <- ""} Test <- paste0("^(|\u0646\u0645\u06CC|\u0645\u06CC|\u0646)",paste0(word1str,collapse=""),"(|\u0646|\u0645|\u06CC|\u06CC\u0645|\u06CC\u062F|\u0646\u062F)$") PWord <- paste0(word1str,collapse="") PWord <- paste(PWord,"\u0030",sep="") if ((word2 %in% c(proprepassneg,propaspassneg,simprepassneg,simpaspassneg))){PWord <- paste("\u0646",PWord,sep="")} if(Context){if(TRUE %in% grepl(Test, textsSplit)){textsSplit[i] <- PWord}} if(!Context){textsSplit[i] <- PWord} textsSplit[i+1] <- "" next } } } if (word1 %in% future){ if(length(word2str) >= 2){ textsSplit[i] <- paste(word2str,collapse="") if(word1 %in% futureneg){textsSplit[i] <- paste("\u0646",textsSplit[i],sep="")} textsSplit[i] <- paste(textsSplit[i],"\u0030",sep="") textsSplit[i+1] <- "" next } } if (word1 %in% futureprog){ if(length(word2str) >= 3){ if(word2str[1] %in% c("\u0628","\u0646")){ if((word2str[length(word2str)] %in% pressinsuf) | (paste(word2str[(length(word2str)-1):length(word2str)],collapse="") %in% presplusuf)){ if(word1 %in% c(futureposprogplu,futurenegprogplu)){word2str[(length(word2str)-1):length(word2str)] <-""} if(word1 %in% c(futureposprogsin,futurenegprogsin)){word2str[length(word2str)]<-""} pre <- word2str[1] word2str[1] <- "" textsSplit[i+1] <- paste(word2str,collapse="") if((word1 %in% futurenegprog) | (pre=="\u0646")){textsSplit[i+1] <- paste("\u0646",textsSplit[i+1],sep="")} textsSplit[i] <- "" textsSplit[i+1] <- paste(textsSplit[i+1],"\u0031",sep="") next } } } } if(!(word1 %in% NoStemVerb) & length(word1str) >= 4){ if((paste(word1str[1:2],collapse="") == '\u0645\u06CC')|(paste(word1str[1:3],collapse="") == '\u0646\u0645\u06CC')){ if((word1str[length(word1str)] %in% pressinsuf) | (paste(word1str[(length(word1str)-1):length(word1str)],collapse="") %in% presplusuf)){ pre <- word1str[1] if(paste(word1str[1:2],collapse="") == '\u0645\u06CC'){word1str <- word1str[3:length(word1str)]} if(paste(word1str[1:3],collapse="") == '\u0646\u0645\u06CC'){word1str <- word1str[4:length(word1str)]} if((length(word1str)>2) & paste(word1str[(length(word1str)-1):length(word1str)],collapse="") %in% presplusuf){ if (!(word1str[(length(word1str)-2)] %in% c("\u0627", "\u0648")) & (length(word1str) > 3)){word1str[(length(word1str)-1):length(word1str)] <-""}} if((word1str[length(word1str)] %in% pressinsuf) & (word1str[length(word1str)] !="\u062F")){word1str[length(word1str)]<-""} if(word1str[length(word1str)]=="\u062F"){word1str[length(word1str)]<-"\u062F\u0034"} textsSplit[i] <- paste(word1str,collapse="") if(pre=="\u0646"){textsSplit[i] <- paste("\u0646",textsSplit[i],sep="")} textsSplit[i] <- paste(textsSplit[i],"\u0032",sep="") next } } } } preroot <- grep("\u0031$|\u0032$",textsSplit, value = TRUE) preroot <- c(unique(gsub("\u0031$|\u0032$|\u0034\u0032$","",preroot))) preroot <- unique(c(preroot, gsub("^\u06CC\u0627","\u0622",preroot), gsub("^\u0622","\u06CC\u0627",preroot), gsub("^\u0622","\u0627",preroot), gsub("^\u0627","\u0622",preroot), gsub("^\u06CC\u0627!","\u0627",preroot), gsub("^\u0646\u0622","\u0646\u06CC\u0627",preroot), gsub("^\u0646\u0627","\u0646\u06CC\u0627",preroot))) prerootpos <- unique(c(preroot[!grepl("^\u0646",preroot)],gsub("^\u0646","",grep("^\u0646\u0646",preroot, value =TRUE)))) prerootneg <- preroot[grepl("^\u0646",preroot)] pasroot <- grep(("\u0030$|\u0032$"),textsSplit, value = TRUE) pasroot <- c(unique(gsub("|\u0030$|\u0032$|\u0034\u0032$","",pasroot))) pasroot <- unique(c(pasroot, gsub("^\u06CC\u0627","\u0622",pasroot), gsub("^\u0622","\u06CC\u0627",pasroot), gsub("^\u0622","\u0627",pasroot), gsub("^\u0627","\u0622",pasroot), gsub("^\u06CC\u0627!","\u0627",pasroot), gsub("^\u0646\u0622","\u0646\u06CC\u0627",pasroot), gsub("^\u0646\u0627","\u0646\u06CC\u0627",pasroot))) pasrootpos <- unique(c(pasroot[!grepl("^\u0646",pasroot)],gsub("^\u0646","",grep("^\u0646\u0646",pasroot, value =TRUE)))) pasrootneg <- pasroot[grepl("^\u0646",pasroot)] if(length(prerootpos)>0){ for (i in 1:length(prerootpos)){ if(grepl("^\u0627",prerootpos[i])==TRUE){ preverbpos1 <- paste0("^(|\u0628\u06CC)",prerootpos[i],"(|\u0645|\u06CC|\u062F|\u06CC\u0645|\u06CC\u062F|\u0646\u062F)$") preverbneg1 <- paste0("^\u0646\u06CC",prerootpos[i],"(|\u0645|\u06CC|\u062F|\u06CC\u0645|\u06CC\u062F|\u0646\u062F)$") textsSplit <- gsub(preverbpos1,paste0(prerootpos[i],"\u0033"),textsSplit) textsSplit <- gsub(preverbneg1,paste0("\u0646\u06CC",prerootpos[i],"\u0033"),textsSplit) }else{ preverbpos1 <- paste0("^(|\u0628)",prerootpos[i],"(|\u0645|\u06CC|\u062F|\u06CC\u0645|\u06CC\u062F|\u0646\u062F)$") preverbneg1 <- paste0("^\u0646",prerootpos[i],"(|\u0645|\u06CC|\u062F|\u06CC\u0645|\u06CC\u062F|\u0646\u062F)$") textsSplit <- gsub(preverbpos1,paste0(prerootpos[i],"\u0033"),textsSplit) textsSplit <- gsub(preverbneg1,paste0("\u0646",prerootpos[i],"\u0033"),textsSplit) } } } if(length(prerootneg)>0){ for (i in 1:length(prerootneg)){ if(grepl("^\u0627",prerootneg[i])==TRUE){ preverbpos2 <- paste0("^(|\u0628\u06CC)",prerootneg[i],"(|\u0645|\u06CC|\u062F|\u06CC\u0645|\u06CC\u062F|\u0646\u062F)$") preverbneg2 <- paste0("^\u0646\u06CC",prerootneg[i],"(|\u0645|\u06CC|\u062F|\u06CC\u0645|\u06CC\u062F|\u0646\u062F)$") textsSplit <- gsub(preverbpos2,paste0(prerootneg[i],"\u0033"),textsSplit) textsSplit <- gsub(preverbneg2,paste0("\u0646\u06CC",prerootneg[i],"\u0033"),textsSplit) }else{ preverbpos2 <- paste0("^(|\u0628)",prerootneg[i],"(|\u0645|\u06CC|\u062F|\u06CC\u0645|\u06CC\u062F|\u0646\u062F)$") preverbneg2 <- paste0("^\u0646",prerootneg[i],"(|\u0645|\u06CC|\u062F|\u06CC\u0645|\u06CC\u062F|\u0646\u062F)$") textsSplit <- gsub(preverbpos2,paste0(prerootneg[i],"\u0033"),textsSplit) textsSplit <- gsub(preverbneg2,paste0("\u0646",prerootneg[i],"\u0033"),textsSplit) } } } if(length(pasrootpos)>0){ for (i in 1:length(pasrootpos)){ if(grepl("^\u0627",pasrootpos[i])==TRUE){ pasverbpos1 <- paste0("^(|\u0645\u06CC)",pasrootpos[i],"(|\u0646|\u0645|\u06CC|\u062F|\u06CC\u0645|\u06CC\u062F|\u0646\u062F)$") pasverbneg1 <- paste0("^(\u0646\u06CC|\u0646\u0645\u06CC)",pasrootpos[i],"(|\u0646|\u0645|\u06CC|\u062F|\u06CC\u0645|\u06CC\u062F|\u0646\u062F)$") textsSplit <- gsub(pasverbpos1,paste0(pasrootpos[i],"\u0033"),textsSplit) textsSplit <- gsub(pasverbneg1,paste0("\u0646\u06CC",pasrootpos[i],"\u0033"),textsSplit) }else{ pasverbpos1 <- paste0("^(|\u0645\u06CC)",pasrootpos[i],"(|\u0646|\u0645|\u06CC|\u062F|\u06CC\u0645|\u06CC\u062F|\u0646\u062F)$") pasverbneg1 <- paste0("^(\u0646|\u0646\u0645\u06CC)",pasrootpos[i],"(|\u0646|\u0645|\u06CC|\u062F|\u06CC\u0645|\u06CC\u062F|\u0646\u062F)$") textsSplit <- gsub(pasverbpos1,paste0(pasrootpos[i],"\u0033"),textsSplit) textsSplit <- gsub(pasverbneg1,paste0("\u0646",pasrootpos[i],"\u0033"),textsSplit) } } } if(length(pasrootneg)>0){ for (i in 1:length(pasrootneg)){ if(grepl("^\u0627",pasrootpos[i])==TRUE){ pasverbpos2 <- paste0("^(|\u0645\u06CC)",pasrootneg[i],"(|\u0646|\u0645|\u06CC|\u062F|\u06CC\u0645|\u06CC\u062F|\u0646\u062F)$") pasverbneg2 <- paste0("^(\u0646\u06CC|\u0646\u0645\u06CC)",pasrootneg[i],"(|\u0646|\u0645|\u06CC|\u062F|\u06CC\u0645|\u06CC\u062F|\u0646\u062F)$") textsSplit <- gsub(pasverbpos2,paste0(pasrootneg[i],"\u0033"),textsSplit) textsSplit <- gsub(pasverbneg2,paste0("\u0646\u06CC",pasrootneg[i],"\u0033"),textsSplit) }else{ pasverbpos2 <- paste0("^(|\u0645\u06CC)",pasrootneg[i],"(|\u0646|\u0645|\u06CC|\u062F|\u06CC\u0645|\u06CC\u062F|\u0646\u062F)$") pasverbneg2 <- paste0("^(\u0646|\u0646\u0645\u06CC)",pasrootneg[i],"(|\u0646|\u0645|\u06CC|\u062F|\u06CC\u0645|\u06CC\u062F|\u0646\u062F)$") textsSplit <- gsub(pasverbpos2,paste0(pasrootneg[i],"\u0033"),textsSplit) textsSplit <- gsub(pasverbneg2,paste0("\u0646",pasrootneg[i],"\u0033"),textsSplit) } } } yaA <- grep("\u0030$|\u0031$|\u0032$|\u0033$",textsSplit, value = TRUE) yaA <- gsub("\u0030$|\u0031$|\u0032$|\u0034\u0032$|\u0033$","",yaA) y <- unique(grep("^\u06CC\u0627|^\u06CC",yaA, value = TRUE)) a <- unique(grep("^\u0627",yaA, value = TRUE)) A <- unique(grep("^\u0622",yaA, value = TRUE)) for (i in 1:length(y)){ if (length(gsub("^\u06CC\u0627","\u0622", y[i]))>0){ if (gsub("^\u06CC\u0627","\u0622", y[i]) %in% A){ v1 <- gsub("^\u06CC\u0627","\u0622", y[i]) v2 <- paste0(v1,"(|\u0645|\u06CC|\u062F|\u06CC\u0645|\u06CC\u062F|\u0646\u062F)$") textsSplit <- gsub(paste0("^",y[i],"(\u0030|\u0031|\u0032|\u0034\u0032|\u0033)$"),paste0(v1,"\u0035"),textsSplit) textsSplit <- gsub(v2,paste0(v1,"\u0035"),textsSplit); next}}; if (length(gsub("^\u06CC","\u0627", y[i]))>0){ if (gsub("^\u06CC","\u0627", y[i]) %in% a){ v1 <- gsub("^\u06CC","\u0627", y[i]) v2 <- paste0(v1,"(|\u0645|\u06CC|\u062F|\u06CC\u0645|\u06CC\u062F|\u0646\u062F)$") textsSplit <- gsub(paste0("^",y[i],"(\u0030|\u0031|\u0032|\u0034\u0032|\u0033)$"),paste0(v1,"\u0035"),textsSplit) textsSplit <- gsub(v2,paste0(v1,"\u0035"),textsSplit); next}} } for (i in 1:length(a)){ if (length(gsub("^\u0627","\u0622", a[i]))>0){ if (gsub("^\u0627","\u0622", a[i]) %in% A){ v1 <- gsub("^\u0627","\u0622", a[i]) v2 <- paste0(v1,"(|\u0645|\u06CC|\u062F|\u06CC\u0645|\u06CC\u062F|\u0646\u062F)$") textsSplit <- gsub(paste0("^",a[i],"(\u0030|\u0031|\u0032|\u0034\u0032|\u0033)$"),paste0(v1,"\u0035"),textsSplit) textsSplit <- gsub(v2,paste0(v1,"\u0035"),textsSplit); next}}; if (length(gsub("^\u0627","\u06CC\u0627", a[i]))>0){ if (gsub("^\u0627","\u06CC\u0627", a[i]) %in% y){ v1 <- gsub("^\u0627","\u06CC\u0627", a[i]) v2 <- paste0(v1,"(|\u0645|\u06CC|\u062F|\u06CC\u0645|\u06CC\u062F|\u0646\u062F)$") textsSplit <- gsub(paste0("^",a[i],"(\u0030|\u0031|\u0032|\u0034\u0032|\u0033)$"),paste0(v1,"\u0035"),textsSplit) textsSplit <- gsub(v2,paste0(v1,"\u0035"),textsSplit); next}} } textsSplit <- gsub("^\u0646\u0622","\u0646\u06CC\u0627",textsSplit) texts <- paste(textsSplit, collapse=" ") texts <- trim(gsub(" {2,}"," ", texts)) return(texts) }
wiki_didyouknow <- function(n_facts = 1L, date = sample(seq(as.Date("2015-01-01"), Sys.Date() - 1, by = "day"), 1), bare_fact = FALSE) { locale <- Sys.getlocale("LC_TIME") if (.Platform$OS.type == "windows") { invisible(Sys.setlocale("LC_TIME", "English")) } else { invisible(Sys.setlocale("LC_TIME", "en_US.UTF-8")) } date <- as.Date(date) date1 <- format(date, "%Y_%B_") date2 <- gsub("^0+", "", format(date, "%d")) date_str <- paste0(date1, date2) invisible(Sys.setlocale("LC_TIME", locale)) input <- paste0("https://en.wikipedia.org/wiki/Wikipedia:Main_Page_history/", date_str) tryCatch({ input <- url(input, "rb") wiki_page <- xml2::read_html(input, fill = TRUE) close(input) dyk <- wiki_page %>% rvest::html_nodes(xpath = '//*[@id="mp-dyk"]') %>% rvest::html_nodes("li") %>% rvest::html_text() %>% subset(grepl("... that", .)) n <- min(n_facts, length(dyk)) dyk <- dyk[grepl("... that", dyk)] %>% sample(n) if (bare_fact == TRUE) { dyk } else { paste0("Did you know ", gsub("\\.\\.\\. ", "", dyk), " (Courtesy of Wikipedia)") } }, error = function (e) {"I got nothin'"}, warning = function (w) {"I got nothin'"}) }
"terms_sources"
"ITI2017" <- Vectorize(function(income, category=1) { if (income < 0) stop("Error: Income must be > 0.") if (category == 1){ if (income <= 300000) {return(0)} if (income > 300000 && income <= 500000) { TI <- income - 300000 IT <- TI*0.10 EC <- IT*0.03 return(IT+EC)} if (income > 500000 && income <= 1000000) { TI <- income - 500000 IT <- (TI*0.20) + 25000 EC <- IT*0.03 return(IT+EC)} if (income > 1000000 && income <= 10000000) { TI <- income - 1000000 IT <- (TI*0.30) + 125000 EC <- IT*0.03 return(IT+EC)} if (income > 10000000) { TI <- income - 1000000 IT <- (TI*0.30) + 125000 SC <- IT*0.15 MR <- if((income-10000000) < SC) (SC-((income-10000000)-(income-10000000)*.30))else(0) NSC <- SC-MR EC <- (IT+NSC)*0.03 return(IT+NSC+EC)} } if (category == 2){ if (income <= 350000) {return(0)} if (income > 350000 && income <= 500000) { TI <- income - 350000 IT <- TI*0.10 EC <- IT*0.03 return(IT+EC)} if (income > 500000 && income <= 1000000) { TI <- income - 500000 IT <- (TI*0.20) + 20000 EC <- IT*0.03 return(IT+EC)} if (income > 1000000 && income <= 10000000) { TI <- income - 1000000 IT <- (TI*0.30) + 120000 EC <- IT*0.03 return(IT+EC)} if (income > 10000000) { TI <- income - 1000000 IT <- (TI*0.30) + 120000 SC <- IT*0.15 MR <- if((income-10000000) < SC) (SC-((income-10000000)-(income-10000000)*.30))else(0) NSC <- SC-MR EC <- (IT+NSC)*0.03 return(IT+NSC+EC)} } if (category == 3){ if (income <= 500000) {return(0)} if (income > 500000 && income <= 1000000) { TI <- income - 500000 IT <- (TI*0.20) EC <- IT*0.03 return(IT+EC)} if (income > 1000000 && income <= 10000000) { TI <- income - 1000000 IT <- (TI*0.30) + 100000 EC <- IT*0.03 return(IT+EC)} if (income > 10000000) { TI <- income - 1000000 IT <- (TI*0.30) + 100000 SC <- IT*0.15 MR <- if((income-10000000) < SC) (SC-((income-10000000)-(income-10000000)*.30))else(0) NSC <- SC-MR EC <- (IT+NSC)*0.03 return(IT+NSC+EC)} } if (category == 4){ if (income <= 250000) {return(0)} if (income > 250000 && income <= 500000) { TI <- income - 300000 IT <- TI*0.10 EC <- IT*0.03 return(IT+EC)} if (income > 500000 && income <= 1000000) { TI <- income - 500000 IT <- (TI*0.20) + 25000 EC <- IT*0.03 return(IT+EC)} if (income > 1000000 && income <= 10000000) { TI <- income - 1000000 IT <- (TI*0.30) + 125000 EC <- IT*0.03 return(IT+EC)} if (income > 10000000) { TI <- income - 1000000 IT <- (TI*0.30) + 125000 SC <- IT*0.15 MR <- if((income-10000000) < SC) (SC-((income-10000000)-(income-10000000)*.30))else(0) NSC <- SC-MR EC <- (IT+NSC)*0.03 return(IT+NSC+EC)} } if (category == 5){ if (income > 0 && income <= 10000) { TI <- income IT <- TI*0.10 EC <- IT*0.03 return(IT+EC)} if (income > 10000 && income <= 20000) { TI <- income-10000 IT <- (TI*0.20) + 1000 EC <- IT*0.03 return(IT+EC)} if (income > 20000 && income <= 10000000) { TI <- income-20000 IT <- (TI*0.30) + 3000 EC <- IT*0.03 return(IT+EC)} if (income > 10000000) { TI <- income-20000 IT <- (TI*0.30) + 3000 SC <- IT*0.12 MR <- if((income-10000000) < SC) (SC-((income-10000000)-(income-10000000)*.30))else(0) NSC <- SC-MR EC <- (IT+NSC)*0.03 return(IT+NSC+EC)} } if (category == 6){ if (income > 0 && income <= 10000000) { TI <- income IT <- (TI*0.30) EC <- IT*0.03 return(IT+EC)} if (income > 10000000) { TI <- income IT <- (TI*0.30) SC <- IT*0.12 MR <- if((income-10000000) < SC) (SC-((income-10000000)-(income-10000000)*.30))else(0) NSC <- SC-MR EC <- (IT+NSC)*0.03 return(IT+NSC+EC)} } stop("ERROR in IIT: category must be either 1 to 6.") })
linearProductionGame <- function(c, A, B, plot=FALSE, show.data=FALSE){ coa <- coalitions(dim(B)[2]) coa1 <- coa$Binary coa2 <- coa$Usual juego <- data.frame(0) colnames(juego) <- c("S={0}") barx <- data.frame() plots <- list() for (i in 2:dim(coa1)[1]){ pos<-which(coa1[i,]!=0) if(length(pos)==1){ bs <- B[,pos] }else{ bs <- apply(B[,pos],1,sum) } prod <- makeLP(c, A, bs) juego[i] <- get.objective(prod) colnames(juego)[i] <- paste0("S={", paste0(strsplit(as.character(coa2[i]), split = "")[[1]], collapse = ","),"}") barx <- rbind(barx, get.variables(prod)) rownames(barx)[i-1] <- paste0("S={", paste0(strsplit(as.character(coa2[i]), split = "")[[1]], collapse = ","),"}") if (plot==T){ plots[[i-1]] <- plotlm(prod, A, bs, c, coa2[i]) } } if(plot==TRUE){ numPlots = length(plots) layout <- matrix(seq(1, 2 * ceiling(numPlots/2)), ncol = 2, nrow = ceiling(numPlots/2), byrow = TRUE) grid.newpage() pushViewport(viewport(layout = grid.layout(nrow(layout), ncol(layout)))) for (i in 1:numPlots) { matchidx <- as.data.frame(which(layout == i, arr.ind = TRUE)) print(plots[[i]], vp = viewport(layout.pos.row = matchidx$row, layout.pos.col = matchidx$col)) } } rownames(juego) <- c("Associated game") colnames(barx) <- rep("", ncol(barx)) if(show.data){ cat(" ------------------------------------------------------------------------\n") cat(" Optimal solution of the problem for each coalition: \n") cat(" ------------------------------------------------------------------------\n") print(round(barx,2)) cat("\n") cat(" ------------------------------------------------------------------------\n") cat(" Cooperative production game: \n") cat(" ------------------------------------------------------------------------\n") print(juego) cat(" ------------------------------------------------------------------------\n") cat("\n") } invisible(list(Sol = round(barx,2), game = juego)) }
NULL weblm <- function(results = NULL, json = NULL, request = NULL) { if (!is.null(results)) stopifnot(is.data.frame(results)) if (!is.null(json)) stopifnot(is.character(json), length(json) == 1) if (!is.null(request)) stopifnot(class(request) == "request") structure(list(results = results, json = json, request = request), class = "weblm") } is.weblm <- function(x) { inherits(x, "weblm") } print.weblm <- function(x, ...) { cat("weblm [", x$request$url, "]\n", sep = "") aintNoVT100NoMo <- panderOptions("table.split.table") panderOptions("table.split.table", getOption("width")) pandoc.table(x$results) panderOptions("table.split.table", aintNoVT100NoMo) }
tobin5 <- function(mdf, y, f = NULL) { if(!is(mdf, "missing_data.frame")) stop("'mdf' must be a 'missing_data.frame'") if(!is.character(y)) stop("'y' must be a character string") if(length(y) != 1) stop("'y' must have length one") if(!(y %in% colnames(mdf))) stop("'y' must be a variable in 'mdf'") y <- mdf@variables[[y]] NAs <- is.na(y) to_drop <- mdf@index[[y@variable_name]] X <- mdf@X[,-to_drop] probit <- bayesglm.fit(X, y = NAs, family = binomial(link = "probit")) class(probit) <- c("bayesglm", "glm", "lm") gamma <- coef(probit) IMR_0 <- dnorm(-fitted(probit)) / pnorm(-fitted(probit)) IMR_1 <- dnorm( fitted(probit)) / pnorm( fitted(probit)) if(is.null(f)) { mark <- colnames(mdf@X)[!grepl("^missing_", colnames(mdf@X))][-1] mark <- mark[mark != y@variable_name] f <- paste(mark, collapse = " + ") f <- paste(y@variable_name, " ~ ", f, " + IMR", sep = "") f <- as.formula(f) } else if(!is(f, "formula")) stop("'f' must be 'NULL' or a formula") df <- as.data.frame(cbind(mdf@X, IMR = IMR_0)) if(is(y, "continuous")) { model_0 <- bayesglm(f, family = gaussian, data = df, subset = !NAs) } else stop("only continuous dependent variables are supported at the moment") df <- as.data.frame(cbind(mdf@X, IMR = IMR_1)) if(is(y, "continuous")) { model_1 <- bayesglm(f, family = gaussian, data = df, subset = NAs) } se_0 <- model_0$dispersion se_1 <- model_1$dispersion delta_0 <- IMR_0^2 - fitted(probit) * IMR_0 delta_1 <- IMR_1^2 + fitted(probit) * IMR_1 betaL_0 <- coef(model_0) betaL_0 <- betaL_0[length(betaL_0)] betaL_1 <- coef(model_1) betaL_1 <- betaL_1[length(betaL_1)] sigma_0 <- sqrt(se_0^2 + (betaL_0 * delta_0)^2) sigma_1 <- sqrt(se_1^2 + (betaL_1 * delta_1)^2) rho_0 <- -betaL_0 / sigma_0 rho_1 <- betaL_1 / sigma_1 return(list(probit = probit, model_0 = model_0, model_1 = model_1, rho_0 = rho_0, rho_1 = rho_1)) } tobin5 <- function(imputations, y, f = NULL) { if(!is(imputations, "mi")) stop("'imputations' must be a 'mi' object") if(!is.character(y)) stop("'y' must be a character string") if(length(y) != 1) stop("'y' must have length one") if(!(y %in% colnames(imputations))) stop("'y' must be a variable in 'imputations'") dfs <- complete(imputations) mdf <- imputations@data[[1]] to_drop <- mdf@index[[y@variable_name]] cn <- colnames(mdf@X[,-to_drop])[-1] f1 <- paste(cn, collapse = " + ") NAs <- is.na(mdf@variables[[y]]) if(paste("missing", y, sep = "_") %in% colnames(mdf@X)) { f1 <- paste(paste("missing", y, sep = "_"), "~", f1) } else for(i in seq_along(dfs)) { dfs[[i]] <- cbind(dfs[[i]], NAs) colnames(dfs[[i]]) <- c(colnames(dfs[[i]]), paste("missing", y, sep = "_")) } f1 <- as.formula(f1) probit <- pool(f1, data = dfs, family = binomial(link = "probit")) gamma <- sapply(probit@models, coef) Pr <- sapply(probit@models, fitted) IMR_0 <- apply(Pr, 2, FUN = function(p) dnorm(-p) / pnorm(-p)) IMR_1 <- apply(Pr, 2, FUN = function(p) dnorm( p) / pnorm( p)) if(is.null(f)) { mark <- colnames(mdf@X)[!grepl("^missing_", colnames(mdf@X))][-1] mark <- mark[mark != y] f <- paste(mark, collapse = " + ") f <- paste(y@variable_name, " ~ ", f, " + IMR", sep = "") f <- as.formula(f) } else if(!is(f, "formula")) stop("'f' must be 'NULL' or a formula") if(!is(mdf@variables[[y]], "continuous")) { stop("only continuous dependent variables are supported at the moment") } for(i in seq_along(dfs)) dfs[[i]]$IMR <- IMR_0[,i] model_0 <- pool(f, data = dfs, family = gaussian, subset = !NAs) for(i in seq_along(dfs)) dfs[[i]]$IMR <- IMR_1[,i] model_1 <- pool(f, data = dfs, family = gaussian, subset = NAs) se_0 <- sapply(model_0@models, FUN = function(m) m$dispersion) se_1 <- sapply(model_1@models, FUN = function(m) m$dispersion) delta_0 <- IMR_0^2 - Pr * IMR_0 delta_1 <- IMR_1^2 + Pr * IMR_1 betaL_0 <- sapply(model_0@models, coef) betaL_0 <- betaL_0[nrow(betaL_0)] betaL_1 <- sapply(model_1@models, coef) betaL_1 <- betaL_1[nrow(betaL_1)] sigma_0 <- sqrt(se_0^2 + sweep(delta_0, 2, betaL_0, FUN = "*")^2) sigma_1 <- sqrt(se_1^2 + sweep(delta_1, 2, betaL_1, FUN = "*")^2) rho_0 <- -betaL_0 / sigma_0 rho_1 <- betaL_1 / sigma_1 return(list(probit = probit, model_0 = model_0, model_1 = model_1, rho_0 = rho_0, rho_1 = rho_1)) }
`make.cepnames` <- function (names, seconditem = FALSE) { names <- make.names(names, unique = FALSE) names <- gsub("\\.[\\.]+", ".", names) names <- gsub("\\.$", "", names) names <- lapply(strsplit(names, "\\."), function(x) if (length(x) > 1) substring(x, 1, 4) else x ) names <- unlist(lapply(names, function(x) if (length(x) > 1) paste(x[c(1, if(seconditem) 2 else length(x))], collapse = "") else x)) names <- abbreviate(names, 8) make.names(names, unique = TRUE) }
check_set_priors <- function(priors,M,R) { if (is.null(priors)) { priors <- vector("list",M) for (m in seq_len(M)) priors[[m]] <- list("cat",4) } if (!is.list(priors) || length(priors) != M) { stop("priors must be a list with one element for each column of x") } for (m in seq_len(M)) { if (!is.list(priors[[m]]) || length(priors[[m]]) == 0) { stop("each prior specification must be a list with at least one element") } else if (priors[[m]][[1]] == "cat") { if (length(priors[[m]]) != 2 || !is.numeric(priors[[m]][[2]]) || priors[[m]][[2]] <= 0) { stop("positive prior full conditional std. dev. must be specified") } priors[[m]][[3]] <- 1/priors[[m]][[2]]^2 names(priors[[m]]) <- c("type","sd","tau") } else if (priors[[m]][[1]] == "gmrf") { if (length(priors[[m]]) != 3 || priors[[m]][[2]] <= 2 || priors[[m]][[3]] <= 0) { stop(paste("prior degrees of freedom parameter greater than 2", "and positive scale parameter must be specified")) } priors[[m]][[4]] <- priors[[m]][[2]]/2 priors[[m]][[5]] <- priors[[m]][[2]]/2*priors[[m]][[3]] names(priors[[m]]) <- c("type","nu","s","a","b") } else if (priors[[m]][[1]] == "re") { if (length(priors[[m]]) != 3) { stop("must supply prior degrees of freedom and scale matrix") } if (!is.numeric(priors[[m]][[2]]) || priors[[m]][[2]] < R + 2) { stop("prior degrees of freedom must be at least R + 2") } if (!(is.matrix(priors[[m]][[3]]) && all(dim(priors[[m]][[3]]) == R) && isSymmetric(priors[[m]][[3]]) && all(eigen(priors[[m]][[3]],TRUE)$values > 0))) { stop("must supply positive-definite R x R prior scale matrix") } names(priors[[m]]) <- c("type","nu","s") } else if (priors[[m]][[1]] == "zero") { names(priors[[m]])[1] <- "type" } else stop("prior type must be cat, gmrf, re, or zero") } priors }
write_veg <- function(outfolder, start_date, veg_info, source){ start_year <- lubridate::year(start_date) out_file <- paste(source, start_year, "veg", "rds", sep = ".") out_file_full <- file.path(outfolder, out_file) dir.create(outfolder, showWarnings = FALSE, recursive = TRUE) saveRDS(veg_info, file = out_file_full) return(out_file_full) }
check_heterogeneity <- function(x, select = NULL, group = NULL) { .Deprecated("performance::check_heterogeneity_bias()") if (insight::is_model(x)) { group <- insight::find_random(x, split_nested = TRUE, flatten = TRUE) if (is.null(group)) { stop("Model is no mixed model. Please provide a mixed model, or a data frame and arguments 'select' and 'group'.") } data <- insight::get_data(x) select <- insight::find_predictors(x, effects = "fixed", component = "conditional", flatten = TRUE) } else { if (inherits(select, "formula")) { select <- all.vars(select) } if (inherits(group, "formula")) { group <- all.vars(group) } data <- x } unique_groups <- .n_unique(data[[group]]) combinations <- expand.grid(select, group) result <- mapply(function(predictor, id) { d <- datawizard::demean(data, select = predictor, group = id, verbose = FALSE) within_name <- paste0(predictor, "_within") if (any(sum(abs(d[[within_name]]) > 1e-5, na.rm = TRUE) > 0)) { predictor } else { NULL } }, as.character(combinations[[1]]), as.character(combinations[[2]]), SIMPLIFY = FALSE) out <- unname(unlist(.compact_list(result))) if (is.null(out)) { message("No predictor found that could cause heterogeneity bias.") return(invisible(NULL)) } class(out) <- c("check_heterogeneity", class(out)) out } print.check_heterogeneity <- function(x, ...) { cat("Possible heterogeneity bias due to following predictors: ") insight::print_color(paste(x, collapse = ", "), "red") cat("\n") invisible(x) } .n_unique <- function(x, na.rm = TRUE) { if (is.null(x)) { return(0) } if (isTRUE(na.rm)) x <- stats::na.omit(x) length(unique(x)) }
"grid_state_correspondence_table"
test_that('stop_when_too_toxic_selector does what it should.', { skeleton <- c(0.05, 0.1, 0.25, 0.4, 0.6) target <- 0.25 model1 <- get_dfcrm(skeleton = skeleton, target = target) %>% stop_when_too_toxic(dose = 1, tox_threshold = 0.35, confidence = 0.8) set.seed(123) fit <- model1 %>% fit('2NTN 1TT') prob_too_toxic <- prob_tox_exceeds(fit, target + 0.1) expect_equal(recommended_dose(fit), fit$parent$dfcrm_fit$mtd) expect_equal(continue(fit), prob_too_toxic[1] < 0.8) expect_equal(dose_admissible(fit), prob_too_toxic < 0.8) set.seed(123) fit <- model1 %>% fit('2NTN 1TTT') prob_too_toxic <- prob_tox_exceeds(fit, target + 0.1) expect_equal(continue(fit), prob_too_toxic[1] < 0.8) expect_equal(dose_admissible(fit), prob_too_toxic < 0.8) }) test_that('stop_when_too_toxic_selector supports correct interface.', { skeleton <- c(0.05, 0.1, 0.25, 0.4, 0.6) target <- 0.25 model_fitter <- get_dfcrm(skeleton = skeleton, target = target) %>% stop_when_too_toxic(dose = 1, tox_threshold = 0.35, confidence = 0.7) x <- fit(model_fitter, '1NNN 2NNN') expect_equal(tox_target(x), 0.25) expect_true(is.numeric(tox_target(x))) expect_equal(num_patients(x), 6) expect_true(is.integer(num_patients(x))) expect_equal(cohort(x), c(1,1,1, 2,2,2)) expect_true(is.integer(cohort(x))) expect_equal(length(cohort(x)), num_patients(x)) expect_equal(doses_given(x), c(1,1,1, 2,2,2)) expect_true(is.integer(doses_given(x))) expect_equal(length(doses_given(x)), num_patients(x)) expect_equal(tox(x), c(0,0,0, 0,0,0)) expect_true(is.integer(tox(x))) expect_equal(length(tox(x)), num_patients(x)) expect_equal(num_tox(x), 0) expect_true(is.integer(num_tox(x))) expect_true(all(model_frame(x) - data.frame(patient = c(1,2,3,4,5,6), cohort = c(1,1,1,2,2,2), dose = c(1,1,1,2,2,2), tox = c(0,0,0,0,0,0)) == 0)) expect_equal(nrow(model_frame(x)), num_patients(x)) expect_equal(num_doses(x), 5) expect_true(is.integer(num_doses(x))) expect_equal(dose_indices(x), 1:5) expect_true(is.integer(dose_indices(x))) expect_equal(length(dose_indices(x)), num_doses(x)) expect_equal(recommended_dose(x), 5) expect_true(is.integer(recommended_dose(x))) expect_equal(length(recommended_dose(x)), 1) expect_equal(continue(x), TRUE) expect_true(is.logical(continue(x))) expect_equal(n_at_dose(x), c(3,3,0,0,0)) expect_true(is.integer(n_at_dose(x))) expect_equal(length(n_at_dose(x)), num_doses(x)) expect_equal(n_at_dose(x, dose = 0), 0) expect_true(is.integer(n_at_dose(x, dose = 0))) expect_equal(length(n_at_dose(x, dose = 0)), 1) expect_equal(n_at_dose(x, dose = 1), 3) expect_true(is.integer(n_at_dose(x, dose = 1))) expect_equal(length(n_at_dose(x, dose = 1)), 1) expect_equal(n_at_dose(x, dose = 'recommended'), 0) expect_true(is.integer(n_at_dose(x, dose = 'recommended'))) expect_equal(length(n_at_dose(x, dose = 'recommended')), 1) expect_equal(n_at_recommended_dose(x), 0) expect_true(is.integer(n_at_recommended_dose(x))) expect_equal(length(n_at_recommended_dose(x)), 1) expect_equal(is_randomising(x), FALSE) expect_true(is.logical(is_randomising(x))) expect_equal(length(is_randomising(x)), 1) expect_equal(unname(prob_administer(x)), c(0.5,0.5,0,0,0)) expect_true(is.numeric(prob_administer(x))) expect_equal(length(prob_administer(x)), num_doses(x)) expect_equal(tox_at_dose(x), c(0,0,0,0,0)) expect_true(is.integer(tox_at_dose(x))) expect_equal(length(tox_at_dose(x)), num_doses(x)) expect_true(is.numeric(empiric_tox_rate(x))) expect_equal(length(empiric_tox_rate(x)), num_doses(x)) expect_true(is.numeric(mean_prob_tox(x))) expect_equal(length(mean_prob_tox(x)), num_doses(x)) expect_true(is.numeric(median_prob_tox(x))) expect_equal(length(median_prob_tox(x)), num_doses(x)) expect_true(is.logical(dose_admissible(x))) expect_equal(length(dose_admissible(x)), num_doses(x)) expect_true(is.numeric(prob_tox_quantile(x, p = 0.9))) expect_equal(length(prob_tox_quantile(x, p = 0.9)), num_doses(x)) expect_true(is.numeric(prob_tox_exceeds(x, 0.5))) expect_equal(length(prob_tox_exceeds(x, 0.5)), num_doses(x)) expect_true(is.logical(supports_sampling(x))) expect_true(is.data.frame(prob_tox_samples(x))) expect_true(is.data.frame(prob_tox_samples(x, tall = TRUE))) expect_error(summary(x), NA) expect_output(print(x)) expect_true(tibble::is_tibble(as_tibble(x))) expect_true(nrow(as_tibble(x)) >= num_doses(x)) x <- fit(model_fitter, '') expect_equal(tox_target(x), 0.25) expect_true(is.numeric(tox_target(x))) expect_equal(num_patients(x), 0) expect_true(is.integer(num_patients(x))) expect_equal(cohort(x), integer(0)) expect_true(is.integer(cohort(x))) expect_equal(length(cohort(x)), num_patients(x)) expect_equal(doses_given(x), integer(0)) expect_true(is.integer(doses_given(x))) expect_equal(length(doses_given(x)), num_patients(x)) expect_equal(tox(x), integer(0)) expect_true(is.integer(tox(x))) expect_equal(length(tox(x)), num_patients(x)) expect_equal(num_tox(x), 0) expect_true(is.integer(num_tox(x))) mf <- model_frame(x) expect_equal(nrow(mf), 0) expect_equal(ncol(mf), 4) expect_equal(num_doses(x), 5) expect_true(is.integer(num_doses(x))) expect_equal(dose_indices(x), 1:5) expect_true(is.integer(dose_indices(x))) expect_equal(length(dose_indices(x)), num_doses(x)) expect_equal(recommended_dose(x), 1) expect_true(is.integer(recommended_dose(x))) expect_equal(length(recommended_dose(x)), 1) expect_equal(continue(x), TRUE) expect_true(is.logical(continue(x))) expect_equal(n_at_dose(x), c(0,0,0,0,0)) expect_true(is.integer(n_at_dose(x))) expect_equal(length(n_at_dose(x)), num_doses(x)) expect_equal(n_at_dose(x, dose = 0), 0) expect_true(is.integer(n_at_dose(x, dose = 0))) expect_equal(length(n_at_dose(x, dose = 0)), 1) expect_equal(n_at_dose(x, dose = 1), 0) expect_true(is.integer(n_at_dose(x, dose = 1))) expect_equal(length(n_at_dose(x, dose = 1)), 1) expect_equal(n_at_dose(x, dose = 'recommended'), 0) expect_true(is.integer(n_at_dose(x, dose = 'recommended'))) expect_equal(length(n_at_dose(x, dose = 'recommended')), 1) expect_equal(n_at_recommended_dose(x), 0) expect_true(is.integer(n_at_recommended_dose(x))) expect_equal(length(n_at_recommended_dose(x)), 1) expect_equal(is_randomising(x), FALSE) expect_true(is.logical(is_randomising(x))) expect_equal(length(is_randomising(x)), 1) expect_true(is.numeric(prob_administer(x))) expect_equal(length(prob_administer(x)), num_doses(x)) expect_equal(tox_at_dose(x), c(0,0,0,0,0)) expect_true(is.integer(tox_at_dose(x))) expect_equal(length(tox_at_dose(x)), num_doses(x)) expect_true(is.numeric(empiric_tox_rate(x))) expect_equal(length(empiric_tox_rate(x)), num_doses(x)) expect_true(is.numeric(mean_prob_tox(x))) expect_equal(length(mean_prob_tox(x)), num_doses(x)) expect_true(is.numeric(median_prob_tox(x))) expect_equal(length(median_prob_tox(x)), num_doses(x)) expect_true(is.logical(dose_admissible(x))) expect_equal(length(dose_admissible(x)), num_doses(x)) expect_true(is.numeric(prob_tox_quantile(x, p = 0.9))) expect_equal(length(prob_tox_quantile(x, p = 0.9)), num_doses(x)) expect_true(is.numeric(prob_tox_exceeds(x, 0.5))) expect_equal(length(prob_tox_exceeds(x, 0.5)), num_doses(x)) expect_true(is.logical(supports_sampling(x))) expect_true(is.data.frame(prob_tox_samples(x))) expect_true(is.data.frame(prob_tox_samples(x, tall = TRUE))) expect_error(summary(x), NA) expect_output(print(x)) expect_true(tibble::is_tibble(as_tibble(x))) expect_true(nrow(as_tibble(x)) >= num_doses(x)) outcomes <- tibble( cohort = c(1,1,1, 2,2,2), dose = c(1,1,1, 2,2,2), tox = c(0,0,0, 0,0,1) ) x <- fit(model_fitter, outcomes) expect_equal(tox_target(x), 0.25) expect_true(is.numeric(tox_target(x))) expect_equal(num_patients(x), 6) expect_true(is.integer(num_patients(x))) expect_equal(cohort(x), c(1,1,1, 2,2,2)) expect_true(is.integer(cohort(x))) expect_equal(length(cohort(x)), num_patients(x)) expect_equal(doses_given(x), c(1,1,1, 2,2,2)) expect_true(is.integer(doses_given(x))) expect_equal(length(doses_given(x)), num_patients(x)) expect_equal(tox(x), c(0,0,0, 0,0,1)) expect_true(is.integer(tox(x))) expect_equal(length(tox(x)), num_patients(x)) expect_equal(num_tox(x), 1) expect_true(is.integer(num_tox(x))) expect_true(all((model_frame(x) - data.frame(patient = c(1,2,3,4,5,6), cohort = c(1,1,1,2,2,2), dose = c(1,1,1,2,2,2), tox = c(0,0,0,0,0,1))) == 0)) expect_equal(nrow(model_frame(x)), num_patients(x)) expect_equal(num_doses(x), 5) expect_true(is.integer(num_doses(x))) expect_equal(dose_indices(x), 1:5) expect_true(is.integer(dose_indices(x))) expect_equal(length(dose_indices(x)), num_doses(x)) expect_equal(recommended_dose(x), 2) expect_true(is.integer(recommended_dose(x))) expect_equal(length(recommended_dose(x)), 1) expect_equal(continue(x), TRUE) expect_true(is.logical(continue(x))) expect_equal(n_at_dose(x), c(3,3,0,0,0)) expect_true(is.integer(n_at_dose(x))) expect_equal(length(n_at_dose(x)), num_doses(x)) expect_equal(n_at_dose(x, dose = 0), 0) expect_true(is.integer(n_at_dose(x, dose = 0))) expect_equal(length(n_at_dose(x, dose = 0)), 1) expect_equal(n_at_dose(x, dose = 1), 3) expect_true(is.integer(n_at_dose(x, dose = 1))) expect_equal(length(n_at_dose(x, dose = 1)), 1) expect_equal(n_at_dose(x, dose = 'recommended'), 3) expect_true(is.integer(n_at_dose(x, dose = 'recommended'))) expect_equal(length(n_at_dose(x, dose = 'recommended')), 1) expect_equal(n_at_recommended_dose(x), 3) expect_true(is.integer(n_at_recommended_dose(x))) expect_equal(length(n_at_recommended_dose(x)), 1) expect_equal(is_randomising(x), FALSE) expect_true(is.logical(is_randomising(x))) expect_equal(length(is_randomising(x)), 1) expect_equal(unname(prob_administer(x)), c(0.5,0.5,0,0,0)) expect_true(is.numeric(prob_administer(x))) expect_equal(length(prob_administer(x)), num_doses(x)) expect_equal(tox_at_dose(x), c(0,1,0,0,0)) expect_true(is.integer(tox_at_dose(x))) expect_equal(length(tox_at_dose(x)), num_doses(x)) expect_true(is.numeric(empiric_tox_rate(x))) expect_equal(length(empiric_tox_rate(x)), num_doses(x)) expect_true(is.numeric(mean_prob_tox(x))) expect_equal(length(mean_prob_tox(x)), num_doses(x)) expect_true(is.numeric(median_prob_tox(x))) expect_equal(length(median_prob_tox(x)), num_doses(x)) expect_true(is.logical(dose_admissible(x))) expect_equal(length(dose_admissible(x)), num_doses(x)) expect_true(is.numeric(prob_tox_quantile(x, p = 0.9))) expect_equal(length(prob_tox_quantile(x, p = 0.9)), num_doses(x)) expect_true(is.numeric(prob_tox_exceeds(x, 0.5))) expect_equal(length(prob_tox_exceeds(x, 0.5)), num_doses(x)) expect_true(is.logical(supports_sampling(x))) expect_true(is.data.frame(prob_tox_samples(x))) expect_true(is.data.frame(prob_tox_samples(x, tall = TRUE))) expect_error(summary(x), NA) expect_output(print(x)) expect_true(tibble::is_tibble(as_tibble(x))) expect_true(nrow(as_tibble(x)) >= num_doses(x)) })
install.packages(c("ggplot2", "e1071", "caret", "quanteda", "irlba", "randomForest")) spam.raw <- read.csv("spam.csv", stringsAsFactors = FALSE, fileEncoding = "UTF-16") View(spam.raw) spam.raw <- spam.raw[, 1:2] names(spam.raw) <- c("Label", "Text") View(spam.raw) length(which(!complete.cases(spam.raw))) spam.raw$Label <- as.factor(spam.raw$Label) prop.table(table(spam.raw$Label)) spam.raw$TextLength <- nchar(spam.raw$Text) summary(spam.raw$TextLength) library(ggplot2) ggplot(spam.raw, aes(x = TextLength, fill = Label)) + theme_bw() + geom_histogram(binwidth = 5) + labs(y = "Text Count", x = "Length of Text", title = "Distribution of Text Lengths with Class Labels") library(caret) help(package = "caret") set.seed(32984) indexes <- createDataPartition(spam.raw$Label, times = 1, p = 0.7, list = FALSE) train <- spam.raw[indexes,] test <- spam.raw[-indexes,] prop.table(table(train$Label)) prop.table(table(test$Label)) train$Text[21] train$Text[38] train$Text[357] library(quanteda) help(package = "quanteda") train.tokens <- tokens(train$Text, what = "word", remove_numbers = TRUE, remove_punct = TRUE, remove_symbols = TRUE, remove_hyphens = TRUE) train.tokens[[357]] train.tokens <- tokens_tolower(train.tokens) train.tokens[[357]] train.tokens <- tokens_select(train.tokens, stopwords(), selection = "remove") train.tokens[[357]] train.tokens <- tokens_wordstem(train.tokens, language = "english") train.tokens[[357]] train.tokens.dfm <- dfm(train.tokens, tolower = FALSE) train.tokens.matrix <- as.matrix(train.tokens.dfm) View(train.tokens.matrix[1:20, 1:100]) dim(train.tokens.matrix) colnames(train.tokens.matrix)[1:50] train.tokens.df <- cbind(Label = train$Label, data.frame(train.tokens.dfm)) names(train.tokens.df)[c(146, 148, 235, 238)] names(train.tokens.df) <- make.names(names(train.tokens.df)) set.seed(48743) cv.folds <- createMultiFolds(train$Label, k = 10, times = 3) cv.cntrl <- trainControl(method = "repeatedcv", number = 10, repeats = 3, index = cv.folds) library(doSNOW) start.time <- Sys.time() cl <- makeCluster(10, type = "SOCK") registerDoSNOW(cl) rpart.cv.1 <- train(Label ~ ., data = train.tokens.df, method = "rpart", trControl = cv.cntrl, tuneLength = 7) stopCluster(cl) total.time <- Sys.time() - start.time total.time rpart.cv.1 term.frequency <- function(row) { row / sum(row) } inverse.doc.freq <- function(col) { corpus.size <- length(col) doc.count <- length(which(col > 0)) log10(corpus.size / doc.count) } tf.idf <- function(x, idf) { x * idf } train.tokens.df <- apply(train.tokens.matrix, 1, term.frequency) dim(train.tokens.df) View(train.tokens.df[1:20, 1:100]) train.tokens.idf <- apply(train.tokens.matrix, 2, inverse.doc.freq) str(train.tokens.idf) train.tokens.tfidf <- apply(train.tokens.df, 2, tf.idf, idf = train.tokens.idf) dim(train.tokens.tfidf) View(train.tokens.tfidf[1:25, 1:25]) train.tokens.tfidf <- t(train.tokens.tfidf) dim(train.tokens.tfidf) View(train.tokens.tfidf[1:25, 1:25]) incomplete.cases <- which(!complete.cases(train.tokens.tfidf)) train$Text[incomplete.cases] train.tokens.tfidf[incomplete.cases,] <- rep(0.0, ncol(train.tokens.tfidf)) dim(train.tokens.tfidf) sum(which(!complete.cases(train.tokens.tfidf))) train.tokens.tfidf.df <- cbind(Label = train$Label, data.frame(train.tokens.tfidf)) names(train.tokens.tfidf.df) <- make.names(names(train.tokens.tfidf.df)) start.time <- Sys.time() cl <- makeCluster(3, type = "SOCK") registerDoSNOW(cl) rpart.cv.2 <- train(Label ~ ., data = train.tokens.tfidf.df, method = "rpart", trControl = cv.cntrl, tuneLength = 7) stopCluster(cl) total.time <- Sys.time() - start.time total.time rpart.cv.2 train.tokens <- tokens_ngrams(train.tokens, n = 1:2) train.tokens[[357]] train.tokens.dfm <- dfm(train.tokens, tolower = FALSE) train.tokens.matrix <- as.matrix(train.tokens.dfm) train.tokens.dfm train.tokens.df <- apply(train.tokens.matrix, 1, term.frequency) train.tokens.idf <- apply(train.tokens.matrix, 2, inverse.doc.freq) train.tokens.tfidf <- apply(train.tokens.df, 2, tf.idf, idf = train.tokens.idf) train.tokens.tfidf <- t(train.tokens.tfidf) incomplete.cases <- which(!complete.cases(train.tokens.tfidf)) train.tokens.tfidf[incomplete.cases,] <- rep(0.0, ncol(train.tokens.tfidf)) train.tokens.tfidf.df <- cbind(Label = train$Label, data.frame(train.tokens.tfidf)) names(train.tokens.tfidf.df) <- make.names(names(train.tokens.tfidf.df)) gc()
sel_scale_2d = function(cnMax=6,pscnMax=6,ngrid = 100,nslaves = 50, B_new, IT_new, temp){ tt = exp(-(0:6-1)^2);prior_f = tt%*%t(tt);lp_2d = -log(prior_f)*1e-3 rtt = exp(-(6:0-1)^2);rprior_f = rtt%*%t(rtt);rlp_2d = -log(rprior_f)*1e-3 var_baf <- temp$var_baf var_tcn <- temp$var_tcn scale_max <- temp$scale_max scale_min <- temp$scale_min n_seg = nrow(IT_new) p <- 0 sim_func <- function(ss,scale_min=.5,scale_max=2,ngrid=100,pscnMax1=pscnMax,cnMax1 = cnMax,p1=p){ scale = scale_min+ss*(scale_max-scale_min)/ngrid n_seg = nrow(IT_new) L_tot_2d = array(0,dim=c(n_seg,100,51)) for(i in 1:n_seg) L_tot_2d[i,,]=calcll_cpp(as.numeric(IT_new[i,]),as.numeric(B_new[i,]),lp_2d*p1,rlp_2d*p1,var_baf,var_tcn,scale,pscnMax1,cnMax1)[[1]] L_sum = apply(L_tot_2d,c(2,3),sum) out <-min(L_sum) return(out) } ll <- rep(0, 100) for (i in 1:100){ ll[i] <- sim_func(i, scale_min=scale_min,scale_max=scale_max) } ind = 3:(ngrid-2) id = which(ll[ind]<ll[ind+1]&ll[ind]<ll[ind+2]&ll[ind]<ll[ind-1]&ll[ind]<ll[ind-2])+2 if(length(id)>1){id1 = which.min(ll[id]);id2 = which.min(ll[id[-id1]]);id2 = (id[-id1])[id2];id1 = id[id1];id=c(id1,id2)} scale2d = id*(scale_max-scale_min)/ngrid+scale_min res = list() res$ll = ll res$scale_max = scale_max res$scale_min = scale_min res$scale2d = scale2d return(res) }
test_that( "pattern matching operators work", { blue <- rep( "blue" , 10 ) res <- blue %~% "^b" expect_true(all(res)) expect_equal(length(res) , 10 ) cols <- c("blue", "red" ) expect_equal( cols %~% "^b", c(TRUE, FALSE)) expect_equal( cols %!~% "^b", c(FALSE, TRUE)) expect_equal( cols %~|% "^b" , "blue") expect_equal( length(cols %~|% "f") , 0 ) expect_equal( cols %!~|% "^b" , "red" ) expect_equal( cols %!~|% "f" , cols ) expect_true( cols %~*% "e" ) expect_false( cols %~*% "r") expect_false( cols %~*% "i") expect_false( cols %!~*% "e") expect_true( cols %!~*% "r" ) expect_true( cols %!~*% "i" ) expect_true( cols %~+% "e" ) expect_true( cols %~+% "r" ) expect_false( cols %~+% "i" ) expect_false( cols %!~+% "e" ) expect_false( cols %!~+% "r" ) expect_true( cols %!~+% "i" ) }) test_that( "pattern removing works", { cols <- c( "blue", "red" ) expect_equal( cols %-~% "e", c("blu", "rd") ) expect_equal( cols %-~% "pp", cols ) expect_equal( cols %-~% "blue", c( "", "red") ) expect_equal( cols %-~|% "b", "lue" ) expect_equal( cols %-~|% "e", c("blu", "rd" )) cols <- c( "blue.col", "pink", "red.stuff" ) expect_equal( as.vector(cols %o~|% "\\..*$" ), c(".col", ".stuff")) expect_equal( as.vector(cols %o~|% "\\.(.*)$"), c("col", "stuff")) })
testthat::test_that("testthat wrappers return the object", { expect_equal( expect_message_obj( { message("abc") "foo" }, "a" ), "foo" ) expect_equal( expect_warning_obj( { warning("abc") "foo" }, "a" ), "foo" ) expect_equal( expect_condition_obj( { message("abc") "foo" }, "a" ), "foo" ) })
predict.princomp <- function(object, newdata, ...) { if (missing(newdata)) return(object$scores) if(length(dim(newdata)) != 2L) stop("'newdata' must be a matrix or data frame") p <- NCOL(object$loadings) nm <- rownames(object$loadings) if(!is.null(nm)) { if(!all(nm %in% colnames(newdata))) stop("'newdata' does not have named columns matching one or more of the original columns") newdata <- newdata[, nm] } else { if(NCOL(newdata) != p) stop("'newdata' does not have the correct number of columns") } scale(newdata, object$center, object$scale) %*% object$loadings } summary.princomp <- function(object, loadings = FALSE, cutoff = 0.1, ...) { object$cutoff <- cutoff object$print.loadings <- loadings class(object) <- "summary.princomp" object } print.summary.princomp <- function(x, digits = 3L, loadings = x$print.loadings, cutoff = x$cutoff, ...) { vars <- x$sdev^2 vars <- vars/sum(vars) cat("Importance of components:\n") print(rbind("Standard deviation" = x$sdev, "Proportion of Variance" = vars, "Cumulative Proportion" = cumsum(vars))) if(loadings) { cat("\nLoadings:\n") cx <- format(round(x$loadings, digits = digits)) cx[abs(x$loadings) < cutoff] <- strrep(" ", nchar(cx[1,1], type="w")) print(cx, quote = FALSE, ...) } invisible(x) } plot.princomp <- function(x, main = deparse(substitute(x)), ...) screeplot.default(x, main = main, ...) screeplot <- function(x, ...) UseMethod("screeplot") screeplot.default <- function(x, npcs = min(10, length(x$sdev)), type = c("barplot", "lines"), main = deparse(substitute(x)), ...) { main type <- match.arg(type) pcs <- x$sdev^2 xp <- seq_len(npcs) dev.hold(); on.exit(dev.flush()) if(type == "barplot") barplot(pcs[xp], names.arg = names(pcs[xp]), main = main, ylab = "Variances", ...) else { plot(xp, pcs[xp], type = "b", axes = FALSE, main = main, xlab = "", ylab = "Variances", ...) axis(2) axis(1, at = xp, labels = names(pcs[xp])) } invisible() } loadings <- function(x, ...) x$loadings
alfarda.tune <- function(x, ina, a = seq(-1, 1, by = 0.1), nfolds = 10, gam = seq(0, 1, by = 0.1), del = seq(0, 1, by = 0.1), ncores = 1, folds = NULL, stratified = TRUE, seed = FALSE) { toc <- proc.time() n <- length(ina) if ( is.null(folds) ) folds <- Compositional::makefolds(ina, nfolds = nfolds, stratified = stratified, seed = seed) nfolds <- length(folds) if ( min(x) == 0 ) a <- a[ a > 0 ] info <- list() props <- ser <- array( dim = c( length(gam), length(del), length(a) ) ) for ( k in 1:length(a) ) { z <- Compositional::alfa(x, a[k])$aff mod <- Compositional::rda.tune(x = z, ina = ina, nfolds = nfolds, gam = gam, del = del, ncores = ncores, folds = folds, stratified = stratified, seed = seed) props[, , k] <- mod$percent ser[, , k] <- mod$se info[[ k ]] <- mod$per } dimnames(props) <- list(gamma = gam, delta = del, a = a) opt <- apply(props, 3, max) names(opt) <- a percent <- props[ , , which.max(opt)] se <- ser[, , which.max(opt)] confa <- as.vector( which(props == max( props), arr.ind = TRUE )[1, ] ) pera <- array( dim = c( length(gam), length(del), length(a) ) ) opt <- props[ confa[1], confa[2], confa[3] ] seopt <- ser[ confa[1], confa[2], confa[3] ] res <- c( opt, seopt, a[ confa[3] ], gam[ confa[1] ], del[ confa[2] ] ) names(res) <- c( "rate", "se of rate", "best_a", "best_gam", "best del" ) runtime <- proc.time() - toc list(result = res, percent = percent, se = se, runtime = runtime) }
context("PipeOpUpdateTarget") test_that("update target multi to binary", { trafo_fun = function(x) {factor(ifelse(x == "setosa", "setosa", "other"))} pom = PipeOpUpdateTarget$new(param_vals = list(trafo = trafo_fun, new_target_name = "setosa")) expect_pipeop(pom) newtsk = pom$train(list(tsk("iris")))[[1]] expect_task(newtsk) expect_true("setosa" %in% newtsk$target_names) expect_true(all((newtsk$data()$setosa == "setosa") == (tsk("iris")$data()$Species == "setosa"))) expect_true(pom$is_trained) newtsk2 = pom$predict(list(tsk("iris")))[[1]] expect_task(newtsk2) expect_true("setosa" %in% newtsk2$target_names) expect_true(all(levels(newtsk2$data()$setosa) == c("other", "setosa"))) }) test_that("update target regr to classif", { trafo_fun = function(x) {factor(ifelse(x < 25, "<25", ">=25"))} pom = PipeOpUpdateTarget$new(param_vals = list(trafo = trafo_fun, new_target_name = "threshold_25", new_task_type = "classif")) expect_pipeop(pom) newtsk = pom$train(list(tsk("boston_housing")))[[1]] expect_task(newtsk) expect_true("threshold_25" %in% newtsk$target_names) expect_true(all((newtsk$data()$threshold_25 == "<25") == (tsk("boston_housing")$data()$medv < 25))) expect_true(pom$is_trained) newtsk2 = pom$predict(list(tsk("boston_housing")))[[1]] expect_task(newtsk2) expect_true("threshold_25" %in% newtsk2$target_names) expect_true(all(levels(newtsk2$data()$threshold_25) == c("<25", ">=25"))) }) test_that("update target classif to regr", { trafo_fun = function(x) {map_dtc(x, as.numeric)} pom = PipeOpUpdateTarget$new(param_vals = list(trafo = trafo_fun, new_target_name = "quality", new_task_type = "regr")) expect_pipeop(pom) newtsk = pom$train(list(tsk("wine")))[[1]] expect_true(inherits(newtsk, "TaskRegr")) expect_task(newtsk) expect_true("quality" %in% newtsk$target_names) expect_true(all(newtsk$data()$quality == as.numeric(tsk("wine")$data()$type))) expect_true(pom$is_trained) newtsk2 = pom$predict(list(tsk("wine")))[[1]] expect_task(newtsk2) expect_true(inherits(newtsk, "TaskRegr")) expect_true("quality" %in% newtsk2$target_names) }) test_that("update target same target", { pom = PipeOpUpdateTarget$new(param_vals = list(new_target_name = "type", new_task_type = "classif")) expect_pipeop(pom) newtsk = pom$train(list(tsk("wine")))[[1]] expect_task(newtsk) expect_true("type" %in% newtsk$target_names) expect_equal(newtsk$data(), tsk("wine")$data()) expect_true(pom$is_trained) newtsk2 = pom$predict(list(tsk("wine")))[[1]] expect_task(newtsk2) expect_true("type" %in% newtsk2$target_names) expect_equal(newtsk2$data(), tsk("wine")$data()) }) test_that("rename target", { pom = PipeOpUpdateTarget$new(param_vals = list(new_target_name = "new_type")) expect_pipeop(pom) newtsk = pom$train(list(tsk("wine")))[[1]] expect_task(newtsk) expect_true("new_type" %in% newtsk$target_names) expect_true("type" %nin% c(newtsk$target_names, newtsk$feature_names)) expect_equal(newtsk$data()$new_type, tsk("wine")$data()$type) newtsk2 = pom$predict(list(tsk("wine")))[[1]] expect_task(newtsk2) expect_true("new_type" %in% newtsk2$target_names) expect_true("type" %nin% c(newtsk2$target_names, newtsk2$feature_names)) expect_equal(levels(newtsk2$data()$new_type), levels(tsk("wine")$data()$type)) }) test_that("update resample and predict_newdata", { skip_on_cran() t = tsk("wine") pom = PipeOpUpdateTarget$new(param_vals = list(new_target_name = "type", new_task_type = "classif")) g = GraphLearner$new(pom %>>% lrn("classif.rpart")) r = resample(t, g, rsmp("holdout")) expect_numeric(r$score()$classif.ce) g$train(t) g$predict_newdata(t$data(cols = t$feature_names)) }) test_that("make an existing feature a target", { pom = PipeOpUpdateTarget$new(param_vals = list(new_target_name = "ash", new_task_type = "regr", drop_original_target = FALSE)) expect_pipeop(pom) newtsk = pom$train(list(tsk("wine")))[[1]] expect_task(newtsk) expect_true("ash" %in% newtsk$target_names) expect_true("type" %nin% newtsk$target_names) expect_true("type" %in% newtsk$feature_names) expect_equal(newtsk$data()$ash, tsk("wine")$data()$ash) newtsk2 = pom$predict(list(tsk("wine")))[[1]] expect_equivalent(newtsk$hash, newtsk2$hash) })
knitr::opts_chunk$set( collapse = TRUE, comment = "", fig.height = 5.5, fig.width = 5.5, fig.align = "center", out.width = "0.5\\textwidth") setHook("plot.new", list(family = function() par(family = "sans")), "replace") library(sudokuAlt) set.seed(2019) seedGame(3) %>% solve() %>% regulariseGame() %>% plot() g <- makeGame() %>% solve() %>% plot() set.seed(2019) g4 <- seedGame(4) %>% solve() %>% regulariseGame() %>% plot() set.seed(1559707151) g5 <- seedGame(5) %>% solve() %>% regulariseGame() plot(g5, cex = 1) d5 <- designGame(g5) head(d5); tail(d5) g <- emptyGame(4) diag(g) <- LETTERS[1:16] g %>% solve() %>% plot() -> sg g <- emptyGame(3) g[1:3, 1:3] <- matrix(1:9, nrow = 3, byrow = TRUE) solve(g)
print.LearningCurve <- function(x,...) { cat("Learning Curve object\n\n") cat(names(x$results)[[2]],": ",paste(unique(x$results[[2]]),collapse=", "), "\n") cat("Classifiers:\n", paste("\t",levels(x$results$Classifier),collapse="\n"), "\n") cat("Measures:\n", paste("\t",levels(x$results$Measure),collapse="\n"), "\n") cat(length(unique(x$results$repeats)), " repeats\n") cat(sum(is.na(x$results)), " missing\n") } LearningCurveSSL<-function(X, y, ...) { UseMethod("LearningCurveSSL") } LearningCurveSSL.list<-function(X, y, ..., verbose=FALSE, mc.cores=1) { if (is.matrix(X[[1]]) & is.factor(y[[1]])) { curves <- clapply(names(X),function(dname){ if (verbose) cat(dname,"\n"); Xd <- X[[dname]] Xd <- Xd[,colnames(Xd)!="(Intercept)"] Xd <- Xd[,apply(Xd, 2, var, na.rm=TRUE) != 0] yd <- y[[dname]] LearningCurveSSL(Xd,yd,...,verbose=verbose) },mc.cores=mc.cores) } else if (is(X[[1]],"formula") & is.data.frame(y[[1]])) { curves <- clapply(names(X),function(dname){ if (verbose) cat(dname,"\n"); data <- data.frame(y[[dname]]) classname <- all.vars(X[[dname]])[1] Xd <- model.matrix(X[[dname]],y[[dname]]) Xd <- Xd[,colnames(Xd)!="(Intercept)"] Xd <- Xd[,apply(Xd, 2, var, na.rm=TRUE) != 0] yd <- data[,classname] LearningCurveSSL(Xd,yd,...,verbose=verbose) },mc.cores=mc.cores) } else { stop("Unknown input. Should be either a list of matrices and label vectors or formulae and data frames.") } names(curves) <- names(X) results <- dplyr::bind_rows(lapply(names(curves),function(x) {dplyr::mutate(curves[[x]]$results,Dataset=x)})) object<-list(n_l=curves[[1]]$n_l, results=results, n_test=curves[[1]]$n_test) class(object)<-"LearningCurve" return(object) } LearningCurveSSL.matrix<-function(X, y, classifiers, measures=list("Accuracy"=measure_accuracy), type="unlabeled", n_l=NULL, with_replacement=FALSE, sizes=2^(1:8), n_test=1000,repeats=100, verbose=FALSE,n_min=1,dataset_name=NULL,test_fraction=NULL,fracs=seq(0.1,0.9,0.1),time=TRUE,pre_scale=FALSE, pre_pca=FALSE,low_level_cores=1,...) { if (!is.factor(y)) { stop("Labels are not a factor.") } if (nrow(X)!=length(y)) { stop("Number of objects in X and y do not match.") } K <- length(levels(y)) if (pre_scale) X <- scale(X) if (pre_pca) { t_pca <- princomp(X) n_comp <- sum(cumsum(t_pca$sdev^2)/sum(t_pca$sdev^2)<0.99)+1 n_comp <- n_comp X <- t_pca$scores[,1:n_comp,drop=FALSE] } if (type=="unlabeled") { if (is.null(n_l)) stop("Set the number of labeled objects n_l") if (n_l=="enough") { n_l <- max(ncol(X)+5,20) } else if (n_l=="d") { n_l <- ncol(X)+1 } else if (n_l=="2d") { n_l <- max(ncol(X)*2,10) } else if (n_l=="half") { n_l <- ceiling(ncol(X)/2) } else {n_l <- n_l} } if (type=="fraction") { sizes <- fracs } results<-array(NA, dim=c(repeats, length(sizes), length(classifiers), length(measures)+time)) if (is.null(names(classifiers))) { classifier_names <- lapply(classifiers, function(c) {as.character(body(c))[[2]]}) } else { classifier_names <- names(classifiers) } if (is.null(names(measures))) { measure_names <- lapply(measures, function(c) {as.character(body(c))[[2]]}) } else { measure_names <- names(measures) } if (time) { measure_names<-c(measure_names,"Time")} name_list <- list("repeats"=1:repeats, "independent"=sizes, "Classifier"=classifier_names, "Measure"=measure_names ) if (type=="fraction") { names(name_list)[[2]] <- "Fraction of labeled objects" } else { names(name_list)[[2]] <- "Number of unlabeled objects" } dimnames(results)<- name_list if (verbose) cat("Number of features: ", ncol(X),"\n") if (verbose) cat("Number of objects: ", nrow(X),"\n") if (verbose) pb <- txtProgressBar(0,repeats) if (type=="unlabeled") { results <- clapply(1:repeats,function(i) { results <- results[1,,,,drop=FALSE] if (verbose) setTxtProgressBar(pb, i) sample.labeled <- sample_k_per_level(y,n_min) sample.labeled <- c(sample.labeled, sample((1:nrow(X))[-sample.labeled],n_l-(K*n_min),replace=FALSE)) X_l <- X[sample.labeled,,drop=FALSE] y_l <- y[sample.labeled] if (!with_replacement) { sample.unlabeled <- sample((1:nrow(X))[-sample.labeled]) } else { sample.unlabeled <- sample(1:nrow(X),max(sizes)+n_test,replace=TRUE) } X_u <- X[sample.unlabeled,,drop=FALSE] y_u <- y[sample.unlabeled] for (s in 1:length(sizes)) { if (sizes[s]>nrow(X_u)) {break} X_u_s <- X_u[1:sizes[s],,drop=FALSE] y_u_s <- y_u[1:sizes[s]] if (!with_replacement) { X_test <- X_u[-(1:sizes[s]),,drop=FALSE] y_test <- y_u[-(1:sizes[s])] } else { X_test <- X_u[-(1:max(sizes)),,drop=FALSE] y_test <- y_u[-(1:max(sizes))] } for (c in 1:length(classifiers)) { if (time) timed <- proc.time() trained_classifier<-do.call(classifiers[[c]], list(X=X_l, y=y_l, X_u=X_u_s, y_u=y_u_s)) if (time) { timed <- proc.time()-timed results[1,s,c,length(measures)+1] <- timed[[3]] } for (m in 1:length(measures)) { results[1,s,c,m] <- do.call(measures[[m]], list(trained_classifier=trained_classifier, X=X_l, y=y_l, X_u=X_u_s, y_u=y_u_s, X_test=X_test, y_test=y_test)) } } } dimnames(results)$repeats <- i return(reshape2::melt(results)) }, mc.cores=low_level_cores) results <- dplyr::bind_rows(results) } else if (type=="fraction") { results <- clapply(1:repeats,function(i) { results <- results[1,,,,drop=FALSE] sample.guaranteed <- sample_k_per_level(y,n_min) if (!is.null(test_fraction)) { idx_test <- sample((1:nrow(X))[-sample.guaranteed], size=ceiling(nrow(X)*test_fraction)) sampleorder <- c(sample.guaranteed,sample((1:nrow(X))[-c(sample.guaranteed,idx_test)])) } else { sampleorder <- c(sample.guaranteed,sample((1:nrow(X))[-c(sample.guaranteed)])) } for (s in 1:length(fracs)) { idx_lab <- sampleorder[1:ceiling(length(sampleorder)*fracs[s])] X_l <- X[idx_lab,,drop=FALSE] y_l <- y[idx_lab] if (!is.null(test_fraction)) { X_u <- X[-c(idx_lab,idx_test),,drop=FALSE] y_u <- y[-c(idx_lab,idx_test)] X_test <- X[idx_test,,drop=FALSE] y_test <- y[idx_test] } else { X_u <- X[-c(idx_lab),,drop=FALSE] y_u <- y[-c(idx_lab)] X_test <- X_u y_test <- y_u } for (c in 1:length(classifiers)) { if (time) timed <- proc.time() trained_classifier<-do.call(classifiers[[c]], list(X=X_l, y=y_l, X_u=X_u, y_u=y_u)) if (time) { timed <- proc.time()-timed results[1,s,c,length(measures)+1] <- timed[[3]] } for (m in 1:length(measures)) { results[1,s,c,m] <- do.call(measures[[m]], list(trained_classifier=trained_classifier, X=X_l, y=y_l, X_u=X_u, y_u=y_u, X_test=X_test,y_test=y_test)) } } } dimnames(results)$repeats <- i return(reshape2::melt(results)) }, mc.cores=low_level_cores) results <- dplyr::bind_rows(results) } else { stop("Unknown value for argument 'type'") } if (verbose) cat("\n") object<-list(n_l=n_l, results=results, n_test=n_test) class(object)<-"LearningCurve" return(object) } plot.LearningCurve <- function(x, y, ...) { data <- x if (class(data)=="LearningCurve") { data <- list(data) } else if (!(is.list(data) & all(lapply(data,class)=="LearningCurve"))) { stop("Input object should be LearningCurve of list of LearningCurve objects.") } x_label <- names(x$results)[[2]] if ("Dataset" %in% names(x$results)) { plot_frame <- x$results %>% dplyr::group_by(!!dplyr::sym(x_label), .data$Classifier, .data$Measure, .data$Dataset) %>% summarize(Mean=mean(.data$value,na.rm=TRUE),SE=stderror(.data$value)) %>% ungroup() facet_used <- facet_wrap(~ Dataset + Measure,scales="free",ncol=length(unique(plot_frame$Measure))) } else { plot_frame <- x$results %>% dplyr::group_by(!!dplyr::sym(x_label), .data$Classifier, .data$Measure) %>% dplyr::summarize(Mean=mean(.data$value,na.rm=TRUE),SE=stderror(.data$value)) %>% dplyr::ungroup() facet_used <- facet_wrap(~Measure,scales="free") } p <- plot_frame %>% ggplot(aes_string(x=paste0("`",x_label,"`"),y="Mean",color="Classifier",shape="Classifier")) + geom_point(size=1, na.rm=TRUE) + geom_line(aes_string(linetype="Classifier"), na.rm=TRUE) + geom_ribbon(aes_string(ymax="Mean+1*SE",ymin="Mean-1*SE",fill="Classifier"),size=0,alpha=0.3, na.rm=TRUE) + theme_classic() + facet_used + ylab("") + theme(legend.position="bottom", strip.background=element_rect(size = 0), axis.title.y=element_text(angle = 0,size=rel(0.8)), axis.title.x=element_text(size=rel(0.8)), axis.text.y=element_text(size=rel(0.8)), axis.text.x=element_text(size=rel(0.8))) if (x_label=="`Fraction of labeled objects`") { p <- p + scale_x_continuous() } else { p <- p + scale_x_continuous(trans = scales::log2_trans()) } return(p) } sample_k_per_level <- function(y,k) { stopifnot(is.factor(y)) stopifnot(k>0) all_idx <- 1:length(y) sample_idx <- c() for (i in levels(y)) { sample_idx <- c(sample_idx,sample(all_idx[y==i],k)) } return(sample_idx) }
overlay_bound_csv <- reactive({ req(input$overlay_bound_csv_file) vals$overlay.bound <- NULL validate( need(input$overlay_bound_csv_file$type %in% c("text/csv", "application/vnd.ms-excel"), "Error: Selected file is not an Excel .csv file") ) csv.df <- read.csv( input$overlay_bound_csv_file$datapath, stringsAsFactors = FALSE ) validate( need(ncol(csv.df) >= 2, paste("Error: The study area .csv file must have at least two", "columns (longitude and latitude, respectively)")), need(!anyNA(csv.df), paste("Error: The study area polygon must be one, single polygon.", "Please load a csv file without any invalid entries (e.g. NA)", "in the two columns")) ) withProgress(message = 'Importing study area polygon', value = 0.7, { Sys.sleep(0.5) if (min(csv.df[, 1]) > 180) csv.df[, 1] <- csv.df[, 1] - 360 bound.sfc <- try( st_sfc(st_polygon(list(as.matrix(csv.df))), crs = 4326), silent = TRUE ) validate( need(isTruthy(bound.sfc), paste("Error: The study area polygon could not be created", "from the provided points.", "Please ensure that the .csv file has the longitude points", "in the first column, the latitude points in the second", "column, and that the provided points form a closed", "and valid polygon"))) validate( need(st_is_valid(bound.sfc), paste("Error: The provided study area polygon is invalid;", "please ensure that the provided points form a closed", "and valid polygon (no self-intersections)")) ) bound.sfc <- check_dateline(bound.sfc, 60, progress.detail = TRUE) incProgress(0.3) }) vals$overlay.bound <- bound.sfc "" }) overlay_land_csv <- reactive({ req(input$overlay_land_csv_file) vals$overlay.land <- NULL validate( need(input$overlay_land_csv_file$type %in% c("text/csv", "application/vnd.ms-excel"), "Error: Selected file is not an Excel .csv file") ) csv.df <- read.csv( input$overlay_land_csv_file$datapath, stringsAsFactors = FALSE ) withProgress(message = 'Importing land polygon', value = 0.7, { Sys.sleep(0.5) if (min(csv.df[, 1], na.rm = TRUE) > 180) { csv.df[, 1] <- csv.df[, 1] - 360 } land.sfc <- pts2poly_vertices_shiny(csv.df[, 1:2], crs.ll, TRUE) incProgress(0.3) }) vals$overlay.land <- land.sfc "" })
require("setRNG") Sys.info() random.number.test()
library(rcrossref) library(dplyr) library(tidyr) library(readr) out <- list() z <- cr_members(limit = 1) total <- z$meta$total_results times <- (floor(total / 1000) + 1) for (i in seq_len(times)) { if (i == 1) { offset <- NULL } else { offset <- 1000 * (i - 1) } out[[i]] <- cr_members(limit = 1000, offset = offset) } length(out) out[[1]] out[[2]] df <- dplyr::bind_rows(lapply(out, "[[", "data")) length(df$id) length(unique(df$id)) df2 <- select(df, id, prefixes, primary_name) df3 <- mutate(df2, prefixes = strsplit(prefixes, ", ")) %>% unnest(prefixes) crossref_member_prefix <- df3 usethis::use_data(crossref_member_prefix, crossref_member_prefix, internal = TRUE, overwrite = TRUE)