Title: | Alex's Miscellaneous Code |
---|---|
Description: | A collection of variously useful functions and utilities. |
Authors: | Alex M Chubaty [aut, cre, cph] , Eliot J B McIntire [ctb], Ceres Barros [ctb], hrbrmstr [ctb], Jack Wasey [ctb], Josh O'Brien [ctb], mmfrgmpds [ctb] |
Maintainer: | Alex M Chubaty <[email protected]> |
License: | GPL-3 |
Version: | 1.0.1 |
Built: | 2024-12-01 04:25:51 UTC |
Source: | https://github.com/achubaty/amc |
This shouldn't be necessary, since R (usually) handles this correctly and
automatically. However, sometimes when working with large geospatial data
(e.g., using raster
and sp
packages) it can help to free recently
unallocated memory manually.
.gc()
.gc()
Alex Chubaty
Convert integer to binary string
binstr(i, maxBits = NA)
binstr(i, maxBits = NA)
i |
Positive integer <= 2^53 (<= 9.007199e+15). |
maxBits |
Maximum number of bits to print (default |
Character vector.
Alex Chubaty
x <- sample(0:9999, 10000) y <- binstr(x) # length is 14 bits ## Not run: # alternate (but slower) conversion to binary string R.utils::intToBin(x) ## End(Not run) # convert binary string to integer value (very fast) strtoi(y, base = 2) strtoi(substr(y, 1, 4), base = 2) strtoi(substr(y, 5, 8), base = 2) strtoi(substr(y, 9, 11), base = 2) strtoi(substr(y, 12, 14), base = 2) # see also `binary()` and `unbinary()` in the `composition` package (requires x11)
x <- sample(0:9999, 10000) y <- binstr(x) # length is 14 bits ## Not run: # alternate (but slower) conversion to binary string R.utils::intToBin(x) ## End(Not run) # convert binary string to integer value (very fast) strtoi(y, base = 2) strtoi(substr(y, 1, 4), base = 2) strtoi(substr(y, 5, 8), base = 2) strtoi(substr(y, 9, 11), base = 2) strtoi(substr(y, 12, 14), base = 2) # see also `binary()` and `unbinary()` in the `composition` package (requires x11)
Based on https://stackoverflow.com/a/39235076/1380598.
detachAllPackages()
detachAllPackages()
mmfrgmpds
A simple wrapper to detach
using unload = TRUE
.
detachPackage(package)
detachPackage(package)
package |
The name of a currently attached package. |
Alex Chubaty
Copies folders like file.copy
except it replicates links correctly on
unix-like systems. Based on http://stackoverflow.com/a/30107868/1380598.
dir.copy(from, to)
dir.copy(from, to)
from |
|
to |
|
Logical indicating success or failure.
Zach Foster
Alex Chubaty
Only downloads the specified files if it is not found locally. Optionally unzips the files.
dl.data(urls, dest = ".", checksum = TRUE, unzip = FALSE)
dl.data(urls, dest = ".", checksum = TRUE, unzip = FALSE)
urls |
A character vector of data file URLs. |
dest |
The directory path in which data should be downloaded. |
checksum |
Logical indicating whether downloaded files should be checksummed. |
unzip |
Logical indicating whether the file should be unzipped after download. |
Alex Chubaty and Eliot Mcintire
data.table
to a RasterLayer
for plotting, etc.Convert data.table
to a RasterLayer
for plotting, etc.
dt2raster(dt, r, val)
dt2raster(dt, r, val)
dt |
|
r |
|
val |
The name of the column in |
A RasterLayer
object.
Alex Chubaty
library(data.table) library(sp) library(raster) r <- raster(nrows = 10, ncols = 10) r[] <- 10 # using x,y coordinates #dt1 <- data.table(X = , Y = , value = r[]) # using pixel ids dt2 <- data.table(ID = 1L:ncell(r), VALUE = r[]) dt2[, VALUE := sample(1L:10L, ncell(r), replace = TRUE)] if (interactive()) plot(dt2raster(dt2, r, "VALUE"))
library(data.table) library(sp) library(raster) r <- raster(nrows = 10, ncols = 10) r[] <- 10 # using x,y coordinates #dt1 <- data.table(X = , Y = , value = r[]) # using pixel ids dt2 <- data.table(ID = 1L:ncell(r), VALUE = r[]) dt2[, VALUE := sample(1L:10L, ncell(r), replace = TRUE)] if (interactive()) plot(dt2raster(dt2, r, "VALUE"))
Creates a symbolic link (symlink) to a file if possible, possibly falling back to a hard link. Hard links are for files only, and won't work across different physical drives. Symlinks won't work on Windows without admin privileges.
flink(from, to, symlink = TRUE)
flink(from, to, symlink = TRUE)
from , to
|
character vectors, containing file names or paths (can alternatively be the path to a single existing directory). |
symlink |
Logical indicating whether to use symlink (instead of hardlink).
Default |
Use caution with files-backed objects (e.g., rasters). See examples.
Alex Chubaty
file.link()
, file.symlink()
, Sys.readlink()
if (require("datasets", quietly = TRUE)) { library(raster) tmpDir <- file.path(tempdir(), 'symlink-test') |> normalizePath(winslash = '/', mustWork = FALSE) dir.create(tmpDir) f0 <- file.path(tmpDir, "file0.csv") write.csv(iris, f0) d1 <- file.path(tmpDir, "dir1") dir.create(d1) write.csv(iris, file.path(d1, "file1.csv")) d2 <- file.path(tmpDir, "dir2") f2 <- file.path(tmpDir, "file2.csv") ## create a link to the the directory; d2 should look like d1 flink(d1, d2) ## symlink dir.exists(d2) ## TRUE identical(d1, Sys.readlink(d2)) ## TRUE file.exists(file.path(d2, "file1.csv")) ## TRUE ## create link to a file flink(f0, f2) ## symlink file.exists(f2) ## TRUE identical(read.csv(f0), read.csv(f2)) ## TRUE ## deleting the link shouldn't delete the original file unlink(d2, recursive = TRUE) file.exists(file.path(d2, "file1.csv")) ## FALSE file.exists(file.path(d1, "file1.csv")) ## TRUE unlink(f2) file.exists(f2) ## FALSE file.exists(f0) ## TRUE ## using rasters and other file-backed objects f3 <- system.file("external/test.grd", package = "raster") r3 <- raster(f3) f4 <- file.path(tmpDir, "raster4.grd") flink(f3, f4, FALSE) ## hardlink the grd and gri files flink(extension(f3, "gri"), extension(f4, "gri"), FALSE) file.exists(f4) ## TRUE file.exists(extension(f4, "gri")) ## TRUE r4 <- raster(f4) ## hardlink f5 <- file.path(tmpDir, "raster5.grd") flink(f3, f5, TRUE) ## symlink the grd and gri files flink(extension(f3, "gri"), extension(f5, "gri"), TRUE) file.exists(f5) ## TRUE file.exists(extension(f5, "gri")) ## TRUE r5 <- raster(f5) ## symlink works identical(r3, r5) ## TRUE ## cleanup unlink(tmpDir, recursive = TRUE) }
if (require("datasets", quietly = TRUE)) { library(raster) tmpDir <- file.path(tempdir(), 'symlink-test') |> normalizePath(winslash = '/', mustWork = FALSE) dir.create(tmpDir) f0 <- file.path(tmpDir, "file0.csv") write.csv(iris, f0) d1 <- file.path(tmpDir, "dir1") dir.create(d1) write.csv(iris, file.path(d1, "file1.csv")) d2 <- file.path(tmpDir, "dir2") f2 <- file.path(tmpDir, "file2.csv") ## create a link to the the directory; d2 should look like d1 flink(d1, d2) ## symlink dir.exists(d2) ## TRUE identical(d1, Sys.readlink(d2)) ## TRUE file.exists(file.path(d2, "file1.csv")) ## TRUE ## create link to a file flink(f0, f2) ## symlink file.exists(f2) ## TRUE identical(read.csv(f0), read.csv(f2)) ## TRUE ## deleting the link shouldn't delete the original file unlink(d2, recursive = TRUE) file.exists(file.path(d2, "file1.csv")) ## FALSE file.exists(file.path(d1, "file1.csv")) ## TRUE unlink(f2) file.exists(f2) ## FALSE file.exists(f0) ## TRUE ## using rasters and other file-backed objects f3 <- system.file("external/test.grd", package = "raster") r3 <- raster(f3) f4 <- file.path(tmpDir, "raster4.grd") flink(f3, f4, FALSE) ## hardlink the grd and gri files flink(extension(f3, "gri"), extension(f4, "gri"), FALSE) file.exists(f4) ## TRUE file.exists(extension(f4, "gri")) ## TRUE r4 <- raster(f4) ## hardlink f5 <- file.path(tmpDir, "raster5.grd") flink(f3, f5, TRUE) ## symlink the grd and gri files flink(extension(f3, "gri"), extension(f5, "gri"), TRUE) file.exists(f5) ## TRUE file.exists(extension(f5, "gri")) ## TRUE r5 <- raster(f5) ## symlink works identical(r3, r5) ## TRUE ## cleanup unlink(tmpDir, recursive = TRUE) }
Description needed.
geometricMean(x, ...) harmonicMean(x, ...)
geometricMean(x, ...) harmonicMean(x, ...)
x |
A numeric vector. |
... |
Additional arguments to |
A numeric vector of length one.
these have not been thoroughly tested to handle NA
values, etc.
Alex Chubaty
series <- 1:10 mean(series) geometricMean(series) harmonicMean(series)
series <- 1:10 mean(series) geometricMean(series) harmonicMean(series)
Read a package's dependencies from file, rather than searching CRAN. Based on http://stackoverflow.com/a/30225680/1380598.
get_deps(path, dependencies = NA)
get_deps(path, dependencies = NA)
path |
A local file path to a package directory. |
dependencies |
Logical indicating whether to also install uninstalled
packages which these packages depend on/link to/import/suggest
(and so on recursively).
Can also be a character vector, a subset of
|
A character vector of package dependencies.
Josh O'Brien
Alex Chubaty
get_deps(system.file(package = "amc")) get_deps(system.file(package = "amc"), TRUE)
get_deps(system.file(package = "amc")) get_deps(system.file(package = "amc"), TRUE)
source
-ed fileUse getFileName
in a file that is source
-ed.
Based on http://stackoverflow.com/a/1816487/1380598.
getFileName(fullname) ## S4 method for signature 'logical' getFileName(fullname)
getFileName(fullname) ## S4 method for signature 'logical' getFileName(fullname)
fullname |
Logical (default |
Character string representing the filename.
Alex Chubaty
Take a wild stab at guessing how many CPUs to use in cluster when you have some idea of how much RAM is needed per CPU.
guesstimate(ram, prop = 0.8, units = "gb")
guesstimate(ram, prop = 0.8, units = "gb")
ram |
How much ram is required per CPU. |
prop |
Proportion of overall RAM to devote to R. Default |
units |
Units of memory. One of either |
Tries to be conservative by assuming no more than 80% system memory use.
Integer. Number of CPUs to allocate to cluster.
You should take these numbers with several grains of salt.
Alex Chubaty
## Not run: guesstimate(4) guesstimate(4, 0.90, "MB") ## End(Not run)
## Not run: guesstimate(4) guesstimate(4, 0.90, "MB") ## End(Not run)
Hill function
hill(a, b, z)
hill(a, b, z)
a |
DESCRIPTION NEEDED |
b |
DESCRIPTION NEEDED |
z |
DESCRIPTION NEEDED |
DESCRIPTION NEEDED
Devin Goodsman
[a,b]
Default values of a=0; b=1
allow for quick test if
x
is a probability.
inRange(x, a = 0, b = 1)
inRange(x, a = 0, b = 1)
x |
values to be tested |
a |
lower bound (default 0) |
b |
upper bound (default 1) |
Logical vectors. NA
values in x
are retained.
Alex Chubaty
set.seed(100) x <- stats::rnorm(4) ## -0.50219235 0.13153117 -0.07891709 0.88678481 inRange(x, 0, 1) ## FALSE TRUE FALSE TRUE
set.seed(100) x <- stats::rnorm(4) ## -0.50219235 0.13153117 -0.07891709 0.88678481 inRange(x, 0, 1) ## FALSE TRUE FALSE TRUE
Based on https://stackoverflow.com/q/12389158/1380598.
isRstudio()
isRstudio()
Load kNN stand age map
loadkNNageMap(path, url = NULL, studyArea = NULL, ...)
loadkNNageMap(path, url = NULL, studyArea = NULL, ...)
path |
file path where raster will be saved. |
url |
URL from which to download the data (default provided if NULL). |
studyArea |
|
... |
Additional arguments passed to |
Wrapper functions to load()
, save()
,
and unlink()
, permitting lists of objects to be
loaded/saved/deleted all at once.
loadObjects( objects, path = NULL, ext = ".RData", quiet = TRUE, envir = parent.frame() ) saveObjects( objects, path = NULL, ext = ".RData", quiet = TRUE, envir = parent.frame() ) rmObjects(objects, path = NULL, ext = ".RData", quiet = TRUE)
loadObjects( objects, path = NULL, ext = ".RData", quiet = TRUE, envir = parent.frame() ) saveObjects( objects, path = NULL, ext = ".RData", quiet = TRUE, envir = parent.frame() ) rmObjects(objects, path = NULL, ext = ".RData", quiet = TRUE)
objects |
A character list or character vector of object names |
path |
The filepath to the directory in which to save or
from which to load the objects. The path should be
constructed using |
ext |
The file extension to use (default is |
quiet |
Logical. Should output be suppressed? Default is |
envir |
The environment in which to look for and load objects (default: the environment from which the function was called). |
By default, the extension .RData
is used.
Invisibly if quiet=TRUE
. Either a list of objects loaded,
empty list if saved, or if removed either 0
for success,
1
for failure.
Alex Chubaty
file.path()
, load()
, save()
, unlink()
Simple wrapper around sf::st_read()
to load a kml or shapefile,
and optionally reproject it.
loadStudyArea(path = NULL, filename = NULL, proj = NULL)
loadStudyArea(path = NULL, filename = NULL, proj = NULL)
path |
path to directory containing the file |
filename |
the name of the file |
proj |
(optional) a crs projection string to reproject the study area to. |
An sf
object.
Logit function
logit(p)
logit(p)
p |
DESCRIPTION NEEDED |
DESCRIPTION NEEDED
Based on https://stackoverflow.com/q/38686427.
min_r_version(package = NULL, exclude_main_pkg = TRUE)
min_r_version(package = NULL, exclude_main_pkg = TRUE)
package |
Character string giving the name of a package whose dependencies should be checked. |
exclude_main_pkg |
Logical indicating whether |
hrbrmstr and Jack Wasey
Raster*
objects using a function for overlapping areasProvides a wrapper around raster::mosaic()
that cleans up any
temporary intermediate files used, and sets the layer name of the resulting raster.
mosaic2(x, y, ...) ## S4 method for signature 'RasterLayer,RasterLayer' mosaic2( x, y, ..., fun, tolerance = 0.05, filename = NULL, layerName = "layer", inRAM = FALSE ) ## S4 method for signature 'SpatRaster,SpatRaster' mosaic2( x, y, ..., fun, tolerance = 0.05, filename = NULL, layerName = "layer", inRAM = FALSE )
mosaic2(x, y, ...) ## S4 method for signature 'RasterLayer,RasterLayer' mosaic2( x, y, ..., fun, tolerance = 0.05, filename = NULL, layerName = "layer", inRAM = FALSE ) ## S4 method for signature 'SpatRaster,SpatRaster' mosaic2( x, y, ..., fun, tolerance = 0.05, filename = NULL, layerName = "layer", inRAM = FALSE )
x |
|
y |
|
... |
Additional Raster or Extent objects. |
fun |
Function (e.g., |
tolerance |
Numeric. Permissible difference in origin (relative to the
cell resolution). See |
filename |
Character. Output filename (optional). |
layerName |
Character. Name of the resulting raster layer. |
inRAM |
Logical (default |
Alex Chubaty
Draws a convex hull around vertice points of a polygon shapefile, creating a single polygon. If a buffer distance is supplied, will buffer the convex hull inwards or outwards depending on the sign of the distance value.
outerBuffer(x, b = NULL)
outerBuffer(x, b = NULL)
x |
A |
b |
Optional. Distance to buffer. If the value is negative, the buffer will be drawn inwards. |
A SpatialPolygons
object.
Ceres Barros and Alex Chubaty
Which packages were installed from CRAN, GitHub, Bioconductor, etc.?
pkgSrc(pkg, lib.loc = NULL)
pkgSrc(pkg, lib.loc = NULL)
pkg |
a character string with the package name. |
lib.loc |
a character vector of directory names of R libraries,
or |
pkgs <- as.data.frame(installed.packages(), stringsAsFactors = FALSE) ids <- which(!(pkgs$Priority %in% c("base", "recommended"))) pkgs <- pkgs[ids, ] pkgs <- pkgs$Package pkgs[pkgSrc(pkgs) == "CRAN"]
pkgs <- as.data.frame(installed.packages(), stringsAsFactors = FALSE) ids <- which(!(pkgs$Priority %in% c("base", "recommended"))) pkgs <- pkgs[ids, ] pkgs <- pkgs$Package pkgs[pkgSrc(pkgs) == "CRAN"]
Rescale values to a new range
rescale(x, to, from, ...) ## S3 method for class 'numeric' rescale(x, to = c(0, 1), from = range(x, na.rm = TRUE, finite = TRUE), ...) ## S3 method for class 'RasterLayer' rescale( x, to = c(0, 1), from = range(getValues(x), na.rm = TRUE, finite = TRUE), ... ) ## S3 method for class 'SpatRaster' rescale( x, to = c(0, 1), from = range(values(x), na.rm = TRUE, finite = TRUE), ... )
rescale(x, to, from, ...) ## S3 method for class 'numeric' rescale(x, to = c(0, 1), from = range(x, na.rm = TRUE, finite = TRUE), ...) ## S3 method for class 'RasterLayer' rescale( x, to = c(0, 1), from = range(getValues(x), na.rm = TRUE, finite = TRUE), ... ) ## S3 method for class 'SpatRaster' rescale( x, to = c(0, 1), from = range(values(x), na.rm = TRUE, finite = TRUE), ... )
x |
A numeric vector or |
to |
The lower and upper bounds of the new range. Default |
from |
(optional) The lower and upper bounds of the old range (calculated from |
... |
Additional arguments (not used). |
A new object whose values have been rescaled.
Objects with values that are all equal (e.g., all zeroes) will be returned as-is.
This behaviour differs from scales:rescale
which would return a value of 0.5
.
rescale(50, from = c(0, 100), to = c(0, 1)) ## 0.5 x <- 0:100 rescale(x) ## defaults to new range [0,1] rescale(x, c(-1, 1)) f <- system.file("external/test.grd", package = "raster") r <- raster::raster(f) rescale(r) ## defaults to new range [0,1] rescale(r, c(-1, 1)) f <- system.file("ex/test.grd", package = "terra") r <- terra::rast(f) rescale(r) ## defaults to new range [0,1] rescale(r, c(-1, 1))
rescale(50, from = c(0, 100), to = c(0, 1)) ## 0.5 x <- 0:100 rescale(x) ## defaults to new range [0,1] rescale(x, c(-1, 1)) f <- system.file("external/test.grd", package = "raster") r <- raster::raster(f) rescale(r) ## defaults to new range [0,1] rescale(r, c(-1, 1)) f <- system.file("ex/test.grd", package = "terra") r <- terra::rast(f) rescale(r) ## defaults to new range [0,1] rescale(r, c(-1, 1))
Generate a vector of random alphanumeric strings each of an arbitrary length.
rndstr(n = 1, len = 8)
rndstr(n = 1, len = 8)
n |
Number of strings to generate (default 1). Will attempt to coerce to integer value. |
len |
Length of strings to generate (default 8). Will attempt to coerce to integer value. |
Character vector of random strings.
Alex Chubaty
set.seed(11) rndstr() rndstr(len = 10) rndstr(n = 5, len = 10) rndstr(n = 5)
set.seed(11) rndstr() rndstr(len = 10) rndstr(n = 5, len = 10) rndstr(n = 5)
Source a file hosted in a pubic or private GitHub repo
source_github(repo, branch = "master", file, auth = Sys.getenv("GITHUB_PAT"))
source_github(repo, branch = "master", file, auth = Sys.getenv("GITHUB_PAT"))
repo |
Name of the GitHub repository in the form |
branch |
Branch from which to source the file (default master). |
file |
Filename to source, including relative path. |
auth |
Personal Access Token to use for authorization.
Required to access files in private repositories.
By default, checks for |
Alex Chubaty
## Not run: repo = "PredictiveEcology/SpaDES" branch = "development" file = "_ignore/thinSpatialPolygons.R" auth = "" ## your Personal Access Token source_github(repo, branch, file, auth) ## End(Not run)
## Not run: repo = "PredictiveEcology/SpaDES" branch = "development" file = "_ignore/thinSpatialPolygons.R" auth = "" ## your Personal Access Token source_github(repo, branch, file, auth) ## End(Not run)
This tells you the TOTAL system memory (RAM) available. Other processes running on the computer will eat into this total, and as such, you should take these numbers with a grain of salt.
sysmem(x = "GB")
sysmem(x = "GB")
x |
Units to use for output. One of either |
Total amount of system memory (RAM) in units
.
Alex Chubaty
sysmem()
sysmem()
These are wrappers around tempdir
and tempfile
that creates the
directory or file, to ensure a correctly normalized filepath (i.e., on macOS).
td(dir = tempdir()) tf(ext = ".tif", dir = td())
td(dir = tempdir()) tf(ext = ".tif", dir = td())
dir |
Path to use as temporary directory. A subdirectory will be created. Default is to use the R session temporary directory. |
ext |
File extension to give to the newly create file. |
Character string indicating the filepath to the newly created file.
Alex Chubaty