content
stringlengths 0
14.9M
| filename
stringlengths 44
136
|
---|---|
is_string <- function(x) {
is.character(x) && length(x) == 1 && !is.na(x)
}
is_character <- function(x) {
is.character(x) && !any(is.na(x))
}
is_character_or_null <- function(x) {
is.null(x) || is_character(x)
}
is_flag <- function(x) {
is.logical(x) && length(x) == 1 && !is.na(x)
}
is_count <- function(x) {
is.numeric(x) && length(x) == 1 && !is.na(x) &&
as.integer(x) == x
}
| /scratch/gouwar.j/cran-all/cranData/zip/R/assertions.R |
#' Uncompress a raw GZIP stream
#'
#' @param buffer Raw vector, containing the data to uncompress.
#' @param pos Start position of data to uncompress in `buffer`.
#' @param size Uncompressed size estimate, or `NULL`. If not given, or too
#' small, the output buffer is resized multiple times.
#' @return Named list with three entries:
#' - `output`: raw vector, the uncompressed data,
#' - `bytes_read`: number of bytes used from `buffer`,
#' - `bytes_written`: number of bytes written to the output buffer.
#'
#' @seealso [base::memDecompress()] does the same with `type = "gzip"`,
#' but it does not tell you the number of bytes read from the input.
#'
#' @export
#' @examples
#' data_gz <- deflate(charToRaw("Hello world!"))
#' inflate(data_gz$output)
inflate <- function(buffer, pos = 1L, size = NULL) {
stopifnot(
is.raw(buffer),
is_count(pos),
is.null(size) || is_count(size)
)
if (!is.null(size)) size <- as.integer(size)
.Call(c_R_inflate, buffer, as.integer(pos), size)
}
#' Compress a raw GZIP stream
#'
#' @param buffer Raw vector, containing the data to compress.
#' @param level Compression level, integer between 1 (fatest) and 9 (best).
#' @param pos Start position of data to compress in `buffer`.
#' @param size Compressed size estimate, or `NULL`. If not given, or too
#' small, the output buffer is resized multiple times.
#' @return Named list with three entries:
#' - `output`: raw vector, the compressed data,
#' - `bytes_read`: number of bytes used from `buffer`,
#' - `bytes_written`: number of bytes written to the output buffer.
#'
#' @seealso [base::memCompress()] does the same with `type = "gzip"`,
#' but it does not tell you the number of bytes read from the input.
#'
#' @export
#' @examples
#' data_gz <- deflate(charToRaw("Hello world!"))
#' inflate(data_gz$output)
deflate <- function(buffer, level = 6L, pos = 1L, size = NULL) {
stopifnot(
is.raw(buffer),
is_count(level),
level >= 1L && level <= 9L,
is_count(pos),
is.null(size) || is_count(size)
)
if (!is.null(size)) size <- as.integer(size)
.Call(c_R_deflate, buffer, as.integer(level), as.integer(pos), size)
}
| /scratch/gouwar.j/cran-all/cranData/zip/R/inflate.R |
os_type <- function() {
.Platform$OS.type
}
get_tool <- function (prog) {
if (os_type() == "windows") prog <- paste0(prog, ".exe")
exe <- system.file(package = "zip", "bin", .Platform$r_arch, prog)
if (exe == "") {
pkgpath <- system.file(package = "zip")
if (basename(pkgpath) == "inst") pkgpath <- dirname(pkgpath)
exe <- file.path(pkgpath, "src", "tools", prog)
if (!file.exists(exe)) return("")
}
exe
}
unzip_exe <- function() {
get_tool("cmdunzip")
}
zip_exe <- function() {
get_tool("cmdzip")
}
zip_data <- new.env(parent = emptyenv())
## R CMD check fix
super <- ""
#' Class for an external unzip process
#'
#' `unzip_process()` returns an R6 class that represents an unzip process.
#' It is implemented as a subclass of [processx::process].
#'
#' @section Using the `unzip_process` class:
#'
#' ```
#' up <- unzip_process()$new(zipfile, exdir = ".", poll_connection = TRUE,
#' stderr = tempfile(), ...)
#' ```
#'
#' See [processx::process] for the class methods.
#'
#' Arguments:
#' * `zipfile`: Path to the zip file to uncompress.
#' * `exdir`: Directory to uncompress the archive to. If it does not
#' exist, it will be created.
#' * `poll_connection`: passed to the `initialize` method of
#' [processx::process], it allows using [processx::poll()] or the
#' `poll_io()` method to poll for the completion of the process.
#' * `stderr`: passed to the `initialize` method of [processx::process],
#' by default the standard error is written to a temporary file.
#' This file can be used to diagnose errors if the process failed.
#' * `...` passed to the `initialize` method of [processx::process].
#'
#' @return An `unzip_process` R6 class object, a subclass of
#' [processx::process].
#'
#' @export
#' @examples
#' ex <- system.file("example.zip", package = "zip")
#' tmp <- tempfile()
#' up <- unzip_process()$new(ex, exdir = tmp)
#' up$wait()
#' up$get_exit_status()
#' dir(tmp)
unzip_process <- function() {
need_packages(c("processx", "R6"), "creating unzip processes")
zip_data$unzip_class <- zip_data$unzip_class %||%
R6::R6Class(
"unzip_process",
inherit = processx::process,
public = list(
initialize = function(zipfile, exdir = ".", poll_connection = TRUE,
stderr = tempfile(), ...) {
stopifnot(
is_string(zipfile),
is_string(exdir))
exdir <- normalizePath(exdir, winslash = "\\", mustWork = FALSE)
super$initialize(unzip_exe(), enc2c(c(zipfile, exdir)),
poll_connection = poll_connection,
stderr = stderr, ...)
}
),
private = list()
)
zip_data$unzip_class
}
#' Class for an external zip process
#'
#' `zip_process()` returns an R6 class that represents a zip process.
#' It is implemented as a subclass of [processx::process].
#'
#' @section Using the `zip_process` class:
#'
#' ```
#' zp <- zip_process()$new(zipfile, files, recurse = TRUE,
#' poll_connection = TRUE,
#' stderr = tempfile(), ...)
#' ```
#'
#' See [processx::process] for the class methods.
#'
#' Arguments:
#' * `zipfile`: Path to the zip file to create.
#' * `files`: List of file to add to the archive. Each specified file
#' or directory in is created as a top-level entry in the zip archive.
#' * `recurse`: Whether to add the contents of directories recursively.
#' * `include_directories`: Whether to explicitly include directories
#' in the archive. Including directories might confuse MS Office when
#' reading docx files, so set this to `FALSE` for creating them.
#' * `poll_connection`: passed to the `initialize` method of
#' [processx::process], it allows using [processx::poll()] or the
#' `poll_io()` method to poll for the completion of the process.
#' * `stderr`: passed to the `initialize` method of [processx::process],
#' by default the standard error is written to a temporary file.
#' This file can be used to diagnose errors if the process failed.
#' * `...` passed to the `initialize` method of [processx::process].
#'
#' @return A `zip_process` R6 class object, a subclass of
#' [processx::process].
#'
#' @export
#' @examples
#' dir.create(tmp <- tempfile())
#' write.table(iris, file = file.path(tmp, "iris.ssv"))
#' zipfile <- tempfile(fileext = ".zip")
#' zp <- zip_process()$new(zipfile, tmp)
#' zp$wait()
#' zp$get_exit_status()
#' zip_list(zipfile)
zip_process <- function() {
need_packages(c("processx", "R6"), "creating zip processes")
zip_data$zip_class <- zip_data$zip_class %||%
R6::R6Class(
"zip_process",
inherit = processx::process,
public = list(
initialize = function(zipfile, files, recurse = TRUE,
include_directories = TRUE,
poll_connection = TRUE, stderr = tempfile(),
...) {
private$zipfile <- zipfile
private$files <- files
private$recurse <- recurse
private$include_directories <- include_directories
private$params_file <- tempfile()
write_zip_params(files, recurse, include_directories,
private$params_file)
super$initialize(zip_exe(), enc2c(c(zipfile, private$params_file)),
poll_connection = poll_connection,
stderr = stderr, ...)
}
),
private = list(
zipfile = NULL,
files = NULL,
recurse = NULL,
include_directories = NULL,
params_file = NULL
)
)
zip_data$zip_class
}
write_zip_params <- function(files, recurse, include_directories, outfile) {
data <- get_zip_data(files, recurse, keep_path = FALSE,
include_directories = include_directories)
mtime <- as.double(file.info(data$file)$mtime)
con <- file(outfile, open = "wb")
on.exit(close(con))
## Number of files
writeBin(con = con, as.integer(nrow(data)))
## Key, first total length
data$key <- data$key <- fix_absolute_paths(data$key)
warn_for_colon(data$key)
warn_for_dotdot(data$key)
writeBin(con = con, as.integer(sum(nchar(data$key, type = "bytes") + 1L)))
writeBin(con = con, data$key)
## Filenames
writeBin(con = con, as.integer(sum(nchar(data$file, type = "bytes") + 1L)))
writeBin(con = con, data$file)
## Is dir or not
writeBin(con = con, as.integer(data$dir))
## mtime
writeBin(con = con, as.double(mtime))
}
| /scratch/gouwar.j/cran-all/cranData/zip/R/process.R |
`%||%` <- function(l, r) if (is.null(l)) r else l
get_zip_data <- function(files, recurse, keep_path, include_directories) {
list <- if (keep_path) {
get_zip_data_path(files, recurse)
} else {
get_zip_data_nopath(files, recurse)
}
if (!include_directories) {
list <- list[! list$dir, ]
}
list
}
get_zip_data_path <- function(files, recurse) {
if (recurse && length(files)) {
data <- do.call(rbind, lapply(files, get_zip_data_path_recursive))
dup <- duplicated(data$files)
if (any(dup)) data <- data <- data[ !dup, drop = FALSE ]
data
} else {
files <- ignore_dirs_with_warning(files)
data.frame(
stringsAsFactors = FALSE,
key = files,
files = files,
dir = rep(FALSE, length(files))
)
}
}
warn_for_dotdot <- function(files) {
if (any(grepl("^[.][/\\\\]", files))) {
warning("Some paths start with `./`, creating non-portable zip file")
}
if (any(grepl("^[.][.][/\\\\]", files))) {
warning("Some paths reference parent directory, ",
"creating non-portable zip file")
}
files
}
warn_for_colon <- function(files) {
if (any(grepl(":", files, fixed = TRUE))) {
warning("Some paths include a `:` character, this might cause issues ",
"when uncompressing the zip file on Windows.")
}
}
fix_absolute_paths <- function(files) {
if (any(substr(files, 1, 1) == "/")) {
warning("Dropping leading `/` from paths, all paths in a zip file ",
"must be relative paths.")
files <- sub("^/", "", files)
}
files
}
get_zip_data_nopath <- function(files, recurse) {
if ("." %in% files) {
files <- c(setdiff(files, "."), dir(all.files=TRUE, no.. = TRUE))
}
if (recurse && length(files)) {
data <- do.call(rbind, lapply(files, get_zip_data_nopath_recursive))
dup <- duplicated(data$files)
if (any(dup)) data <- data[ !dup, drop = FALSE ]
data
} else {
files <- ignore_dirs_with_warning(files)
data.frame(
stringsAsFactors = FALSE,
key = basename(files),
file = files,
dir = rep(FALSE, length(files))
)
}
}
ignore_dirs_with_warning <- function(files) {
info <- file.info(files)
if (any(info$isdir)) {
warning("directories ignored in zip file, specify recurse = TRUE")
files <- files[!info$isdir]
}
files
}
get_zip_data_path_recursive <- function(x) {
if (file.info(x)$isdir) {
files <- c(x, dir(x, recursive = TRUE, full.names = TRUE,
all.files = TRUE, include.dirs = TRUE, no.. = TRUE))
dir <- file.info(files)$isdir
data.frame(
stringsAsFactors = FALSE,
key = ifelse(dir, paste0(files, "/"), files),
file = normalizePath(files),
dir = dir
)
} else {
data.frame(
stringsAsFactors = FALSE,
key = x,
file = normalizePath(x),
dir = FALSE
)
}
}
get_zip_data_nopath_recursive <- function(x) {
if ("." %in% x) {
x <- c(setdiff(x, "."), dir(all.files=TRUE, no.. = TRUE))
}
x <- normalizePath(x)
wd <- getwd()
on.exit(setwd(wd))
setwd(dirname(x))
bnx <- basename(x)
files <- dir(
bnx,
recursive = TRUE,
all.files = TRUE,
include.dirs = TRUE,
no.. = TRUE
)
key <- c(bnx, file.path(bnx, files))
files <- c(x, file.path(dirname(x), bnx, files))
dir <- file.info(files)$isdir
key <- ifelse(dir, paste0(key, "/"), key)
data.frame(
stringsAsFactors = FALSE,
key = key,
file = normalizePath(files),
dir = dir
)
}
mkdirp <- function(x, ...) {
dir.create(x, showWarnings = FALSE, recursive = TRUE, ...)
}
need_packages <- function(pkgs, what = "this function") {
for (p in pkgs) {
if (!requireNamespace(p, quietly = TRUE)) {
stop(sprintf("The `%s` package is needed for %s", p, what))
}
}
}
enc2c <- function(x) {
if (.Platform$OS.type == "windows") {
enc2utf8(x)
} else {
enc2native(x)
}
}
| /scratch/gouwar.j/cran-all/cranData/zip/R/utils.R |
#' @aliases zip-package NULL
#' @keywords internal
"_PACKAGE"
## usethis namespace: start
## usethis namespace: end
NULL
| /scratch/gouwar.j/cran-all/cranData/zip/R/zip-package.R |
#' @useDynLib zip, .registration = TRUE, .fixes = "c_"
NULL
#' Compress Files into 'zip' Archives
#'
#' `zip()` creates a new zip archive file.
#'
#' `zip_append()` appends compressed files to an existing 'zip' file.
#'
#' ## Relative paths
#'
#' `zip()` and `zip_append()` can run in two different modes: mirror
#' mode and cherry picking mode. They handle the specified `files`
#' differently.
#'
#' ### Mirror mode
#'
#' Mirror mode is for creating the zip archive of a directory structure,
#' exactly as it is on the disk. The current working directory will
#' be the root of the archive, and the paths will be fully kept.
#' zip changes the current directory to `root` before creating the
#' archive.
#'
#' E.g. consider the following directory structure:
#'
#' ```{r echo = FALSE, comment = ""}
#' dir.create(tmp <- tempfile())
#' oldwd <- getwd()
#' setwd(tmp)
#' dir.create("foo/bar", recursive = TRUE)
#' dir.create("foo/bar2")
#' dir.create("foo2")
#' cat("this is file1", file = "foo/bar/file1")
#' cat("this is file2", file = "foo/bar/file2")
#' cat("this is file3", file = "foo2/file3")
#' out <- processx::run("tree", c("--noreport", "--charset=ascii"))
#' cat(crayon::strip_style(out$stdout))
#' setwd(oldwd)
#' ```
#'
#' Assuming the current working directory is `foo`, the following zip
#' entries are created by `zip`:
#' ```{r, echo = 2:4}
#' setwd(tmp)
#' setwd("foo")
#' zip::zip("../test.zip", c("bar/file1", "bar2", "../foo2"))
#' zip_list("../test.zip")[, "filename", drop = FALSE]
#' setwd(oldwd)
#' ```
#'
#' Note that zip refuses to store files with absolute paths, and chops
#' off the leading `/` character from these file names. This is because
#' only relative paths are allowed in zip files.
#'
#' ### Cherry picking mode
#'
#' In cherry picking mode, the selected files and directories
#' will be at the root of the archive. This mode is handy if you
#' want to select a subset of files and directories, possibly from
#' different paths and put all of the in the archive, at the top
#' level.
#'
#' Here is an example with the same directory structure as above:
#'
#' ```{r, echo = 3:4}
#' setwd(tmp)
#' setwd("foo")
#' zip::zip(
#' "../test2.zip",
#' c("bar/file1", "bar2", "../foo2"),
#' mode = "cherry-pick"
#')
#' zip_list("../test2.zip")[, "filename", drop = FALSE]
#' setwd(oldwd)
#' ```
#'
#' From zip version 2.3.0, `"."` has a special meaning in the `files`
#' argument: it will include the files (and possibly directories) within
#' the current working directory, but **not** the working directory itself.
#' Note that this only applies to cherry picking mode.
#'
#' ## Permissions:
#'
#' `zip()` (and `zip_append()`, etc.) add the permissions of
#' the archived files and directories to the ZIP archive, on Unix systems.
#' Most zip and unzip implementations support these, so they will be
#' recovered after extracting the archive.
#'
#' Note, however that the owner and group (uid and gid) are currently
#' omitted, even on Unix.
#'
#' ## `zipr()` and `zipr_append()`
#'
#' These function exist for historical reasons. They are identical
#' to `zip()` and `zipr_append()` with a different default for the
#' `mode` argument.
#'
#' @param zipfile The zip file to create. If the file exists, `zip`
#' overwrites it, but `zip_append` appends to it. If it is a directory
#' an error is thrown.
#' @param files List of file to add to the archive. See details below
#' about absolute and relative path names.
#' @param recurse Whether to add the contents of directories recursively.
#' @param compression_level A number between 1 and 9. 9 compresses best,
#' but it also takes the longest.
#' @param include_directories Whether to explicitly include directories
#' in the archive. Including directories might confuse MS Office when
#' reading docx files, so set this to `FALSE` for creating them.
#' @param root Change to this working directory before creating the
#' archive.
#' @param mode Selects how files and directories are stored in
#' the archive. It can be `"mirror"` or `"cherry-pick"`.
#' See "Relative Paths" below for details.
#' @return The name of the created zip file, invisibly.
#'
#' @export
#' @examples
#' ## Some files to zip up. We will run all this in the R session's
#' ## temporary directory, to avoid messing up the user's workspace.
#' dir.create(tmp <- tempfile())
#' dir.create(file.path(tmp, "mydir"))
#' cat("first file", file = file.path(tmp, "mydir", "file1"))
#' cat("second file", file = file.path(tmp, "mydir", "file2"))
#'
#' zipfile <- tempfile(fileext = ".zip")
#' zip::zip(zipfile, "mydir", root = tmp)
#'
#' ## List contents
#' zip_list(zipfile)
#'
#' ## Add another file
#' cat("third file", file = file.path(tmp, "mydir", "file3"))
#' zip_append(zipfile, file.path("mydir", "file3"), root = tmp)
#' zip_list(zipfile)
zip <- function(zipfile, files, recurse = TRUE, compression_level = 9,
include_directories = TRUE, root = ".",
mode = c("mirror", "cherry-pick")) {
mode <- match.arg(mode)
zip_internal(zipfile, files, recurse, compression_level, append = FALSE,
root = root, keep_path = (mode == "mirror"),
include_directories = include_directories)
}
#' @rdname zip
#' @export
zipr <- function(zipfile, files, recurse = TRUE, compression_level = 9,
include_directories = TRUE, root = ".",
mode = c("cherry-pick", "mirror")) {
mode <- match.arg(mode)
zip_internal(zipfile, files, recurse, compression_level, append = FALSE,
root = root, keep_path = (mode == "mirror"),
include_directories = include_directories)
}
#' @rdname zip
#' @export
zip_append <- function(zipfile, files, recurse = TRUE,
compression_level = 9, include_directories = TRUE,
root = ".", mode = c("mirror", "cherry-pick")) {
mode <- match.arg(mode)
zip_internal(zipfile, files, recurse, compression_level, append = TRUE,
root = root, keep_path = (mode == "mirror"),
include_directories = include_directories)
}
#' @rdname zip
#' @export
zipr_append <- function(zipfile, files, recurse = TRUE,
compression_level = 9, include_directories = TRUE,
root = ".", mode = c("cherry-pick", "mirror")) {
mode <- match.arg(mode)
zip_internal(zipfile, files, recurse, compression_level, append = TRUE,
root = root, keep_path = (mode == "mirror"),
include_directories = include_directories)
}
zip_internal <- function(zipfile, files, recurse, compression_level,
append, root, keep_path, include_directories) {
zipfile <- path.expand(zipfile)
if (dir.exists(zipfile)) {
stop("zip file at `", zipfile, "` already exists and it is a directory")
}
oldwd <- setwd(root)
on.exit(setwd(oldwd), add = TRUE)
if (any(! file.exists(files))) stop("Some files do not exist")
data <- get_zip_data(files, recurse, keep_path, include_directories)
data$key <- fix_absolute_paths(data$key)
warn_for_colon(data$key)
warn_for_dotdot(data$key)
.Call(c_R_zip_zip, enc2c(zipfile), enc2c(data$key),
enc2c(data$file), data$dir, file.info(data$file)$mtime,
as.integer(compression_level), append)
invisible(zipfile)
}
#' List Files in a 'zip' Archive
#'
#' @details Note that `crc32` is formatted using `as.hexmode()`. `offset` refers
#' to the start of the local zip header for each entry. Following the approach
#' of `seek()` it is stored as a `numeric` rather than an `integer` vector and
#' can therefore represent values up to `2^53-1` (9 PB).
#' @param zipfile Path to an existing ZIP file.
#' @return A data frame with columns: `filename`, `compressed_size`,
#' `uncompressed_size`, `timestamp`, `permissions`, `crc32` and `offset`.
#'
#' @family zip/unzip functions
#' @export
zip_list <- function(zipfile) {
zipfile <- enc2c(normalizePath(zipfile))
res <- .Call(c_R_zip_list, zipfile)
df <- data.frame(
stringsAsFactors = FALSE,
filename = res[[1]],
compressed_size = res[[2]],
uncompressed_size = res[[3]],
timestamp = as.POSIXct(res[[4]], tz = "UTC", origin = "1970-01-01")
)
Encoding(df$filename) <- "UTF-8"
df$permissions <- as.octmode(res[[5]])
df$crc32 <- as.hexmode(res[[6]])
df$offset <- res[[7]]
df
}
#' Uncompress 'zip' Archives
#'
#' `unzip()` always restores modification times of the extracted files and
#' directories.
#'
#' @section Permissions:
#'
#' If the zip archive stores permissions and was created on Unix,
#' the permissions will be restored.
#'
#' @param zipfile Path to the zip file to uncompress.
#' @param files Character vector of files to extract from the archive.
#' Files within directories can be specified, but they must use a forward
#' slash as path separator, as this is what zip files use internally.
#' If `NULL`, all files will be extracted.
#' @param overwrite Whether to overwrite existing files. If `FALSE` and
#' a file already exists, then an error is thrown.
#' @param junkpaths Whether to ignore all directory paths when creating
#' files. If `TRUE`, all files will be created in `exdir`.
#' @param exdir Directory to uncompress the archive to. If it does not
#' exist, it will be created.
#'
#' @export
#' @examples
#' ## temporary directory, to avoid messing up the user's workspace.
#' dir.create(tmp <- tempfile())
#' dir.create(file.path(tmp, "mydir"))
#' cat("first file", file = file.path(tmp, "mydir", "file1"))
#' cat("second file", file = file.path(tmp, "mydir", "file2"))
#'
#' zipfile <- tempfile(fileext = ".zip")
#' zip::zip(zipfile, "mydir", root = tmp)
#'
#' ## List contents
#' zip_list(zipfile)
#'
#' ## Extract
#' tmp2 <- tempfile()
#' unzip(zipfile, exdir = tmp2)
#' dir(tmp2, recursive = TRUE)
unzip <- function(zipfile, files = NULL, overwrite = TRUE,
junkpaths = FALSE, exdir = ".") {
stopifnot(
is_string(zipfile),
is_character_or_null(files),
is_flag(overwrite),
is_flag(junkpaths),
is_string(exdir))
zipfile <- enc2c(normalizePath(zipfile))
if (!is.null(files)) files <- enc2c(files)
exdir <- sub("/+$", "", exdir)
mkdirp(exdir)
exdir <- enc2c(normalizePath(exdir))
.Call(c_R_zip_unzip, zipfile, files, overwrite, junkpaths, exdir)
invisible()
}
| /scratch/gouwar.j/cran-all/cranData/zip/R/zip.R |
progs <- if (WINDOWS) {
file.path("tools", c("cmdzip.exe", "cmdunzip.exe", "zip.exe"))
} else {
file.path("tools", c("cmdzip", "cmdunzip"))
}
dest <- file.path(R_PACKAGE_DIR, paste0("bin", R_ARCH))
dir.create(dest, recursive = TRUE, showWarnings = FALSE)
file.copy(progs, dest, overwrite = TRUE)
files <- Sys.glob(paste0("*", SHLIB_EXT))
dest <- file.path(R_PACKAGE_DIR, paste0('libs', R_ARCH))
dir.create(dest, recursive = TRUE, showWarnings = FALSE)
file.copy(files, dest, overwrite = TRUE)
if (file.exists("symbols.rds")) {
file.copy("symbols.rds", dest, overwrite = TRUE)
}
| /scratch/gouwar.j/cran-all/cranData/zip/src/install.libs.R |
if(getRversion() < "3.3.0") setInternet2()
if (!file.exists("../tools/zip.exe")) {
download.file(
"https://github.com/rwinlib/zip/blob/master/zip.exe?raw=true",
"../tools/zip.exe",
quiet = TRUE,
mode = "wb"
)
}
file.copy("../tools/zip.exe", "tools/zip.exe")
| /scratch/gouwar.j/cran-all/cranData/zip/tools/getzipexe.R |
#' broadcasts a shorter vector-like object into a vector of equal length as a longer vector-like object
#' @param longer longer vector-like object
#' @param shorter shorter vector-like object
#'
#'
broadcast <- function(longer, shorter) {
return (rep(shorter, ceiling(length(longer) / length(shorter) ) )[1:length(longer)])
}
| /scratch/gouwar.j/cran-all/cranData/zipR/R/broadcast.R |
#'
#' This function checks that the vector-like objects x, y are of equal length.
#' @param x vector-like object
#' @param y vector-like object
#'
#'
check_length <- function(x, y) {
if (length(x) != length(y)) {
stop("Error: x, y unequal lengths")
}
else {
#pass
}
}
| /scratch/gouwar.j/cran-all/cranData/zipR/R/check_length.R |
#'
#' Use a given fillvalue to fill in a shorter sequence and returns a sequence of equal length to the longer sequence. Takes a subset of the fill sequence if fill sequence is longer than the difference between the longer and shorter sequences
#' @param shorter shorter vector-like object
#' @param longer longer vector-like object
#' @param fillvalue sequence of value(s) to fill in shorter vector. If fillvalue is longer than the difference between `shorter` and `longer`, values from fillvalue will be taken only until `shorter` is the same length as `longer`
#'
#'
fill <- function(longer, shorter, fillvalue) {
diff <- length(longer) - length(shorter)
fillers <- rep(fillvalue, diff)[1:diff]
shorter <- c(shorter, fillers)
return(shorter)
}
| /scratch/gouwar.j/cran-all/cranData/zipR/R/fill.R |
#'
#' zip two vector-like objects into a dataframe
#' @param x vector-like object
#' @param y vector-like object
#' @param broadcast defaults to FALSE; if TRUE, shorter sequence is repeated until its length is equal to that of the longer sequence
#' @param fill defaults to FALSE; bool for whether fillvalue should be implemented
#' @param fillvalue value or sequence of value(s) to fill in shorter sequence until it is the same length as the longer sequence. Defaults to NA
#'
#' @return A dataframe
#' @export
#'
#' @examples
#'
#' a <- c(1,2,3)
#' b <- c(4,5,6)
#' c <- c(1,2,3,4,5,6)
#' d <- c(7,8)
#' z <- c(9)
#' filler <- c(NA)
#'
#' # zip two vectors of the same length
#' zipr(a,b)
#'
#' # zip two vectors of different lengths, repeating the shorter vector
#' zipr(a, z, broadcast = TRUE)
#'
#' # zip two vectors of different lengths, using the default fill value
#' zipr(z, a, fill = TRUE)
#'
#' # zip two vectors of different lengths, using a custom fill value
#' zipr(c,a, fill = TRUE, fillvalue = z)
zipr <- function(x = x, y = x, broadcast = FALSE, fill = FALSE, fillvalue = c(NA)) {
if (broadcast == TRUE & fill == TRUE) {
stop("Error: cannot specify both broadcast = TRUE and fillvalue = seq ")
}
else if (broadcast == FALSE & fill == FALSE) {
check_length(x, y)
}
else if (broadcast == TRUE & fill == FALSE) {
if (length(x) > length(y)) {
y <- broadcast(x, y)
}
else {
x <- broadcast(y, x)
}
}
else if (broadcast == FALSE & fill == TRUE) {
if (length(x) > length(y)) {
y <- fill(x, y, fillvalue)
}
else {
x <- fill(y, x, fillvalue)
}
}
result <- data.frame(x = x,
y = y)
return(result)
}
| /scratch/gouwar.j/cran-all/cranData/zipR/R/zipr.R |
## ----setup, include = FALSE----------------------------------------------
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
## ----echo=FALSE----------------------------------------------------------
library(zipR)
## ----echo=TRUE-----------------------------------------------------------
a <- c(1,2,3)
b <- c(4,5,6)
c <- c(1,2,3,4,5,6)
d <- c(7,8)
z <- c(9)
filler <- c(NA)
## ------------------------------------------------------------------------
zipR::zipr(a,b)
## ------------------------------------------------------------------------
zipr(a, z, broadcast = TRUE)
zipr(a, c, broadcast = TRUE)
## ------------------------------------------------------------------------
zipr(z, a, fill = TRUE)
## ------------------------------------------------------------------------
zipr(c,a, fill = TRUE, fillvalue = z)
zipr(c,z, fill = TRUE, fillvalue = d)
| /scratch/gouwar.j/cran-all/cranData/zipR/inst/doc/my-vignette.R |
---
title: "zipR vignette"
author: "Leslie Huang"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{zipR vignette}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r setup, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
```
## Introducing zipR: zip() for R
zip() is an incredibly handy built-in function in Python. Unlike many other great Python features/structures (such as iterators, generators, and dictionaries), zip() is relatively easy to implement in R. Here is a brief introduction to `zipR`.
This is a work in progress! For bugs and features, please <a href="https://github.com/leslie-huang/zipR">open an issue on GitHub</a>.
### Loading the library
```{r echo=FALSE}
library(zipR)
```
### Dummy data
Some sequences of different lengths, in order to test the different options available in `zipr`.
```{r echo=TRUE}
a <- c(1,2,3)
b <- c(4,5,6)
c <- c(1,2,3,4,5,6)
d <- c(7,8)
z <- c(9)
filler <- c(NA)
```
### zip two vectors of the same length
```{r}
zipR::zipr(a,b)
```
### zip two vectors of different lengths, repeating the shorter vector
`broadcast = TRUE` repeats elements of the shorter vector so that it is the same length as the longer vector
```{r}
zipr(a, z, broadcast = TRUE)
zipr(a, c, broadcast = TRUE)
```
### zip two vectors of different lengths, using the default fill value
`fill = TRUE` without a `fillvalue` specified fills in the shorter vector with `NA`
```{r}
zipr(z, a, fill = TRUE)
```
### zip two vectors of different lengths, using a custom fill value
```{r}
zipr(c,a, fill = TRUE, fillvalue = z)
zipr(c,z, fill = TRUE, fillvalue = d)
```
| /scratch/gouwar.j/cran-all/cranData/zipR/inst/doc/my-vignette.Rmd |
---
title: "zipR vignette"
author: "Leslie Huang"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{zipR vignette}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r setup, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
```
## Introducing zipR: zip() for R
zip() is an incredibly handy built-in function in Python. Unlike many other great Python features/structures (such as iterators, generators, and dictionaries), zip() is relatively easy to implement in R. Here is a brief introduction to `zipR`.
This is a work in progress! For bugs and features, please <a href="https://github.com/leslie-huang/zipR">open an issue on GitHub</a>.
### Loading the library
```{r echo=FALSE}
library(zipR)
```
### Dummy data
Some sequences of different lengths, in order to test the different options available in `zipr`.
```{r echo=TRUE}
a <- c(1,2,3)
b <- c(4,5,6)
c <- c(1,2,3,4,5,6)
d <- c(7,8)
z <- c(9)
filler <- c(NA)
```
### zip two vectors of the same length
```{r}
zipR::zipr(a,b)
```
### zip two vectors of different lengths, repeating the shorter vector
`broadcast = TRUE` repeats elements of the shorter vector so that it is the same length as the longer vector
```{r}
zipr(a, z, broadcast = TRUE)
zipr(a, c, broadcast = TRUE)
```
### zip two vectors of different lengths, using the default fill value
`fill = TRUE` without a `fillvalue` specified fills in the shorter vector with `NA`
```{r}
zipr(z, a, fill = TRUE)
```
### zip two vectors of different lengths, using a custom fill value
```{r}
zipr(c,a, fill = TRUE, fillvalue = z)
zipr(c,z, fill = TRUE, fillvalue = d)
```
| /scratch/gouwar.j/cran-all/cranData/zipR/vignettes/my-vignette.Rmd |
#' Separate address elements
#' @description
#' \Sexpr[results=rd, stage=render]{lifecycle::badge("experimental")}
#' Parses and decomposes address string into elements of
#' prefecture, city, and lower address.
#' @param str Input vector. address strings.
#' @return A list of elements that make up an address.
#' @examples
#' separate_address("\u5317\u6d77\u9053\u672d\u5e4c\u5e02\u4e2d\u592e\u533a")
#' @export
separate_address <- function(str) {
. <- NULL
city_name_regex <-
"(\u5ca1\u5c71\u5e02\u5357\u533a|(\u98ef\u80fd|\u4e0a\u5c3e|\u5b89\u4e2d|\u5742\u4e95|\u753a\u7530|\u5e02\u539f|\u5e02\u5ddd|\u6751\u4e0a)\u5e02|\u6751\u5c71\u5e02|\u4f59\u5e02\u90e1(\u4f59\u5e02\u753a|\u4ec1\u6728\u753a|\u8d64\u4e95\u5ddd\u6751)|(\u4f59\u5e02|\u9ad8\u5e02)\u90e1.+(\u753a|\u6751)|\u67f4\u7530\u90e1(\u6751\u7530\u753a|\u5927\u6cb3\u539f\u753a)|(\u6b66\u8535|\u6771)\u6751\u5c71\u5e02|\u897f\u6751\u5c71\u90e1\u6cb3\u5317\u753a|\u5317\u6751\u5c71\u90e1\u5927\u77f3\u7530\u753a|(\u6771|\u897f|\u5317)\u6751\u5c71\u90e1.+(\u753a|\u6751)|\u7530\u6751(\u5e02|\u90e1..\u753a)|\u82b3\u8cc0\u90e1\u5e02\u8c9d\u753a|(\u4f50\u6ce2\u90e1)?\u7389\u6751\u753a|[\u7fbd\u5927]\u6751\u5e02|(\u5341\u65e5|\u5927)\u753a\u5e02|(\u4e2d\u65b0\u5ddd\u90e1)?\u4e0a\u5e02\u753a|(\u91ce\u3005|[\u56db\u5eff]\u65e5)\u5e02\u5e02|\u897f\u516b\u4ee3\u90e1\u5e02\u5ddd\u4e09\u90f7\u753a|\u795e\u5d0e\u90e1\u5e02\u5ddd\u753a|\u9ad8\u5e02\u90e1(\u9ad8\u53d6\u753a|\u660e\u65e5\u9999\u6751)|(\u5409\u91ce\u90e1)?\u4e0b\u5e02\u753a|(\u6775\u5cf6\u90e1)?\u5927\u753a\u753a|(\u5357\u76f8\u99ac|\u5317\u4e0a|\u5965\u5dde|\u90a3\u9808\u5869\u539f|\u5370\u897f|\u4e0a\u8d8a|\u59eb\u8def|\u7389\u91ce|\u5c71\u53e3|\u4f50\u4f2f|\u5317\u898b|\u58eb\u5225|\u5bcc\u826f\u91ce|\u65ed\u5ddd|\u4f0a\u9054|\u77f3\u72e9|\u5bcc\u5c71|\u9ed2\u90e8|\u5c0f\u8af8|\u5869\u5c3b|\u677e\u962a|\u8c4a\u5ddd|\u798f\u77e5\u5c71|\u5468\u5357|\u897f\u6d77|\u5225\u5e9c)\u5e02|(\u5343\u4ee3\u7530|\u4e2d\u592e|\u6e2f|\u65b0\u5bbf|\u6587\u4eac|\u53f0\u6771|\u58a8\u7530|\u6c5f\u6771|\u54c1\u5ddd|\u76ee\u9ed2|\u5927\u7530|\u4e16\u7530\u8c37|\u6e0b\u8c37|\u4e2d\u91ce|\u6749\u4e26|\u8c4a\u5cf6|\u5317|\u8352\u5ddd|\u677f\u6a4b|\u7df4\u99ac|\u8db3\u7acb|\u845b\u98fe|\u6c5f\u6238\u5ddd)\u533a|.+\u5e02.+\u533a|\u5e02|\u753a|\u6751)"
res <-
purrr::map(
str,
function(str) {
split_pref <-
stringr::str_split(str,
stringr::regex("(?<=(\u6771\u4eac\u90fd|\u9053|\u5e9c|\u770c))"),
n = 2,
simplify = TRUE) %>%
stringr::str_subset(".{1}", negate = FALSE)
if (length(split_pref) == 1L) {
if (is_prefecture(str)) {
split_pref <- c(split_pref, NA_character_)
} else {
if (stringr::str_detect(split_pref,
city_name_regex)) {
split_pref <- c(NA_character_, split_pref)
} else {
split_pref <- c(NA_character_, NA_character_)
}
}
}
res <-
list(prefecture = split_pref[1])
if (length(split_pref[2] %>%
stringr::str_split(city_name_regex,
n = 2,
simplify = TRUE) %>%
stringr::str_subset(".{1}", negate = FALSE)) == 0L) {
res <-
res %>%
purrr::list_merge(
city =
split_pref[2] %>%
dplyr::if_else(is_address_block(.),
stringr::str_remove(., "((\u571f\u5730\u533a\u753b|\u8857\u533a).+)") %>%
stringr::str_remove("\u571f\u5730\u533a\u753b|\u8857\u533a"),
.) %>%
stringr::str_replace("(.\u5e02)(.+\u753a.+)", "\\1") %>%
stringr::str_replace(city_name_regex,
replacement = "\\1")
)
} else {
res <-
res %>%
purrr::list_merge(
city =
split_pref[2] %>%
dplyr::if_else(is_address_block(.),
stringr::str_remove(., "((\u571f\u5730\u533a\u753b|\u8857\u533a).+)") %>%
stringr::str_remove("\u571f\u5730\u533a\u753b|\u8857\u533a"),
.) %>%
stringr::str_replace(
paste0(city_name_regex, "(.+)"),
replacement = "\\1"))
}
res <-
res %>%
purrr::list_merge(
street = split_pref[2] %>%
stringr::str_remove(res %>%
purrr::pluck("city")))
res %>%
purrr::map(
~ dplyr::if_else(.x == "", NA_character_, .x)
)
}
)
if (length(res) == 1L) {
purrr::flatten(res)
} else {
res
}
}
is_address_block <- function(str) {
str %>%
stringr::str_detect("(\u571f\u5730\u533a\u753b\u4e8b\u696d\u5730\u5185|\u8857\u533a|\u8857\u533a.+)$")
}
| /scratch/gouwar.j/cran-all/cranData/zipangu/R/address.R |
convert_jyear_impl1 <- function(jyear) {
jyear <-
stringr::str_trim(jyear)
res <- rep(NA_real_, length(jyear))
# Convert to position to ignore NAs
idx_ad <-
which(stringr::str_detect(jyear, "([0-9]{4}|[0-9]{4}.+\u5e74)"))
idx_wareki <-
which(is_jyear(jyear))
# If there are some index not covered by AD or Wareki, show a warning
if (length(setdiff(seq_along(jyear), c(idx_ad, idx_wareki, which(is.na(jyear))))) > 0) {
rlang::warn("Unsupported Japanese imperial year.\nPlease include the year after 1868 or the year used since then, Meiji, Taisho, Showa, Heisei and Reiwa.")
}
# For AD years, simply parse the numbers
res[idx_ad] <-
as.numeric(stringr::str_replace(jyear[idx_ad], "\u5e74", ""))
# For Wareki years, do some complex stuff...
jyear_wareki <-
jyear_initial_tolower(jyear[idx_wareki])
wareki_yr <-
as.integer(
stringr::str_extract(
jyear_wareki,
pattern = "[0-9]{1,2}"))
wareki_roman <-
stringr::str_sub(jyear_wareki, 1, 1) %>%
purrr::map_chr(convert_jyear_roman)
res[idx_wareki] <-
wareki_yr +
wareki_roman %>%
purrr::map_dbl(function(.x) {
jyear_sets %>%
purrr::map("start_year") %>%
purrr::map(~ .x - 1) %>%
purrr::pluck(stringr::str_which(.x, names(jyear_sets)))
})
res
}
convert_jdate_impl1 <- function(date) {
date %>%
purrr::map(
~ rlang::exec(lubridate::make_date,
!!!split_ymd_elements(.x))
) %>%
purrr::reduce(c)
}
jyear_initial_tolower <- function(jyear) {
jyear <-
stringr::str_replace(jyear, "\u5143", "1")
idx <-
which(stringr::str_detect(jyear, "[A-Za-z]"))
jyear[idx] <-
stringr::str_to_lower(jyear[idx])
jyear
}
split_ymd_elements <- function(x) {
x %>%
purrr::map(
function(.x) {
if (is.na(.x)) {
NA_real_
} else {
.x %>%
stringi::stri_trans_general(id = "nfkc") %>%
stringr::str_split("(\u5e74|\u6708|\u65e5)|(\\.)|(\\-)|(\\/)",
simplify = TRUE) %>%
purrr::keep(~ nchar(.) > 0) %>%
purrr::modify_at(1,
~ convert_jyear_impl1(.x)) %>%
purrr::map(as.integer) %>%
purrr::set_names(c("year", "month", "day"))
}
}
) %>%
purrr::flatten()
}
is_jyear <- function(jyear) {
pattern <- paste0(
"^(",
paste(jyear_sets %>%
purrr::map(~ .x[c("kanji", "roman")]) %>%
purrr::flatten() %>%
purrr::as_vector(),
collapse = "|"),
")")
res <-
stringr::str_detect(jyear_initial_tolower(jyear),
pattern)
res %>%
purrr::map2_lgl(
.y = jyear,
function(.x, .y) {
if (is.na(.x)) {
.x
} else if (.x == FALSE) {
pattern <- paste0(
"^(",
paste(jyear_sets %>%
purrr::map(~ .x[c("kanji_capital", "roman_capital")]) %>%
purrr::flatten(),
collapse = "|"),
")([0-9]|[\u3007\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d\u5341])")
stringr::str_detect(jyear_initial_tolower(.y),
pattern)
} else {
TRUE
}
}
)
}
convert_jyear_roman <- function(x) {
check_roman <-
stringr::str_which(x,
jyear_sets %>%
purrr::map(`[`, c("roman_capital")) %>%
unlist())
if (length(check_roman) > 0) {
names(jyear_sets)[check_roman]
} else {
l_kanji <-
jyear_sets %>%
purrr::map_chr("kanji_capital")
l_roman <-
names(l_kanji) %>%
purrr::set_names(l_kanji)
dplyr::recode(x, !!!l_roman)
}
}
jyear_sets <-
list(
c("\u660e\u6cbb",
"\u5927\u6b63",
"\u662d\u548c",
"\u5e73\u6210",
"\u4ee4\u548c"),
list("meiji",
c("taisyo", "taisho", "taisyou"),
c("syouwa", "showa"),
"heisei",
"reiwa")) %>%
rep(each = 2) %>%
purrr::map_at(2,
~ stringr::str_sub(.x, 1, 1)) %>%
purrr::map_at(4,
~ purrr::map(.x, stringr::str_sub, 1, 1) %>%
unlist() %>%
unique()) %>%
purrr::set_names(c("kanji", "kanji_capital", "roman", "roman_capital")) %>%
purrr::list_merge(start_year = c(1868, 1912, 1926, 1989, 2019)) %>%
purrr::transpose(.names = c("meiji", "taisyo", "syouwa", "heisei", "reiwa")) %>%
purrr::simplify()
| /scratch/gouwar.j/cran-all/cranData/zipangu/R/convert-jyear-legacy.R |
#' Convert Japanese imperial year to Anno Domini
#' @description
#' \Sexpr[results=rd, stage=render]{lifecycle::badge("maturing")}
#' @param jyear Japanese imperial year (jyear). Kanji or Roman character
#' @param legacy A logical to switch converter. If `TRUE` supplied, use the legacy
#' converter instead of 'ICU' implementation.
#' @section Examples:
#' ```{r, child = "man/rmd/setup.Rmd"}
#' ```
#'
#' ```{r}
#' convert_jyear("R1")
#' convert_jyear("Heisei2")
#' convert_jyear("\u5e73\u6210\u5143\u5e74")
#' convert_jyear(c("\u662d\u548c10\u5e74", "\u5e73\u621014\u5e74"))
#' convert_jyear(kansuji2arabic_all("\u5e73\u6210\u4e09\u5e74"))
#' ```
#' @export
convert_jyear <- function(jyear, legacy = FALSE) {
if (legacy) {
convert_jyear_impl1(jyear)
} else {
convert_jyear_impl2(jyear)
}
}
#' Convert Japanese date format to date object
#' @description
#' \Sexpr[results=rd, stage=render]{lifecycle::badge("maturing")}
#' @param date A character object.
#' @param legacy A logical to switch converter. If `TRUE` supplied, use the legacy
#' converter instead of 'ICU' implementation.
#' @section Examples:
#' ```{r, child = "man/rmd/setup.Rmd"}
#' ```
#'
#' ```{r}
#' convert_jdate("R3/2/27")
#' convert_jdate("\u4ee4\u548c2\u5e747\u67086\u65e5")
#' ```
#' @export
convert_jdate <- function(date, legacy = FALSE) {
if (legacy) {
convert_jdate_impl1(date)
} else {
convert_jdate_impl2(date)
}
}
convert_jyear_impl2 <- function(jyear) {
jyear <- stringi::stri_trim(jyear) %>%
stringi::stri_trans_nfkc()
dplyr::if_else(
stringi::stri_detect_regex(jyear, "[:number:]{3,}"),
{
stringi::stri_datetime_parse(
jyear,
format = "yy\u5e74"
) %>%
lubridate::year()
},
{
stringi::stri_datetime_parse(
format_jdate(jyear),
format = "Gy\u5e74",
locale = "ja-JP-u-ca-japanese"
) %>%
lubridate::year()
}
)
}
convert_jdate_impl2 <- function(jdate) {
jdate <- stringi::stri_trim(jdate) %>%
stringi::stri_trans_nfkc() %>%
format_jdate()
sp <- stringi::stri_split_regex(
jdate,
"(\u5e74|\u6708|\u65e5)|(\\.)|(\\-)|(\\/)",
) %>%
purrr::map_chr(~ paste0(.[1], "\u5e74", .[2], "\u6708", .[3], "\u65e5"))
stringi::stri_datetime_parse(
sp,
format = "Gy\u5e74M\u6708d\u65e5",
locale = "ja-JP-u-ca-japanese"
) %>%
lubridate::as_date()
}
format_jdate <- function(jdate) {
stringi::stri_trans_tolower(jdate) %>%
stringi::stri_replace_all_regex(
c("meiji", "taisyo|taisho|taisyou", "syouwa|showa", "heisei", "reiwa"),
c("m", "t", "s", "h", "r"),
vectorise_all = FALSE
) %>%
stringi::stri_replace_all_regex(
c("m|\u660e(?!\u6cbb)", "t|\u5927(?!\u6b63)", "s|\u662d(?!\u548c)", "h|\u5e73(?!\u6210)", "r|\u4ee4(?!\u548c)"),
c("\u660e\u6cbb", "\u5927\u6b63", "\u662d\u548c", "\u5e73\u6210", "\u4ee4\u548c"),
vectorise_all = FALSE
)
}
| /scratch/gouwar.j/cran-all/cranData/zipangu/R/convert-jyear.R |
#' Converts the kind of string used as Japanese
#' @description
#' \Sexpr[results=rd, stage=render]{lifecycle::badge("stable")}
#' @details Converts the types of string treat by Japanese people to
#' each other. The following types are supported.
#' * Hiraganra to Katakana
#' * Zenkaku to Hankaku
#' * Latin (Roman) to Hiragana
#' @inheritParams kansuji2arabic
#' @param fun convert function
#' @param to Select the type of character to convert.
#' @seealso These functions are powered by the stringi
#' package's [stri_trans_general()][stringi::stri_trans_general].
#' @examples
#' str_jconv("\u30a2\u30a4\u30a6\u30a8\u30aa", str_conv_hirakana, to = "hiragana")
#' str_jconv("\u3042\u3044\u3046\u3048\u304a", str_conv_hirakana, to = "katakana")
#' str_jconv("\uff41\uff10", str_conv_zenhan, "hankaku")
#' str_jconv("\uff76\uff9e\uff6f", str_conv_zenhan, "zenkaku")
#' str_jconv("\u30a2\u30a4\u30a6\u30a8\u30aa", str_conv_romanhira, "roman")
#' str_jconv("\u2460", str_conv_normalize, "nfkc")
#' str_conv_hirakana("\u30a2\u30a4\u30a6\u30a8\u30aa", to = "hiragana")
#' str_conv_hirakana("\u3042\u3044\u3046\u3048\u304a", to = "katakana")
#' str_conv_zenhan("\uff41\uff10", "hankaku")
#' str_conv_zenhan("\uff76\uff9e\uff6f", "zenkaku")
#' str_conv_romanhira("aiueo", "hiragana")
#' str_conv_romanhira("\u3042\u3044\u3046\u3048\u304a", "roman")
#' str_conv_normalize("\u2460", "nfkc")
#' @export
str_jconv <- function(str, fun, to) {
fun(str, to)
}
#' @rdname str_jconv
#' @export
str_conv_hirakana <- function(str, to = c("hiragana", "katakana")) {
rlang::arg_match(to)
if (to == "hiragana") {
stringi::stri_trans_general(str, "Katakana-Hiragana")
} else {
stringi::stri_trans_general(str, "Hiragana-Katakana")
}
}
#' @rdname str_jconv
#' @export
str_conv_zenhan <- function(str, to = c("zenkaku", "hankaku")) {
rlang::arg_match(to)
switch (to,
"zenkaku" = stringi::stri_trans_general(str, "Halfwidth-Fullwidth"),
"hankaku" = stringi::stri_trans_general(str, "Fullwidth-Halfwidth")
)
}
#' @rdname str_jconv
#' @export
str_conv_romanhira <- function(str, to = c("roman", "hiragana")) {
rlang::arg_match(to)
switch (to,
"roman" = stringi::stri_trans_general(str, "Any-Latin"),
"hiragana" = stringi::stri_trans_general(str, "Latin-Hiragana")
)
}
#' @rdname str_jconv
#' @export
str_conv_normalize <- function(str, to = c("nfkc")) {
rlang::arg_match(to)
stringi::stri_trans_general(str, "nfkc")
}
| /scratch/gouwar.j/cran-all/cranData/zipangu/R/convert-str.R |
convert_prefecture_to_kanji <- function(x) {
x <- enc2utf8(as.character(x)) # Encoding to UTF-8
if (any(is_prefecture(x) | x == "\u5168\u56fd"))
stop(
"\u65e5\u672c\u8a9e\u8868\u8a18\u304c\u542b\u307e\u308c\u3066\u3044\u307e\u3059"
) # check:is Japanese
x <- stringr::str_to_sentence(x) # Convert to sentence
x <- stringr::str_c("^", x, "$")
for (i in 1:length(x)) {
if (any(stringr::str_detect(prefecture_list[[5]], x[i]))) {
x[i] <-
prefecture_list[[1]][stringr::str_detect(prefecture_list[[5]], x[i])] #Convert japanese to roman
} else if (any(stringr::str_detect(prefecture_list[[6]], x[i]))) {
x[i] <-
prefecture_list[[2]][stringr::str_detect(prefecture_list[[6]], x[i])] #Convert japanese to roman
} else {
stop(
"\u5b58\u5728\u3057\u306a\u3044\u5730\u57df\u304c\u542b\u307e\u308c\u3066\u3044\u307e\u3059"
) # check;is Japan
}
}
return(x)
}
convert_prefecture_to_roman <- function(x) {
x <- enc2utf8(as.character(x)) # Encoding to UTF-8
if (any(!is_prefecture(x) & x != "\u5168\u56fd"))
stop(
"\u65e5\u672c\u8a9e\u8868\u8a18\u4ee5\u5916\u304c\u542b\u307e\u308c\u3066\u3044\u307e\u3059"
) # check:is Japanese
x <- stringr::str_c("^", x, "$")
for (i in 1:length(x)) {
if (any(stringr::str_detect(prefecture_list[[1]], x[i]))) {
x[i] <-
prefecture_list[[5]][stringr::str_detect(prefecture_list[[1]], x[i])] #Convert japanese to roman
} else if (any(stringr::str_detect(prefecture_list[[2]], x[i]))) {
x[i] <-
prefecture_list[[6]][stringr::str_detect(prefecture_list[[2]], x[i])] #Convert japanese to roman
} else {
stop(
"\u5b58\u5728\u3057\u306a\u3044\u5730\u57df\u304c\u542b\u307e\u308c\u3066\u3044\u307e\u3059"
) #check;is Japan
}
}
return(x)
}
#' Convert prefecture names to roman or kanji
#'
#' @param x prefecture name in kanji
#' @param to conversion destination
#'
#' @examples
#' convert_prefecture(c("tokyo-to", "osaka", "ALL"), to="kanji")
#' convert_prefecture(
#' c("\u6771\u4eac", "\u5927\u962a\u5e9c",
#' "\u5317\u6d77\u9053", "\u5168\u56fd"),
#' to = "roman")
#' @export
convert_prefecture <- function(x, to) {
if (to == "kanji") {
convert_prefecture_to_kanji(x)
} else if (to == "roman") {
convert_prefecture_to_roman(x)
} else {
stop("to\u304c\u6b63\u3057\u304f\u3042\u308a\u307e\u305b\u3093")
}
}
| /scratch/gouwar.j/cran-all/cranData/zipangu/R/convert_prefecture.R |
#' Convert prefecture names from kana
#'
#' @param x prefecture name in kana
#'
#' @examples
#' convert_prefecture_from_kana(c("\u3068\u3046\u304d\u3087\u3046\u3068"))
#' convert_prefecture_from_kana(c("\u30c8\u30a6\u30ad\u30e7\u30a6\u30c8", "\u30ad\u30e7\u30a6\u30c8"))
#' convert_prefecture_from_kana(c("\u30c8\u30a6\u30ad\u30e7\u30a6", "\u304a\u304a\u3055\u304b"))
#'
#' @export
convert_prefecture_from_kana <- function(x) {
x <- enc2utf8(as.character(x)) # Encoding to UTF-8
x <- str_conv_hirakana(x, to = "hiragana") # Convert to hiragana
# Avoid conflicts between
# "\u304d\u3087\u3046\u3068" and "\u3068\u3046\u304d\u3087\u3046\u3068"
x <- stringr::str_c("^", x, "$")
for (i in 1:length(x)) {
if (any(stringr::str_detect(prefecture_list[[3]], x[i]))) {
x[i] <-
prefecture_list[[1]][stringr::str_detect(prefecture_list[[3]], x[i])]
} else if (any(stringr::str_detect(prefecture_list[[4]], x[i]))) {
x[i] <-
prefecture_list[[2]][stringr::str_detect(prefecture_list[[4]], x[i])]
} else {
stop(
"\u5b58\u5728\u3057\u306a\u3044\u5730\u57df\u304c\u542b\u307e\u308c\u3066\u3044\u307e\u3059"
)
}
}
return(x)
}
| /scratch/gouwar.j/cran-all/cranData/zipangu/R/convert_prefecture_from_kana.R |
prefecture_list <- list(
c("\u5317\u6d77\u9053","\u9752\u68ee\u770c","\u5ca9\u624b\u770c","\u5bae\u57ce\u770c",
"\u79cb\u7530\u770c","\u5c71\u5f62\u770c","\u798f\u5cf6\u770c","\u8328\u57ce\u770c",
"\u6803\u6728\u770c","\u7fa4\u99ac\u770c","\u57fc\u7389\u770c","\u5343\u8449\u770c",
"\u6771\u4eac\u90fd","\u795e\u5948\u5ddd\u770c","\u65b0\u6f5f\u770c","\u5bcc\u5c71\u770c",
"\u77f3\u5ddd\u770c","\u798f\u4e95\u770c","\u5c71\u68a8\u770c","\u9577\u91ce\u770c",
"\u5c90\u961c\u770c","\u9759\u5ca1\u770c","\u611b\u77e5\u770c","\u4e09\u91cd\u770c",
"\u6ecb\u8cc0\u770c","\u4eac\u90fd\u5e9c","\u5927\u962a\u5e9c","\u5175\u5eab\u770c",
"\u5948\u826f\u770c","\u548c\u6b4c\u5c71\u770c","\u9ce5\u53d6\u770c","\u5cf6\u6839\u770c",
"\u5ca1\u5c71\u770c","\u5e83\u5cf6\u770c","\u5c71\u53e3\u770c","\u5fb3\u5cf6\u770c",
"\u9999\u5ddd\u770c","\u611b\u5a9b\u770c","\u9ad8\u77e5\u770c","\u798f\u5ca1\u770c",
"\u4f50\u8cc0\u770c","\u9577\u5d0e\u770c","\u718a\u672c\u770c","\u5927\u5206\u770c",
"\u5bae\u5d0e\u770c","\u9e7f\u5150\u5cf6\u770c","\u6c96\u7e04\u770c","\u5168\u56fd"),
c("\u5317\u6d77\u9053","\u9752\u68ee","\u5ca9\u624b","\u5bae\u57ce",
"\u79cb\u7530","\u5c71\u5f62","\u798f\u5cf6","\u8328\u57ce",
"\u6803\u6728","\u7fa4\u99ac","\u57fc\u7389","\u5343\u8449",
"\u6771\u4eac","\u795e\u5948\u5ddd","\u65b0\u6f5f","\u5bcc\u5c71",
"\u77f3\u5ddd","\u798f\u4e95","\u5c71\u68a8","\u9577\u91ce",
"\u5c90\u961c","\u9759\u5ca1","\u611b\u77e5","\u4e09\u91cd",
"\u6ecb\u8cc0","\u4eac\u90fd","\u5927\u962a","\u5175\u5eab",
"\u5948\u826f","\u548c\u6b4c\u5c71","\u9ce5\u53d6","\u5cf6\u6839",
"\u5ca1\u5c71","\u5e83\u5cf6","\u5c71\u53e3","\u5fb3\u5cf6",
"\u9999\u5ddd","\u611b\u5a9b","\u9ad8\u77e5","\u798f\u5ca1",
"\u4f50\u8cc0","\u9577\u5d0e","\u718a\u672c","\u5927\u5206",
"\u5bae\u5d0e","\u9e7f\u5150\u5cf6","\u6c96\u7e04","\u5168\u56fd"),
c("\u307b\u3063\u304b\u3044\u3069\u3046","\u3042\u304a\u3082\u308a\u3051\u3093","\u3044\u308f\u3066\u3051\u3093",
"\u307f\u3084\u304e\u3051\u3093","\u3042\u304d\u305f\u3051\u3093","\u3084\u307e\u304c\u305f\u3051\u3093",
"\u3075\u304f\u3057\u307e\u3051\u3093","\u3044\u3070\u3089\u304d\u3051\u3093","\u3068\u3061\u304e\u3051\u3093",
"\u3050\u3093\u307e\u3051\u3093","\u3055\u3044\u305f\u307e\u3051\u3093","\u3061\u3070\u3051\u3093",
"\u3068\u3046\u304d\u3087\u3046\u3068","\u304b\u306a\u304c\u308f\u3051\u3093","\u306b\u3044\u304c\u305f\u3051\u3093",
"\u3068\u3084\u307e\u3051\u3093","\u3044\u3057\u304b\u308f\u3051\u3093","\u3075\u304f\u3044\u3051\u3093",
"\u3084\u307e\u306a\u3057\u3051\u3093","\u306a\u304c\u306e\u3051\u3093","\u304e\u3075\u3051\u3093",
"\u3057\u305a\u304a\u304b\u3051\u3093","\u3042\u3044\u3061\u3051\u3093","\u307f\u3048\u3051\u3093",
"\u3057\u304c\u3051\u3093","\u304d\u3087\u3046\u3068\u3075","\u304a\u304a\u3055\u304b\u3075",
"\u3072\u3087\u3046\u3054\u3051\u3093","\u306a\u3089\u3051\u3093","\u308f\u304b\u3084\u307e\u3051\u3093",
"\u3068\u3063\u3068\u308a\u3051\u3093","\u3057\u307e\u306d\u3051\u3093","\u304a\u304b\u3084\u307e\u3051\u3093",
"\u3072\u308d\u3057\u307e\u3051\u3093","\u3084\u307e\u3050\u3061\u3051\u3093","\u3068\u304f\u3057\u307e\u3051\u3093",
"\u304b\u304c\u308f\u3051\u3093","\u3048\u3072\u3081\u3051\u3093","\u3053\u3046\u3061\u3051\u3093",
"\u3075\u304f\u304a\u304b\u3051\u3093","\u3055\u304c\u3051\u3093","\u306a\u304c\u3055\u304d\u3051\u3093",
"\u304f\u307e\u3082\u3068\u3051\u3093","\u304a\u304a\u3044\u305f\u3051\u3093","\u307f\u3084\u3056\u304d\u3051\u3093",
"\u304b\u3054\u3057\u307e\u3051\u3093","\u304a\u304d\u306a\u308f\u3051\u3093","\u305c\u3093\u3053\u304f"),
c("\u307b\u3063\u304b\u3044\u3069\u3046","\u3042\u304a\u3082\u308a","\u3044\u308f\u3066",
"\u307f\u3084\u304e","\u3042\u304d\u305f","\u3084\u307e\u304c\u305f",
"\u3075\u304f\u3057\u307e","\u3044\u3070\u3089\u304d","\u3068\u3061\u304e",
"\u3050\u3093\u307e","\u3055\u3044\u305f\u307e","\u3061\u3070",
"\u3068\u3046\u304d\u3087\u3046","\u304b\u306a\u304c\u308f","\u306b\u3044\u304c\u305f",
"\u3068\u3084\u307e","\u3044\u3057\u304b\u308f","\u3075\u304f\u3044",
"\u3084\u307e\u306a\u3057","\u306a\u304c\u306e","\u304e\u3075",
"\u3057\u305a\u304a\u304b","\u3042\u3044\u3061","\u307f\u3048",
"\u3057\u304c","\u304d\u3087\u3046\u3068","\u304a\u304a\u3055\u304b",
"\u3072\u3087\u3046\u3054","\u306a\u3089","\u308f\u304b\u3084\u307e",
"\u3068\u3063\u3068\u308a","\u3057\u307e\u306d","\u304a\u304b\u3084\u307e",
"\u3072\u308d\u3057\u307e","\u3084\u307e\u3050\u3061","\u3068\u304f\u3057\u307e",
"\u304b\u304c\u308f","\u3048\u3072\u3081","\u3053\u3046\u3061",
"\u3075\u304f\u304a\u304b","\u3055\u304c","\u306a\u304c\u3055\u304d",
"\u304f\u307e\u3082\u3068","\u304a\u304a\u3044\u305f","\u307f\u3084\u3056\u304d",
"\u304b\u3054\u3057\u307e","\u304a\u304d\u306a\u308f","\u305c\u3093\u3053\u304f"),
c("Hokkaido","Aomori-ken","Iwate-ken","Miyagi-ken","Akita-ken","Yamagata-ken",
"Fukushima-ken","Ibaraki-ken","Tochigi-ken","Gunma-ken","Saitama-ken","Chiba-ken",
"Tokyo-to","Kanagawa-ken","Niigata-ken","Toyama-ken","Ishikawa-ken","Fukui-ken",
"Yamanashi-ken","Nagano-ken","Gifu-ken","Shizuoka-ken","Aichi-ken","Mie-ken",
"Shiga-ken","Kyoto-fu","Osaka-fu","Hyogo-ken","Nara-ken","Wakayama-ken",
"Tottori-ken","Shimane-ken","Okayama-ken","Hiroshima-ken","Yamaguchi-ken","Tokushima-ken",
"Kagawa-ken","Ehime-ken","Kochi-ken","Fukuoka-ken","Saga-ken","Nagasaki-ken",
"Kumamoto-ken","Oita-ken","Miyazaki-ken","Kagoshima-ken","Okinawa-ken","All"),
c("Hokkaido","Aomori","Iwate","Miyagi","Akita","Yamagata",
"Fukushima","Ibaraki","Tochigi","Gunma","Saitama","Chiba","Tokyo",
"Kanagawa","Niigata","Toyama","Ishikawa","Fukui",
"Yamanashi","Nagano","Gifu","Shizuoka","Aichi","Mie",
"Shiga","Kyoto","Osaka","Hyogo","Nara","Wakayama",
"Tottori","Shimane","Okayama","Hiroshima","Yamaguchi","Tokushima",
"Kagawa","Ehime","Kochi","Fukuoka","Saga","Nagasaki",
"Kumamoto","Oita","Miyazaki","Kagoshima","Okinawa","All")
)
| /scratch/gouwar.j/cran-all/cranData/zipangu/R/convert_prefecture_list.R |
#' Prefectural informations in Japan
#' @description Prefectures dataset.
#' @format A tibble with 47 rows 5 variables:
#' \itemize{
#' \item{jis_code: jis code}
#' \item{prefecture_kanji: prefecture names}
#' \item{prefecture: prefecture names}
#' \item{region: region}
#' \item{major_island: }
#' }
#' @examples
#' jpnprefs
"jpnprefs"
| /scratch/gouwar.j/cran-all/cranData/zipangu/R/data-jpnprefs.R |
#' Public holidays in Japan
#' @description
#' \Sexpr[results=rd, stage=render]{lifecycle::badge("experimental")}
#' @details Holiday information refers to data published as of December 21, 2020.
#' Future holidays are subject to change.
#' @param year numeric years after 1949.
#' If `NA` supplied, `jholiday_spec` returns `NA` respectively.
#' On the other hand, `jholiday` always omits any `NA` values.
#' @param name holiday names.
#' If this argument is not the same length of year, the first element will be recycled.
#' @param lang switch for turning values to "en" or "jp".
#' @references Public Holiday Law [https://www8.cao.go.jp/chosei/shukujitsu/gaiyou.html](https://www8.cao.go.jp/chosei/shukujitsu/gaiyou.html),
#' [https://elaws.e-gov.go.jp/document?lawid=323AC1000000178](https://elaws.e-gov.go.jp/document?lawid=323AC1000000178)
#' @rdname jholiday
#' @section Examples:
#' ```{r, child = "man/rmd/setup.Rmd"}
#' ```
#'
#' ```{r}
#' jholiday_spec(2019, "Sports Day")
#' jholiday_spec(2021, "Sports Day")
#' ```
#' List of a specific year holidays
#' ```{r}
#' jholiday(2021, "en")
#' ```
#' @importFrom rlang :=
#' @export
jholiday_spec <- function(year, name, lang = "en") {
if (are_all_current_law_yr(year)) {
if (length(year) < length(name))
rlang::abort("`year` must be a vector of length 1 or longer length than `name`.")
if (!identical(length(name), 1L) & (length(year) > length(name))) {
rlang::warn(
paste("`name` is expected to be a vector of length 1 or the same length of `year`.",
"the first element of `name` is recycled."
))
name <- name[1]
}
jholiday_names <- jholiday_list[[lang]]
if (!purrr::every(name, ~ match(., jholiday_names, nomatch = 0) > 0)) {
rlang::abort(
sprintf("No such holiday: %s",
purrr::discard(name, ~ match(., jholiday_names, nomatch = 0) > 0))
)
}
res <-
purrr::map2(year, name, function(yr, nm) {
fn_name <- paste("jholiday_spec", yr, lang, sep = "_")
if (!rlang::env_has(.pkgenv, fn_name)) {
rlang::env_bind(
.pkgenv,
!!fn_name := memoise::memoise(jholiday_spec_impl()(yr, lang))
)
}
rlang::env_get(.pkgenv, fn_name, inherit = TRUE)(nm)
}) %>%
unlist() %>%
lubridate::as_date()
res
}
}
#' @noRd
jholiday_spec_impl <- function() {
fn <- function(year, name, lang) {
if (!is.numeric(year) || is.na(year)) {
# early return
return(lubridate::as_date(NA_character_))
}
jholiday_names <- jholiday_list[[lang]]
dplyr::case_when(
# New Year's Day
name == jholiday_names[1] ~
lubridate::make_date(year, 1, 1),
# Coming of Age Day
name == jholiday_names[2] ~
dplyr::if_else(
year >= 2000,
find_date_by_wday(year, 1, 2, 2),
lubridate::ymd(paste0(year, "0115"))
),
# Foundation Day
name == jholiday_names[3] ~
dplyr::if_else(
year >= 1967,
lubridate::ymd(paste0(year, "0211")),
lubridate::as_date(NA_character_)
),
# Vernal Equinox Day
name == jholiday_names[4] ~
lubridate::make_date(year, 3, day = shunbun_day(year)),
# Showa Day (2007-), Greenery Day (1989-2006), and The Emperor's Birthday (-1989)
(name == jholiday_names[5] & year >= 2007) |
(name == jholiday_names[6] & dplyr::between(year, 1989, 2006)) |
(name == jholiday_names[7] & year < 1989) ~
lubridate::make_date(year, 4, 29),
# Constitution Memorial Day
name == jholiday_names[8] ~
lubridate::make_date(year, 5, 3),
# Greenery Day (2007-), and Citizens' Holiday (1988-2006)
(name == jholiday_names[9] & year >= 2007) |
(name == jholiday_names[10] & dplyr::between(year, 1988, 2006)) ~
lubridate::make_date(year, 5, 4),
# Children's Day
name == jholiday_names[11] & year >= 1949 ~
lubridate::make_date(year, 5, 5),
# Marine Day
name == jholiday_names[12] & year == 2020 ~
lubridate::as_date("20200723"),
name == jholiday_names[12] & year == 2021 ~
lubridate::as_date("20210722"),
name == jholiday_names[12] & year >= 2003 & year != 2020 & year != 2021 ~
find_date_by_wday(year, 7, 2, 3),
name == jholiday_names[12] & dplyr::between(year, 1996, 2002) ~
lubridate::make_date(year, 7, 20),
# Mountain Day
name == jholiday_names[13] & year == 2020 ~
lubridate::as_date("20200810"),
name == jholiday_names[13] & year == 2021 ~
lubridate::as_date("20210808"),
name == jholiday_names[13] & year >= 2016 & year != 2020 & year != 2021 ~
lubridate::make_date(year, 8, 11),
# Respect for the Aged Day
name == jholiday_names[14] & dplyr::between(year, 1966, 2002) ~
lubridate::make_date(year, 9, 15),
name == jholiday_names[14] & year >= 2003 ~
find_date_by_wday(year, 9, 2, 3),
# Autumnal Equinox Day
name == jholiday_names[15] ~
lubridate::make_date(year, 9, day = shubun_day(year)),
# Sports Day
name == jholiday_names[17] & year == 2020 ~
lubridate::as_date("20200724"),
name == jholiday_names[17] & year == 2021 ~
lubridate::as_date("20210723"),
name %in% jholiday_names[16] & dplyr::between(year, 2000, 2019) ~
find_date_by_wday(year, 10, 2, 2),
name %in% jholiday_names[17] & year >= 2022 ~
find_date_by_wday(year, 10, 2, 2),
name %in% jholiday_names[16] & dplyr::between(year, 1966, 1999) ~
lubridate::make_date(year, 10, 10),
# Culture Day
name == jholiday_names[18] ~
lubridate::make_date(year, 11, 3),
# Labour Thanksgiving Day
name == jholiday_names[19] ~
lubridate::make_date(year, 11, 23),
# The Emperor's Birthday
name == jholiday_names[20] & dplyr::between(year, 1989, 2018) ~
lubridate::make_date(year, 12, 23),
name == jholiday_names[20] & year >= 2020 ~
lubridate::make_date(year, 2, 23),
# default
TRUE ~ lubridate::as_date(NA_character_)
)
}
function(year, lang) {
purrr::partial(fn, year = year, lang = lang)
}
}
#' @rdname jholiday
#' @export
jholiday <- function(year, lang = "en") {
jholiday_names <- jholiday_list[[lang]]
if (are_all_current_law_yr(year)) {
res <-
jholiday_names %>%
purrr::map(~ jholiday_spec(year, name = .x, lang = lang)) %>%
purrr::set_names(jholiday_names)
res <-
res[!duplicated(res)]
res <-
res %>%
purrr::discard(~ all(is.na(.))) %>%
purrr::imap(function(x, y) {
sort(x)
})
res <-
res[res %>%
purrr::map(1) %>%
purrr::flatten_dbl() %>%
purrr::set_names(names(res)) %>%
sort() %>%
names()]
res
}
}
are_all_current_law_yr <- function(years) {
# This check omits any NAs, NULL, and empty strings for convenience.
checked <- all(as.numeric(years) >= 1948, na.rm = TRUE)
if (!checked)
rlang::warn("The year specified must be after the law was enacted in 1948")
checked
}
shunbun_day <- function(year) {
dplyr::case_when(
year <= 1947 ~ NA_real_,
year <= 1979 ~ trunc(20.8357 + 0.242194 * (year - 1980) - trunc((year -
1983) /
4)),
year <= 2099 ~ trunc(20.8431 + 0.242194 * (year - 1980) - trunc((year -
1980) /
4)),
year <= 2150 ~ trunc(21.851 + 0.242194 * (year - 1980) - trunc((year -
1980) /
4))
)
}
shubun_day <- function(year) {
dplyr::case_when(
year <= 1947 ~ NA_real_,
year <= 1979 ~ trunc(23.2588 + 0.242194 * (year - 1980) - trunc((year -
1983) /
4)),
year <= 2099 ~ trunc(23.2488 + 0.242194 * (year - 1980) - trunc((year -
1980) /
4)),
year <= 2150 ~ trunc(24.2488 + 0.242194 * (year - 1980) - trunc((year -
1980) /
4))
)
}
#' Is x a public holidays in Japan?
#' @description
#' \Sexpr[results=rd, stage=render]{lifecycle::badge("experimental")}
#' Whether it is a holiday defined by Japanese law (enacted in 1948)
#' @details Holiday information refers to data published as of December 21, 2020.
#' Future holidays are subject to change.
#' @param date a vector of [POSIXt], numeric or character objects
#' @return TRUE if x is a public holidays in Japan, FALSE otherwise.
#' @rdname is_jholiday
#' @section Examples:
#' ```{r, child = "man/rmd/setup.Rmd"}
#' ```
#'
#' ```{r}
#' is_jholiday("2021-01-01")
#' is_jholiday("2018-12-23")
#' is_jholiday("2019-12-23")
#' ```
#' @export
is_jholiday <- function(date) {
date <-
lubridate::as_date(date)
yr <-
unique(lubridate::year(date[!is.na(date)]))
jholidays <-
unique(c(
jholiday_df$date, # Holidays from https://www8.cao.go.jp/chosei/shukujitsu/syukujitsu.csv
lubridate::as_date(unlist(jholiday(yr, "en"))) # Calculated holidays
))
# exclude NA from jholidays then check if the date is Japanese Holiday or not.
date %in% jholidays[!is.na(jholidays)]
}
#' Find out the date of the specific month and weekday
#' @description
#' \Sexpr[results=rd, stage=render]{lifecycle::badge("experimental")}
#' Get the date of the Xth the specific weekday
#' @param year numeric year
#' @param month numeric month
#' @param wday numeric weekday
#' @param ordinal number of week
#' @return a vector of class POSIXct
#' @rdname find_date_by_wday
#' @examples
#' find_date_by_wday(2021, 1, 2, 2)
#' @export
find_date_by_wday <- function(year, month, wday, ordinal) {
date_begin <-
lubridate::make_date(year, month)
# If the lubridate.week.start option is set, lubridate::wday results is affected by it.
# To get the correct Japanese Holiday information, explicitly pass Sunday (7) as week_start.
wday_of_date_begin <-
lubridate::wday(date_begin, week_start = 7)
# First dates of the specified wday on each year-month
first_wday <-
date_begin + (wday - wday_of_date_begin) %% 7
# Add 1 ordinal = 1 week = 7 days
result <- first_wday + 7 * (ordinal - 1)
# If the calculated result is beyond the end of the month, fill it with NA
dplyr::if_else(
lubridate::month(result) == lubridate::month(date_begin),
result,
lubridate::as_date(NA_character_)
)
}
jholiday_list <-
list(
jp = c("\u5143\u65e5",
"\u6210\u4eba\u306e\u65e5",
"\u5efa\u56fd\u8a18\u5ff5\u306e\u65e5",
"\u6625\u5206\u306e\u65e5",
list("\u662d\u548c\u306e\u65e5", "\u307f\u3069\u308a\u306e\u65e5", "\u5929\u7687\u8a95\u751f\u65e5"),
"\u61b2\u6cd5\u8a18\u5ff5\u65e5",
list("\u307f\u3069\u308a\u306e\u65e5", "\u56fd\u6c11\u306e\u4f11\u65e5"),
"\u3053\u3069\u3082\u306e\u65e5",
"\u6d77\u306e\u65e5",
"\u5c71\u306e\u65e5",
"\u656c\u8001\u306e\u65e5",
"\u79cb\u5206\u306e\u65e5",
list("\u4f53\u80b2\u306e\u65e5", "\u30b9\u30dd\u30fc\u30c4\u306e\u65e5"),
"\u6587\u5316\u306e\u65e5",
"\u52e4\u52b4\u611f\u8b1d\u306e\u65e5",
list("\u5929\u7687\u8a95\u751f\u65e5")),
en = c("New Year's Day",
"Coming of Age Day",
"Foundation Day",
"Vernal Equinox Day",
list("Showa Day", "Greenery Day", "The Emperor's Birthday"),
"Constitution Memorial Day",
list("Greenery Day", "Citizens' Holiday"),
"Children's Day",
"Marine Day",
"Mountain Day",
"Respect for the Aged Day",
"Autumnal Equinox Day",
list("Sports Day", "Sports Day"),
"Culture Day",
"Labour Thanksgiving Day",
list("The Emperor's Birthday")))
| /scratch/gouwar.j/cran-all/cranData/zipangu/R/jholiday.R |
#' Create kana vector
#' @description
#' \Sexpr[results=rd, stage=render]{lifecycle::badge("experimental")}
#' Generates a vector consisting of the elements of kana.
#' Options exist for the inclusion of several elements.
#' @param type "hiragana" ("hira") or "katakana" ("kata")
#' @inheritDotParams hiragana
#' @rdname kana
#' @examples
#' kana(type = "hira", core = TRUE)
#' kana(type = "hira", core = TRUE, handakuon = TRUE)
#' @export
kana <- function(type, ...) {
type <- rlang::arg_match(type,
c("hira", "hiragana",
"kata", "katakana"))
switch (type,
"hira" = hiragana(...),
"hiragana" = hiragana(...),
"kata" = katakana(...),
"katakana" = katakana(...)
)
}
#' @param core is include core kana characters.
#' @param dakuon e.g. ga, gi, gu, ge, go
#' @param handakuon e.g. pa, pi, pu, pe, po
#' @param kogaki small character
#' @param historical old style
#' @rdname kana
#' @export
hiragana <- function(core = TRUE, dakuon = FALSE, handakuon = FALSE, kogaki = FALSE, historical = FALSE) {
x <-
seq.int(12353, 12438)
if (core == TRUE) {
x_at <-
c(seq.int(2, 10, by = 2),
seq.int(11, 30, by = 2),
c(31, 33, 36, 38, 40),
seq.int(42, 46),
seq.int(47, 59, by = 3),
seq.int(62, 66),
seq.int(68, 72, by = 2),
seq.int(73, 77),
c(79, 82, 83))
} else {
x_at <-
NULL
}
if (historical == TRUE) {
x_at <-
c(x_at, 80, 81)
}
if (dakuon == TRUE) {
x_at <-
c(x_at,
c(seq.int(12, 30, by = 2),
c(c(32, 34),
seq.int(37, 41, by = 2)),
seq.int(48, 60, by = 3),
84))
}
if (handakuon == TRUE) {
x_at <-
c(x_at,
seq.int(49, 61, by = 3))
}
if (kogaki == TRUE) {
x_at <-
c(x_at,
seq.int(1, 10, by = 2),
35,
seq.int(67, 71, by = 2),
c(78, 85, 86))
}
if (is.null(x_at)) {
rlang::warn(
"There is no matching character. Please specify TRUE for either arguments."
)
}
purrr::map_chr(x[sort(x_at)],
intToUtf8)
}
#' @inheritParams hiragana
#' @export
#' @rdname kana
katakana <- function(core = TRUE, dakuon = FALSE, handakuon = FALSE, kogaki = FALSE, historical = FALSE) {
x <-
hiragana(core = core, dakuon = dakuon, handakuon = handakuon, kogaki = kogaki, historical = historical) %>%
stringi::stri_trans_general(id = "kana")
if (kogaki == TRUE) {
x <-
x[seq.int(1, length(x)-2)]
}
x
}
| /scratch/gouwar.j/cran-all/cranData/zipangu/R/kana.R |
#' Convert kansuji character to arabic
#' @description
#' \Sexpr[results=rd, stage=render]{lifecycle::badge("experimental")}
#' Converts a given Kansuji element such as Ichi (1) and Nana (7) to an Arabic.
#' [kansuji2arabic_all()] converts only Kansuji in the string.
#' [kansuji2arabic_num()] convert kansuji that contain the positions (e.g. Hyaku,
#' Sen, etc) with the numbers represented by kansuji. [kansuji2arabic_str()]
#' converts kansuji in a string to numbers represented by kansuji while
#' retaining the non-kansuji characters.
#' @param str Input vector.
#' @param convert If `FALSE`, will return as numeric. The default value is `TRUE`,
#' and numeric values are treated as strings.
#' @param .under Number scale to be converted. The default value is infinity.
#' @return a character or numeric.
#' @rdname kansuji
#' @examples
#' kansuji2arabic("\u4e00")
#' kansuji2arabic(c("\u4e00", "\u767e"))
#' kansuji2arabic(c("\u4e00", "\u767e"), convert = FALSE)
#' # Keep Kansuji over 1000.
#' kansuji2arabic(c("\u4e00", "\u767e", "\u5343"), .under = 1000)
#' # Convert all character
#' kansuji2arabic_all("\u3007\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d\u5341")
#' kansuji2arabic_all("\u516b\u4e01\u76ee")
#' # Convert kansuji that contain the positions with the numbers represented by kansuji.
#' kansuji2arabic_num("\u4e00\u5104\u4e8c\u5343\u4e09\u767e\u56db\u5341\u4e94\u4e07")
#' kansuji2arabic_num("\u4e00\u5104\u4e8c\u4e09\u56db\u4e94\u4e07\u516d\u4e03\u516b\u4e5d")
#' # Converts kansuji in a string to numbers represented by kansuji.
#' kansuji2arabic_str("\u91d1\u4e00\u5104\u4e8c\u5343\u4e09\u767e\u56db\u5341\u4e94\u4e07\u5186")
#' kansuji2arabic_str("\u91d1\u4e00\u5104\u4e8c\u4e09\u56db\u4e94\u4e07\u516d\u4e03\u516b\u4e5d\u5186")
#' kansuji2arabic_str("\u91d11\u51042345\u4e076789\u5186")
#' @export
kansuji2arabic <- function(str, convert = TRUE, .under = Inf) {
kanjiarabic_key <-
c(0,
seq.int(0, 10),
10^c(seq.int(2, 4), 8, 12, 16)
) %>%
purrr::set_names(
stringr::str_split(
paste0(
"\u96f6",
"\u3007\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d\u5341",
"\u767e\u5343\u4e07",
"\u5104\u5146\u4eac"),
pattern = stringr::boundary("character"),
simplify = TRUE)) %>%
purrr::keep(
~ .x < .under) %>%
purrr::map(
~ as.character(.x)
)
res <-
dplyr::recode(str, !!!kanjiarabic_key)
if (convert == FALSE)
res <- res %>% as.numeric()
res
}
#' @param ... Other arguments to carry over to [kansuji2arabic()]
#' @rdname kansuji
#' @export
kansuji2arabic_all <- function(str, ...) {
purrr::map_chr(str, function(str, ...){
stringr::str_split(str,
pattern = stringr::boundary("character")) %>%
purrr::map(kansuji2arabic, ...) %>%
purrr::reduce(c) %>%
paste(collapse = "")
}, ...)
}
kansuji2arabic_num_single <- function(str, consecutive = c("convert", "non"), ...) {
consecutive <- match.arg(consecutive)
if(is.na(str) || is.nan(str) || is.infinite(str) || is.null(str)){
warning("Only strings consisting only of kansuji characters can be converted.")
return(NA)
}
n <- stringr::str_split(str,
pattern = stringr::boundary("character"))%>%
purrr::reduce(c)
if(any(stringr::str_detect(n, pattern = "[^\u96f6\u3007\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d\u5341\u767e\u5343\u4e07\u5104\u5146\u4eac]"))){
warning("Only strings consisting only of kansuji characters can be converted.")
return(NA)
}
n <- n %>% purrr::map(kansuji2arabic) %>% as.numeric()
if(!any(n >= 10) && length(n) > 1){
if(consecutive == "convert") return(kansuji2arabic_all(str, ...))
if(consecutive == "non") return(str)
}
if(length(n) > 2 && any(n >= 10000) && all(n != 10) && all(n !=100) && all(n != 1000)){
for(i in 1:(length(n) - 1)){
if(n[i] < 1000 && n[i + 1] < 10){
n[i + 1] <- as.numeric(stringr::str_c(c(n[i], n[i + 1]), collapse = ""))
n[i] <- NA
}
}
n <- stats::na.omit(n)
}
if(!any(n >= 10000)){
if(length(n) == 1){
res <- n
}else{
res <- NULL
for(i in 1:length(n)){
if(i == length(n) && n[i - 1] >= 10)
res[i] <- n[i]
else if(length(n[i - 1]) == 0 && n[i] >= 10)
res[i] <- n[i]
else if(n[i] <= 9 && n[i + 1] >= 10 )
res[i] <- n[i] * n[i + 1]
else if(n[i] >=10 && n[i - 1] >=10)
res[i] <- n[i]
}
}
res <- sum(stats::na.omit(res))
}else{
if(length(n) == 1){
res <- n
}else{
ans <- NULL
l <- 1
k <- 1
digits_location <- which(n >= 10000)
digits <- sum(n >= 10000)
digits_number <- n[n >= 10000]
if(max(which(n >= 10000)) <= max(which(!n >= 10000))){
digits <- digits + 1
digits_number <- c(digits_number, 1)
digits_location <- c(digits_location, (max(which(n >= 0)) + 1))
}
for (j in 1:digits) {
m <- digits_location[k] - 1
nn <- n[l:m]
res <- NULL
for (i in 1:length(nn)) {
if(length(nn) <= 1)
res[i] <- nn[i]
else if(i == length(nn) && nn[i - 1] >= 10)
res[i] <- nn[i]
else if(length(nn[i - 1]) == 0 && nn[i] >= 10)
res[i] <- nn[i]
else if(nn[i] <= 9 && nn[i + 1] >= 10 )
res[i] <- nn[i] * nn[i + 1]
else if(nn[i] >=10 && nn[i - 1] >=10)
res[i] <- nn[i]
else if(nn[i] <= 9 && nn[i + 1] <=9){
warning("This format of kansuji characters cannot be converted.")
return(NA)
}
}
ans[k] <- sum(stats::na.omit(res)) * digits_number[k]
l <- digits_location[k] + 1
k <- k + 1
}
res <- sum(stats::na.omit(ans))
}
}
return(as.character(res))
}
#' @rdname kansuji
#' @export
kansuji2arabic_num <- function(str, consecutive = c("convert", "non"), ...){
consecutive <- match.arg(consecutive)
purrr::map(str, kansuji2arabic_num_single, consecutive, ...) %>% unlist()
}
kansuji2arabic_str_single <- function(str, consecutive = c("convert", "non"), widths = c("all", "halfwidth"), ...){
consecutive <- match.arg(consecutive)
widths <- match.arg(widths)
if(is.na(str) || is.nan(str) || is.infinite(str) || is.null(str)){
warning("It is a type that cannot be converted.")
return(NA)
}
if(widths == "all"){
arabicn_half <- "1234567890"
arabicn_full <- "\uff11\uff12\uff13\uff14\uff15\uff16\uff17\uff18\uff19\uff10"
arabicn_half <- unlist(stringr::str_split(arabicn_half, ""))
arabicn_full <- unlist(stringr::str_split(arabicn_full, ""))
names(arabicn_half) <- arabicn_full
str <- stringr::str_replace_all(str, arabicn_half)
}
str <- arabic2kansuji::arabic2kansuji(str)
str_num <- stringr::str_split(str, pattern = "[^\u96f6\u3007\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d\u5341\u767e\u5343\u4e07\u5104\u5146\u4eac]")[[1]]
str_num[str_num == ""] <- NA
str <- stringr::str_replace_all(str, pattern = "[\u96f6\u3007\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d\u5341\u767e\u5343\u4e07\u5104\u5146\u4eac]", replacement = "\u3007\u3007")
doc_cha <- stringr::str_split(str, pattern = "[\u96f6\u3007\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d\u5341\u767e\u5343\u4e07\u5104\u5146\u4eac]")[[1]]
str_num <- kansuji2arabic_num(stats::na.omit(str_num), consecutive)
j <- 1
for(i in 1:length(doc_cha)){
if(doc_cha[i] == "" && i == 1){
doc_cha[i] <- str_num[j]
j <- j + 1
}
else if(consecutive == "non"){
if((stringr::str_detect(doc_cha[i - 1], pattern = "[^0123456789]")
&& stringr::str_detect(doc_cha[i - 1], pattern = "[^\u96f6\u3007\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d]"))
&& doc_cha[i] == ""){
doc_cha[i] <- str_num[j]
j <- j + 1
}
}
else if(stringr::str_detect(doc_cha[i - 1], pattern = "[^0123456789]")
&& doc_cha[i] == ""){
doc_cha[i] <- str_num[j]
j <- j + 1
}
if((length(str_num) + 1) == j) break
}
ans <- stringr::str_c(doc_cha, collapse = "")
return(ans)
}
#' @param consecutive If you select "convert", any sequence of 1 to 9 kansuji will
#' be replaced with Arabic numerals. If you select "non", any sequence of 1-9
#' kansuji will not be replaced by Arabic numerals.
#' @param widths If you select "all", both full-width and half-width Arabic numerals
#' are taken into account when calculating kansuji, but if you select "halfwidth",
#' only half-width Arabic numerals are taken into account when calculating kansuji.
#' @rdname kansuji
#' @export
kansuji2arabic_str <- function(str, consecutive = c("convert", "non"), widths = c("all", "halfwidth"),...){
consecutive <- match.arg(consecutive)
widths <- match.arg(widths)
purrr::map(str, kansuji2arabic_str_single, consecutive, widths, ...) %>% unlist()
}
| /scratch/gouwar.j/cran-all/cranData/zipangu/R/kansuji.R |
#' Label numbers in Kansuji format
#'
#' @description
#' Automatically scales and labels with the Kansuji Myriad Scale (e.g. "Man",
#' "Oku", etc).
#' Use [label_kansuji()] converts the label value to either Kansuji value or a
#' mixture of Arabic numerals and the Kansuji Scales for ten thousands,
#' billions, and ten quadrillions.
#' Use [label_kansuji_suffix()] converts the label value to an Arabic numeral
#' followed by the Kansuji Scale with the suffix.
#'
#' @param unit Optional units specifier.
#' @param sep Separator between number and Kansuji unit.
#' @param prefix Symbols to display before value.
#' @param big.mark Character used between every 3 digits to separate thousands.
#' @param number If Number is arabic, it will return a mixture of Arabic and the
#' Kansuji Myriad Scale; if Kansuji, it will return only Kansuji numerals.
#' @param ... Other arguments passed on to [base::prettyNum()], [scales::label_number()] or
#' [arabic2kansuji::arabic2kansuji_all()].
#' @rdname label_kansuji
#'
#' @return All `label_()` functions return a "labelling" function, i.e. a function
#' that takes a vector x and returns a character vector of length(x) giving a
#' label for each input value.
#'
#' @section Examples:
#' ```{r, child = "man/rmd/setup.Rmd"}
#' ```
#'
#' ```{r, eval = FALSE, echo = TRUE}
#' library("scales")
#' demo_continuous(c(1, 1e9), label = label_kansuji())
#' demo_continuous(c(1, 1e9), label = label_kansuji_suffix())
#' ```
#' @export
label_kansuji <- function(unit = NULL, sep = "", prefix = "", big.mark = "", number = c("arabic", "kansuji"), ...){
number <- match.arg(number)
if(number == "arabic"){
function(x){
purrr::map_chr(x, function(x){
x <- prettyNum(x, scientific = FALSE) %>% arabic2kansuji::arabic2kansuji_all()
x.kansuji <- stringr::str_split(x, pattern = "[^\u3007\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d\u5341\u767e\u5343]")[[1]]
x.kansuji[x.kansuji == ""] <- NA
x.kansuji <- stats::na.omit(x.kansuji)
for(i in 1:length(x.kansuji)){
if(is.na(x.kansuji[i])) break
x <- stringr::str_replace(x, pattern = x.kansuji[i], replacement = prettyNum(zipangu::kansuji2arabic_num(x.kansuji[i]), big.mark = big.mark, ...))
}
paste0(prefix, x, unit, sep = sep)
}
)
}
}else if(number == "kansuji"){
function(x){
x <- prettyNum(x, scientific = FALSE) %>% arabic2kansuji::arabic2kansuji_all(...)
paste0(prefix, x, unit, sep = sep)
}
}
}
#' @param accuracy A number to round to. Use (e.g.) 0.01 to show 2 decimal
#' places of precision.
#' @param significant.digits Determines whether or not the value of accurary is
#' valid as a significant figure with a decimal point. The default is FALSE, in
#' which case if accurary is 2 and the value is 1.10, 1.1 will be displayed,
#' but if TRUE and installed '{scales}` package, 1.10 will be displayed.
#' @rdname label_kansuji
#' @export
label_kansuji_suffix <- function(accuracy = 1, unit = NULL, sep = NULL, prefix = "", big.mark = "", significant.digits = FALSE, ...) {
function(x) {
breaks <- c(0, MAN = 10000, OKU = 1e+08, CHO = 1e+12, KEI = 1e+16)
n_suffix <- cut(abs(x),
breaks = c(0, 10000, 1e+08, 1e+12, 1e+16, Inf),
labels = c("", "\u4e07", "\u5104", "\u5146", "\u4eac"),
right = FALSE)
n_suffix[is.na(n_suffix)] <- ""
suffix <- paste0(sep, n_suffix, unit)
n_suffix <- cut(abs(x),
breaks = c(unname(breaks), Inf),
labels = c(names(breaks)),
right = FALSE)
n_suffix[is.na(n_suffix)] <- ""
scale <- 1 / breaks[n_suffix]
scale[which(scale %in% c(Inf, NA))] <- 1
if(significant.digits){
if(requireNamespace("scales", quietly = TRUE))
scales::number(x,
accuracy = accuracy,
scale = unname(scale),
suffix = suffix,
big.mark = big.mark,
...)
else{
warning("`scales` package needs to be installed.", call. = FALSE)
paste0(prefix, prettyNum(round(x * scale, digits = nchar(1 / (accuracy * 10))), big.mark = big.mark, ...), suffix, sep = sep)
}
}else{
paste0(prefix, prettyNum(round(x * scale, digits = nchar(1 / (accuracy * 10))), big.mark = big.mark, ...), suffix, sep = sep)
}
}
}
| /scratch/gouwar.j/cran-all/cranData/zipangu/R/label-kansuji.R |
#' Converts characters following the rules of 'neologd'
#' @details Converts the characters into normalized style
#' basing on rules that is recommended by the Neologism dictionary for MeCab.
#' @seealso \url{https://github.com/neologd/mecab-ipadic-neologd/wiki/Regexp.ja}
#' @param str Input vector.
#' @return a character
#' @examples
#' str_jnormalize(
#' paste0(
#' " \uff30",
#' "\uff32\uff2d\uff2c\u300 \u526f \u8aad \u672c "
#' )
#' )
#' str_jnormalize(
#' paste0(
#' "\u5357\u30a2\u30eb\u30d7\u30b9\u306e\u3000\u5929\u7136\u6c34",
#' "-\u3000\uff33\uff50\uff41\uff52\uff4b\uff49\uff4e\uff47\u3000",
#' "\uff2c\uff45\uff4d\uff4f\uff4e\u3000\u30ec\u30e2\u30f3\u4e00\u7d5e\u308a"
#' )
#' )
#' @export
str_jnormalize <- function(str) {
res <- str_conv_normalize(str, to = "nfkc")
res <- stringr::str_replace_all(
res,
c("\'", "\"") %>%
purrr::set_names(c(intToUtf8(8217), intToUtf8(8221)))) %>%
stringr::str_replace_all(
"[\\-\u02d7\u058a\u2010\u2011\u2012\u2013\u2043\u207b\u208b\u2212]+", "-"
) %>%
stringr::str_replace_all(
"[\ufe63\uff0d\uff70\u2014\u2015\u2500\u2501\u30fc]+", enc2utf8("\u30fc")
) %>%
stringr::str_replace_all(
"([:blank:]){2,}", " "
) %>%
stringr::str_replace_all(
stringr::str_c(
"([\uff10-\uff19\u3041-\u3093\u30a1-\u30f6\u30fc\u4e00-\u9fa0[:punct:]]+)",
"[[:blank:]]*",
"([\u0021-\u007e[:punct:]]+)"
),
"\\1\\2"
) %>%
stringr::str_replace_all(
stringr::str_c(
"([\u0021-\u007e\uff10-\uff19\u3041-\u3093\u30a1-\u30f6\u30fc\u4e00-\u9fa0[:punct:]]*)",
"[[:blank:]]*",
"([\uff10-\uff19\u3041-\u3093\u30a1-\u30f6\u30fc\u4e00-\u9fa0[:punct:]]+)"
),
"\\1\\2"
)
res <- stringr::str_remove_all(res, "[~\u223c\u223e\u301c\u3030\uff5e]+")
res <- stringr::str_trim(res)
res <- stringr::str_remove_all(res, "[[:cntrl:]]+")
return(res)
}
| /scratch/gouwar.j/cran-all/cranData/zipangu/R/normalize-str.R |
#' Harmonize the notation of Japanese prefecture names.
#' @description
#' \Sexpr[results=rd, stage=render]{lifecycle::badge("experimental")}
#' @details Convert with and without terminal notation, respectively.
#' * long option, long formal name
#' * Use the short option to omit the trailing characters
#' @param x Input vector.
#' @param to Option. Whether to use longer ("long") or shorter ("short")
#' prefectures.
#' @examples
#' x <- c("\u6771\u4eac\u90fd", "\u5317\u6d77\u9053", "\u6c96\u7e04\u770c")
#' harmonize_prefecture_name(x, to = "short")
#' x <- c("\u6771\u4eac", "\u5317\u6d77\u9053", "\u6c96\u7e04")
#' harmonize_prefecture_name(x, to = "long")
#' @export
harmonize_prefecture_name <- function(x, to) {
type <-
rlang::arg_match(to,
c("short", "long"))
if (to == "short") {
tgt_index <-
x %>%
stringr::str_detect("^(\u5317\u6d77\u9053|\u6771\u4eac\u90fd|(\u5927\u962a|\u4eac\u90fd)\u5e9c|(\u795e\u5948\u5ddd|\u548c\u6b4c\u5c71|\u9e7f\u5150\u5cf6)\u770c|(\u9752\u68ee|\u5ca9\u624b|\u5bae\u57ce|\u79cb\u7530|\u5c71\u5f62|\u798f\u5cf6|\u8328\u57ce|\u6803\u6728|\u7fa4\u99ac|\u57fc\u7389|\u5343\u8449|\u65b0\u6f5f|\u5bcc\u5c71|\u77f3\u5ddd|\u798f\u4e95|\u5c71\u68a8|\u9577\u91ce|\u5c90\u961c|\u9759\u5ca1|\u611b\u77e5|\u4e09\u91cd|\u6ecb\u8cc0|\u5175\u5eab|\u5948\u826f|\u9ce5\u53d6|\u5cf6\u6839|\u5ca1\u5c71|\u5e83\u5cf6|\u5c71\u53e3|\u5fb3\u5cf6|\u9999\u5ddd|\u611b\u5a9b|\u9ad8\u77e5|\u798f\u5ca1|\u4f50\u8cc0|\u9577\u5d0e|\u718a\u672c|\u5927\u5206|\u5bae\u5d0e|\u6c96\u7e04)\u770c)$") %>%
which()
} else if (to == "long") {
tgt_index <-
x %>%
stringr::str_detect("^(\u5317\u6d77\u9053|\u6771\u4eac|\u5927\u962a|\u4eac\u90fd|\u795e\u5948\u5ddd|\u548c\u6b4c\u5c71|\u9e7f\u5150\u5cf6|\u9752\u68ee|\u5ca9\u624b|\u5bae\u57ce|\u79cb\u7530|\u5c71\u5f62|\u798f\u5cf6|\u8328\u57ce|\u6803\u6728|\u7fa4\u99ac|\u57fc\u7389|\u5343\u8449|\u65b0\u6f5f|\u5bcc\u5c71|\u77f3\u5ddd|\u798f\u4e95|\u5c71\u68a8|\u9577\u91ce|\u5c90\u961c|\u9759\u5ca1|\u611b\u77e5|\u4e09\u91cd|\u6ecb\u8cc0|\u5175\u5eab|\u5948\u826f|\u9ce5\u53d6|\u5cf6\u6839|\u5ca1\u5c71|\u5e83\u5cf6|\u5c71\u53e3|\u5fb3\u5cf6|\u9999\u5ddd|\u611b\u5a9b|\u9ad8\u77e5|\u798f\u5ca1|\u4f50\u8cc0|\u9577\u5d0e|\u718a\u672c|\u5927\u5206|\u5bae\u5d0e|\u6c96\u7e04)$") %>%
which()
}
if (length(tgt_index) > 0) {
x <-
replace(x,
tgt_index,
x[tgt_index] %>%
convert_prefecture_name(to = to))
}
x
}
convert_prefecture_name <- function(x, to) {
if (to == "short") {
stringr::str_remove(x, "(\u90fd|\u5e9c|\u770c)$")
} else if (to == "long") {
dplyr::case_when(
stringr::str_detect(x, "\u5317\u6d77\u9053") ~ "\u5317\u6d77\u9053",
stringr::str_detect(x, "\u6771\u4eac") ~ paste0(x, "\u90fd"),
stringr::str_detect(x, "\u5927\u962a|\u4eac\u90fd") ~ paste0(x, "\u5e9c"),
stringr::str_detect(x, "\u5317\u6d77\u9053|\u6771\u4eac|\u5927\u962a|\u4eac\u90fd",
negate = TRUE) ~ paste0(x, "\u770c"))
}
}
#' Check correctly prefecture names
#' @description
#' \Sexpr[results=rd, stage=render]{lifecycle::badge("stable")}
#' @details Check if the string is a prefectural string.
#' If it contains the name of the prefecture and other
#' strings (e.g. city name), it returns `FALSE`.
#' @inheritParams harmonize_prefecture_name
#' @return logical
#' @examples
#' is_prefecture("\u6771\u4eac\u90fd")
#' is_prefecture(c("\u6771\u4eac", "\u4eac\u90fd", "\u3064\u304f\u3070"))
#' @export
#' @rdname is_prefecture
is_prefecture <- function(x) {
stringr::str_detect(x,
stringr::regex("^(\u5317\u6d77\u9053|\u6771\u4eac\u90fd|(\u5927\u962a|\u4eac\u90fd)\u5e9c|(\u795e\u5948\u5ddd|\u548c\u6b4c\u5c71|\u9e7f\u5150\u5cf6)\u770c|(\u9752\u68ee|\u5ca9\u624b|\u5bae\u57ce|\u79cb\u7530|\u5c71\u5f62|\u798f\u5cf6|\u8328\u57ce|\u6803\u6728|\u7fa4\u99ac|\u57fc\u7389|\u5343\u8449|\u65b0\u6f5f|\u5bcc\u5c71|\u77f3\u5ddd|\u798f\u4e95|\u5c71\u68a8|\u9577\u91ce|\u5c90\u961c|\u9759\u5ca1|\u611b\u77e5|\u4e09\u91cd|\u6ecb\u8cc0|\u5175\u5eab|\u5948\u826f|\u9ce5\u53d6|\u5cf6\u6839|\u5ca1\u5c71|\u5e83\u5cf6|\u5c71\u53e3|\u5fb3\u5cf6|\u9999\u5ddd|\u611b\u5a9b|\u9ad8\u77e5|\u798f\u5ca1|\u4f50\u8cc0|\u9577\u5d0e|\u718a\u672c|\u5927\u5206|\u5bae\u5d0e|\u6c96\u7e04)\u770c|\u6771\u4eac|\u5927\u962a|\u4eac\u90fd|\u795e\u5948\u5ddd|\u548c\u6b4c\u5c71|\u9e7f\u5150\u5cf6|\u9752\u68ee|\u5ca9\u624b|\u5bae\u57ce|\u79cb\u7530|\u5c71\u5f62|\u798f\u5cf6|\u8328\u57ce|\u6803\u6728|\u7fa4\u99ac|\u57fc\u7389|\u5343\u8449|\u65b0\u6f5f|\u5bcc\u5c71|\u77f3\u5ddd|\u798f\u4e95|\u5c71\u68a8|\u9577\u91ce|\u5c90\u961c|\u9759\u5ca1|\u611b\u77e5|\u4e09\u91cd|\u6ecb\u8cc0|\u5175\u5eab|\u5948\u826f|\u9ce5\u53d6|\u5cf6\u6839|\u5ca1\u5c71|\u5e83\u5cf6|\u5c71\u53e3|\u5fb3\u5cf6|\u9999\u5ddd|\u611b\u5a9b|\u9ad8\u77e5|\u798f\u5ca1|\u4f50\u8cc0|\u9577\u5d0e|\u718a\u672c|\u5927\u5206|\u5bae\u5d0e|\u6c96\u7e04)$"))
}
| /scratch/gouwar.j/cran-all/cranData/zipangu/R/prefecture.R |
#' Pipe operator
#'
#' See \code{magrittr::\link[magrittr:pipe]{\%>\%}} for details.
#'
#' @name %>%
#' @rdname pipe
#' @keywords internal
#' @export
#' @importFrom magrittr %>%
#' @usage lhs \%>\% rhs
NULL
| /scratch/gouwar.j/cran-all/cranData/zipangu/R/utils-pipe.R |
## usethis namespace: start
#' @importFrom lifecycle deprecate_soft
## usethis namespace: end
NULL
#' @noRd
.pkgenv <- rlang::env()
| /scratch/gouwar.j/cran-all/cranData/zipangu/R/zipangu-package.R |
#' Read Japan post's zip-code file
#' @description
#' \Sexpr[results=rd, stage=render]{lifecycle::badge("experimental")}
#' @details
#' Reads zip-code data in csv format provided by japan post group and parse it as a data.frame.
#' Corresponds to the available "oogaki", "kogaki", "roman" and "jigyosyo" types.
#' These file types must be specified by the argument.
#' @param path local file path or zip file URL
#' @param type Input file type, one of "oogaki", "kogaki", "roman", "jigyosyo"
#' @return [tibble][tibble::tibble]
#' @seealso [https://www.post.japanpost.jp/zipcode/dl/readme.html](https://www.post.japanpost.jp/zipcode/dl/readme.html),
#' [https://www.post.japanpost.jp/zipcode/dl/jigyosyo/readme.html](https://www.post.japanpost.jp/zipcode/dl/jigyosyo/readme.html)
#' @examples
#' # Input sources
#' read_zipcode(path = system.file("zipcode_dummy/13TOKYO_oogaki.CSV", package = "zipangu"),
#' type = "oogaki")
#' read_zipcode(system.file("zipcode_dummy/13TOKYO_kogaki.CSV", package = "zipangu"),
#' "oogaki")
#' read_zipcode(system.file("zipcode_dummy/KEN_ALL_ROME.CSV", package = "zipangu"),
#' "roman")
#' read_zipcode(system.file("zipcode_dummy/JIGYOSYO.CSV", package = "zipangu"),
#' "jigyosyo")
#' \dontrun{
#' # Or directly from a URL
#' read_zipcode("https://www.post.japanpost.jp/zipcode/dl/jigyosyo/zip/jigyosyo.zip")
#' }
#' @rdname read_zipcode
#' @export
read_zipcode <- function(path, type = c("oogaki", "kogaki", "roman", "jigyosyo")) {
# nocov start
if (is_japanpost_zippath(path)) {
dl <- dl_zipcode_file(path)
path <- dl[[1]]
type <- dl[[2]]
}
# nocov end
rlang::arg_match(type)
read_csv_jp <-
purrr::partial(utils::read.csv,
fileEncoding = "cp932",
stringsAsFactors = FALSE)
address_level <- c("prefecture", "city", "street")
col_vars <-
list(yomi = c("jis_code", "old_zip_code", "zip_code",
paste0(address_level, "_kana"),
address_level,
"is_street_duplicate",
"is_banchi",
"is_cyoumoku",
"is_zipcode_duplicate",
"status",
"modify_type"
),
roman = c("zip_code",
address_level,
paste0(address_level, "_roman")),
jigyosyo = c("jis_code", "name_kana", "name",
address_level,
"street_sub",
"jigyosyo_identifier",
"old_zip_code",
"grouped",
"individual_id",
"multiple_type",
"update_type"))
if (type == "oogaki") {
df <-
read_csv_jp(file = path,
col.names = col_vars$yomi,
colClasses = c(rep("character", 9),
rep("double", 3),
rep("double", 3)))
} else if (type == "kogaki") {
df <-
dplyr::mutate_at(read_csv_jp(file = path,
col.names = col_vars$yomi,
colClasses = c(rep("character", 9),
rep("double", 3),
rep("double", 3))),
stringr::str_subset(col_vars$roman, "^is_"),
as.logical)
} else if (type == "roman") {
df <-
dplyr::mutate_at(read_csv_jp(file = path,
col.names = col_vars$roman,
colClasses = rep("character", 7)),
stringr::str_subset(col_vars$roman, "roman$"),
stringr::str_to_title)
} else if (type == "jigyosyo") {
df <-
read_csv_jp(file = path,
col.names = col_vars$jigyosyo,
colClasses = c(rep("character", 10),
rep("integer", 3)))
}
tibble::as_tibble(
dplyr::mutate_if(
dplyr::mutate_if(df,
is.character,
stringi::stri_trans_general,
id = "nfkc"),
is.character,
stringr::str_trim)
)
}
#' Test zip-code
#' @description
#' \Sexpr[results=rd, stage=render]{lifecycle::badge("experimental")}
#' @param x Zip-code. Number or character. Hyphens may be included,
#' but the input must contain a 7-character number.
#' @rdname is_zipcode
#' @examples
#' is_zipcode(7000027)
#' is_zipcode("700-0027")
#' @return A logical vector.
#' @export
is_zipcode <- function(x) {
checked <- stringr::str_detect(x,
"^[0-9]{3}-?[0-9]{4}$")
if (rlang::is_false(checked))
rlang::inform("7\u6841\u306e\u6570\u5024\u3067\u306f\u3042\u308a\u307e\u305b\u3093")
checked
}
#' Insert and remove zip-code connect character
#' @description
#' \Sexpr[results=rd, stage=render]{lifecycle::badge("maturing")}
#' Inserts a hyphen as a delimiter in the given zip-code string.
#' Or exclude the hyphen.
#' @inheritParams is_zipcode
#' @param remove Default is `FALSE`. If `TRUE`, remove the hyphen.
#' @rdname zipcode_spacer
#' @examples
#' zipcode_spacer(7000027)
#' zipcode_spacer("305-0053")
#' zipcode_spacer("305-0053", remove = TRUE)
#' @export
zipcode_spacer <- function(x, remove = FALSE) {
purrr::map_chr(x,
~ if (rlang::is_true(is_zipcode(.x)))
if (rlang::is_false(remove)) {
if (stringr::str_detect(.x,
"-",
negate = FALSE)) {
.x
} else {
paste0(stringr::str_sub(.x, 1, 3),
"-",
stringr::str_sub(.x, 4, 7))
}
} else {
stringr::str_remove_all(.x, "-")
}
else
NA_character_)
}
#' Check if it is a zip file provided by japanpost
#' @param url character.
#' @noRd
#' @return A logical vector.
is_japanpost_zippath <- function(url) {
stringr::str_detect(url,
"https://www.post.japanpost.jp/zipcode/dl/.+/.+.zip")
}
#' Download a zip-code file
#' @description
#' \Sexpr[results=rd, stage=render]{lifecycle::badge("maturing")}
#' @inheritParams read_zipcode
#' @param exdir The directory to extract zip file. If `NULL`, use temporary folder.
#' @rdname dl_zipcode_file
#' @examples
#' \dontrun{
#' dl_zipcode_file(path = "https://www.post.japanpost.jp/zipcode/dl/oogaki/zip/02aomori.zip")
#' dl_zipcode_file("https://www.post.japanpost.jp/zipcode/dl/oogaki/zip/02aomori.zip",
#' exdir = getwd())
#' }
#' @export
dl_zipcode_file <- function(path, exdir = NULL) {
# nocov start
if (rlang::is_true(is_japanpost_zippath(path))) {
if (is.null(exdir))
exdir <- tempdir()
type <-
stringr::str_extract(path, "oogaki|kogaki|roman|jigyosyo")
unzip_path <-
stringr::str_to_upper(stringr::str_replace(basename(path),
"zip",
"CSV")) %>%
stringr::str_remove("\\?.+")
dl_file_path <-
list.files(exdir,
pattern = unzip_path,
full.names = TRUE)
if (sum(file.exists(dl_file_path)) == 0) {
tmp_zip <-
tempfile(fileext = ".zip")
utils::download.file(url = path,
destfile = tmp_zip)
utils::unzip(zipfile = tmp_zip,
exdir = exdir)
path <-
list.files(exdir,
pattern = ".CSV",
full.names = TRUE)
} else {
path <- dl_file_path
}
list(path, type)
} else {
rlang::abort("zip file URL not found.")
}
# nocov end
}
| /scratch/gouwar.j/cran-all/cranData/zipangu/R/zipcode.R |
```{r, include = FALSE}
options(
tibble.print_min = 4,
tibble.max_extra_cols = 8,
digits = 2,
crayon.enabled = FALSE,
cli.unicode = FALSE
)
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
```
| /scratch/gouwar.j/cran-all/cranData/zipangu/man/rmd/setup.Rmd |
#' ZCTA to Census Tract (2010) Crosswalk
#'
#' A dataset containing the relationships between ZIP code tabulation areas (ZCTA) and Census Tracts. This contains selected variables from the official crosswalk file.
#'
#' @format A data frame with 148897 rows and 4 variables:
#' \describe{
#' \item{ZCTA5}{2010 ZIP Code Tabulation Area}
#' \item{TRACT}{2010 Census Tract Code}
#' \item{GEOID}{Concatenation of 2010 State, County, and Tract}
#' }
#' @source \url{https://www.census.gov/geographies/reference-files/time-series/geo/relationship-files.html}
"zcta_crosswalk"
#' ZIP Code Database
#'
#' A dataset containing detailed information for U.S. ZIP codes
#'
#' @format A data frame with 41877 rows and 24 variables:
#' \describe{
#' \item{zipcode}{5 digit U.S. ZIP code}
#' \item{zipcode_type}{2010 State FIPS Code}
#' \item{major_city}{Major city serving the ZIP code}
#' \item{post_office_city}{City of post office serving the ZIP code}
#' \item{common_city_list}{List of common cities represented by the ZIP code}
#' \item{county}{Name of county containing the ZIP code}
#' \item{state}{Two-digit state code for ZIP code location}
#' \item{lat}{Latitude of the centroid for the ZIP code}
#' \item{lng}{Longitude of the centroid for the ZIP code}
#' \item{timezone}{Timezone of the ZIP code}
#' \item{radius_in_miles}{Radius of the ZIP code in miles}
#' \item{area_code_list}{List of area codes for telephone numbers within this ZIP code}
#' \item{population}{Total population of the ZIP code}
#' \item{population_density}{Population density of the ZIP code (persons per square mile)}
#' \item{land_area_in_sqmi}{Area of the land contained within the ZIP code in square miles}
#' \item{water_area_in_sqmi}{Area of the waters contained within the ZIP code in square miles}
#' \item{housing_units}{Number of housing units within the ZIP code}
#' \item{occupied_housing_units}{Number of housing units within the ZIP code}
#' \item{median_home_value}{Median home price within the ZIP code}
#' \item{median_household_income}{Median household income within the ZIP code}
#' \item{bounds_west}{Bounding box coordinates}
#' \item{bounds_east}{Bounding box coordinates}
#' \item{bounds_north}{Bounding box coordinates}
#' \item{bounds_south}{Bounding box coordinates}
#' }
#' @source \url{https://github.com/MacHu-GWU/uszipcode-project/files/5183256/simple_db.log}
"zip_code_db"
#' ZIP Code to Congressional District Relationship File
#'
#' A dataset containing mappings between ZIP codes and congressional districts
#'
#' @format A data frame with 45914 rows and 2 variables:
#' \describe{
#' \item{ZIP}{5 digit U.S. ZIP code}
#' \item{CD}{Four digit congressional district code (State FIPS code + district number)}
#' }
#' @source \url{https://www.huduser.gov/portal/datasets/usps_crosswalk.html}
"zip_to_cd"
| /scratch/gouwar.j/cran-all/cranData/zipcodeR/R/data.r |
#' Download updated data files needed for library functionality to the package's data directory. To be implemented for future updates.
#'
#' @param force Boolean, if set to TRUE will force overwrite existing data files with new version
#' @return Data files needed for package functionality, stored in data directory of package install
#' @examples
#' \dontrun{
#' download_zip_data()
#' }
#' @importFrom RSQLite dbConnect
#' @importFrom DBI dbGetQuery
#' @importFrom jsonlite fromJSON
#' @importFrom httr http_error
#' @importFrom dplyr `%>%`
#' @importFrom dplyr filter
#' @importFrom curl has_internet
#' @export
download_zip_data <- function(force = FALSE) {
# Define URLs for downloading external datasets used in the package
url_crosswalk <- "https://github.com/gavinrozzi/zipcodeR-data/blob/master/zcta_crosswalk.rda?raw=true"
url_cd <- "https://github.com/gavinrozzi/zipcodeR-data/blob/master/zip_to_cd.rda?raw=true"
# Test if ZCTA crosswalk file exists, download if not present
if (file.exists(system.file("data", "zcta_crosswalk.rda", package = "zipcodeR")) == TRUE && force == FALSE) {
cat("Crosswalk file found, skipping")
} else if (file.exists(system.file("data", "zcta_crosswalk.rda", package = "zipcodeR")) == FALSE) {
cat(paste("zipcodeR: Downloading ZCTA crosswalk file", "\n"))
utils::download.file(url_crosswalk, paste0(system.file("data", package = "zipcodeR"), "/zcta_crosswalk.rda"))
} else if (force == TRUE) {
cat(paste("zipcodeR: forcing Download of ZCTA crosswalk file", "\n"))
utils::download.file(url_crosswalk, paste0(system.file("data", package = "zipcodeR"), "/zcta_crosswalk.rda"))
}
# Test if ZIP code db file exists, download if not present
# if (file.exists(system.file("data", "zip_code_db.rda", package = "zipcodeR")) == TRUE && force == FALSE) {
# cat("ZIP code database file found, skipping")
# } else if (file.exists(system.file("data", "zip_code_db.rda", package = "zipcodeR")) == FALSE) {
# cat("Downloading ZIP code database file")
# utils::download.file(url_zip_db, paste0(system.file("data", package = "zipcodeR"), "/zip_code_db.rda"))
# } else if (force == TRUE) {
# cat("Forcing download of ZIP code database file")
# utils::download.file(url_zip_db, paste0(system.file("data", package = "zipcodeR"), "/zip_code_db.rda"))
# }
# Get the latest SQLite zipcode database from the GitHub API
file_data <- jsonlite::fromJSON("https://api.github.com/repos/MacHu-GWU/uszipcode-project/releases/latest")
assets <- file_data$assets
# Get URL to download simple ZIP code dataset
zip_db_url <- assets %>%
dplyr::filter(.data$name == "simple_db.sqlite")
# Store the latest download URL from GitHub
file_name <- zip_db_url$browser_download_url
# create a temporary directory and file for downloading the data
td <- tempdir()
zip_file <- tempfile(fileext = ".sqlite", tmpdir = tempdir())
# Check if internet connection exists before attempting data download
if (curl::has_internet() == FALSE) {
message("No internet connection. Please connect to the internet and try again.")
return(NULL)
}
# Check if data is available and download the data
if (httr::http_error(file_name)) {
message("zip_code_db data source broken. Please try again.")
return(NULL)
} else {
message("zipcodeR: downloading zip_code_db")
utils::download.file(file_name, zip_file, mode = "wb")
}
# Connect to the database
conn <- RSQLite::dbConnect(RSQLite::SQLite(), dbname = zip_file)
# Read in the new data
zip_code_db <- dbGetQuery(conn, "SELECT * FROM simple_zipcode")
# Save the updated zip_code_db file to package data directory
save(zip_code_db, file = paste0(system.file("data", package = "zipcodeR"), "/zip_code_db.rda"))
# Save the latest version of zip_code_db to internal package data
zip_code_db_version <- as.Date(zip_db_url$created_at)
save(zip_code_db_version, file = paste0(system.file("R", package = "zipcodeR"), "/sysdata.rda"))
# Tear down the database connection
RSQLite::dbDisconnect(conn)
# Test if congressional district relationship file exists, download if not present
if (file.exists(system.file("data", "zip_to_cd.rda", package = "zipcodeR")) == TRUE && force == FALSE) {
cat("Congressional district file found, skipping")
} else if (file.exists(system.file("data", "zip_to_cd.rda", package = "zipcodeR")) == FALSE) {
cat("zipcodeR: Downloading congressional district data file")
utils::download.file(url_cd, paste0(system.file("data", package = "zipcodeR"), "/zip_to_cd.rda"))
} else if (force == TRUE) {
cat("Forcing download of congressional district data file")
utils::download.file(url_cd, paste0(system.file("data", package = "zipcodeR"), "/zip_to_cd.rda"))
}
}
| /scratch/gouwar.j/cran-all/cranData/zipcodeR/R/download_data.r |
utils::globalVariables(c("zcta_crosswalk", "zip_code_db", "zcta_crosswalk", "zip_to_cd"))
| /scratch/gouwar.j/cran-all/cranData/zipcodeR/R/globals.r |
#' Normalize ZIP codes
#'
#'
#' @param zipcode messy ZIP code to be normalized
#' @return Normalized zipcode
#' @examples
#' normalize_zip(0008731)
#' @importFrom tidyr extract
#' @importFrom dplyr pull
#' @importFrom dplyr tibble
#' @importFrom dplyr left_join
#' @export
normalize_zip <- function(zipcode) {
capture_group <- function(data, regex) {
tibble(data) %>%
extract(col = data, into = "captured", regex = regex) %>%
pull(.data$captured)
}
# input can be numeric or character
# we need to treat these differently
if (is.character(zipcode)) {
zipcode <- ifelse( # remove parts after - if there is one
grepl("^\\s*(\\d+)-.*", zipcode),
capture_group(zipcode, "^\\s*(\\d+)-.*"),
zipcode
)
nas <- is.na(zipcode)
# remove trailing four digits if too long
zipcode <- ifelse(
nchar(zipcode) > 5,
capture_group(zipcode, "(.*)\\d\\d\\d\\d"),
zipcode
)
# pad with zeros if too short
zipcode <- ifelse(
nchar(zipcode) < 5,
sprintf("%05i", as.numeric(zipcode)),
zipcode
)
# restor NA values
zipcode[nas] <- NA_character_
return(zipcode)
}
if (!isTRUE(is.numeric(zipcode))) {
stop("input must be character or numeric")
}
zipcode <- ifelse(
zipcode > 100000,
floor(zipcode / 10000),
zipcode
)
# keep position of NAs to recover later
nas <- is.na(zipcode)
# pad with zeros where needed
zipcode <- sprintf("%05i", as.numeric(zipcode))
zipcode[nas] <- NA_character_
zipcode
}
#' Calculate the distance between two ZIP codes in miles
#'
#'
#' @param zipcode_a First vector of ZIP codes
#' @param zipcode_b Second vector of ZIP codes
#' @param lonlat lonlat argument to pass to raster::pointDistance() to select method of distance calculation. Default is TRUE to calculate distance over a spherical projection. FALSE will calculate the distance in Euclidean (planar) space.
#' @param units Specify which units to return distance calculations in. Choices include meters or miles.
#' @return a data.frame containing a column for each ZIP code and a new column containing the distance between the two columns of ZIP code
#'
#' @examples
#' zip_distance("08731", "08901")
#'
#' @importFrom raster pointDistance
#' @export
zip_distance <- function(zipcode_a, zipcode_b, lonlat = TRUE, units = "miles") {
zipcode_a <- as.character(zipcode_a)
zipcode_b <- as.character(zipcode_b)
# assemble zipcodes in dataframe
zip_data <- data.frame(zipcode_a, zipcode_b)
# create subset of zip_code_db with only zipcode, lat, and lng
zip_db_small <- zip_code_db %>%
dplyr::select(.data$zipcode, .data$lat, .data$lng) %>%
dplyr::filter(.data$lat != "NA" & .data$lng != "NA")
# join input data with zip_code_db
zip_data <- zip_data %>%
dplyr::left_join(zip_db_small, by = c('zipcode_a' = 'zipcode')) %>%
dplyr::left_join(zip_db_small, by = c('zipcode_b' = 'zipcode'), suffix = c('.a', '.b'))
# assemble matrices for distance calculation
points_a <- cbind(cbind(zip_data$lng.a, zip_data$lat.a))
points_b <- cbind(cbind(zip_data$lng.b, zip_data$lat.b))
# Calculate the distance matrix between both sets of points
distance <- raster::pointDistance(points_a, points_b, lonlat = lonlat)
# Convert the distance matrix from meters to miles
if (units == "miles") {
distance <- distance * 0.000621371
}
# Round to 2 decimal places to match search_radius()
distance <- round(distance, digits = 2)
# Put together the results in a data.frame
result <- data.frame(zipcode_a, zipcode_b, distance)
return(result)
}
| /scratch/gouwar.j/cran-all/cranData/zipcodeR/R/zip_helper_functions.R |
#' Search for ZIP codes located within a given state
#'
#'
#' @param state_abb Two-digit code representing a U.S. state
#' @return tibble of all ZIP codes for each state code defined in state_abb
#' @examples
#' search_state("NJ")
#' search_state(c("NJ", "NY", "CT"))
#' @export
search_state <- function(state_abb) {
# Ensure state abbreviation is capitalized for consistency
state_abb <- toupper(state_abb)
# Get matching ZIP codes for state
state_zips <- zip_code_db %>%
dplyr::filter(.data$state %in% state_abb)
# Throw an error if nothing found
if (nrow(state_zips) == 0) {
stop(paste("No ZIP codes found for state:", state_abb))
}
return(dplyr::as_tibble(state_zips))
}
#' Search ZIP codes for a county
#'
#'
#' @param state_abb Two-digit code for a U.S. state
#' @param county_name Name of a county within a U.S. state
#' @param ... if the parameter similar = TRUE, then send the parameter max.distance to the base function agrep. Default is 0.1.
#' @return tibble of all ZIP codes for given county name
#'
#' @examples
#' middlesex <- search_county("Middlesex", "NJ")
#' alameda <- search_county("alameda", "CA")
#' search_county("ST BERNARD", "LA", similar = TRUE)$zipcode
#' @importFrom stringr str_detect
#' @importFrom rlang list2
#' @export
search_county <- function(county_name, state_abb, ...) {
dots <- rlang::list2(...)
if (stringr::str_detect(state_abb, "^[:upper:]+$") == FALSE) {
state_abb <- toupper(state_abb)
}
if ("similar" %in% names(dots) && dots$similar == TRUE) {
if ("max.distance" %in% names(dots)) {
max.distance <- dots$max.distance
} else {
max.distance <- 0.1
}
state_counties <- zip_code_db %>% dplyr::filter(.data$state == state_abb)
county_name_proper <- agrep(county_name, state_counties$county,
ignore.case = TRUE, value = TRUE, max.distance = max.distance
)
county_zips <- zip_code_db %>% dplyr::filter(.data$state ==
state_abb & .data$county %in% county_name_proper)
} else {
if (stringr::str_detect(county_name, "^[:upper:]") == FALSE) {
first_char <- toupper(substring(county_name, 0, 1))
remainder <- substring(county_name, 2, nchar(county_name))
county_name <- paste0(first_char, remainder)
}
county_name_proper <- paste(county_name, "County")
county_zips <- zip_code_db %>% dplyr::filter(.data$state ==
state_abb & .data$county == county_name_proper)
}
if (nrow(county_zips) == 0) {
stop(paste(
"No ZIP codes found for county:", county_name,
",", state_abb
))
}
return(dplyr::as_tibble(county_zips))
}
#' Given a ZIP code, returns columns of metadata about that ZIP code
#'
#'
#' @param zip_code A 5-digit U.S. ZIP code or chracter vector with multiple ZIP codes
#' @return A tibble containing data for the ZIP code(s)
#'
#' @examples
#' reverse_zipcode("90210")
#' reverse_zipcode("08731")
#' reverse_zipcode(c("08734", "08731"))
#' reverse_zipcode("07762")$county
#' reverse_zipcode("07762")$state
#' @export
reverse_zipcode <- function(zip_code) {
# Sanity check: validate input for single ZIP before doing anything else
if (length(zip_code) == 1) {
zip_char <- nchar(as.character(zip_code))
if (zip_char != 5) {
stop(paste("Invalid ZIP code detected, expected 5 digit ZIP code, got", zip_char))
}
}
# Convert to character so leading zeroes are preserved
zip_code <- as.character(zip_code)
# Get matching ZIP code record for
zip_code_data <- zip_code_db %>%
dplyr::filter(.data$zipcode %in% zip_code)
# Iterate over input and insert NA rows for those with no match
for (i in seq_along(zip_code)) {
if (zip_code[i] %in% zip_code_db$zipcode == FALSE) {
warning(paste("No data found for ZIP code", zip_code[i]))
zip_code_data <- zip_code_data %>%
dplyr::add_row(zipcode = zip_code[i], .before = i)
}
}
# Throw an error if nothing found
if (nrow(zip_code_data) == 0) {
stop(paste("No data found for provided ZIP code", .data$zip_code, ",", .data$state))
}
return(dplyr::as_tibble(zip_code_data))
}
#' Search ZIP codes for a given city within a state
#'
#'
#' @param state_abb Two-digit code for a U.S. state
#' @param city_name Name of major city to search
#' @return tibble of all ZIP code data found for given city
#'
#' @examples
#' search_city("Spring Lake", "NJ")
#' search_city("Chappaqua", "NY")
#' @importFrom stringr str_detect
#' @export
search_city <- function(city_name, state_abb) {
# Test if state name input is capitalized, capitalize if lowercase
if (stringr::str_detect(state_abb, "^[:upper:]+$") == FALSE) {
state_abb <- toupper(state_abb)
}
# Test if first letter of city name input is capitalized, capitalize if input is lowercase
if (stringr::str_detect(city_name, "^[:upper:]") == FALSE) {
first_char <- toupper(substring(city_name, 0, 1))
remainder <- substring(city_name, 2, nchar(city_name))
city_name <- paste0(first_char, remainder)
}
# Get matching ZIP codes for city
city_zips <- zip_code_db %>%
dplyr::filter(.data$state == state_abb & .data$major_city == city_name)
# Throw an error if nothing found
if (nrow(city_zips) == 0) {
stop(paste("No ZIP codes found for city:", city_name, ",", state_abb))
}
return(dplyr::as_tibble(city_zips))
}
#' Search all ZIP codes located within a given timezone
#'
#' @param tz Timezone
#' @return tibble of all ZIP codes found for given timezone
#'
#' @examples
#' eastern <- search_tz("Eastern")
#' pacific <- search_tz("Mountain")
#' @export
search_tz <- function(tz) {
# Get matching ZIP codes for timezone
tz_zips <- zip_code_db %>%
dplyr::filter(.data$timezone %in% tz)
# Throw an error if nothing found
if (nrow(tz_zips) == 0) {
stop(paste("No ZIP codes found for timezone:", tz))
}
return(dplyr::as_tibble(tz_zips))
}
#' Returns all ZIP codes found within a given FIPS code
#'
#' @param state_fips A U.S. FIPS code
#' @param county_fips A 1-3 digit county FIPS code (optional)
#' @return tibble of Census tracts and data from Census crosswalk file found for given ZIP code
#'
#' @examples
#' search_fips("34")
#' search_fips("34", "03")
#' search_fips("34", "3")
#' search_fips("36", "003")
#' @importFrom rlang .data
#' @export
search_fips <- function(state_fips, county_fips) {
# Get FIPS code data from tidycensus
fips_data <- tidycensus::fips_codes
# Separate routine if only state_fips code provided
if (missing(county_fips)) {
# Get matching FIPS data for provided state FIPS code
fips_result <- fips_data %>%
dplyr::filter(.data$state_code == state_fips)
# Compare ZIP code database against provided state FIPS code, store matching ZIP code entries
result <- zip_code_db %>%
dplyr::filter(.data$state == fips_result$state[1])
return(result)
} else {
# Clean up county FIPS code input by adding leading zeroes to match FIPS code data if not present
if (nchar(county_fips < 3)) {
difference <- base::abs(nchar(county_fips) - 3)
county_fips <- base::paste0(strrep("0", difference), county_fips)
}
# Get matching FIPS data for provided state & county FIPS code
fips_result <- fips_data %>%
dplyr::filter(.data$state_code == state_fips & .data$county_code == county_fips)
# Compare ZIP code database against provided state FIPS code, store matching ZIP code entries
result <- zip_code_db %>%
dplyr::filter(.data$state == fips_result$state[1] & .data$county == fips_result$county[1])
return(dplyr::as_tibble(result))
}
}
#' Get all Census tracts within a given ZIP code
#'
#' @param zip_code A U.S. ZIP code
#' @return tibble of Census tracts and data from Census crosswalk file found for given ZIP code
#'
#' @examples
#' get_tracts("08731")
#' get_tracts("90210")
#' @importFrom dplyr %>%
#' @importFrom rlang .data
#' @export
get_tracts <- function(zip_code) {
# Validate input, raise error if input is not a 5-digit ZIP code
if (nchar(zip_code) != 5) {
stop("Invalid input detected. Please enter a 5-digit U.S. ZIP code.")
}
# Get tract data given ZCTA
tracts <- zcta_crosswalk %>%
dplyr::filter(.data$ZCTA5 == zip_code)
if (nrow(tracts) == 0) {
stop(paste("No Census tracts found for ZIP code", zip_code))
}
return(tracts)
}
#' Get all congressional districts for a given ZIP code
#'
#' @param zip_code A U.S. ZIP code
#' @return a named list of two-digit state code and two digit district code
#'
#' @examples
#' get_cd("08731")
#' get_cd("90210")
#' @importFrom dplyr %>%
#' @importFrom rlang .data
#' @import tidycensus
#' @export
get_cd <- function(zip_code) {
# Get state FIPS codes data from tidycensus library
state_fips <- tidycensus::fips_codes
# Match ZIP codes with congressional districts located within this ZIP
matched_cds <- zip_to_cd %>%
dplyr::filter(.data$ZIP == zip_code)
# Break out the match from the ZIP to congressional district lookup into state FIPS code and congressional district codes
district <- stringr::str_sub(matched_cds$CD, -2)
state <- stringr::str_sub(matched_cds$CD, 1, 2)
# Bind the separated district and state codes together as a dataframe
result <- data.frame(cbind(district, state))
# Join the lookup result with tidycensus FIPS code data for more info
joined <- result %>%
dplyr::left_join(state_fips, by = c("state" = "state_code"))
output <- data.frame(joined$state.y[1], district) %>%
dplyr::rename("state" = "joined.state.y.1.")
return(list(state_fips = joined$state.y[1], district = district))
}
#' Get all ZIP codes that fall within a given congressional district
#'
#' @param state_fips_code A two-digit U.S. FIPS code for a state
#' @param congressional_district A two digit number specifying a congressional district in a given
#' @return tibble of all congressional districts found for given ZIP code, including state code
#'
#' @examples
#' search_cd("34", "03")
#' search_cd("36", "05")
#' @importFrom dplyr %>%
#' @importFrom rlang .data
#' @export
search_cd <- function(state_fips_code, congressional_district) {
# Create code from state and congressional district to match lookup table
cd_code <- base::paste0(state_fips_code, congressional_district)
matched_zips <- zip_to_cd %>%
dplyr::filter(.data$CD == cd_code)
if (nrow(matched_zips) == 0) {
stop(paste("No ZIP codes found for congressional district:", congressional_district))
}
output <- matched_zips %>%
dplyr::select(-.data$CD)
output$state_fips <- state_fips_code
output$congressional_district <- congressional_district
return(dplyr::as_tibble(output))
}
#' Returns true if the given ZIP code is also a ZIP code tabulation area (ZCTA)
#'
#'
#' @param zip_code A 5-digit U.S. ZIP code
#' @return Boolean TRUE or FALSE based upon whether provided ZIP code is a ZCTA by testing whether it exists in the U.S. Census crosswalk data
#'
#' @examples
#' is_zcta("90210")
#' is_zcta("99999")
#' is_zcta("07762")
#' @export
is_zcta <- function(zip_code) {
# Convert to character so leading zeroes are preserved
zip_code <- as.character(zip_code)
# Test if provided ZIP code exists within Census ZCTA crosswalk
result <- zip_code %in% zcta_crosswalk$ZCTA5
return(result)
}
#' Returns that lat / lon pair of the centroid of a given ZIP code
#'
#'
#' @param zip_code A 5-digit U.S. ZIP code
#' @return tibble of lat lon coordinates
#'
#' @examples
#' geocode_zip("07762")
#' geocode_zip("90210")
#' geocode_zip("90210")$lat
#' geocode_zip("90210")$lng
#' @export
geocode_zip <- function(zip_code) {
# Convert to character so leading zeroes are preserved
zip_code <- as.character(zip_code)
# Get matching ZIP code record for
result <- zip_code_db %>%
dplyr::filter(.data$zipcode %in% zip_code) %>%
dplyr::select(.data$zipcode, .data$lat, .data$lng) %>%
dplyr::as_tibble()
if (nrow(result) == 0) {
stop(paste("No results found for ZIP code", zip_code))
}
return(result)
}
#' Search for ZIP codes that are within a given radius from a point
#'
#'
#' @param lat latitude
#' @param lng longitude
#' @param radius distance to search in miles, set by default to 1
#' @return a tibble containing the ZIP code(s) within the provided radius and distance from the provided coordinates in miles
#'
#' @examples
#' \dontrun{
#' search_radius(39.9, -74.3, 10)
#' }
#' @importFrom raster pointDistance
#' @export
search_radius <- function(lat, lng, radius = 1) {
# Create an instance of the ZIP code database for calculating distance,
# filter to those with lat / lon pairs
zip_data <- zip_code_db %>%
dplyr::filter(lat != "NA")
# Calculate the distance between all points and the provided coordinate pair
for (i in seq_len(nrow(zip_data))) {
zip_data$distance[i] <- raster::pointDistance(c(lng, lat), c(zip_data$lng[i], zip_data$lat[i]), lonlat = TRUE)
}
# Convert meters to miles for distance measurement
zip_data$distance <- zip_data$distance * 0.000621371
# Get matching ZIP codes within specified search radius
result <- zip_data %>%
# Filter results to those less than or equal to the search radius
dplyr::filter(.data$distance <= radius) %>%
dplyr::select(.data$zipcode, .data$distance) %>%
dplyr::as_tibble() %>%
dplyr::arrange(.data$distance)
# Warn if there is nothing found
if (nrow(result) == 0) {
warning(paste("No ZIP codes found for coordinates", paste0(lat, ",", lng), "with radius", radius, "mi"))
}
return(result)
}
| /scratch/gouwar.j/cran-all/cranData/zipcodeR/R/zip_lookups.r |
## ----setup, include=FALSE-----------------------------------------------------
library(zipcodeR)
knitr::opts_chunk$set(echo = TRUE)
set.seed(1000)
## -----------------------------------------------------------------------------
zip_distance('08731','08753')
## -----------------------------------------------------------------------------
geocode_zip('08731')
## -----------------------------------------------------------------------------
geocode_zip(c('08731','08721','08753'))
## -----------------------------------------------------------------------------
search_radius(39.9, -74.3, radius = 20)
| /scratch/gouwar.j/cran-all/cranData/zipcodeR/inst/doc/geographic.R |
---
title: "Geographic functions in zipcodeR"
author: "Gavin Rozzi"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
description: >
This is a quick overview of the new geographic functions introduced in zipcodeR 0.3 and above
vignette: >
%\VignetteIndexEntry{Geographic functions in zipcodeR}
%\VignetteEngine{knitr::knitr}
\usepackage[utf8]{inputenc}
---
```{r setup, include=FALSE}
library(zipcodeR)
knitr::opts_chunk$set(echo = TRUE)
set.seed(1000)
```
`{zipcodeR}` has introduced several new functions geared towards geographic applications. In this vignette we will explore these new functions and some of their typical use cases with examples.
## Calculating the distance between two ZIP codes
This version introduces the new function `zip_distance()` for calculating the distance between two ZIP codes in miles.
```{r}
zip_distance('08731','08753')
```
## Geocoding a ZIP code
Users often are seeking to use zipcodeR to geocode ZIP codes. While it is possible to do this already, I have introduced a simple wrapper function that only returns that centroid coordinates of each provided ZIP code to make this process easier.
```{r}
geocode_zip('08731')
```
You can also pass a vector of ZIP codes to geocode to quickly geocode ZIP code-level data
```{r}
geocode_zip(c('08731','08721','08753'))
```
## Searching for ZIP codes within a radius
Given a pair of latitude / longitude coordinates in WGS84 format you can search for all ZIP codes located within a provided radius in miles. This function will default to searching within 1 mile of your provided coordinates, but can be configured to search any arbitrary radius via the radius argument.
The below code searches for all ZIP codes within 20 miles of the
```{r}
search_radius(39.9, -74.3, radius = 20)
```
| /scratch/gouwar.j/cran-all/cranData/zipcodeR/inst/doc/geographic.Rmd |
## ----setup, include=FALSE-----------------------------------------------------
library(zipcodeR)
real_estate_data <- tibble::tribble(
~postal_code, ~zip_name,
"34102", "naples, fl",
"64105", "kansas city, mo",
"33544", "wesley chapel, fl",
"76550", "lampasas, tx",
"85335", "el mirage, az",
"61264", "milan, il",
"51551", "malvern, ia",
"95380", "turlock, ca",
"50438", "garner, ia",
"62895", "wayne city, il"
)
real_estate_data <- dplyr::filter(real_estate_data,nchar(postal_code) == 5)
knitr::opts_chunk$set(echo = TRUE)
set.seed(1000)
## -----------------------------------------------------------------------------
search_state('NY')
## -----------------------------------------------------------------------------
nyzip <- search_state('NY')$zipcode
## -----------------------------------------------------------------------------
states <- c('NY','NJ','CT')
search_state(states)
## -----------------------------------------------------------------------------
search_county('Ocean','NJ')
## -----------------------------------------------------------------------------
search_county("ST BERNARD","LA", similar = TRUE)$zipcode
## -----------------------------------------------------------------------------
head(real_estate_data)
## -----------------------------------------------------------------------------
real_estate_data[1,]
## -----------------------------------------------------------------------------
# Get the ZIP code of the first row of data
zip_code <- real_estate_data[1,]$postal_code
# Pass the ZIP code to the reverse_zipcode() function
reverse_zipcode(zip_code)
## -----------------------------------------------------------------------------
get_tracts(zip_code)
## -----------------------------------------------------------------------------
is_zcta(zip_code)
| /scratch/gouwar.j/cran-all/cranData/zipcodeR/inst/doc/zipcodeR.R |
---
title: "Introduction to zipcodeR"
author: "Gavin Rozzi"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
description: >
This is a short intro to using zipcodeR
vignette: >
%\VignetteIndexEntry{Introduction to zipcodeR}
%\VignetteEngine{knitr::knitr}
\usepackage[utf8]{inputenc}
---
```{r setup, include=FALSE}
library(zipcodeR)
real_estate_data <- tibble::tribble(
~postal_code, ~zip_name,
"34102", "naples, fl",
"64105", "kansas city, mo",
"33544", "wesley chapel, fl",
"76550", "lampasas, tx",
"85335", "el mirage, az",
"61264", "milan, il",
"51551", "malvern, ia",
"95380", "turlock, ca",
"50438", "garner, ia",
"62895", "wayne city, il"
)
real_estate_data <- dplyr::filter(real_estate_data,nchar(postal_code) == 5)
knitr::opts_chunk$set(echo = TRUE)
set.seed(1000)
```
`zipcodeR` is an all-in-one toolkit of functions and data for working with ZIP codes in R.
This document will introduce the tools provided by zipcodeR for improving your workflow when working with ZIP code-level data. The goal of these examples is to help you quickly get up and running with zipcodeR using real-world examples.
## Basic search functions
First thing's first: `zipcodeR`'s data & basic search functions are a core component of the package. We'll cover these before showing you how you can implement this package with a real-world example.
## Data
The package ships with an offline database containing 24 columns of data for each ZIP code. You can either keep all 24 variables or filter to just one of these depending on what data you need.
The columns of data provided are: **`r colnames(zip_code_db)`**
## Searching for ZIP codes by state
Let's begin by using zipcodeR to find all ZIP codes within a given state.
Getting all ZIP codes for a single state is simple, you only need to pass a two-digit abbreviation of a state's name to get a tibble of all ZIP codes in that state. Let's start by finding all of the ZIP codes in New York:
```{r}
search_state('NY')
```
What if you only wanted the actual ZIP codes and no other variables? You can use R's dollar sign operator to select one column at a time from the output of `zipcodeR`'s search functions:
```{r}
nyzip <- search_state('NY')$zipcode
```
### Searching multiple states at once
You can also search for ZIP codes in multiple states at once by passing a vector of state abbreviations to the search_states function like so:
```{r}
states <- c('NY','NJ','CT')
search_state(states)
```
This results in a tibble containing all ZIP codes for the states passed to the `search_states()` function.
## Searching by county
It is also possible to search for ZIP codes located in a particular county within a state.
Let's find all of the ZIP codes located within Ocean County, New Jersey:
```{r}
search_county('Ocean','NJ')
```
### Approximate matching of county names
Sometimes working with county names can be messy and there might not be a 100% match between our database and the name. The `search_county()` function can be configured to use base R's `agrep` function for these cases via an optional parameter.
One example where this feature is useful comes from the state of Louisiana. Since Louisiana has parishes, their county names don't line up exactly with how other states name their counties.
This example uses approxmiate matching to retrieve all ZIP codes for St. Bernard Parish in Louisiana:
```{r}
search_county("ST BERNARD","LA", similar = TRUE)$zipcode
```
Try running the above code with the similar parameter set to FALSE or not present and you'll receive an error.
## Finding out more about your ZIP codes
What if you already have a dataset containing ZIP codes and want to find out more about that particular area?
Using the reverse_zipcode() function, we can get up to 24 more columns of data when given a ZIP code.
## Data: U.S. Real Estate Market
To explore how zipcodeR can enhance your data & workflow, we will use a public dataset from the [National Association of Realtors](https://www.realtor.com/research/data/) containing data about housing market trends in the United States.
This dataset, which is updated monthly, contains `r nrow(real_estate_data)` observations with current housing market data from the National Association of Realtors [hosted on Amazon S3](https://econdata.s3-us-west-2.amazonaws.com/Reports/Core/RDC_Inventory_Core_Metrics_Zip.csv)
This is what the data we will be working with looks like:
```{r}
head(real_estate_data)
```
Note: The data used in this vignette was filtered to only include valid 5-digit ZIP codes as zipcodeR does not yet have a function for normalizing ZIP codes. The full Realtor dataset will have a different number of rows.
We'll focus on the first row for now, which represents the town of `r stringr::str_to_title(real_estate_data[1,]$zip_name)`.
```{r}
real_estate_data[1,]
```
The Realtor dataset contains a column named **postal_code** containing the ZIP code that identifies the town. We'll use this to find out more about `r gsub("(.*),.*", "\\1", stringr::str_to_title(real_estate_data[1,]$zip_name))` than what is provided in the housing market data.
## Reverse ZIP code search
So far we've covered the functions provided by `zipcodeR` for searching ZIP codes across multiple geographies. The package also provides a function for going in reverse, when given a 5-digit ZIP code. Introducing `reverse_zipcode()`:
```{r}
# Get the ZIP code of the first row of data
zip_code <- real_estate_data[1,]$postal_code
# Pass the ZIP code to the reverse_zipcode() function
reverse_zipcode(zip_code)
```
## Relating ZIP codes to Census data
You may also be interested in relating data at the ZIP code level to Census data. `zipcodeR` currently provides a function for getting all Census tracts when provided with a 5-digit ZIP code.
Let's find out how many Census tracts are in the ZIP code from the previous example.
```{r}
get_tracts(zip_code)
```
Now that you have all of the tracts for this ZIP code, it would be very easy to join this with other Census data, such as that which is available from the American Community Survey and other sources.
But ZIP codes alone are not terribly useful for social science research since they are only meant to represent USPS service areas. The Census Bureau has established [ZIP code tabulation areas (ZCTAs)](https://www.census.gov/programs-surveys/geography/guidance/geo-areas/zctas.html) that provide a representation of ZIP codes and can be used for joining with Census data. But not every ZIP code is also a ZCTA.
## Testing if a ZIP code is a ZCTA
`zipcodeR` provides a function for testing if a given ZIP code is also a ZIP code tabulation area. When provided with a vector of 5-digit ZIP codes the function will return TRUE or FALSE based upon whether the ZIP code is also a ZCTA.
```{r}
is_zcta(zip_code)
```
| /scratch/gouwar.j/cran-all/cranData/zipcodeR/inst/doc/zipcodeR.Rmd |
---
title: "Geographic functions in zipcodeR"
author: "Gavin Rozzi"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
description: >
This is a quick overview of the new geographic functions introduced in zipcodeR 0.3 and above
vignette: >
%\VignetteIndexEntry{Geographic functions in zipcodeR}
%\VignetteEngine{knitr::knitr}
\usepackage[utf8]{inputenc}
---
```{r setup, include=FALSE}
library(zipcodeR)
knitr::opts_chunk$set(echo = TRUE)
set.seed(1000)
```
`{zipcodeR}` has introduced several new functions geared towards geographic applications. In this vignette we will explore these new functions and some of their typical use cases with examples.
## Calculating the distance between two ZIP codes
This version introduces the new function `zip_distance()` for calculating the distance between two ZIP codes in miles.
```{r}
zip_distance('08731','08753')
```
## Geocoding a ZIP code
Users often are seeking to use zipcodeR to geocode ZIP codes. While it is possible to do this already, I have introduced a simple wrapper function that only returns that centroid coordinates of each provided ZIP code to make this process easier.
```{r}
geocode_zip('08731')
```
You can also pass a vector of ZIP codes to geocode to quickly geocode ZIP code-level data
```{r}
geocode_zip(c('08731','08721','08753'))
```
## Searching for ZIP codes within a radius
Given a pair of latitude / longitude coordinates in WGS84 format you can search for all ZIP codes located within a provided radius in miles. This function will default to searching within 1 mile of your provided coordinates, but can be configured to search any arbitrary radius via the radius argument.
The below code searches for all ZIP codes within 20 miles of the
```{r}
search_radius(39.9, -74.3, radius = 20)
```
| /scratch/gouwar.j/cran-all/cranData/zipcodeR/vignettes/geographic.Rmd |
---
title: "Introduction to zipcodeR"
author: "Gavin Rozzi"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
description: >
This is a short intro to using zipcodeR
vignette: >
%\VignetteIndexEntry{Introduction to zipcodeR}
%\VignetteEngine{knitr::knitr}
\usepackage[utf8]{inputenc}
---
```{r setup, include=FALSE}
library(zipcodeR)
real_estate_data <- tibble::tribble(
~postal_code, ~zip_name,
"34102", "naples, fl",
"64105", "kansas city, mo",
"33544", "wesley chapel, fl",
"76550", "lampasas, tx",
"85335", "el mirage, az",
"61264", "milan, il",
"51551", "malvern, ia",
"95380", "turlock, ca",
"50438", "garner, ia",
"62895", "wayne city, il"
)
real_estate_data <- dplyr::filter(real_estate_data,nchar(postal_code) == 5)
knitr::opts_chunk$set(echo = TRUE)
set.seed(1000)
```
`zipcodeR` is an all-in-one toolkit of functions and data for working with ZIP codes in R.
This document will introduce the tools provided by zipcodeR for improving your workflow when working with ZIP code-level data. The goal of these examples is to help you quickly get up and running with zipcodeR using real-world examples.
## Basic search functions
First thing's first: `zipcodeR`'s data & basic search functions are a core component of the package. We'll cover these before showing you how you can implement this package with a real-world example.
## Data
The package ships with an offline database containing 24 columns of data for each ZIP code. You can either keep all 24 variables or filter to just one of these depending on what data you need.
The columns of data provided are: **`r colnames(zip_code_db)`**
## Searching for ZIP codes by state
Let's begin by using zipcodeR to find all ZIP codes within a given state.
Getting all ZIP codes for a single state is simple, you only need to pass a two-digit abbreviation of a state's name to get a tibble of all ZIP codes in that state. Let's start by finding all of the ZIP codes in New York:
```{r}
search_state('NY')
```
What if you only wanted the actual ZIP codes and no other variables? You can use R's dollar sign operator to select one column at a time from the output of `zipcodeR`'s search functions:
```{r}
nyzip <- search_state('NY')$zipcode
```
### Searching multiple states at once
You can also search for ZIP codes in multiple states at once by passing a vector of state abbreviations to the search_states function like so:
```{r}
states <- c('NY','NJ','CT')
search_state(states)
```
This results in a tibble containing all ZIP codes for the states passed to the `search_states()` function.
## Searching by county
It is also possible to search for ZIP codes located in a particular county within a state.
Let's find all of the ZIP codes located within Ocean County, New Jersey:
```{r}
search_county('Ocean','NJ')
```
### Approximate matching of county names
Sometimes working with county names can be messy and there might not be a 100% match between our database and the name. The `search_county()` function can be configured to use base R's `agrep` function for these cases via an optional parameter.
One example where this feature is useful comes from the state of Louisiana. Since Louisiana has parishes, their county names don't line up exactly with how other states name their counties.
This example uses approxmiate matching to retrieve all ZIP codes for St. Bernard Parish in Louisiana:
```{r}
search_county("ST BERNARD","LA", similar = TRUE)$zipcode
```
Try running the above code with the similar parameter set to FALSE or not present and you'll receive an error.
## Finding out more about your ZIP codes
What if you already have a dataset containing ZIP codes and want to find out more about that particular area?
Using the reverse_zipcode() function, we can get up to 24 more columns of data when given a ZIP code.
## Data: U.S. Real Estate Market
To explore how zipcodeR can enhance your data & workflow, we will use a public dataset from the [National Association of Realtors](https://www.realtor.com/research/data/) containing data about housing market trends in the United States.
This dataset, which is updated monthly, contains `r nrow(real_estate_data)` observations with current housing market data from the National Association of Realtors [hosted on Amazon S3](https://econdata.s3-us-west-2.amazonaws.com/Reports/Core/RDC_Inventory_Core_Metrics_Zip.csv)
This is what the data we will be working with looks like:
```{r}
head(real_estate_data)
```
Note: The data used in this vignette was filtered to only include valid 5-digit ZIP codes as zipcodeR does not yet have a function for normalizing ZIP codes. The full Realtor dataset will have a different number of rows.
We'll focus on the first row for now, which represents the town of `r stringr::str_to_title(real_estate_data[1,]$zip_name)`.
```{r}
real_estate_data[1,]
```
The Realtor dataset contains a column named **postal_code** containing the ZIP code that identifies the town. We'll use this to find out more about `r gsub("(.*),.*", "\\1", stringr::str_to_title(real_estate_data[1,]$zip_name))` than what is provided in the housing market data.
## Reverse ZIP code search
So far we've covered the functions provided by `zipcodeR` for searching ZIP codes across multiple geographies. The package also provides a function for going in reverse, when given a 5-digit ZIP code. Introducing `reverse_zipcode()`:
```{r}
# Get the ZIP code of the first row of data
zip_code <- real_estate_data[1,]$postal_code
# Pass the ZIP code to the reverse_zipcode() function
reverse_zipcode(zip_code)
```
## Relating ZIP codes to Census data
You may also be interested in relating data at the ZIP code level to Census data. `zipcodeR` currently provides a function for getting all Census tracts when provided with a 5-digit ZIP code.
Let's find out how many Census tracts are in the ZIP code from the previous example.
```{r}
get_tracts(zip_code)
```
Now that you have all of the tracts for this ZIP code, it would be very easy to join this with other Census data, such as that which is available from the American Community Survey and other sources.
But ZIP codes alone are not terribly useful for social science research since they are only meant to represent USPS service areas. The Census Bureau has established [ZIP code tabulation areas (ZCTAs)](https://www.census.gov/programs-surveys/geography/guidance/geo-areas/zctas.html) that provide a representation of ZIP codes and can be used for joining with Census data. But not every ZIP code is also a ZCTA.
## Testing if a ZIP code is a ZCTA
`zipcodeR` provides a function for testing if a given ZIP code is also a ZIP code tabulation area. When provided with a vector of 5-digit ZIP codes the function will return TRUE or FALSE based upon whether the ZIP code is also a ZCTA.
```{r}
is_zcta(zip_code)
```
| /scratch/gouwar.j/cran-all/cranData/zipcodeR/vignettes/zipcodeR.Rmd |
EV <- function (obj, N=NA, ...) UseMethod("EV")
EVm <- function (obj, m, N=NA, ...) UseMethod("EVm")
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/EV_EVm.R |
## generic stubs for EV and EVm (when not provided by the respective LNRE model
EV.lnre <- function (obj, N=NA, ...)
{
if (! inherits(obj, "lnre")) stop("argument must be object of class 'lnre'")
stop("EV() method not implemented for ",obj$name," LNRE model (lnre.",obj$type,")")
}
EVm.lnre <- function (obj, m, N=NA, ...)
{
if (! inherits(obj, "lnre")) stop("argument must be object of class 'lnre'")
stop("EVm() method not implemented for ",obj$name," LNRE model (lnre.",obj$type,")")
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/EV_EVm_lnre.R |
EV.lnre.fzm <- function (obj, N=NA, ...)
{
if (! inherits(obj, "lnre.fzm")) stop("argument must be object of class 'lnre.fzm'")
if (missing(N)) stop("argument 'N' is required for 'lnre.fzm' objects")
if (!(is.numeric(N) && all(N >= 0))) stop("argument 'N' must be non-negative integer")
alpha <- obj$param$alpha
A <- obj$param$A
B <- obj$param$B
C <- obj$param2$C
if (obj$exact) {
term1 <- (N ^ alpha) *
(Igamma(1 - alpha, N * A, lower=FALSE) - Igamma(1 - alpha, N * B, lower=FALSE))
term2 <- (1 - exp(- N * A)) / A^alpha - (1 - exp(- N * B)) / B^alpha
(C / alpha) * (term1 + term2)
}
else {
term1 <- (N ^ alpha) * Igamma(1 - alpha, N * A, lower=FALSE)
term2 <- (A ^ (-alpha)) * (1 - exp(-N * A))
(C / alpha) * (term1 + term2)
}
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/EV_lnre_fzm.R |
EV.lnre.gigp <- function (obj, N=NA, ...)
{
if (! inherits(obj, "lnre.gigp")) stop("argument must be object of class 'lnre.gigp'")
if (missing(N)) stop("argument 'N' is required for 'lnre.gigp' objects")
if (!(is.numeric(N) && all(N >= 0))) stop("argument 'N' must be non-negative integer")
gamma <- obj$param$gamma
b <- obj$param$B # use original notation from Baayen (2001)
c <- obj$param$C
Z <- obj$param2$Z
term <- 1 + N/Z
factor1 <- 2 * Z / b # Baayen (2001), p. 90
factor2 <- besselK(b, gamma) / besselK(b, gamma+1) # factor1 * factor2 = S
factor3 <- besselK(b * sqrt(term), gamma) / (term^(gamma/2) * besselK(b, gamma))
factor1 * factor2 * (1 - factor3)
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/EV_lnre_gigp.R |
EV.lnre.zm <- function (obj, N=NA, ...)
{
if (! inherits(obj, "lnre.zm")) stop("argument must be object of class 'lnre.zm'")
if (missing(N)) stop("argument 'N' is required for 'lnre.zm' objects")
if (!(is.numeric(N) && all(N >= 0))) stop("argument 'N' must be non-negative integer")
alpha <- obj$param$alpha
B <- obj$param$B
C <- obj$param2$C
if (obj$exact) {
(C * N^alpha / alpha) *
(Igamma(1 - alpha, N * B) - (1 - exp(- N * B)) * (N * B)^(-alpha))
}
else {
C * N^alpha * Cgamma(1 - alpha) / alpha
}
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/EV_lnre_zm.R |
EV.spc <- function (obj, N, allow.extrapolation=FALSE, ...)
{
if (! inherits(obj, "spc")) stop("first argument must be object of class 'spc'")
if (attr(obj, "m.max") > 0) stop("cannot interpolate from incomplete frequency spectrum")
if (attr(obj, "expected")) stop("cannot interpolate from expected frequency spectrum")
if (! (is.numeric(N) && all(N >= 0))) stop("'N' must be vector of non-negative numbers")
## Baayen (2001), p. 65, Eq. (2.43)
N0 <- N(obj)
V0 <- V(obj)
if (any(N > N0) && !allow.extrapolation)
stop("binomial extrapolation to N=", max(N), " from N0=", N0, " not allowed!")
n.samples <- length(N)
E.V <- numeric(n.samples)
for (.i in 1:n.samples) {
.N <- N[.i]
factor <- 1 - .N/N0
E.V[.i] <- V0 - sum( obj$Vm * (factor ^ obj$m) )
}
E.V
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/EV_spc.R |
EVm.lnre.fzm <- function (obj, m, N=NA, ...)
{
if (! inherits(obj, "lnre.fzm")) stop("argument must be object of class 'lnre.fzm'")
if (missing(N)) stop("argument 'N' is required for 'lnre.fzm' objects")
if (!(is.numeric(N) && all(N >= 0))) stop("argument 'N' must be non-negative integer")
if (!(is.numeric(m) && all(m >= 1))) stop("argument 'm' must be positive integer")
alpha <- obj$param$alpha
A <- obj$param$A
B <- obj$param$B
C <- obj$param2$C
if (obj$exact) {
term1 <- exp(Igamma(m - alpha, N * A, lower=FALSE, log=TRUE) - Cgamma(m + 1, log=TRUE))
# term1 = Igamma(m - alpha, N * A, lower=FALSE) / m!
term2 <- exp(Igamma(m - alpha, N * B, lower=FALSE, log=TRUE) - Cgamma(m + 1, log=TRUE))
# term1 = Igamma(m - alpha, N * B, lower=FALSE) / m!
C * N^alpha * (term1 - term2)
}
else {
factor <- exp(Igamma(m - alpha, N * A, lower=FALSE, log=TRUE) - Cgamma(m + 1, log=TRUE))
# factor = Igamma(m - alpha, N * A, lower=FALSE) / m!
C * N^alpha * factor
}
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/EVm_lnre_fzm.R |
EVm.lnre.gigp <- function (obj, m, N=NA, ...)
{
if (! inherits(obj, "lnre.gigp")) stop("argument must be object of class 'lnre.gigp'")
if (missing(N)) stop("argument 'N' is required for 'lnre.gigp' objects")
if (!(is.numeric(N) && all(N >= 0))) stop("argument 'N' must be non-negative integer")
if (!(is.numeric(m) && all(m >= 1))) stop("argument 'm' must be positive integer")
gamma <- obj$param$gamma
b <- obj$param$B # use original notation from Baayen (2001)
c <- obj$param$C
Z <- obj$param2$Z
## TODO: re-implement using recurrence relation for V_m / alpha_m (Baayen 2001, p. 91)
## because factor2 becomes very small and factor3 very large
## (probably requires C code for good performance because of recursive nature of code)
term <- 1 + N/Z
factor1 <- 2 * Z / (b * besselK(b, gamma+1) * term^(gamma/2)) # Baayen (2001), p. 90
factor2 <- ( b * N / (2 * Z * sqrt(term)) )^(m) / Cgamma(m+1)
factor3 <- besselK(b * sqrt(term), m + gamma)
factor1 * factor2 * factor3
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/EVm_lnre_gigp.R |
EVm.lnre.zm <- function (obj, m, N=NA, ...)
{
if (! inherits(obj, "lnre.zm")) stop("argument must be object of class 'lnre.zm'")
if (missing(N)) stop("argument 'N' is required for 'lnre.zm' objects")
if (!(is.numeric(N) && all(N >= 0))) stop("argument 'N' must be non-negative integer")
if (!(is.numeric(m) && all(m >= 1))) stop("argument 'm' must be positive integer")
alpha <- obj$param$alpha
B <- obj$param$B
C <- obj$param2$C
if (obj$exact) {
factor <- exp(Igamma(m - alpha, N * B, log=TRUE) - Cgamma(m + 1, log=TRUE)) # = Igamma(m - alpha, N*B) / m!
C * N^alpha * factor
}
else {
factor <- exp(Cgamma(m - alpha, log=TRUE) - Cgamma(m + 1, log=TRUE)) # = Cgamma(m - alpha) / m!
C * N^alpha * factor
}
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/EVm_lnre_zm.R |
EVm.spc <- function (obj, m, N, allow.extrapolation=FALSE, ...)
{
if (! inherits(obj, "spc")) stop("first argument must be object of class 'spc'")
if (attr(obj, "m.max") > 0) stop("cannot interpolate from incomplete frequency spectrum")
if (attr(obj, "expected")) stop("cannot interpolate from expected frequency spectrum")
if (! (is.numeric(N) && all(N >= 0))) stop("'N' must be vector of non-negative numbers")
if (! (is.numeric(m) && all(m >= 1))) stop("'m' must be vector of integers >= 1")
if (!is.integer(m)) {
if (any(m != floor(m))) stop("only integer values are allowed for 'm'")
m <- as.integer(m)
}
m.length <- length(m)
N.length <- length(N)
n.items <- max(m.length, N.length)
if (m.length == 1) {
m <- rep(m, n.items)
}
else if (N.length == 1) {
N <- rep(N, n.items)
}
else { # m.length > 1 && N.length > 1
stop("either 'N' or 'm' must be a single value")
}
## Baayen (2001), p. 65, Eq. (2.41)
N0 <- N(obj)
if (any(N > N0) && !allow.extrapolation)
stop("binomial extrapolation to N=", max(N), " from N0=", N0, " not allowed!")
E.Vm <- numeric(n.items)
for (.i in 1:n.items) {
.N <- N[.i]
.m <- m[.i]
.idx <- obj$m >= .m
if (.N <= N0) { # interpolation -> use binomial probabilities
E.Vm[.i] <- sum( obj$Vm[.idx] * dbinom(.m, obj$m[.idx], .N / N0) )
}
else { # extrapolation -> compute alternating sum in the dumb way
.f1 <- .N / N0
.f2 <- 1 - .f1
.k <- obj$m[.idx] # this is the summation variable k in Baayen's formula
E.Vm[.i] <- sum( obj$Vm[.idx] * choose(.k, .m) * (.f1 ^ .m) * (.f2 ^ (.k-.m)) )
}
}
E.Vm
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/EVm_spc.R |
N <- function (obj, ...) UseMethod("N")
V <- function (obj, ...) UseMethod("V")
Vm <- function (obj, m, ...) UseMethod("Vm")
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/N_V_Vm.R |
N.lnre <- function (obj, ...)
{
if (! inherits(obj, "lnre")) stop("argument must belong to a subclass of 'lnre'")
spc <- obj$spc
if (is.null(spc)) stop("LNRE model has not been estimated from observed frequency spectrum")
N(spc)
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/N_lnre.R |
N.spc <- function (obj, ...)
{
if (! inherits(obj, "spc")) stop("argument must be object of class 'spc'")
attr(obj, "N")
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/N_spc.R |
N.tfl <- function (obj, ...)
{
if (! inherits(obj, "tfl")) stop("argument must be object of class 'tfl'")
attr(obj, "N")
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/N_tfl.R |
N.vgc <- function (obj, ...)
{
if (! inherits(obj, "vgc")) stop("argument must be object of class 'vgc'")
obj$N
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/N_vgc.R |
VV <- function (obj, N=NA, ...) UseMethod("VV")
VVm <- function (obj, m, N=NA, ...) UseMethod("VVm")
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/VV_VVm.R |
VV.lnre <- function (obj, N=NA, ...)
{
if (! inherits(obj, "lnre")) stop("first argument must be object of class 'lnre'")
if (missing(N)) stop("argument 'N' is required for 'lnre' objects")
if (!(is.numeric(N) && all(N >= 0))) stop("argument 'N' must be non-negative integer")
EV(obj, 2*N) - EV(obj, N)
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/VV_lnre.R |
VV.spc <- function (obj, N=NA, ...)
{
if (! inherits(obj, "spc")) stop("argument must be object of class 'spc'")
if (!attr(obj, "hasVariances")) stop("no variance data available for frequency spectrum")
if (!missing(N)) stop("argument 'N' not allowed for object of class 'spc'")
attr(obj, "VV")
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/VV_spc.R |
VV.vgc <- function (obj, N=NA, ...)
{
if (! inherits(obj, "vgc")) stop("argument must be object of class 'vgc'")
if (!attr(obj, "hasVariances")) stop("no variance data available for vocabulary growth curve")
if (!missing(N)) stop("argument 'N' not allowed for object of class 'vgc'")
structure(obj$VV, names=obj$N)
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/VV_vgc.R |
VVm.lnre <- function (obj, m, N=NA, ...)
{
if (! inherits(obj, "lnre")) stop("first argument must be object of class 'lnre'")
if (missing(N)) stop("argument 'N' is required for 'lnre' objects")
if (!(is.numeric(N) && all(N >= 0))) stop("argument 'N' must be non-negative number")
if (!(is.numeric(m) && all(m >= 1))) stop("argument 'm' must be positive integer")
factor <- exp(lchoose(2*m, m) - 2*m * log(2)) # = choose(2*m, m) / 2^(2*m)
EVm(obj, m, N) - factor * EVm(obj, 2*m, 2*N)
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/VVm_lnre.R |
VVm.spc <- function (obj, m, N=NA, ...)
{
if (! inherits(obj, "spc")) stop("argument must be object of class 'spc'")
m <- as.integer(m)
if ( any(is.na(m)) || any(m < 1) ) stop("second argument must be integer(s) >= 1")
if (!attr(obj, "hasVariances")) stop("no variance data available for frequency spectrum")
if (!missing(N)) stop("argument 'N' not allowed for object of class 'spc'")
## fill in 0's for empty frequency classes
idx <- match(m, obj$m)
VVm <- ifelse(is.na(idx), 0, obj$VVm[idx])
## unlisted classes in incomplete spectrum are set to NA
m.max <- attr(obj, "m.max")
if (m.max > 0) {
idx <- m > m.max
if (any(idx)) VVm[idx] <- NA
}
VVm
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/VVm_spc.R |
VVm.vgc <- function (obj, m, N=NA, ...)
{
if (! inherits(obj, "vgc")) stop("argument must be object of class 'vgc'")
m <- as.integer(m)
if ( length(m) != 1 || any(is.na(m)) || any(m < 1) ) stop("second argument must be integer >= 1")
if (!attr(obj, "hasVariances")) stop("no variance data available for vocabulary growth curve")
if (!missing(N)) stop("argument 'N' not allowed for object of class 'vgc'")
varname <- paste("VV", m, sep="")
if (m > attr(obj, "m.max"))
stop("spectrum variances '",varname,"' not included in vocabulary growth curve")
structure(obj[[ varname ]], names=obj$N)
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/VVm_vgc.R |
V.lnre <- function (obj, ...)
{
if (! inherits(obj, "lnre")) stop("argument must belong to a subclass of 'lnre'")
spc <- obj$spc
if (is.null(spc)) stop("LNRE model has not been estimated from observed frequency spectrum")
V(spc)
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/V_lnre.R |
V.spc <- function (obj, ...)
{
if (! inherits(obj, "spc")) stop("argument must be object of class 'spc'")
attr(obj, "V")
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/V_spc.R |
V.tfl <- function (obj, ...)
{
if (! inherits(obj, "tfl")) stop("argument must be object of class 'tfl'")
attr(obj, "V")
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/V_tfl.R |
V.vgc <- function (obj, ...)
{
if (! inherits(obj, "vgc")) stop("argument must be object of class 'vgc'")
structure(obj$V, names=obj$N)
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/V_vgc.R |
Vm.lnre <- function (obj, m, ...)
{
if (! inherits(obj, "lnre")) stop("argument must belong to a subclass of 'lnre'")
spc <- obj$spc
if (is.null(spc)) stop("LNRE model has not been estimated from observed frequency spectrum")
Vm(spc, m)
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/Vm_lnre.R |
Vm.spc <- function (obj, m, ...)
{
if (! inherits(obj, "spc")) stop("first argument must be object of class 'spc'")
m <- as.integer(m)
if ( any(is.na(m)) || any(m < 1) ) stop("second argument must be integer(s) >= 1")
## fill in 0's for empty frequency classes
idx <- match(m, obj$m)
Vm <- ifelse(is.na(idx), 0, obj$Vm[idx])
## unlisted classes in incomplete spectrum are set to NA
m.max <- attr(obj, "m.max")
if (m.max > 0) {
idx <- m > m.max
if (any(idx)) Vm[idx] <- NA
}
Vm
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/Vm_spc.R |
Vm.tfl <- function (obj, m, ...)
{
if (! inherits(obj, "tfl")) stop("first argument must be object of class 'tfl'")
m <- as.integer(m)
if (length(m) != 1 || any(m < 0) ) stop("second argument must be single non-negative integer")
if (attr(obj, "incomplete") && (m < attr(obj, "f.min") || m > attr(obj, "f.max"))) {
NA
}
else {
sum(obj$f == m)
}
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/Vm_tfl.R |
Vm.vgc <- function (obj, m, ...)
{
if (! inherits(obj, "vgc")) stop("first argument must be object of class 'vgc'")
m <- as.integer(m)
if ( length(m) != 1 || any(is.na(m)) || any(m < 1) ) stop("second argument must be integer >= 1")
varname <- paste("V", m, sep="")
if (m > attr(obj, "m.max"))
stop("spectrum element '",varname,"' not included in vocabulary growth curve")
structure(obj[[ varname ]], names=obj$N)
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/Vm_vgc.R |
##
## internal: automatically read/write compressed files based on filename extension (.gz)
##
## This function returns an unopened file(), gzfile() or bzfile() or xzfile() connection,
## depending on whether <filename> ends in ".gz", ".bz2" or ".xz" (case-insensitive),
## with character encoding set appropriately.
## It is safe to use file=auto.gzfile(filename) in read.table() and write.table().
auto.gzfile <- function (filename, encoding=getOption("encoding")) {
stopifnot(length(filename) == 1, is.character(filename))
if (grepl("\\.gz$", filename, ignore.case=TRUE)) {
gzfile(filename, encoding=encoding) # return connection to gzip-compressed file, which can be used for reading or writing
}
if (grepl("\\.bz2$", filename, ignore.case=TRUE)) {
bzfile(filename, encoding=encoding) # bzip2-compressed file
}
if (grepl("\\.xz$", filename, ignore.case=TRUE)) {
xzfile(filename, encoding=encoding) # xz-compressed file
}
else {
file(filename, encoding=encoding) # return file() connection for plain files
## when used for reading, this should auto-detect compressed files with different extension
}
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/auto_gzfile.R |
Cgamma <- function (a, log=!missing(base), base=exp(1))
{
if (log) {
if (missing(base)) {
lgamma(a)
} else {
lgamma(a) / log(base)
}
} else {
gamma(a)
}
}
Rgamma <- function (a, x, lower=TRUE, log=!missing(base), base=exp(1))
{
if (log) {
if (missing(base)) {
pgamma(x, shape=a, scale=1, lower.tail=lower, log.p=TRUE)
} else {
pgamma(x, shape=a, scale=1, lower.tail=lower, log.p=TRUE) / log(base)
}
} else {
pgamma(x, shape=a, scale=1, lower.tail=lower, log.p=FALSE)
}
}
Rgamma.inv <- function(a, y, lower=TRUE, log=!missing(base), base=exp(1))
{
if (log) {
if (missing(base)) {
qgamma(y, shape=a, scale=1, lower.tail=lower, log.p=TRUE)
} else {
qgamma(y * log(base), shape=a, scale=1, lower.tail=lower, log.p=TRUE)
}
} else {
qgamma(y, shape=a, scale=1, lower.tail=lower, log.p=FALSE)
}
}
Igamma <- function (a, x, lower=TRUE, log=!missing(base), base=exp(1))
{
if (log) {
Cgamma(a, log=TRUE, base=base) + Rgamma(a, x, lower=lower, log=TRUE, base=base)
} else {
Cgamma(a, log=FALSE) * Rgamma(a, x, lower=lower, log=FALSE)
}
}
Igamma.inv <- function (a, y, lower=TRUE, log=!missing(base), base=exp(1))
{
if (log) {
Rgamma.inv(a, y - Cgamma(a, log=TRUE, base=base), lower=lower, log=TRUE, base=base)
} else {
Rgamma.inv(a, y / Cgamma(a, log=FALSE), lower=lower, log=FALSE)
}
}
Cbeta <- function(a, b, log=!missing(base), base=exp(1))
{
if (log) {
if (missing(base)) {
lbeta(a, b)
} else {
lbeta(a, b) / log(base)
}
} else {
beta(a, b)
}
}
Rbeta <- function (x, a, b, lower=TRUE, log=!missing(base), base=exp(1))
{
if (log) {
if (missing(base)) {
pbeta(x, shape1=a, shape2=b, lower.tail=lower, log.p=TRUE)
} else {
pbeta(x, shape1=a, shape2=b, lower.tail=lower, log.p=TRUE) / log(base)
}
} else {
pbeta(x, shape1=a, shape2=b, lower.tail=lower, log.p=FALSE)
}
}
Rbeta.inv <- function (y, a, b, lower=TRUE, log=!missing(base), base=exp(1))
{
if (log) {
if (missing(base)) {
qbeta(y, shape1=a, shape2=b, lower.tail=lower, log.p=TRUE)
} else {
qbeta(y * log(base), shape1=a, shape2=b, lower.tail=lower, log.p=TRUE)
}
} else {
qbeta(y, shape1=a, shape2=b, lower.tail=lower, log.p=FALSE)
}
}
Ibeta <- function (x, a, b, lower=TRUE, log=!missing(base), base=exp(1))
{
if (log) {
Cbeta(a, b, log=TRUE, base=base) + Rbeta(x, a, b, lower=lower, log=TRUE, base=base)
} else {
Cbeta(a, b, log=FALSE) * Rbeta(x, a, b, lower=lower, log=FALSE)
}
}
Ibeta.inv <- function (y, a, b, lower=TRUE, log=!missing(base), base=exp(1))
{
if (log) {
Rbeta.inv(y - Cbeta(a, b, log=TRUE, base=base), a, b, lower=lower, log=TRUE, base=base)
} else {
Rbeta.inv(y / Cbeta(a, b, log=FALSE), a, b, lower=lower, log=FALSE)
}
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/beta_gamma.R |
bootstrap.confint <- function (x, level=0.95, method=c("normal", "mad", "empirical"),
data.frame=FALSE) {
method <- match.arg(method)
.sig.level <- (1 - level) / 2 # one-sided significance level corresponding to selected confidence level
if (inherits(x, "data.frame")) {
if (!all(sapply(x, is.numeric))) stop("all columns of data.frame x must be numeric")
x <- as.matrix(x)
}
if (!(is.matrix(x) && is.numeric(x))) stop("x must be a numeric matrix")
replicates <- nrow(x)
if (method == "empirical") {
n.outliers <- round(replicates * .sig.level) # number of "outliers" to drop from each tail
if (n.outliers < 3) stop("insufficient bootstrap data for confidence level=", level, " (need at least ", ceiling(3 / .sig.level)," replicates)")
.sig.level <- n.outliers / replicates # "true" significance level of the empirical interval
}
confint.labels <- c(sprintf("%g%%", 100 * c(.sig.level, 1 - .sig.level)), "center", "spread")
## confint.fnc takes a vector x and returns the four estimates (lower, upper, center, spread)
confint.fnc <- switch(
method,
## estimates based on Gaussian distribution (mean + s.d.)
normal = function (x) {
.mean <- mean(x)
.sd <- sd(x)
.C <- -qnorm(.sig.level) # extension of confidence interval in s.d. (z-score)
c(.mean - .C * .sd, .mean + .C * .sd, .mean, .sd)
},
## estimates based on median absolute deviation (median, MAD adusted to s.d.)
mad = function (x) {
.mid <- median(x)
y <- x - .mid
.right <- y >= 0 # data points above median
.left <- y < 0 # data points below median
.madR <- median(abs(y[.right])) # one-sided median absolute deviation
.madL <- median(abs(y[.left]))
.sdR <- .madR / qnorm(3/4) # robust MAD estimator for s.d. of Gaussian distribution
.sdL <- .madL / qnorm(3/4) # (cf. Wikipedia article "Median absolute deviation")
.C <- -qnorm(.sig.level) # extension of confidence interval in s.d. (z-score)
c(.mid - .C * .sdL, .mid + .C * .sdR, .mid, mean(.sdL, .sdR))
},
## empirical confidence interval (median, IQR/2 adjusted to s.d.)
empirical = function (x) {
y <- sort(x)
c(y[n.outliers + 1], y[replicates - n.outliers], median(x), IQR(x) / (2 * qnorm(3/4)))
}
)
confint.wrap <- function (x) {
## catch some special cases
if (!any(is.na(x)) && min(x) == Inf && max(x) == Inf) {
c(Inf, Inf, Inf, Inf) # special case for infinite population diversity
}
else if (any(!is.finite(x))) {
c(NA, NA, NA, NA) # if there are missing or infinite values
}
else confint.fnc(x)
}
.res.table <- apply(x, 2, confint.wrap)
rownames(.res.table) <- confint.labels
if (data.frame) as.data.frame(.res.table, optional=TRUE) else .res.table
} | /scratch/gouwar.j/cran-all/cranData/zipfR/R/bootstrap_confint.R |
confint.lnre <- function (object, parm, level=0.95, method=c("mad", "normal", "empirical"), plot=FALSE, breaks="Sturges", ...)
{ ## object should belong to class "lnre" if this method is called
if (!("bootstrap" %in% names(object))) stop("no bootstrapping data available for LNRE model")
replicates <- length(object$bootstrap)
method <- match.arg(method)
.type <- object$type
if (missing(parm) || is.null(parm)) {
parm <- switch(.type,
zm=c("alpha", "B"),
fzm=c("alpha", "B", "A"),
gigp=c("gamma", "B", "C"))
parm <- c(parm, "S", "X2")
}
n.parm <- length(parm)
idx.parm <- parm %in% names(object$param)
idx.gof <- parm %in% names(object$gof)
idx.S <- parm == "S"
idx.logP <- parm == "logP"
idx.fail <- !(idx.parm | idx.gof | idx.S | idx.logP)
if (any(idx.fail)) stop("unknown parameter(s): ", paste(parm[idx.fail], collapse=", "))
.res.list <- lapply(object$bootstrap, function (.M) {
.res <- numeric(length=n.parm)
if (any(idx.parm)) .res[idx.parm] <- sapply(parm[idx.parm], function (.name) .M$param[[.name]])
if (any(idx.gof)) .res[idx.gof] <- sapply(parm[idx.gof], function (.name) .M$gof[[.name]])
if (any(idx.S)) .res[idx.S] <- .M$S
if (any(idx.logP)) .res[idx.logP] <- -log10(.M$gof$p)
names(.res) <- parm
.res
})
.res.table <- bootstrap.confint(do.call(rbind, .res.list), level=level, method=method)
colnames(.res.table) <- parm
if (plot) {
for (.p in parm) {
x <- sapply(.res.list, function (.r) .r[.p])
.stats <- .res.table[, .p]
.min <- min(x)
.max <- max(x)
if (.min > -Inf && .max < Inf) {
hist(x, freq=FALSE, main=sprintf("Bootstrap of %s over %d replicates", .p, replicates),
breaks=breaks, xlab=.p, xlim=c(min(.min, .stats[1]), max(.max, .stats[2])))
abline(v=.stats[3], lwd=2, col="red") # central value
abline(v=.stats[1:2], lwd=1, col="red") # boundaries of confidence interval
lines(density(x), col="blue", lwd=2)
}
}
}
as.data.frame(.res.table)
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/confint_lnre.R |
tdlnre <- function (model, x, ...) UseMethod("tdlnre")
tplnre <- function (model, q, lower.tail=FALSE, ...) UseMethod("tplnre")
tqlnre <- function (model, p, lower.tail=FALSE, ...) UseMethod("tqlnre")
dlnre <- function (model, x, ...) UseMethod("dlnre")
plnre <- function (model, q, lower.tail=TRUE, ...) UseMethod("plnre")
qlnre <- function (model, p, lower.tail=TRUE, ...) UseMethod("qlnre")
ltdlnre <- function (model, x, base=10, log.x=FALSE, ...) UseMethod("ltdlnre")
ldlnre <- function (model, x, base=10, log.x=FALSE, ...) UseMethod("ldlnre")
rlnre <- function (model, n, what=c("tokens", "tfl"), ...) UseMethod("rlnre")
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/distribution.R |
ltdlnre.lnre <- function (model, x, base=10, log.x=FALSE, ...)
{
if (! inherits(model, "lnre")) stop("first argument must be object of class 'lnre'")
if (log.x) x <- base ^ x
log(base) * x * tdlnre(model, x)
}
ldlnre.lnre <- function (model, x, base=10, log.x=FALSE, ...)
{
if (! inherits(model, "lnre")) stop("first argument must be object of class 'lnre'")
if (log.x) x <- base ^ x
log(base) * x * dlnre(model, x)
}
rlnre.lnre <- function (model, n, what=c("tokens", "tfl"), debug=FALSE, ...)
{
if (! inherits(model, "lnre")) stop("first argument must be object of class 'lnre'")
what <- match.arg(what)
if (length(n) != 1) n <- length(n)
if (n == 0) {
if (what == "tokens") factor() else vec2tfl(factor()) # return empty sample
}
else {
if (what == "tokens") {
## generate token vector
x <- runif(n)
y <- 1 + floor( tplnre(model, qlnre(model, x)) ) # 1 + floor( G( F^-1(x) ) )
factor(y) # type numbers are converted to strings
}
else {
## generate type-frequency list directly as mixed sample:
## A) types with expected frequency >= 1: sample from multinomial distribution
V.multi <- ceiling(tplnre(model, 1 / n)) # number of types with pi >= 1/n i.e. E[f] >= 1
pi0 <- tqlnre(model, V.multi) # corresponding probability threshold
p.multi <- plnre(model, pi0, lower.tail=FALSE) # total probability mass P of these types
n.multi <- rbinom(1, n, p.multi) # number of tokens to be sampled
if (n.multi < 1) {
if (debug) cat(sprintf(" - falling back on sampling %d tokens\n", n))
return(vec2tfl(rlnre(model, n, what="tokens", ...))) # multinomial part is empty
}
pi.multi <- -diff(plnre(model, tqlnre(model, 0:V.multi))) # F( G^-1(k) ) = 1 - (pi_1 + pi_2 + ... + pi_k)
## TODO: compute such differences with improved accuracy (avoiding cancellation)
## (note that 1-F already gives more accurate differences than F for small values of pi_k)
if (debug) cat(sprintf(" - multinomial sample N = %d, V = %d, P = %.5f = %.5f\n", n.multi, V.multi, p.multi, sum(pi.multi)))
f.multi <- drop(rmultinom(1, n.multi, pi.multi))
## B) types with expected frequency <= 1: sample token vector, then count
n.tokens <- n - n.multi
p.tokens <- plnre(model, pi0) # total probability mass 1-P of types from which tokens are sampled
if (debug) cat(sprintf(" - token sample N = %d, P = %.5f\n", n.tokens, p.tokens))
x <- runif(n.tokens, 0, p.tokens) # sample from remaining range (0, 1-P) of distribution function F
y <- 1 + floor( tplnre(model, qlnre(model, x)) ) # guarantees that sampled type IDs are > n.multi
f.tokens <- table(y)
## combine A) and B) into type-frequency list
tfl(f=c(f.multi, f.tokens), type=c(seq_len(V.multi), names(f.tokens)), delete.zeros=TRUE)
}
}
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/distribution_lnre.R |
tdlnre.lnre.fzm <- function (model, x, ...)
{
if (! inherits(model, "lnre.fzm")) stop("first argument must be object of class 'lnre.fzm'")
alpha <- model$param$alpha
A <- model$param$A
B <- model$param$B
C <- model$param2$C
below <- x < A
above <- x > B
ok <- !(below | above)
d <- numeric(length(x))
d[below] <- 0
d[above] <- 0
d[ok] <- C * (x[ok] ^ (-alpha - 1))
d
}
tplnre.lnre.fzm <- function (model, q, lower.tail=FALSE, ...)
{
if (! inherits(model, "lnre.fzm")) stop("first argument must be object of class 'lnre.fzm'")
alpha <- model$param$alpha
A <- model$param$A
B <- model$param$B
C <- model$param2$C
S <- model$S
below <- q < A
above <- q > B
ok <- !(below | above)
p <- numeric(length(q))
p[below] <- S
p[above] <- 0
p[ok] <- (C / alpha) * (q[ok]^(-alpha) - B^(-alpha))
if (lower.tail) p <- S - p
p
}
tqlnre.lnre.fzm <- function (model, p, lower.tail=FALSE, ...)
{
if (! inherits(model, "lnre.fzm")) stop("first argument must be object of class 'lnre.fzm'")
alpha <- model$param$alpha
A <- model$param$A
B <- model$param$B
C <- model$param2$C
S <- model$S
if (lower.tail) p <- S - p
below <- p < 0
above <- p > S
ok <- !(below)
q <- numeric(length(p))
q[below] <- B
q[above] <- A
q[ok] <- ( (alpha / C) * p[ok] + B^(-alpha) ) ^ (-1 / alpha)
q
}
dlnre.lnre.fzm <- function (model, x, ...)
{
if (! inherits(model, "lnre.fzm")) stop("first argument must be object of class 'lnre.fzm'")
alpha <- model$param$alpha
A <- model$param$A
B <- model$param$B
C <- model$param2$C
below <- x < A
above <- x > B
ok <- !(below | above)
d <- numeric(length(x))
d[below] <- 0
d[above] <- 0
d[ok] <- C * x[ok]^(-alpha)
d
}
plnre.lnre.fzm <- function (model, q, lower.tail=TRUE, ...)
{
if (! inherits(model, "lnre.fzm")) stop("first argument must be object of class 'lnre.fzm'")
alpha <- model$param$alpha
A <- model$param$A
B <- model$param$B
C <- model$param2$C
below <- q < A
above <- q > B
ok <- !(below | above)
p <- numeric(length(q))
p[below] <- 0
p[above] <- 1
p[ok] <- (q[ok]^(1-alpha) - A^(1-alpha)) / (B^(1-alpha) - A^(1-alpha))
if (!lower.tail) p <- 1 - p
p
}
qlnre.lnre.fzm <- function (model, p, lower.tail=TRUE, ...)
{
if (! inherits(model, "lnre.fzm")) stop("first argument must be object of class 'lnre.fzm'")
if (!lower.tail) p <- 1 - p
alpha <- model$param$alpha
A <- model$param$A
B <- model$param$B
C <- model$param2$C
below <- p < 0
above <- p > 1
ok <- !(below | above)
q <- numeric(length(p))
q[below] <- A
q[above] <- B
q[ok] <- ( ((1-alpha)/C) * p[ok] + A^(1-alpha) ) ^ (1/(1-alpha))
q
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/distribution_lnre_fzm.R |
tdlnre.lnre.gigp <- function (model, x, ...)
{
if (! inherits(model, "lnre.gigp")) stop("first argument must be object of class 'lnre.gigp'")
gamma <- model$param$gamma
b <- model$param$B # original notation from Baayen (2001)
c <- model$param$C
C <- (2 / (b*c))^(gamma+1) / (2 * besselK(b, gamma+1))
d <- C * x^(gamma-1) * exp(- x/c - (b*b*c)/(4*x))
d
}
dlnre.lnre.gigp <- function (model, x, ...)
{
if (! inherits(model, "lnre.gigp")) stop("first argument must be object of class 'lnre.gigp'")
gamma <- model$param$gamma
b <- model$param$B # original notation from Baayen (2001)
c <- model$param$C
C <- (2 / (b*c))^(gamma+1) / (2 * besselK(b, gamma+1))
d <- C * x^gamma * exp(- x/c - (b*b*c)/(4*x))
d
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/distribution_lnre_gigp.R |
tdlnre.lnre.zm <- function (model, x, ...)
{
if (! inherits(model, "lnre.zm")) stop("first argument must be object of class 'lnre.zm'")
alpha <- model$param$alpha
B <- model$param$B
C <- model$param2$C
below <- x < 0
above <- x > B
ok <- !(below | above)
d <- numeric(length(x))
d[below] <- 0
d[above] <- 0
d[ok] <- C * (x[ok] ^ (-alpha - 1))
d
}
tplnre.lnre.zm <- function (model, q, lower.tail=FALSE, ...)
{
if (! inherits(model, "lnre.zm")) stop("first argument must be object of class 'lnre.zm'")
if (lower.tail)
stop("lower-tail type distribution not meaningful for LNRE model with S = Inf")
alpha <- model$param$alpha
B <- model$param$B
C <- model$param2$C
S <- Inf
below <- q < 0
above <- q > B
ok <- !(below | above)
p <- numeric(length(q))
p[below] <- Inf
p[above] <- 0
p[ok] <- (C / alpha) * q[ok]^(-alpha) - (1 - alpha) / (B * alpha)
p
}
tqlnre.lnre.zm <- function (model, p, lower.tail=FALSE, ...)
{
if (! inherits(model, "lnre.zm")) stop("first argument must be object of class 'lnre.zm'")
if (lower.tail)
stop("lower-tail type distribution not meaningful for LNRE model with S = Inf")
alpha <- model$param$alpha
B <- model$param$B
C <- model$param2$C
below <- p < 0
ok <- !(below)
q <- numeric(length(p))
q[below] <- B
q[ok] <- ( (alpha / C) * p[ok] + B^(-alpha) ) ^ (-1 / alpha)
q
}
dlnre.lnre.zm <- function (model, x, ...)
{
if (! inherits(model, "lnre.zm")) stop("first argument must be object of class 'lnre.zm'")
alpha <- model$param$alpha
B <- model$param$B
C <- model$param2$C
below <- x < 0
above <- x > B
ok <- !(below | above)
d <- numeric(length(x))
d[below] <- 0
d[above] <- 0
d[ok] <- C * x[ok]^(-alpha)
d
}
plnre.lnre.zm <- function (model, q, lower.tail=TRUE, ...)
{
if (! inherits(model, "lnre.zm")) stop("first argument must be object of class 'lnre.zm'")
alpha <- model$param$alpha
B <- model$param$B
C <- model$param2$C
below <- q < 0
above <- q > B
ok <- !(below | above)
p <- numeric(length(q))
p[below] <- 0
p[above] <- 1
p[ok] <- (q[ok] ^ (1-alpha)) / (B ^ (1-alpha))
if (!lower.tail) p <- 1 - p
p
}
qlnre.lnre.zm <- function (model, p, lower.tail=TRUE, ...)
{
if (! inherits(model, "lnre.zm")) stop("first argument must be object of class 'lnre.zm'")
if (!lower.tail) p <- 1 - p
alpha <- model$param$alpha
B <- model$param$B
C <- model$param2$C
below <- p < 0
above <- p > 1
ok <- !(below | above)
q <- numeric(length(p))
q[below] <- 0
q[above] <- B
q[ok] <- B * (p[ok] ^ (1 / (1-alpha)))
q
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/distribution_lnre_zm.R |
## internal: estimate parameters of LNRE model of specified class
estimate.model <- function (model, spc, param.names,
method, cost.function, m.max=15,
runs=3, debug=FALSE, ...)
{
UseMethod("estimate.model")
}
## generic estimation procedure for class 'lnre'
estimate.model.lnre <- function (model, spc, param.names,
method, cost.function, m.max=15,
runs=3, debug=FALSE, ...)
{
## "Custom" not implemented for this LNRE model -> fall back to standard optimization method
if (method == "Custom") {
method <- if (length(param.names) > 1) "Nelder-Mead" else "NLM" # probably the best choices
}
compute.cost <- function (P.vector, param.names, model, spc, m.max=15, debug=FALSE)
{
P.trans <- as.list(P.vector) # translate parameter vector into list
names(P.trans) <- param.names
P <- model$util$transform(P.trans, inverse=TRUE) # convert parameters to normal scale
model <- model$util$update(model, P) # update model parameters (checks ranges)
cost <- cost.function(model, spc, m.max)
if (debug) {
report <- as.data.frame(model$param)
report$cost <- round(cost, digits=2)
rownames(report) <- ""
print(report)
}
cost
}
res.list <- list()
cost.list <- numeric(0)
err.list <- character(0)
for (R. in 1:runs) {
## vector of init values for parameters in transformed scale (same order as in param.names)
param.values <- if (R. == 1) rep(0, length(param.names)) else rnorm(length(param.names), sd=2)
if (method == "NLM") { # NLM = standard nonlinear minimization
result <- try(
nlm(compute.cost, param.values, print.level=debug, stepmax=10, steptol=1e-12,
param.names=param.names, model=model, spc=spc, m.max=m.max, debug=debug),
silent=TRUE)
if (inherits(result, "try-error")) {
err.list <- append(err.list, result)
} else {
res.code <- result$code
if (res.code > 3) {
err.list <- append(err.list, sprintf("parameter estimation failed (code %d)", res.code))
}
else if (res.code == 3) {
err.list <- append(err.list, "estimated parameter values may be incorrect (code 3)")
}
else {
P.estimate <- as.list(result$estimate)
names(P.estimate) <- param.names
res.list <- append(res.list, list(P.estimate))
cost.list <- append(cost.list, result$minimum)
}
}
}
else { # Nelder-Mead, SANN, BFGS = selected optim() algorithm
result <- try(
optim(param.values, compute.cost, method=method,
control=list(trace=debug, reltol=1e-12),
param.names=param.names, model=model, spc=spc, m.max=m.max, debug=debug),
silent=TRUE)
if (inherits(result, "try-error")) {
err.list <- append(err.list, result)
} else {
res.conv <- result$convergence
if (res.conv > 1) {
err.list <- append(err.list, sprintf("parameter estimation failed (code %d)", res.conv))
}
else if (res.conv > 0) {
err.list <- append(err.list, "iteration limit exceeded, estimated parameter values may be incorrect (code 1)")
}
else {
P.estimate <- as.list(result$par)
names(P.estimate) <- param.names
res.list <- append(res.list, list(P.estimate))
cost.list <- append(cost.list, result$value)
}
}
}
}
if (length(res.list) == 0) {
stop("parameter estimation failed (errors: ", paste(err.list, collapse="; "), ")")
}
idx <- which.min(cost.list) # best run
P.estimate <- res.list[[idx]]
model <- model$util$update(model, P.estimate, transformed=TRUE)
model$gof <- lnre.goodness.of.fit(model, spc, n.estimated=length(param.names))
model
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/estimate_model.R |
estimate.model.lnre.fzm <- function (model, spc, param.names,
method, cost.function, m.max=15,
runs=1, debug=FALSE, ...)
{
if (! inherits(model, "lnre.fzm")) stop("argument must be object of class 'lnre.fzm'")
if (runs > 1) warning("multiple estimation runs not yet implemented for Custom method (please set runs=1)")
## root function used to solve implicit equation E[V(N)] = V for B
B.root.function <- function (B, N, V, model) {
B <- B
model <- model$util$update(model, list(B=B))
E.V <- EV(model, N)
E.V - V
}
## B is computed directly (so that E[V] = V) and not controlled by the optimization procedure
compute.B <- function(model, spc) {
alpha <- model$param$alpha
A <- model$param$A
N <- N(spc)
V <- V(spc)
## estimate for the non-exact model can be computed directly
term1 <- (N ^ alpha) * Igamma(1 - alpha, N * A, lower=FALSE)
term2 <- (A ^ (-alpha)) * (1 - exp(-N * A))
C <- alpha * V / (term1 + term2)
B <- ( (1 - alpha) / C + A ^ (1 - alpha) ) ^ (1 / (1 - alpha))
if (B > 1e6) {
if (debug) warning("Estimate B = ",B," > 1e6 from inexact model, adjusting to 1e6")
B <- 1e6
}
## for the exact model, this estimate leads to E[V] < V (because of the nature of the
## approximation), so we have to adjust B appropriately in this case
if (model$exact) {
.eps <- 10 * .Machine$double.eps
upper.B <- B
lower.B <- upper.B
.diff <- B.root.function(lower.B, N, V, model)
if (.diff >= 0) { # if E[V] < V isn't met, don't know how to search for better solution
if (debug) warning("Can't adjust estimate B = ",B," from inexact model ",
"since E[V] - V = ",.diff," > 0")
}
else { # now find a lower boundary for the search interval with E[V] > V
while ((lower.B - A) > .eps && .diff < 0) {
lower.B <- (lower.B + A) / 2
.diff <- B.root.function(lower.B, N, V, model)
}
if (.diff < 0) { # can't find suitable lower boundary -> fall back to inexact estimate
if (debug) warning("Can't find exact estimate for B, since lowest possible value ",
"B = ",lower.B," has E[V] - V = ",.diff," < 0")
}
else { # now use uniroot() to find B in this range with E[V] = V
res <- uniroot(B.root.function, lower=lower.B, upper=upper.B, tol=.eps * B,
N=N, V=V, model=model)
if (abs(res$f.root) > .5) { # estimate for B is not satisfactory
if (debug) warning("No exact estimate for B found. Best guess was ",
"B = ",res$root," with E[V] - V = ",res$f.root)
}
else { # found satisfactory exact estimate for B -> update value
B <- res$root
}
}
}
}
B
}
if ("B" %in% param.names) {
param.names <- param.names[param.names != "B"]
}
else {
warning("parameter B cannot be fixed in fZM estimation, ignoring specified value")
}
param.values <- rep(0, length(param.names))
if ("alpha" %in% param.names) {
tmp <- list(alpha=Vm(spc, 1) / V(spc)) # start with direct ZM estimate, cf. Evert (2004), p. 130
tmp <- model$util$transform(tmp)
param.values[param.names == "alpha"] <- tmp$alpha
}
compute.cost <- function (P.vector, param.names, model, spc, m.max=15, debug=FALSE)
{
P.trans <- as.list(P.vector) # translate parameter vector into list
names(P.trans) <- param.names
P <- model$util$transform(P.trans, inverse=TRUE) # convert parameters to normal scale
P$B <- max(1, 10 * P$A) # make sure that B is valid (just a dummy, correct value is computed below)
model <- model$util$update(model, P) # update model parameters (checks ranges)
B <- compute.B(model, spc) # compute B from other model parameters and spectrum
model <- model$util$update(model, list(B=B))
cost <- cost.function(model, spc, m.max)
if (debug) {
report <- as.data.frame(model$param)
report$cost <- round(cost, digits=2)
rownames(report) <- ""
print(report)
}
cost
}
if (length(param.names) > 1) { # multi-dimensional minimization with Nelder-Mead
result <- optim(param.values, compute.cost, method="Nelder-Mead",
control=list(trace=debug, reltol=1e-12),
param.names=param.names, model=model, spc=spc, m.max=m.max, debug=debug)
res.conv <- result$convergence
if (res.conv > 1) stop("parameter estimation failed (code ", res.conv, ")")
if (res.conv > 0)
warning("iteration limit exceeded, estimated parameter values may be incorrect (code 1)")
P.estimate <- as.list(result$par)
names(P.estimate) <- param.names
model <- model$util$update(model, P.estimate, transformed=TRUE)
}
else if (length(param.names) >= 1) { # one-dimensional minimization with NLM
result <- nlm(compute.cost, param.values, print.level=debug, stepmax=10, steptol=1e-12,
param.names=param.names, model=model, spc=spc, m.max=m.max, debug=debug)
res.code <- result$code
if (res.code > 3) stop("parameter estimation failed (code ", res.code,")")
if (res.code == 3) warning("estimated parameter values may be incorrect (code 3)")
P.estimate <- as.list(result$estimate)
names(P.estimate) <- param.names
model <- model$util$update(model, P.estimate, transformed=TRUE)
}
## if B was the only parameter to be estimated, we can just compute it directly
B <- compute.B(model, spc)
model <- model$util$update(model, list(B=B))
model$gof <- lnre.goodness.of.fit(model, spc, n.estimated=length(param.names) + 1)
model
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/estimate_model_lnre_fzm.R |
estimate.model.lnre.zm <- function (model, spc, param.names,
method, cost.function, m.max=15,
runs=1, debug=FALSE, ...)
{
if (! inherits(model, "lnre.zm")) stop("argument must be object of class 'lnre.zm'")
if (runs > 1) warning("multiple estimation runs not yet implemented for Custom method (please set runs=1)")
## root function used to solve implicit equation E[V(N)] = V for B
B.root.function <- function (B, N, V, model) {
B <- B
model <- model$util$update(model, list(B=B))
E.V <- EV(model, N)
E.V - V
}
## B is computed directly (so that E[V] = V) and not controlled by the optimization procedure
compute.B <- function(model, spc) {
alpha <- model$param$alpha
N <- N(spc)
V <- V(spc)
## estimate for the non-exact model can be computed directly
C <- alpha * V / (Cgamma(1-alpha) * N^alpha)
B <- ( (1 - alpha) / C ) ^ (1 / (1 - alpha))
if (B > 1e6) {
if (debug) warning("Estimate B = ",B," > 1e6 from inexact model, adjusting to 1e6")
B <- 1e6
}
## for the exact model, this estimate leads to E[V] < V (because of the nature of the
## approximation), so we have to adjust B appropriately in this case
if (model$exact) {
.eps <- 10 * .Machine$double.eps
upper.B <- B
lower.B <- upper.B
.diff <- B.root.function(lower.B, N, V, model)
if (.diff >= 0) { # if E[V] < V isn't met, don't know how to search for better solution
if (debug) warning("Can't adjust estimate B = ",B," from inexact model ",
"since E[V] - V = ",.diff," > 0")
}
else { # now find a lower boundary for the search interval with E[V] > V
while (lower.B > 0 && .diff < 0) {
lower.B <- lower.B / 2
.diff <- B.root.function(lower.B, N, V, model)
}
if (.diff < 0) { # can't find suitable lower boundary -> fall back to inexact estimate
if (debug) warning("Can't find exact estimate for B, since all B > 0 have ",
"E[V] - V <= ",.diff," < 0")
}
else { # now use uniroot() to find B in this range with E[V] = V
res <- uniroot(B.root.function, lower=lower.B, upper=upper.B, tol=.eps * B,
N=N, V=V, model=model)
if (abs(res$f.root) > .5) { # estimate for B is not satisfactory
if (debug) warning("No exact estimate for B found. Best guess was ",
"B = ",res$root," with E[V] - V = ",res$f.root)
}
else { # found satisfactory exact estimate for B -> update value
B <- res$root
}
}
}
}
B
}
if ("B" %in% param.names) {
param.names <- param.names[param.names != "B"]
}
else {
warning("parameter B cannot be fixed in ZM estimation, ignoring specified value")
}
param.values <- rep(0, length(param.names))
if ("alpha" %in% param.names) {
tmp <- list(alpha=Vm(spc, 1) / V(spc)) # start with direct ZM estimate, cf. Evert (2004), p. 130
tmp <- model$util$transform(tmp)
param.values[param.names == "alpha"] <- tmp$alpha
}
compute.cost <- function (P.vector, param.names, model, spc, m.max=15, debug=FALSE)
{
P.trans <- as.list(P.vector) # translate parameter vector into list
names(P.trans) <- param.names
P <- model$util$transform(P.trans, inverse=TRUE) # convert parameters to normal scale
P$B <- 1 # make sure that B is valid (just a dummy, correct value is computed below)
model <- model$util$update(model, P) # update model parameters (checks ranges)
B <- compute.B(model, spc) # compute B from other model parameters and spectrum
model <- model$util$update(model, list(B=B))
cost <- cost.function(model, spc, m.max)
if (debug) {
report <- as.data.frame(model$param)
report$cost <- round(cost, digits=2)
rownames(report) <- ""
print(report)
}
cost
}
if (length(param.names) > 0) { # at most 1 parameter is estimated -> one-dimensional minimization with NLM
result <- nlm(compute.cost, param.values, print.level=debug, stepmax=10, steptol=1e-12,
param.names=param.names, model=model, spc=spc, m.max=m.max, debug=debug)
res.code <- result$code
if (res.code > 3) stop("parameter estimation failed (code ", res.code,")")
if (res.code == 3) warning("estimated parameter values may be incorrect (code 3)")
P.estimate <- as.list(result$estimate)
names(P.estimate) <- param.names
model <- model$util$update(model, P.estimate, transformed=TRUE)
}
## if B was the only parameter to be estimated, we can just compute it directly
B <- compute.B(model, spc)
model <- model$util$update(model, list(B=B))
model$gof <- lnre.goodness.of.fit(model, spc, n.estimated=length(param.names) + 1)
model
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/estimate_model_lnre_zm.R |
# gtlnre <- function (model, m, N=NULL) {
# if (! inherits(model, "lnre")) stop("first argument must be object of class 'lnre'")
# if (missing(N)) N <- N(model)
# if (!(is.numeric(N) && all(N >= 0))) stop("argument 'N' must be non-negative integer")
# if (!(is.numeric(m) && all(m >= 1))) stop("argument 'm' must be positive integer")
#
# ## TODO: add code for special case m=0 (with finite population size S, possibly specified by user)
# (m+1) * EVm(model, m+1, N) / EVm(model, m, N)
# } | /scratch/gouwar.j/cran-all/cranData/zipfR/R/good_turing.R |
lnre <- function (type=c("zm", "fzm", "gigp"),
spc=NULL, debug=FALSE,
cost=c("gof", "chisq", "linear", "smooth.linear", "mse", "exact"),
m.max=15, runs=5,
method=c("Nelder-Mead", "NLM", "BFGS", "SANN", "Custom"),
exact=TRUE, sampling=c("Poisson", "multinomial"),
bootstrap=0, verbose=TRUE, parallel=1L,
...)
{
type <- match.arg(type)
sampling <- match.arg(sampling)
user.param <- list(...) # model parameters passed by user
user.pnames <- names(user.param)
method <- match.arg(method)
if (sampling == "multinomial") {
warning("multinomial sampling not yet implemented, falling back to Poisson sampling")
sampling <- "Poisson"
}
if (!is.function(cost)) {
cost <- match.arg(cost)
cost.function <- switch(cost, # implementation of chosen cost function
gof=lnre.cost.gof,
chisq=lnre.cost.chisq,
linear=lnre.cost.linear,
smooth.linear=lnre.cost.smooth.linear,
mse=lnre.cost.mse,
exact=lnre.cost.mse, # use MSE cost with adjusted value for m.max
stop("internal error - can't find suitable cost function"))
} else {
cost.function <- cost
cost <- "User"
}
constructor <- switch(type, # select appropriate constructor function
zm = lnre.zm,
fzm = lnre.fzm,
gigp = lnre.gigp,
stop("internal error - can't find suitable LNRE model constructor"))
model <- constructor(param=user.param) # initialize model with user-specified parameter values
model$exact <- exact
model$multinomial <- sampling == "multinomial"
pnames <- names(model$param) # get list of model parameters
given.param <- pnames[pnames %in% user.pnames]
missing.param <- pnames[! (pnames %in% user.pnames)]
unknown.param <- user.pnames[! (user.pnames %in% pnames)]
if (length(unknown.param) > 0) warning("unknown parameter(s) ignored: ", unknown.param)
if (length(missing.param) > 0) {
## incomplete model -> estimate parameters from observed frequency spectrum
if (missing(spc)) stop("parameter(s) ", paste(missing.param, collapse=", ")," not specified")
if (debug) {
cat("Estimating parameter(s) <", missing.param, "> from observed spectrum.\n")
cat("Default values for other parameters:\n")
print(as.data.frame(model$param))
}
if (cost == "exact") {
## adjust m.max for "exact" parameter estimation (to match V and first V_m exactly)
m.max <- max(length(missing.param) - 1, 1)
}
else if (missing(m.max)) {
## otherwise auto-adjust unspecified m.max to avoid low-frequency spectrum elements with poor normal approximation
keep <- Vm(spc, 1:m.max) >= 5
if (!all(keep)) {
new.max <- min(which(!keep)) - 1
new.max <- max(new.max, length(missing.param) + 2) # need at least as many spectrum elements as parameters to be estimated (better a few more)
m.max <- min(m.max, new.max)
}
}
if (method == "Custom") { # custom estimation uses method call to fall back on default automatically
model <- estimate.model(model, spc=spc, param.names=missing.param, debug=debug,
method=method, cost.function=cost.function, m.max=m.max, runs=runs)
}
else {
model <- estimate.model.lnre(model, spc=spc, param.names=missing.param, debug=debug,
method=method, cost.function=cost.function, m.max=m.max, runs=runs)
}
model$spc <- spc
if (bootstrap > 0) {
model$bootstrap <- lnre.bootstrap(
model, N(spc), ESTIMATOR=lnre, STATISTIC=identity, replicates=bootstrap, simplify=FALSE, verbose=verbose, parallel=parallel,
type=type, cost=cost, m.max=m.max, method=method, exact=exact, sampling=sampling, debug=FALSE, ...)
}
}
else {
## all parameters specified -> no estimation necessary
if (! missing(spc)) warning("no use for observed frequency spectrum 'spc' (ignored)")
if (bootstrap > 0) warning("can't bootstrap fully specified model (skipped)")
## parameter values have already been set in constructor call above
}
model
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/lnre.R |
##
## Parametric bootstrapping can be used to obtain approximate confidence intervals for parameters, predictions, etc.
##
lnre.bootstrap <- function (model, N, ESTIMATOR, STATISTIC, replicates=100, sample=c("spc", "tfl", "tokens"),
simplify=TRUE, verbose=TRUE, parallel=1L, seed=NULL, ...) {
if (!inherits(model, "lnre")) stop("first argument must belong to a subclass of 'lnre'")
if (!is.function(sample)) sample <- match.arg(sample)
stopifnot(replicates >= 1)
stopifnot(is.function(ESTIMATOR))
stopifnot(is.function(STATISTIC))
par.method <- "single"
if (inherits(parallel, "cluster")) {
n.proc <- length(clusterCall(parallel, function () library(zipfR)))
par.method <- "cluster"
} else {
n.proc <- parallel
stopifnot(is.numeric(n.proc), length(n.proc) == 1, n.proc >= 1)
n.proc <- as.integer(n.proc)
if (n.proc > 1) par.method <- "fork"
}
## select batch size so that
## - each batch computes at most 10 replicate pre process
## - there are at least 10 batches (assuming that small value of replicates indicates high computational cost)
## - batch size is a multiple of n.proc so that work is divided evenly
n.batch <- n.proc * max(1, min(10, floor(replicates / (10 * n.proc))))
if (par.method == "single") n.batch <- 1
## worker function that generates and processes a single sample
## (all parameters should be bound by the closure, so no arguments need to be passed)
SAMPLER <- if (is.function(sample)) sample else
switch(sample,
tokens = function (model, n) rlnre(model, n, what="tokens"),
tfl = function (model, n) rlnre(model, n, what="tfl"),
spc = function (model, n) tfl2spc(rlnre(model, n, what="tfl")))
.worker <- function (n) {
.sample <- SAMPLER(model, n)
.estimated.model <- try(suppressWarnings(ESTIMATOR(.sample, ...)), silent=TRUE)
if (is(.estimated.model, "try-error")) return(NULL)
.stats <- try(suppressWarnings(STATISTIC(.estimated.model)), silent=TRUE)
if (is(.stats, "try-error")) return(NULL)
return(.stats)
}
if (verbose) {
if (n.proc > 1) {
cat(sprintf("Bootstrapping from %s object, using %d processes ...\n", class(model)[1], n.proc))
} else {
cat(sprintf("Bootstrapping from %s object ...\n", class(model)[1]))
}
.progress <- txtProgressBar(min=0, max=replicates, initial=0, style=3)
}
.result <- list()
.errors <- 0
if (!is.null(seed)) set.seed(seed)
.got <- 0
while (.got < replicates) {
if (.errors > replicates) stop("failure rate > 50%, procedure aborted")
n <- min(n.batch, replicates - .got)
n <- n.proc * ceiling(n / n.proc) # round up to multiple of workers
batch <- switch(
par.method,
single = list(.worker(N)),
fork = mclapply(rep(N, n), .worker, mc.cores=n.proc),
cluster = clusterApply(parallel, rep(N, n), .worker),
stop("internal error (invalid par.method)"))
stopifnot(n == length(batch)) # sanity check
for (res in batch) {
if (is.null(res)) {
.errors <- .errors + 1
} else {
.got <- .got + 1
.result[[.got]] <- res
}
}
if (verbose) setTxtProgressBar(.progress, min(.got, replicates))
}
if (verbose) {
close(.progress)
if (.errors > 0) cat("[bootstrap failed for", .errors, "samples]\n")
}
if (.got > replicates) .result <- .result[1:replicates]
if (simplify) {
do.call(rbind, .result)
}
else {
attr(.result, "N") <- N
attr(.result, "errors") <- .errors
attr(.result, "model") <- model
.result
}
}
## ***TODO*** -- implement and document prediction intervals as predict.lnre method (? or in EV, EVm, ...)
## bootstrap.extrap <- function (model, replicates=100, ...) {
## lnre.bootstrap(
## model,
## function (spc, ...) lnre(model$type, spc, ...),
## function (m, ...) c(EV(m, 2*N(m)), EVm(m, 1, 2*N(m))),
## col.names=c("EV.2N", "EV1.2N"), verbose=TRUE, replicates=replicates,
## ...
## )
## }
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/lnre_bootstrap.R |
##
## internal: various cost functions for parameter estimation of LNRE models
##
## common signature: lnre.cost(model, spc, m.max=15)
## LIKELIHOOD / GOODNESS-OF-FIT (lnre.cost.gof)
## compute goodness-of-fit statistic from multivariate chi-squared test
## - under the multivariate normal approximation, likelihood is a monotonic function of this statistic
## - no automatic adjustment of m.max to avoid inaccurate normal approximation for small E[Vm] and V[Vm]
## - see lnre.goodness.of.fit for explanation of the computation and references
lnre.cost.gof <- function (model, spc, m.max=15)
{
N <- N(spc)
V <- V(spc)
m.vec <- seq_len(m.max)
Vm <- Vm(spc, m.vec)
E.Vm <- EVm(model, m.vec, N)
E.V <- EV(model, N)
E.Vm.2N <- EVm(model, seq_len(2 * m.max), 2 * N)
E.V.2N <- EV(model, 2 * N)
err.vec <- c(V, Vm) - c(E.V, E.Vm)
cov.Vm.Vk <- diag(E.Vm, nrow=m.max) -
outer(m.vec, m.vec, function (m, k) choose(m+k, m) * E.Vm.2N[m+k] / 2^(m+k))
cov.Vm.V <- E.Vm.2N[m.vec] / 2^(1:m.max)
R <- rbind(c(VV(model, N), cov.Vm.V),
cbind(cov.Vm.V, cov.Vm.Vk))
t(err.vec) %*% solve(R, err.vec)
}
## CHI-SQUARED COST FUNCTION (lnre.cost.chisq)
## compute standard chi-squared statistic for observed data wrt. model
## - observations are V_1, ..., V_m.max and V+ = V - (V_1 + ... + V_m.max)
## - statistic assumes independence of these random variables
## (!= multivariate chi-squared used for g.o.f.)
## - means and standard deviations of variables are obtained from model
## - s.d. is clamped to >= 3 to avoid scaling up small differences
## for which normal approximation is unsuitable
lnre.cost.chisq <- function (model, spc, m.max=15)
{
N <- N(spc)
E.Vm <- EVm(model, 1:m.max, N) # expected values according to LNRE model
E.V <- EV(model, N)
E.Vplus <- E.V - sum(E.Vm)
V.Vm <- VVm(model, 1:m.max, N) # variances according to LNRE model
V.V <- VV(model, N)
V.Vplus <- V.V - sum(V.Vm) # since we assume independence of the V_k
V.Vm <- pmax(V.Vm, 9) # clamp variance to >= 9 (i.e., s.d. >= 3)
V.Vplus <- max(V.Vplus, 9)
O.Vm <- Vm(spc, 1:m.max) # observed values
O.V <- V(spc)
O.Vplus <- O.V - sum(O.Vm)
X2 <- sum( (O.Vm - E.Vm)^2 / V.Vm ) + (O.Vplus - E.Vplus)^2 / V.Vplus
X2
}
## LINEAR COST FUNCTION (lnre.cost.linear)
## sum of absolute values of differences between observed and expected values
## - for vocabulary size V and spectrum elements V_1, ... , V_m.max
lnre.cost.linear <- function (model, spc, m.max=15)
{
N <- N(spc)
E.Vm <- EVm(model, 1:m.max, N)
E.V <- EV(model, N)
O.Vm <- Vm(spc, 1:m.max)
O.V <- V(spc)
abs(E.V - O.V) + sum( abs(E.Vm - O.Vm) )
}
## SMOOTH LINEAR COST FUNCTION (lnre.cost.smooth.linear)
## smoothed version of linear cost function which avoids kink of abs(x) at x=0
## - sum of sqrt(1 + (O-E)^2) (min. cost = 1, approximates abs(O-E) for larger differences)
## - for vocabulary size V and spectrum elements V_1, ... , V_m.max
lnre.cost.smooth.linear <- function (model, spc, m.max=15)
{
N <- N(spc)
E.Vm <- EVm(model, 1:m.max, N)
E.V <- EV(model, N)
O.Vm <- Vm(spc, 1:m.max)
O.V <- V(spc)
sqrt(1 + (E.V - O.V)^2) + sum( sqrt(1 + (E.Vm - O.Vm)^2) )
}
## MEAN SQUARED ERROR (MSE) COST FUNCTION (lnre.cost.mse)
## sum (or average) of squared differences between observed and expected values
## - for vocabulary size V and spectrum elements V_1, ... , V_m.max
lnre.cost.mse <- function (model, spc, m.max=15)
{
N <- N(spc)
E.Vm <- EVm(model, 1:m.max, N)
E.V <- EV(model, N)
O.Vm <- Vm(spc, 1:m.max)
O.V <- V(spc)
( (E.V - O.V)^2 + sum((E.Vm - O.Vm)^2) ) / (1 + m.max)
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/lnre_cost.R |
lnre.fzm <- function (alpha=.8, A=1e-9, B=.01, param=list())
{
if (! is.list(param)) stop("'param' argument must be a list of parameter=value pairs")
pnames <- names(param)
## explicitly specified parameters override the values in 'param'
if (!missing(alpha) || !("alpha" %in% pnames)) param$alpha <- alpha
if (!missing(A) || !("A" %in% pnames)) param$A <- A
if (!missing(B) || !("B" %in% pnames)) param$B <- B
## initialize lnre.fzm model object
self <- list(type="fzm", name="finite Zipf-Mandelbrot",
param=list(), param2=list(),
util=list(update=lnre.fzm.update, transform=lnre.fzm.transform, print=lnre.fzm.print, label=lnre.fzm.label))
class(self) <- c("lnre.fzm", "lnre", class(self))
## update model parameters to specified values & compute secondary parameters
self <- lnre.fzm.update(self, param)
self
}
lnre.fzm.update <- function (self, param=list(), transformed=FALSE)
{
if (! is.list(param)) stop("'param' argument must be a list")
if (! inherits(self, "lnre.fzm")) stop("this function can only be applied to 'lnre.fzm' objects")
if (transformed) param <- lnre.fzm.transform(param, inverse=TRUE)
pnames <- names(param)
unused <- !(pnames %in% c("alpha", "A", "B"))
if (any(unused)) warning("unused parameters in 'param' argument: ", pnames[unused])
if ("alpha" %in% pnames) {
alpha <- param$alpha
if (alpha <= 0 || alpha >= 1) stop("parameter alpha = ",alpha," out of range (0,1)")
self$param$alpha <- alpha
}
else {
alpha <- self$param$alpha
}
if ("B" %in% pnames) {
B <- param$B
if (B <= 0) stop("parameter B = ",B," out of range (0, Inf)")
self$param$B <- B
}
else {
B <- self$param$B
}
if ("A" %in% pnames) {
A <- param$A
if (A <= 0 || A >= B) stop("parameter A = ",A," out of range (0, B) = (0, ",B,")")
self$param$A <- A
}
else {
A <- self$param$A
}
self$param2$a <- 1 / alpha # parameters of Zipf-Mandelbrot law are same as for ZM, only constanct C is different
self$param2$b <- (1 - alpha) / (B * alpha)
C <- (1 - alpha) / ( B ^ (1 - alpha) - A ^ (1 - alpha) ) # Evert (2004: 128)
S <- (C / alpha) * ((A ^ -alpha) - (B ^ -alpha))
self$param2$C <- C
self$S <- S
self
}
lnre.fzm.transform <- function (param, inverse=FALSE)
{
alpha <- param$alpha
A <- param$A
B <- param$B
new.param <- list()
if (inverse) {
## alpha = inv.logit(alpha*) = 1 / (1 + exp(-alpha*))
if (! is.null(alpha)) new.param$alpha <- 1 / (1 + exp(-alpha))
## A = exp(A* + log(1e-9))
if (! is.null(A)) new.param$A <- exp(A + log(1e-9))
## B = exp(B*)
if (! is.null(B)) new.param$B <- exp(B)
}
else {
## alpha* = logit(alpha) = log(alpha / (1-alpha))
if (! is.null(alpha)) new.param$alpha <- log(alpha / (1-alpha))
## A* = log(A) - log(1e-9) [shifted so that A* = 0 is a sensible init value]
if (! is.null(A)) new.param$A <- log(A) - log(1e-9)
## B* = log(B)
if (! is.null(B)) new.param$B <- log(B)
}
new.param
}
lnre.fzm.print <- function (self)
{
cat("finite Zipf-Mandelbrot LNRE model.\n")
cat("Parameters:\n")
cat(" Shape: alpha =", self$param$alpha, "\n")
cat(" Lower cutoff: A =", self$param$A, "\n")
cat(" Upper cutoff: B =", self$param$B, "\n")
cat(" [ Normalization: C =", self$param2$C, "]\n")
}
lnre.fzm.label <- function (self) sprintf("fZM(alpha=%.5g, A=%.5g, B=%.5g)", self$param$alpha, self$param$A, self$param$B)
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/lnre_fzm.R |
lnre.gigp <- function (gamma=-.5, B=.01, C=.01, param=list())
{
if (! is.list(param)) stop("'param' argument must be a list of parameter=value pairs")
pnames <- names(param)
## explicitly specified parameters override the values in 'param'
if (!missing(gamma) || !("gamma" %in% pnames)) param$gamma <- gamma
if (!missing(B) || !("B" %in% pnames)) param$B <- B
if (!missing(C) || !("C" %in% pnames)) param$C <- C
## initialize lnre.fzm model object
self <- list(type="gigp", name="Generalized Inverse Gauss-Poisson (GIGP)",
param=list(), param2=list(),
util=list(update=lnre.gigp.update, transform=lnre.gigp.transform, print=lnre.gigp.print, label=lnre.gigp.label))
class(self) <- c("lnre.gigp", "lnre", class(self))
## update model parameters to specified values & compute secondary parameters
self <- lnre.gigp.update(self, param)
self
}
lnre.gigp.update <- function (self, param=list(), transformed=FALSE)
{
if (! is.list(param)) stop("'param' argument must be a list")
if (! inherits(self, "lnre.gigp")) stop("this function can only be applied to 'lnre.gigp' objects")
if (transformed) param <- lnre.gigp.transform(param, inverse=TRUE)
pnames <- names(param)
unused <- !(pnames %in% c("gamma", "B", "C"))
if (any(unused)) warning("unused parameters in 'param' argument: ", pnames[unused])
if ("gamma" %in% pnames) {
gamma <- param$gamma
if (gamma <= -1 || gamma >= 0) stop("parameter gamma = ",gamma," out of range (-1,0)")
self$param$gamma <- gamma
}
else {
gamma <- self$param$gamma
}
if ("B" %in% pnames) {
B <- param$B
if (B < 0) stop("parameter B = ",B," out of range [0, Inf)")
self$param$B <- B
}
else {
B <- self$param$B
}
if ("C" %in% pnames) {
C <- param$C
if (C < 0) stop("parameter C = ",C," out of range [0, Inf)")
self$param$C <- C
}
else {
C <- self$param$C
}
Z <- 1 / C
S <- (2 * besselK(B, gamma)) / (besselK(B, gamma+1) * B * C)
self$param2$Z <- Z
self$S <- S
self
}
lnre.gigp.transform <- function (param, inverse=FALSE)
{
gamma <- param$gamma
B <- param$B
C <- param$C
new.param <- list()
if (inverse) {
## gamma = -inv.logit(gamma*) = -1 / (1 + exp(-gamma*))
if (! is.null(gamma)) new.param$gamma <- -1 / (1 + exp(-gamma))
## B = exp(B* - 5)
if (! is.null(B)) new.param$B <- exp(B - 5)
## C = exp(C* - 5)
if (! is.null(C)) new.param$C <- exp(C - 5)
}
else {
## gamma* = logit(-gamma) = log(-gamma / (1+gamma))
if (! is.null(gamma)) new.param$gamma <- log(-gamma / (1+gamma))
## B* = log(B) + 5 [shifted so that B* = 0 -> B = .0067 is a useful init value]
if (! is.null(B)) new.param$B <- log(B) + 5
## C* = log(C) + 5 [shifted so that C* = 0 -> C = .0067 is a useful init value]
if (! is.null(C)) new.param$C <- log(C) + 5
}
new.param
}
lnre.gigp.print <- function (self)
{
cat("Generalized Inverse Gauss-Poisson (GIGP) LNRE model.\n")
cat("Parameters:\n")
cat(" Shape: gamma =", self$param$gamma, "\n")
cat(" Lower decay: B =", self$param$B, "\n")
cat(" Upper decay: C =", self$param$C, "\n")
cat(" [ Zipf size: Z =", self$param2$Z, "]\n")
}
lnre.gigp.label <- function (self) sprintf("GIGP(gamma=%.5g, B=%.5g, C=%.5g)", self$param$gamma, self$param$B, self$param$C)
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/lnre_gigp.R |
lnre.goodness.of.fit <- function(model, spc, n.estimated=0, m.max=15)
{
if (! inherits(model, "lnre")) stop("first argument must belong to a subclass of 'lnre'")
if (model$multinomial) warning("goodness-of-fit test for multinomial sampling not available yet, falling back to Poisson sampling")
## automatically reduce number of spectrum elements if variances become too small
V.Vm <- VVm(model, 1:m.max, N(spc))
keep <- V.Vm >= 5 # normal approximation to binomial-type distributions should be reasonably good
if (!all(keep) && missing(m.max)) {
new.max <- min(which(!keep)) - 1 # first 1:new.max spectrum elements are suitable
if (new.max < n.estimated + 2) new.max <- n.estimated + 2 # ensure that df >= 3
m.max <- new.max
}
df <- m.max + 1 - n.estimated # degrees of freedom of the computed chi-squared statistic
if (df < 1) stop("m.max too small (must be larger than number of estimated parameters)")
## compute multivariate chi-squared test statistic, following Baayen (2001), p. 119ff
N <- N(spc) # observed N, V, Vm from spectrum
V <- V(spc)
Vm <- Vm(spc, 1:m.max)
E.Vm <- EVm(model, 1:m.max, N) # E[Vm(N)]
E.Vm.2N <- EVm(model, 1:(2*m.max), 2*N) # E[Vm(2N)]
E.V <- EV(model, N) # E[V(N)]
E.V.2N <- EV(model, 2 * N) # E[V(2N)]
## construct covariance matrix R
err.vec <- c(V, Vm) - c(E.V, E.Vm) # error vector (p. 119)
cov.Vm.Vk <- diag(E.Vm, nrow=m.max) - # "inner part" of covariance matrix (p. 120, (3.61))
outer(1:m.max, 1:m.max, function (m,k) choose(m+k, m) * E.Vm.2N[m+k] / 2^(m+k))
cov.Vm.V <- E.Vm.2N[1:m.max] / 2^(1:m.max) # (p. 121, (3.63))
R <- rbind(c(VV(model, N), cov.Vm.V), # construct covariance matrix R (p. 119, (3.58))
cbind(cov.Vm.V, cov.Vm.Vk))
## compute chi-squared statistic X2 = err.vec %*% R^(-1) %*% err.vec
x2 <- t(err.vec) %*% solve(R, err.vec) # (p. 119, (3.59)) -- solve(R, e) returns R^(-1) %*% e, but should be more accurate and stable
p <- pchisq(x2, df=df, lower.tail=FALSE) # x2 has this chi-squared distribution under H0 (p. 119f, following (3.59))
result <- data.frame(X2=x2, df=df, p=p)
rownames(result) <- ""
result
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/lnre_goodness_of_fit.R |
lnre.productivity.measures <- function (model, N=NULL, measures, data.frame=TRUE,
bootstrap=FALSE, method="normal", conf.level=.95, sample=NULL,
replicates=1000, parallel=1L, verbose=TRUE, seed=NULL)
{
if (! inherits(model, "lnre")) stop("first argument must belong to a subclass of 'lnre'")
if (is.null(N)) N <- N(model)
if (! (is.numeric(N) && all(N > 0))) stop("'N' must be a positive integer vector")
if (is.null(sample))
sample <- "spc"
else
if (!is.function(sample)) stop("'sample' must be a callback function suitable for lnre.bootstrap()")
supported <- qw("V TTR R C k U W P Hapax H S alpha2 K D")
if (bootstrap) supported <- c(supported, qw("Entropy eta"))
if (missing(measures) || is.null(measures)) measures <- supported
measures <- sapply(measures, match.arg, choices=supported)
## empirical distribution from parametric bootstrapping
if (bootstrap) {
if (length(N) > 1L) stop("only a single 'N' value is allowed with bootstrap=TRUE")
res <- lnre.bootstrap(model, N, ESTIMATOR=productivity.measures, measures=measures,
STATISTIC=identity, sample=sample, simplify=TRUE,
replicates=replicates, parallel=parallel, seed=seed, verbose=verbose)
return(bootstrap.confint(res, level=conf.level, method=method, data.frame=data.frame))
}
## delta = probability of drawing same type twice = second moment of tdf
delta <- function (model) {
if (inherits(model, "lnre.fzm")) {
alpha <- model$param$alpha
A <- model$param$A
B <- model$param$B
C <- model$param2$C
C / (2 - alpha) * (B^(2 - alpha) - A^(2 - alpha))
}
else if (inherits(model, "lnre.zm")) {
alpha <- model$param$alpha
B <- model$param$B
C <- model$param2$C
C / (2 - alpha) * B^(2 - alpha)
}
else stop("cannot compute delta for LNRE model of class ", class(model)[1])
}
.EV <- EV(model, N)
.EV1 <- EVm(model, 1, N)
.EV2 <- EVm(model, 2, N)
res <- sapply(measures, function (M.) {
switch(M.,
## measures based on V and N
V = .EV,
TTR = .EV / N,
R = .EV / sqrt(N),
C = log(.EV) / log(N),
k = log(.EV) / log(log(N)),
U = log(N)^2 / (log(N) - log(.EV)),
W = N ^ (.EV ^ -0.172),
## measures based on hapax count (V1)
P = .EV1 / N,
Hapax = .EV1 / .EV,
H = 100 * log(N) / (1 - .EV1 / .EV),
## measures based on the first two spectrum elements (V1 and V2)
S = .EV2 / .EV,
alpha2 = 1 - 2 * .EV2 / .EV1,
## Yule K and Simpson D can only be computed from full spectrum
K = 10e4 * (N - 1) / N * delta(model),
D = rep(delta(model), length(N)),
stop("internal error -- measure '", M., "' not implemented yet"))
})
if (!is.matrix(res)) res <- t(res)
rownames(res) <- N
if (data.frame) as.data.frame(res, optional=TRUE) else res
}
## if (!is.null(conf.sd)) {
## sds <- c(-conf.sd, +conf.sd)
## conf.int <- switch(what,
## R = (V(obj) + sds * sqrt(VV(obj))) / sqrt(N(obj)),
## C = log( V(obj) + sds * sqrt(VV(obj)) ) / log( N(obj) ),
## P = (Vm(obj, 1) + sds * sqrt(VVm(obj, 1))) / N(obj),
## TTR = (V(obj) + sds * sqrt(VV(obj))) / N(obj),
## V = V(obj) + sds * sqrt(VV(obj)))
## res$lower <- conf.int[1]
## res$upper <- conf.int[2]
## }
## if (!is.null(conf.sd)) {
## ## Evert (2004b, Lemma A.8) gives the following approximation for the variance:
## ## - Var[Vm / V] = Var[V] / E[V]^2 * (s(1 - s) + (r - s)^2)
## ## - with r = E[Vm] / E[V] and s = Var[Vm] / Var[V]
## sd.VmV <- function (obj, m) {
## r <- Vm(obj, m) / V(obj)
## s <- VVm(obj, m) / VV(obj)
## sqrt(VV(obj)) / V(obj) * sqrt( s * (1-s) + (r - s)^2 )
## }
## sds <- c(-conf.sd, +conf.sd)
## conf.int <- switch(what,
## S = (res$estimate + sds * sd.VmV(obj, 2)),
## H = 100 * log( N(obj) ) / (1 - (Vm(obj, 1) / V(obj) + sds * sd.VmV(obj, 1))),
## Hapax = (res$estimate + sds * sd.VmV(obj, 1)))
## res$lower <- conf.int[1]
## res$upper <- conf.int[2]
## }
## conf.sd <- if (isTRUE(attr(obj, "hasVariances"))) -qnorm((1 - conf.level) / 2) else NULL
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/lnre_productivity_measures.R |
lnre.spc <- function (model, N=NULL, variances=FALSE, m.max=100)
{
if (! inherits(model, "lnre")) stop("first argument must belong to a subclass of 'lnre'")
if (is.null(N)) N <- N(model) # if specified as default value, R complains about "recursive reference"
if (! (is.numeric(N) && length(N) == 1 && all(N > 0)))
stop("'N' argument must be a single positive number")
if (variances && missing(m.max)) m.max <- 50
m.vec <- 1:m.max
E.Vm <- EVm(model, m.vec, N)
E.V <- EV(model, N)
if (variances) {
V.Vm <- VVm(model, m.vec, N)
V.V <- VV(model, N)
spc(Vm=E.Vm, m=m.vec, VVm=V.Vm, N=N, V=E.V, VV=V.V, m.max=m.max, expected=TRUE)
}
else {
spc(Vm=E.Vm, m=m.vec, N=N, V=E.V, m.max=m.max, expected=TRUE)
}
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/lnre_spc.R |
lnre.vgc <- function (model, N, m.max=0, variances=FALSE)
{
if (!inherits(model, "lnre")) stop("first argument must belong to a subclass of 'lnre'")
if (! (is.numeric(N) && all(N >= 0)))
stop("'N' argument must be a vector of non-negative numbers")
if (!missing(m.max) && !(length(m.max) == 1 && is.numeric(m.max) && 0 <= m.max && m.max <= 9))
stop("'m.max' must be a single integer in the range 1 ... 9")
E.V <- EV(model, N)
E.Vm.list <- list()
if (m.max > 0) E.Vm.list <- lapply(1:m.max, function (.m) EVm(model, .m, N))
if (!variances) {
vgc(N=N, V=E.V, Vm=E.Vm.list, expected=TRUE)
}
else {
V.V <- VV(model, N)
V.Vm.list <- list()
if (m.max > 0) V.Vm.list <- lapply(1:m.max, function (.m) VVm(model, .m, N))
vgc(N=N, V=E.V, VV=V.V, Vm=E.Vm.list, VVm=V.Vm.list, expected=TRUE)
}
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/lnre_vgc.R |
lnre.zm <- function (alpha=.8, B=.01, param=list())
{
if (! is.list(param)) stop("'param' argument must be a list of parameter=value pairs")
pnames <- names(param)
## explicitly specified parameters override the values in 'param'
if (!missing(alpha) || !("alpha" %in% pnames)) param$alpha <- alpha
if (!missing(B) || !("B" %in% pnames)) param$B <- B
## initialize lnre.zm model object
self <- list(type="zm", name="Zipf-Mandelbrot",
param=list(), param2=list(),
util=list(update=lnre.zm.update, transform=lnre.zm.transform, print=lnre.zm.print, label=lnre.zm.label))
class(self) <- c("lnre.zm", "lnre", class(self))
## update model parameters to specified values & compute secondary parameters
self <- lnre.zm.update(self, param)
self
}
lnre.zm.update <- function (self, param=list(), transformed=FALSE)
{
if (! is.list(param)) stop("'param' argument must be a list")
if (! inherits(self, "lnre.zm")) stop("this function can only be applied to 'lnre.zm' objects")
if (transformed) param <- lnre.zm.transform(param, inverse=TRUE)
pnames <- names(param)
unused <- !(pnames %in% c("alpha", "B"))
if (any(unused)) warning("unused parameters in 'param' argument: ", pnames[unused])
if ("alpha" %in% pnames) {
alpha <- param$alpha
if (alpha <= 0 || alpha >= 1) stop("parameter alpha = ", alpha, " out of range (0,1)")
self$param$alpha <- alpha
}
else {
alpha <- self$param$alpha
}
if ("B" %in% pnames) {
B <- param$B
if (B <= 0) stop("parameter B = ", B, " out of range (0, Inf)")
self$param$B <- param$B
}
else {
B <- self$param$B
}
self$param2$a <- 1 / alpha # parameters of Zipf-Mandelbrot law (Evert 2004: 126)
self$param2$b <- (1 - alpha) / (B * alpha)
C <- (1 - alpha) / B^(1 - alpha) # Evert (2004: 126)
self$param2$C <- C
self$S <- Inf
self
}
lnre.zm.transform <- function (param, inverse=FALSE)
{
alpha <- param$alpha
B <- param$B
new.param <- list()
if (inverse) {
## alpha = inv.logit(alpha*) = 1 / (1 + exp(-alpha*))
if (! is.null(alpha)) new.param$alpha <- 1 / (1 + exp(-alpha))
## B = exp(B*)
if (! is.null(B)) new.param$B <- exp(B)
}
else {
## alpha* = logit(alpha) = log(alpha / (1-alpha))
if (! is.null(alpha)) new.param$alpha <- log(alpha / (1-alpha))
## B* = log(B)
if (! is.null(B)) new.param$B <- log(B)
}
new.param
}
lnre.zm.print <- function (self)
{
cat("Zipf-Mandelbrot LNRE model.\n")
cat("Parameters:\n")
cat(" Shape: alpha =", self$param$alpha, "\n")
cat(" Upper cutoff: B =", self$param$B, "\n")
cat(" [ Normalization: C =", self$param2$C, "]\n")
}
lnre.zm.label <- function (self) sprintf("ZM(alpha=%.5g, B=%.5g)", self$param$alpha, self$param$B)
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/lnre_zm.R |
merge.tfl <- function (x, y, ...)
{
tfl.list <- c(list(x, y), list(...))
ok <- sapply(tfl.list, function (x) inherits(x, "tfl"))
if (!all(ok)) stop("all arguments must be type frequency lists (of class tfl)")
ok <- sapply(tfl.list, function (x) "type" %in% colnames(x))
if (!all(ok)) stop("all type frequency lists to be merged must contain type labels")
ok <- sapply(tfl.list, function (x) !isTRUE(attr(x, "incomplete")))
if (!all(ok)) stop("only complete type frequency lists can be merged")
vocab <- Reduce(union, lapply(tfl.list, function (x) x$type))
f.total <- numeric(length(vocab))
for (x in tfl.list) {
idx <- match(x$type, vocab)
stopifnot(!any(is.na(idx)))
f.total[idx] <- f.total[idx] + x$f
}
tfl(f.total, type=vocab)
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/merge_tfl.R |
plot.lnre <- function (x, y, ...,
type=c("types", "probability", "cumulative"),
xlim=c(1e-9, 1), ylim=NULL, steps=200,
xlab=NULL, ylab=NULL, legend=NULL, grid=FALSE,
main="LNRE Population Distribution",
lty=NULL, lwd=NULL, col=NULL, bw=zipfR.par("bw"))
{
## collect all specified LNRE models in single list
if (is.list(x) && inherits(x[[1]], "lnre")) {
if (!missing(y)) stop("only a single list of LNRE models may be specified")
Models <- x
} else {
Models <- list(x) # this is a bit complicated because of the plot() prototype
if (! missing(y)) Models <- c(Models, list(y), list(...))
}
n.mod <- length(Models)
## check other arguments
type <- match.arg(type)
if (isTRUE(legend)) legend <- sapply(Models, function (.M) .M$util$label(.M))
if (!is.null(legend) && length(legend) != n.mod) stop("'legend' argument must be character or expression vector of same length as number of LNRE models")
if (is.null(xlab)) xlab <- expression(pi)
if (is.null(ylab)) ylab <- switch(type, types="type density", probability="probability density", cumulative="cumulative probability")
## evaluate density or cumulative probability distribution
X <- 10 ^ seq(log10(xlim[1]), log10(xlim[2]), length.out=steps) # logarithmically equidistant steps
if (type == "cumulative") {
Ys <- lapply(Models, function (.M) plnre(.M, X, lower.tail=TRUE))
if (is.null(ylim)) ylim <- c(0, 1)
} else {
log.density <- if (type == "types") ltdlnre else ldlnre # will also be used further below
Ys <- lapply(Models, function (.M) log.density(.M, X))
if (is.null(ylim)) ylim <- c(0, 1.05 * do.call(max, Ys))
}
## get default styles unless manually overridden
if (is.null(lty)) lty <- zipfR.par("lty", bw.mode=bw)
if (is.null(lwd)) lwd <- zipfR.par("lwd", bw.mode=bw)
if (is.null(col)) col <- zipfR.par("col", bw.mode=bw)
## set up plotting region and labels
plot(1, 1, type="n", xlim=xlim, ylim=ylim, log="x", xaxs="i", yaxs="i",
xlab=xlab, ylab=ylab, main=main)
if (grid) {
rng <- c(round(log10(xlim[1])), floor(round(xlim[2])))
if (diff(rng) >= 0) abline(v=10^seq(rng[1], rng[2], 1), lwd=.5)
if (type != "types") abline(h=seq(0, ylim[2], .1), lwd=.5)
}
for (i in seq_len(n.mod)) { # plot all specified models
x <- X
y <- Ys[[i]]
M <- Models[[i]]
## special case for better display of (f)ZM type densities at cutoff
if (type != "cumulative" && inherits(M, c("lnre.zm", "lnre.fzm"))) {
B <- M$param$B # apply upper cutoff
idx <- x > B
if (any(idx)) {
y <- c(y[!idx], log.density(M, B), 0)
x <- c(x[!idx], B, B)
}
if (inherits(M, "lnre.fzm")) {
A <- M$param$A # apply lower cutoff
idx <- x < A
if (any(idx)) {
y <- c(0, log.density(M, A), y[!idx])
x <- c(A, A, x[!idx])
}
}
}
lines(x, y, col=col[i], lwd=lwd[i], lty=lty[i])
}
if (!is.null(legend)) { # add legend if specified by user
legend.args <- list(if (type == "types") "topright" else "topleft",
inset=.02, bg="white", legend=legend, col=col, lwd=lwd + 1, lty=lty)
do.call("legend", legend.args)
}
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/plot_lnre.R |
plot.spc <- function(x, y, ...,
m.max=if (log=="") 15 else 50,
log="", conf.level=.95,
bw=zipfR.par("bw"), points=TRUE,
xlim=NULL, ylim=NULL,
xlab="m", ylab="V_m", legend=NULL,
main="Frequency Spectrum",
barcol=NULL, pch=NULL, lty=NULL, lwd=NULL, col=NULL)
{
## collect all specified frequency spectra in single list
if (is.list(x) && inherits(x[[1]], "spc")) {
spectra <- x
if (!missing(y)) stop("only a single list of frequency spectra may be specified")
} else {
spectra <- list(x) # this is a bit complicated because of the plot() prototype
if (!missing(y)) spectra <- c(spectra, list(y), list(...))
}
n.spc <- length(spectra)
## check other arguments & collect some statistics
if (! (log %in% c("", "x", "y", "xy"))) stop("allowed values for 'log' argument are '', 'x', 'y' and 'xy'")
V.max <- max(sapply(spectra, function (.S) max(Vm(.S, 1:m.max))))
if (!is.null(legend) && length(legend) != n.spc)
stop("'legend' argument must be character or expression vector of same length as number of spectra")
x.log <- log == "x" || log == "xy"
y.log <- log == "y" || log == "xy"
## get default styles unless manually overridden
if (is.null(barcol)) barcol <- zipfR.par("barcol", bw.mode=bw)
if (is.null(pch)) pch <- zipfR.par("pch", bw.mode=bw)
if (is.null(lty)) lty <- zipfR.par("lty", bw.mode=bw)
if (is.null(lwd)) lwd <- zipfR.par("lwd", bw.mode=bw)
if (is.null(col)) col <- zipfR.par("col", bw.mode=bw)
## typeset default label on y-axis, depending on whether spectra are observed or expected
expected <- sapply(spectra, function (.S) attr(.S, "expected"))
if (missing(ylab)) {
if (all(expected)) {
ylab <- expression(E * group("[", V[m], "]"))
}
else if (all(!expected)) {
ylab <- expression(V[m])
}
else {
ylab <- expression(V[m] / E * group("[", V[m], "]"))
}
}
## choose suitable ranges on the axes, unless specified by user
if (is.null(xlim)) xlim <- c(1, m.max)
if (is.null(ylim)) ylim <- if (y.log) c(0.1, 2 * V.max) else c(0, 1.05 * V.max)
## default: non-logarithmic barplot (log parameter not specified)
if (log == "") {
my.data <- sapply(spectra, function (.S) Vm(.S, 1:m.max))
barplot(t(my.data), beside=TRUE, ylim=ylim,
col=barcol[1:n.spc], names.arg = 1:m.max,
xlab=xlab, ylab=ylab, main=main, legend=legend)
}
## lines or points+lines for any kind of logarithmic plot (log="" for non-logarithmic scale)
else {
plot(1, 1, type="n", xlim=xlim, ylim=ylim, log=log, yaxs="i",
xlab=xlab, ylab=ylab, main=main)
for (i in 1:n.spc) { # go through all specified frequency spectra
curr.spc <- spectra[[i]]
x.values <- 1:m.max
y.values <- Vm(curr.spc, 1:m.max)
## draw confidence intervals for expected spectrum with variances
if (attr(curr.spc, "hasVariances") && is.numeric(conf.level)) {
st.dev <- sqrt(VVm(curr.spc, 1:m.max))
factor <- - qnorm((1 - conf.level) / 2) # approximate confidence interval
y.minus <- y.values - factor * st.dev
y.plus <- y.values + factor * st.dev
if (y.log) y.minus[y.minus <= 0] <- ylim[1] / 10
segments(x.values, y.minus, x.values, y.plus, lwd=1, col=col[i])
segments(x.values-.4, y.plus, x.values+.4, y.plus, lwd=1, col[i])
segments(x.values-.4, y.minus, x.values+.4, y.minus, lwd=1, col[i])
}
if (y.log) y.values[y.values <= 0] <- ylim[1] / 10
if (points) { # overplot points and thin lines
points(x.values, y.values, type="o",
pch=pch[i], lty="solid", col=col[i])
} else { # lines only, with different styles
lines(x.values, y.values, lty=lty[i], lwd=lwd[i], col=col[i])
}
}
if (!missing(legend)) { # add legend if specified by user
if (points) {
legend("topright", inset=.02, bg="white", legend=legend, pch=pch, col=col)
} else {
legend("topright", inset=.02, bg="white", legend=legend, lty=lty, lwd=lwd, col=col)
}
}
}
}
| /scratch/gouwar.j/cran-all/cranData/zipfR/R/plot_spc.R |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.