Title: | Omnidirectional R Code Snippets |
---|---|
Description: | I tend to repeat the same code chunks over and over again. At first, this was fine for me and I paid little attention to such redundancies. A little later, when I got tired of manually replacing Linux filepaths with the referring Windows versions, and vice versa, I started to stuff some very frequently used work-steps into functions and, even later, into a proper R package. And that's what this package is - a hodgepodge of various R functions meant to simplify (my) everyday-life coding work without, at the same time, being devoted to a particular scope of application. |
Authors: | Florian Detsch [cre, aut], Tim Appelhans [aut], Baptiste Auguie [ctb], OpenStreetMap contributors [cph] |
Maintainer: | Florian Detsch <[email protected]> |
License: | MIT + file LICENSE |
Version: | 1.2.3 |
Built: | 2024-11-07 04:43:04 UTC |
Source: | https://github.com/fdetsch/orcs |
Omnidirectional R Code Snippets
The package provides a variety of functions which I regularly use during my everyday work.
Florian Detsch, Tim Appelhans, Baptiste Auguie,
OpenStreetMap contributors
Maintainer: Florian Detsch [email protected]
Assign an SSH key to a local Git repository to bypass user/password prompts during 'git push. See Generating an SSH Key for further information on how to generate an SSH key and add it to your GitHub account.
assignSSH(user, repo)
assignSSH(user, repo)
user |
GitHub user name as |
repo |
GitHub repository name as |
https://docs.github.com/articles/generating-an-ssh-key/.
## Not run: ## for an arbitrary git repository assignSSH() ## for this very git repository assignSSH(user = "fdetsch", repo = "Orcs") ## End(Not run)
## Not run: ## for an arbitrary git repository assignSSH() ## for this very git repository assignSSH(user = "fdetsch", repo = "Orcs") ## End(Not run)
Since the use of underscores ('_') is not permitted when streaming
bookdown documents via GitHub Pages, this
wrapper function serves to remove any unwanted underscores from subfolders
and link .html
documents created by bookdown::render_book()
.
buildBook(output_dir = "book", ...)
buildBook(output_dir = "book", ...)
output_dir |
Output directory as |
... |
Arguments passed to |
While all remaining arguments passed to bookdown::render_book()
remain
untouched, and hence their specification is freely up to the user, the
default value of 'output_dir' is explicitly set to "book"
here. If this
were not the case (i.e. if the default value were used), the output document
would be created in "_book"
which is not desirable for obvious reasons.
Florian Detsch
This function let's you bump the version number and creation date of your
package's DESCRIPTION
file. Additionally, it bumps the version numbers of a
NEWS.md
file and automatically generates a corresponding plain NEWS file
(for R-help pages). Supported versioning system is
MAJOR.MINOR.PATCH.
bumpVersion( element = "patch", pkg.repo = ".", news = file.path(pkg.repo, "NEWS.md"), plain_news = TRUE )
bumpVersion( element = "patch", pkg.repo = ".", news = file.path(pkg.repo, "NEWS.md"), plain_news = TRUE )
element |
|
pkg.repo |
Path to package repository folder. Default is current working
directory, i.e. |
news |
The |
plain_news |
whether to generate a plain NEWS file in the package root
directory from the |
Tim Appelhans
This function will produce a plot of two density functions displayed side by side.
compareDistributions( left, right, add.spread = TRUE, print.stats = TRUE, xlim = NULL, ylim = NULL, clrs = c("purple", "lightblue"), xlab = "density", ylab = "value", ... )
compareDistributions( left, right, add.spread = TRUE, print.stats = TRUE, xlim = NULL, ylim = NULL, clrs = c("purple", "lightblue"), xlab = "density", ylab = "value", ... )
left |
|
right |
|
add.spread |
|
print.stats |
|
xlim , ylim
|
|
clrs |
A |
xlab , ylab
|
|
... |
Additional arguments passed to |
A trellis
object.
Tim Appelhans
compareDistributions(rnorm(1000, 2, 3), rnorm(1000, -5, 1)) compareDistributions(rnorm(1000, 2, 3), rnorm(1000, -5, 1), add.spread = FALSE) compareDistributions(rnorm(1000, 2, 3), rnorm(1000, -5, 1), add.spread = TRUE, clrs = c("red", "brown")) compareDistributions(rnorm(1000, 2, 5), rnorm(1000, -5, 4), print.stats = FALSE, add.spread = FALSE) ## pass additional parameters to stats::density() compareDistributions(rnorm(1000, 2, 5), rnorm(1000, -5, 4), print.stats = FALSE, add.spread = FALSE, bw = 5) compareDistributions(rnorm(1000, 2, 5), rnorm(1000, -5, 4), print.stats = FALSE, add.spread = FALSE, bw = 8, kernel = "rectangular") compareDistributions(rnorm(1000, 2, 5), rnorm(1000, -5, 4), print.stats = FALSE, add.spread = TRUE, bw = 8, n = 3) compareDistributions(rnorm(1000, 2, 5), rnorm(1000, -5, 4), print.stats = TRUE, add.spread = TRUE, bw = 0.1) compareDistributions(rnorm(1000, 2, 5), rnorm(1000, -5, 4), print.stats = TRUE, add.spread = TRUE, bw = 0.5)
compareDistributions(rnorm(1000, 2, 3), rnorm(1000, -5, 1)) compareDistributions(rnorm(1000, 2, 3), rnorm(1000, -5, 1), add.spread = FALSE) compareDistributions(rnorm(1000, 2, 3), rnorm(1000, -5, 1), add.spread = TRUE, clrs = c("red", "brown")) compareDistributions(rnorm(1000, 2, 5), rnorm(1000, -5, 4), print.stats = FALSE, add.spread = FALSE) ## pass additional parameters to stats::density() compareDistributions(rnorm(1000, 2, 5), rnorm(1000, -5, 4), print.stats = FALSE, add.spread = FALSE, bw = 5) compareDistributions(rnorm(1000, 2, 5), rnorm(1000, -5, 4), print.stats = FALSE, add.spread = FALSE, bw = 8, kernel = "rectangular") compareDistributions(rnorm(1000, 2, 5), rnorm(1000, -5, 4), print.stats = FALSE, add.spread = TRUE, bw = 8, n = 3) compareDistributions(rnorm(1000, 2, 5), rnorm(1000, -5, 4), print.stats = TRUE, add.spread = TRUE, bw = 0.1) compareDistributions(rnorm(1000, 2, 5), rnorm(1000, -5, 4), print.stats = TRUE, add.spread = TRUE, bw = 0.5)
SpatialLines*
Create a SpatialLines*
object from a Line
object or set of point
coordinates in one go, i.e. without being required to run through the single
steps outlined in sp::SpatialLines()
.
## S4 method for signature 'matrix' coords2Lines(coords, ID, data, match.ID = TRUE, ...) ## S4 method for signature 'Line' coords2Lines(coords, ID, data, match.ID = TRUE, ...)
## S4 method for signature 'matrix' coords2Lines(coords, ID, data, match.ID = TRUE, ...) ## S4 method for signature 'Line' coords2Lines(coords, ID, data, match.ID = TRUE, ...)
coords |
|
ID |
|
data |
|
match.ID |
|
... |
Further arguments passed on to |
If 'data' is missing, a SpatialLines
object; else a
SpatialLinesDataFrame
object.
library(sp) coords1 <- cbind(c(2, 4, 4, 1, 2), c(2, 3, 5, 4, 2)) sln1 <- coords2Lines(coords1, ID = "A") coords2 <- cbind(c(5, 4, 2, 5), c(2, 3, 2, 2)) sln2 <- coords2Lines(coords2, ID = "B") plot(sln1, col = "grey75") plot(sln2, col = "grey25", add = TRUE)
library(sp) coords1 <- cbind(c(2, 4, 4, 1, 2), c(2, 3, 5, 4, 2)) sln1 <- coords2Lines(coords1, ID = "A") coords2 <- cbind(c(5, 4, 2, 5), c(2, 3, 2, 2)) sln2 <- coords2Lines(coords2, ID = "B") plot(sln1, col = "grey75") plot(sln2, col = "grey25", add = TRUE)
SpatialPolygons*
Create a SpatialPolygons*
object from a Polygon
object or set of point
coordinates in one go, i.e. without being required to run through the single
steps outlined in sp::SpatialPolygons()
.
## S4 method for signature 'matrix' coords2Polygons(coords, hole = NA, ID, data, match.ID = TRUE, ...) ## S4 method for signature 'Polygon' coords2Polygons(coords, ID, data, match.ID = TRUE, ...)
## S4 method for signature 'matrix' coords2Polygons(coords, hole = NA, ID, data, match.ID = TRUE, ...) ## S4 method for signature 'Polygon' coords2Polygons(coords, ID, data, match.ID = TRUE, ...)
coords |
|
hole |
|
ID |
|
data |
|
match.ID |
|
... |
Further arguments passed on to |
If 'data' is missing, a SpatialPolygons
object; else a
SpatialPolygonsDataFrame
object.
library(sp) coords1 <- cbind(c(2, 4, 4, 1, 2), c(2, 3, 5, 4, 2)) spy1 <- coords2Polygons(coords1, ID = "A") coords2 <- cbind(c(5, 4, 2, 5), c(2, 3, 2, 2)) spy2 <- coords2Polygons(coords2, ID = "B") plot(spy1, col = "grey75") plot(spy2, col = "grey25", add = TRUE)
library(sp) coords1 <- cbind(c(2, 4, 4, 1, 2), c(2, 3, 5, 4, 2)) spy1 <- coords2Polygons(coords1, ID = "A") coords2 <- cbind(c(5, 4, 2, 5), c(2, 3, 2, 2)) spy2 <- coords2Polygons(coords2, ID = "B") plot(spy1, col = "grey75") plot(spy2, col = "grey25", add = TRUE)
Compute selected evaluation metrics for binary (i.e. two-class) confusion matrices.
evalMetrics(mat, type = c("accuracy", "precision", "recall"))
evalMetrics(mat, type = c("accuracy", "precision", "recall"))
mat |
Binary confusion |
type |
Target evaluation metric as |
A single numeric
.
Florian Detsch
University of Michigan (2017) Applied Machine Learning in Python. Available online: https://www.coursera.org/learn/python-machine-learning/home/welcome.
in1 = matrix(c(96, 4, 8, 19), nc = 2L, byrow = TRUE) rownames(in1) = c("Condition Positive", "Condition Negative") colnames(in1) = c("Predicted Positive", "Predicted Negative") evalMetrics(in1) # default: "accuracy" evalMetrics(in1, "precision") evalMetrics(in1, "recall") in2 = matrix(c(26, 17, 7, 400), nc = 2, byrow = TRUE) evalMetrics(in2, "precision") evalMetrics(in2, "recall")
in1 = matrix(c(96, 4, 8, 19), nc = 2L, byrow = TRUE) rownames(in1) = c("Condition Positive", "Condition Negative") colnames(in1) = c("Predicted Positive", "Predicted Negative") evalMetrics(in1) # default: "accuracy" evalMetrics(in1, "precision") evalMetrics(in1, "recall") in2 = matrix(c(26, 17, 7, 400), nc = 2, byrow = TRUE) evalMetrics(in2, "precision") evalMetrics(in2, "recall")
Convert a spatial extent to polygons.
ext2spy(x, crs = "EPSG:4326", as_sf = TRUE)
ext2spy(x, crs = "EPSG:4326", as_sf = TRUE)
x |
A |
crs |
Coordinate reference system set via |
as_sf |
|
Depending on 'as_sf', either a c(sf, data.frame)
or SpatVector
object.
Florian Detsch
ext = terra::ext(c(25, 70, -5, 30)) ext2spy(ext) # 'sf' (default) ext2spy(ext, as_sf = FALSE) # 'Spatial*'
ext = terra::ext(c(25, 70, -5, 30)) ext2spy(ext) # 'sf' (default) ext2spy(ext, as_sf = FALSE) # 'Spatial*'
If a target file already exists, it is simply being imported into R. However,
if the specified target file does not exist, it is first created by a
user-defined function and subsequently returned, thus rendering explicit
calls to file.exists()
unnecessary.
ifMissing(ofl, fun0 = terra::rast, fun1 = terra::writeRaster, arg1, ...)
ifMissing(ofl, fun0 = terra::rast, fun1 = terra::writeRaster, arg1, ...)
ofl |
Target file name as |
fun0 |
If 'ofl' exists, |
fun1 |
If 'ofl' does not exist, |
arg1 |
Argument in 'fun1' (as |
... |
Additional arguments passed to 'fun0' and 'fun1'. |
If 'ofl' has already existed, the contents of 'ofl' derived from 'fun0'; else the output resultant from 'fun1'.
Florian Detsch
# simply import existing file logo <- system.file("ex/logo.tif", package = "terra") s <- ifMissing(logo) # create nonexisting file and import it afterwards logo2 <- file.path(tempdir(), "rlogo.tif") s2 <- ifMissing(logo2, arg1 = "filename", x = s, datatype = "INT1U") # this also works with text files and more sophisticated custom functions fun = function(x, file = "", ...) { write.csv(x, file, ...) read.csv(file) } data(iris) ofl <- file.path(tempdir(), "iris.csv") iris2 <- ifMissing(ofl, fun1 = fun, x = iris, file = ofl, quote = FALSE, row.names = FALSE)
# simply import existing file logo <- system.file("ex/logo.tif", package = "terra") s <- ifMissing(logo) # create nonexisting file and import it afterwards logo2 <- file.path(tempdir(), "rlogo.tif") s2 <- ifMissing(logo2, arg1 = "filename", x = s, datatype = "INT1U") # this also works with text files and more sophisticated custom functions fun = function(x, file = "", ...) { write.csv(x, file, ...) read.csv(file) } data(iris) ofl <- file.path(tempdir(), "iris.csv") iris2 <- ifMissing(ofl, fun1 = fun, x = iris, file = ofl, quote = FALSE, row.names = FALSE)
This function combines multiple lattice plot objects in a faceted grid.
Note that the global plot settings (e.g. 'xlim', 'ylim', ...) are taken from
the first object though the user can specify whether 'scales' should be
identical or not. This is particularly useful when looping over large amounts
of data using lapply()
or the like (see Examples).
latticeCombineGrid( trellis.list, between = list(y = 0.3, x = 0.3), as.table = TRUE, ... )
latticeCombineGrid( trellis.list, between = list(y = 0.3, x = 0.3), as.table = TRUE, ... )
trellis.list |
A |
between |
Space between panels. |
as.table |
If |
... |
Additional arguments passed to |
A single lattice plot object.
Tim Appelhans
library(lattice) p1 = xyplot(1:10 ~ 1:10) p2 = xyplot(10:1 ~ 1:10) ( p = latticeCombineGrid( list(p1, p2) ) ) if (requireNamespace("raster", quietly = TRUE)) { # load data # Use a probability map assuming high potential for city expansion is just # resulting from proximity to current urban area: prd = raster::raster(system.file("extdata/probability.rst", package = "Orcs")) # observed city growth between 1990 and 2006 obs = raster::raster(system.file("extdata/citygrowth.tif", package = "Orcs")) # masking current urban area since these pixels have no potential for change msk = raster::raster(system.file("extdata/citymask.tif", package = "Orcs")) # create data list dat <- list(prd, obs, msk) # create list of lattice plots plist <- lapply(dat, raster::spplot, scales = list(draw = TRUE)) # # draw individually # plist[[1]] # plist[[2]] # plist[[3]] # combine to grid, using c(1, 3) layout p = latticeCombineGrid(plist, layout = c(1, 3)) print(p) }
library(lattice) p1 = xyplot(1:10 ~ 1:10) p2 = xyplot(10:1 ~ 1:10) ( p = latticeCombineGrid( list(p1, p2) ) ) if (requireNamespace("raster", quietly = TRUE)) { # load data # Use a probability map assuming high potential for city expansion is just # resulting from proximity to current urban area: prd = raster::raster(system.file("extdata/probability.rst", package = "Orcs")) # observed city growth between 1990 and 2006 obs = raster::raster(system.file("extdata/citygrowth.tif", package = "Orcs")) # masking current urban area since these pixels have no potential for change msk = raster::raster(system.file("extdata/citymask.tif", package = "Orcs")) # create data list dat <- list(prd, obs, msk) # create list of lattice plots plist <- lapply(dat, raster::spplot, scales = list(draw = TRUE)) # # draw individually # plist[[1]] # plist[[2]] # plist[[3]] # combine to grid, using c(1, 3) layout p = latticeCombineGrid(plist, layout = c(1, 3)) print(p) }
This function combines multiple lattice plot objects drawing each as a
layer on top of the previous plots. Note that the global plot settings (e.g.
'xlim', 'ylim', ...) are taken from the first object. This is particularly
useful when looping over large amounts of data using lapply()
(see
Examples).
latticeCombineLayer(trellis.list, ...)
latticeCombineLayer(trellis.list, ...)
trellis.list |
A |
... |
Additional arguments passed to |
A single lattice plot object.
Tim Appelhans
library(latticeExtra) dat <- list(1:10, 10:1, 3:7, 7:3) plist <- lapply(seq(dat), function(i) { tmp <- xyplot(dat[[i]] ~ seq(dat[[i]]), type = "l", col = i) }) p <- latticeCombineLayer(plist) print(p)
library(latticeExtra) dat <- list(1:10, 10:1, 3:7, 7:3) plist <- lapply(seq(dat), function(i) { tmp <- xyplot(dat[[i]] ~ seq(dat[[i]]), type = "l", col = i) }) p <- latticeCombineLayer(plist) print(p)
This function converts between DOS and UNIX style line endings by invoking
unix2dos
(or dos2unix
) upon a text file (see also
system("unix2dos --help")
). Note that 'unix2dos' must be installed on your
local system, see Source.
lineEnding(infile, pattern = NULL, outfile = NULL, to = c("dos", "unix"), ...)
lineEnding(infile, pattern = NULL, outfile = NULL, to = c("dos", "unix"), ...)
infile |
Input filename(s). |
pattern |
See |
outfile |
Output filename. If not supplied, 'infile' will be overwritten. |
to |
Either |
... |
Additional arguments passed to |
Florian Detsch
Dos2Unix/Unix2Dos Text file format converters.
## input file infile <- paste(system.file(package = "Orcs"), "DESCRIPTION", sep = "/") ## convert to dos line endings and write to output file ofl = file.path(tempdir(), "DESCRIPTION4wd") lineEnding(infile, outfile = ofl, to = "dos")
## input file infile <- paste(system.file(package = "Orcs"), "DESCRIPTION", sep = "/") ## convert to dos line endings and write to output file ofl = file.path(tempdir(), "DESCRIPTION4wd") lineEnding(infile, outfile = ofl, to = "dos")
data.frame
from list
Create a data.frame
from a list
directly, i.e. without being required to
explicitly call rbind()
first.
list2df(x, bind = c("rows", "cols"), ...)
list2df(x, bind = c("rows", "cols"), ...)
x |
A |
bind |
Binding direction. Available options are |
... |
Additional arguments passed to |
A data.frame
object.
lst <- list(letters[1:3], letters[4:6], letters[7:9]) do.call("rbind", lst) # results in matrix list2df(lst) # results in data.frame created using rbind() list2df(lst, bind = "cols") # same for cbind()
lst <- list(letters[1:3], letters[4:6], letters[7:9]) do.call("rbind", lst) # results in matrix list2df(lst) # results in data.frame created using rbind() list2df(lst, bind = "cols") # same for cbind()
This function comprises multiple steps required to install and load a package directly from GitHub.
loadFromGit(repo = "fdetsch/Orcs", ...)
loadFromGit(repo = "fdetsch/Orcs", ...)
repo |
Repository address as |
... |
Additional arguments passed to |
Florian Detsch
## Not run: ## install 'Orcs' from GitHub loadFromGit("fdetsch/Orcs") ## End(Not run)
## Not run: ## install 'Orcs' from GitHub loadFromGit("fdetsch/Orcs") ## End(Not run)
Load and attach multiple packages at once.
loadPkgs(pkgs, ...)
loadPkgs(pkgs, ...)
pkgs |
Packages to load as |
... |
Additional arguments passed to |
Package start-up messages are automatically disabled.
Florian Detsch
loadPkgs(c("terra", "lattice"))
loadPkgs(c("terra", "lattice"))
Calculate the mean difference between two datasets as suggested by Wang et al. (2012).
## S4 method for signature 'SpatRaster' meanDifference(x, y) ## S4 method for signature 'numeric' meanDifference(x, y)
## S4 method for signature 'SpatRaster' meanDifference(x, y) ## S4 method for signature 'numeric' meanDifference(x, y)
x , y
|
Pairwise objects of class |
The mean difference between the two inputs as numeric
.
Wang et al. (2012) Impact of sensor degradation on the MODIS NDVI time series. Remote Sensing of Environment 119, 55-61, doi:10.1016/j.rse.2011.12.001.
Detsch et al. (2016) A Comparative Study of Cross-Product NDVI Dynamics in the Kilimanjaro Region - A Matter of Sensor, Degradation Calibration, and Significance. Remote Sensing 8(2), 159, doi:10.3390/rs8020159.
x <- 1:10 y <- 2:11 meanDifference(x, y)
x <- 1:10 y <- 2:11 meanDifference(x, y)
Complementing existing merge methods, e.g. terra::merge()
for Spat*
objects, which typically work with one or two inputs only, this function
accepts a list
of objects that are to be merged together.
## S4 method for signature 'list,missing' merge(x, by = 1L, all = TRUE, ...)
## S4 method for signature 'list,missing' merge(x, by = 1L, all = TRUE, ...)
x |
A |
by , all
|
See |
... |
Additional arguments passed to the underlying merge method (e.g.
arguments compatible with |
A merged object (e.g. a new Spat*
object with a larger spatial extent).
Florian Detsch
## `SpatRaster` input dms = list.files(system.file("extdata", package = "Orcs") , pattern = "ASTGTM2.*dem.tif$", full.names = TRUE) dms = lapply(dms, terra::rast) dem = merge(dms[3:4]) terra::plot(dem) ## data.frame input mrg = merge(list(iris, iris, iris) , by = c("Species", "Sepal.Length", "Petal.Width")) head(mrg)
## `SpatRaster` input dms = list.files(system.file("extdata", package = "Orcs") , pattern = "ASTGTM2.*dem.tif$", full.names = TRUE) dms = lapply(dms, terra::rast) dem = merge(dms[3:4]) terra::plot(dem) ## data.frame input mrg = merge(list(iris, iris, iris) , by = c("Species", "Sepal.Length", "Petal.Width")) head(mrg)
This function is a convenient wrapper around knitr::knit()
as it
automatically converts multiple R Markdown files (.Rmd
) located in a
specified folder (and, optionally, matching a particular pattern) to standard
Markdown (.md
).
multiKnit(path_in = ".", path_out = path_in, pattern = "*.Rmd$", ...)
multiKnit(path_in = ".", path_out = path_in, pattern = "*.Rmd$", ...)
path_in |
Input file path as |
path_out |
Output file path as |
pattern |
Passed to |
... |
Additional arguments passed to |
Output filenames as character
.
Florian Detsch
trellis
PlotThis is a wrapper function around Orcs:::calcOffsetGridText
and grid
based text drawing functions (currently including grid::grid.text()
and
grid.stext()
) that automatically adds offset text annotations to a
trellis
plot.
offsetGridText( x, y = NULL, labels, xlim = NULL, ylim = NULL, pos = NULL, stext = FALSE, offset = 0.02, ... )
offsetGridText( x, y = NULL, labels, xlim = NULL, ylim = NULL, pos = NULL, stext = FALSE, offset = 0.02, ... )
x |
A |
y |
A |
labels |
The text to be written as |
xlim , ylim
|
X and Y-axis limits ( |
pos |
Text position specifier(s) as |
stext |
|
offset |
A |
... |
Additional arguments passed to the respective grid text drawing function (depends on 'stext'). |
Florian Detsch
KiLi = terra::rast(system.file("extdata/KiLi.tif", package = "Orcs")) # kilimanjaro peaks peaks = data.frame(Peak = c("Kibo", "Mawenzi", "Shira") , Lon = c(37.359031, 37.455061, 37.210408) , Lat = c(-3.065053, -3.095436, -3.038222)) peaks = sf::st_as_sf(peaks, crs = 4326, coords = c("Lon", "Lat")) # visualization xlim_kili <- c(37.15, 37.55) ylim_kili <- c(-3.25, -2.9) if (requireNamespace("raster", quietly = TRUE)) { p = raster::spplot(KiLi[[1]], col.regions = "transparent", colorkey = FALSE, xlim = xlim_kili, ylim = ylim_kili, scales = list(draw = TRUE, y = list(rot = 90)), sp.layout = rgb2spLayout(KiLi, quantiles = c(0, 1), alpha = .8)) + latticeExtra::layer(sp.points(as(peaks, "Spatial"), cex = 1.5, pch = 20, col = "black")) print(p) grid::downViewport(lattice::trellis.vpname(name = "figure")) offsetGridText(x = sf::st_coordinates(peaks), labels = peaks$Peak, xlim = xlim_kili, ylim = ylim_kili, stext = TRUE, offset = .02, gp = grid::gpar(fontsize = 16)) }
KiLi = terra::rast(system.file("extdata/KiLi.tif", package = "Orcs")) # kilimanjaro peaks peaks = data.frame(Peak = c("Kibo", "Mawenzi", "Shira") , Lon = c(37.359031, 37.455061, 37.210408) , Lat = c(-3.065053, -3.095436, -3.038222)) peaks = sf::st_as_sf(peaks, crs = 4326, coords = c("Lon", "Lat")) # visualization xlim_kili <- c(37.15, 37.55) ylim_kili <- c(-3.25, -2.9) if (requireNamespace("raster", quietly = TRUE)) { p = raster::spplot(KiLi[[1]], col.regions = "transparent", colorkey = FALSE, xlim = xlim_kili, ylim = ylim_kili, scales = list(draw = TRUE, y = list(rot = 90)), sp.layout = rgb2spLayout(KiLi, quantiles = c(0, 1), alpha = .8)) + latticeExtra::layer(sp.points(as(peaks, "Spatial"), cex = 1.5, pch = 20, col = "black")) print(p) grid::downViewport(lattice::trellis.vpname(name = "figure")) offsetGridText(x = sf::st_coordinates(peaks), labels = peaks$Peak, xlim = xlim_kili, ylim = ylim_kili, stext = TRUE, offset = .02, gp = grid::gpar(fontsize = 16)) }
data.frame
Similar to base-R nrow()
, ncol()
and dim()
, this set of functions
let's you retrieve the number of rows and columns of a data.frame
.
nrowC(x) ncolC(x) dimC(x)
nrowC(x) ncolC(x) dimC(x)
x |
A |
dimC()
returns an integer
vector of length 2 (number of rows and
columns); nrowC()
(or ncolC()
) returns the number of rows (or columns)
as a single integer
.
nrowC()
:
ncolC()
:
dimC()
:
Florian Detsch
dat <- data.frame(a = 1:4, b = 2:5, c = 3:6) nrowC(dat)
dat <- data.frame(a = 1:4, b = 2:5, c = 3:6) nrowC(dat)
By calling the Unix terminal or Windows command prompt, this function performs parallelized 7-zip compression of selected files based on the built-in parallel package.
par7zip(outfile, nodes = 1L, ...)
par7zip(outfile, nodes = 1L, ...)
outfile |
Target file for compression as |
nodes |
Number of cores to use for parallelization as |
... |
Additional arguments passed to |
Output filename(s) as character
.
Florian Detsch
As opposed to basename()
, this function returns the pure basename of one or
multiple file names, i.e. without extension.
pureBasename(path, slash = FALSE)
pureBasename(path, slash = FALSE)
path |
File name(s) as |
slash |
A |
File name(s) without extension as character
.
Florian Detsch
ifl = tempfile(fileext = ".tif") pureBasename(ifl) pureBasename(ifl, slash = TRUE)
ifl = tempfile(fileext = ".tif") pureBasename(ifl) pureBasename(ifl, slash = TRUE)
Retrieve the p-value associated with a univariate linear regression.
pvalue(mod)
pvalue(mod)
mod |
An object of class |
A numeric
p-value.
retrieving p-values in lm on R-help mailing list.
## taken from ?lm ctl <- c(4.17,5.58,5.18,6.11,4.50,4.61,5.17,4.53,5.33,5.14) trt <- c(4.81,4.17,4.41,3.59,5.87,3.83,6.03,4.89,4.32,4.69) group <- gl(2, 10, 20, labels = c("Ctl","Trt")) weight <- c(ctl, trt) lm.D9 <- lm(weight ~ group) pvalue(lm.D9)
## taken from ?lm ctl <- c(4.17,5.58,5.18,6.11,4.50,4.61,5.17,4.53,5.33,5.14) trt <- c(4.81,4.17,4.41,3.59,5.87,3.83,6.03,4.89,4.32,4.69) group <- gl(2, 10, 20, labels = c("Ctl","Trt")) weight <- c(ctl, trt) lm.D9 <- lm(weight ~ group) pvalue(lm.D9)
Raster*
to Use with spplot()
This function takes a red-green-blue SpatRaster
or Raster*
object and
produces a list with color information that can be passed on as 'sp.layout'
to sp::spplot()
.
rgb2spLayout(x, quantiles = c(0.02, 0.98), alpha = 1)
rgb2spLayout(x, quantiles = c(0.02, 0.98), alpha = 1)
x |
A 3-layered |
quantiles |
Upper and lower quantiles used for color stretching. |
alpha |
Level of transparency. |
Tim Appelhans, Florian Detsch
b = terra::rast(system.file("ex/logo.tif", package="terra")) ## using plotRGB terra::plotRGB(b) ## convert raster to list lout = rgb2spLayout(b) lout_alph = rgb2spLayout(b, alpha = 0.5) ## create random spatial points for plotting df = data.frame( dat = rnorm(100, 2, 1) , x = rnorm(100, 50, 20) , y = rnorm(100, 50, 25) ) df = sf::st_as_sf(df, coords = c("x", "y")) ## plot spatial points with rgb background if (require(sp, quietly = TRUE)) { spplot(as(df, "Spatial"), sp.layout = lout) spplot(as(df, "Spatial"), sp.layout = lout_alph) }
b = terra::rast(system.file("ex/logo.tif", package="terra")) ## using plotRGB terra::plotRGB(b) ## convert raster to list lout = rgb2spLayout(b) lout_alph = rgb2spLayout(b, alpha = 0.5) ## create random spatial points for plotting df = data.frame( dat = rnorm(100, 2, 1) , x = rnorm(100, 50, 20) , y = rnorm(100, 50, 25) ) df = sf::st_as_sf(df, coords = c("x", "y")) ## plot spatial points with rgb background if (require(sp, quietly = TRUE)) { spplot(as(df, "Spatial"), sp.layout = lout) spplot(as(df, "Spatial"), sp.layout = lout_alph) }
data.frame
Automatically detect and remove columns from a data.frame
based on
duplicated headers.
rmDuplCols(x, keep_first = TRUE, ...)
rmDuplCols(x, keep_first = TRUE, ...)
x |
Input |
keep_first |
A |
... |
Currently not in use. |
Revised data.frame
.
Florian Detsch
## sample data set.seed(123) dat <- data.frame(matrix(rnorm(28), nc = 7)) names(dat) <- c("Col1", "Col1", "Col1", "Col2", "Col3", "Col3", "Col4") dat rmDuplCols(dat) rmDuplCols(dat, keep_first = FALSE)
## sample data set.seed(123) dat <- data.frame(matrix(rnorm(28), nc = 7)) names(dat) <- c("Col1", "Col1", "Col1", "Col2", "Col3", "Col3", "Col4") dat rmDuplCols(dat) rmDuplCols(dat, keep_first = FALSE)
Similar to setwd()
, this function sets the working directory to a
user-defined path. Rather than supplying a single 'dir' argument, however,
both an OS-sensitive path to the desired hard disk partition and, optionally,
an extension of this file path are required.
setwdOS(lin = "/media/permanent/", win = "C:/", ext = NULL)
setwdOS(lin = "/media/permanent/", win = "C:/", ext = NULL)
lin , win
|
Absolute file paths to the Linux and Windows partition as
|
ext |
Optional file path extension as |
Florian Detsch
## Not run: # desired partition setwdOS() # including file path extension setwdOS(ext = "kilimanjaro/nubiscope") ## End(Not run)
## Not run: # desired partition setwdOS() # including file path extension setwdOS(ext = "kilimanjaro/nubiscope") ## End(Not run)
Create and draw shadow text by wrapping a textual expression into a colored framing.
stextGrob( label, x = grid::unit(0.5, "npc"), y = grid::unit(0.5, "npc"), col = "white", fill = "black", r = 0.1, gp = grid::gpar(), vp = NULL, name = NULL, ... )
stextGrob( label, x = grid::unit(0.5, "npc"), y = grid::unit(0.5, "npc"), col = "white", fill = "black", r = 0.1, gp = grid::gpar(), vp = NULL, name = NULL, ... )
label |
A |
x , y
|
Horizontal and vertical text position as |
col , fill
|
Framing and fill color passed to |
r |
Blur radius of colored framing as |
name , gp , vp
|
Graphical parameters passed to |
... |
Additional arguments passed to [grid::grid.text()]. |
A text grob created by grid::gTree()
.
Baptiste Auguie, Florian Detsch
library(grid) grid.newpage() grid.rect(gp = gpar(fill = "grey")) grid.stext("test")
library(grid) grid.newpage() grid.rect(gp = gpar(fill = "grey")) grid.stext("test")
Extract substrings from a character
vector in C++.
substrC(x, pos, len)
substrC(x, pos, len)
x |
A |
pos |
The start point of the substring as |
len |
The length of the substring as |
A character
vector of the same length as 'x'.
https://cplusplus.com/reference/string/string/substr/, substr()
.
substrC("Hello, world!", pos = 1, len = 5)
substrC("Hello, world!", pos = 1, len = 5)
This is a wrapper function around convert -trim
to automatically remove any
whitespace from locally saved images. Note that 'ImageMagick' must be
installed on your local system, see Source.
trimImages(path = ".", pattern = c(".png$", ".tiff$"))
trimImages(path = ".", pattern = c(".png$", ".tiff$"))
path |
File path leading to image files as |
pattern |
A regular expression as |
A character
vector containing the names of the processed images.
Florian Detsch
Ooms J (2018) The magick package: Advanced Image-Processing in R. Available online: https://cran.r-project.org/package=magick/vignettes/intro.html.
## Not run: ## trim image of bart simpson download.file("http://pngimg.com/uploads/simpsons/simpsons_PNG93.png?i=1" , destfile = (ofl <- file.path(tempdir(), "bart.png", fsep = "\\")) , mode = "wb") par(mfrow = c(1, 2)) img = brick(ofl) plotRGB(img) jnk = trimImages(tempdir(), "bart.png") trm = brick(jnk) plotRGB(trm) dev.off() ## End(Not run)
## Not run: ## trim image of bart simpson download.file("http://pngimg.com/uploads/simpsons/simpsons_PNG93.png?i=1" , destfile = (ofl <- file.path(tempdir(), "bart.png", fsep = "\\")) , mode = "wb") par(mfrow = c(1, 2)) img = brick(ofl) plotRGB(img) jnk = trimImages(tempdir(), "bart.png") trm = brick(jnk) plotRGB(trm) dev.off() ## End(Not run)
strsplit()
Per default, strsplit()
returns a list
, with each entry holding the
vector of splits of the initial string(s). This function is a simple wrapper
that casts unlist()
upon the returned list to produce a concatenated
character
vector consisting of the single split elements.
unlistStrsplit(x, split, ...)
unlistStrsplit(x, split, ...)
x |
A |
split |
A |
... |
Additional arguments passed to |
Florian Detsch
## 1st example x <- "This is a test." unlistStrsplit(x, " ") ## 2nd example; note that 'split' defaults to 'whitespace' x2 <- "This is a 2nd test." unlistStrsplit(c(x, x2))
## 1st example x <- "This is a test." unlistStrsplit(x, " ") ## 2nd example; note that 'split' defaults to 'whitespace' x2 <- "This is a 2nd test." unlistStrsplit(c(x, x2))
Casting factor()
upon a (character
) vector usually results in
alphabetically ordered factor levels. Although this seems reasonable in most
cases, the automated ordering of factor levels is seldomly desirable in the
context of visualization, e.g. when working with tiled lattice or
ggplot2 figures. This function returns a factor
with levels ordered
according to their first appearance in the supplied vector.
unsortedFactor(x, ...)
unsortedFactor(x, ...)
x |
A |
... |
Additional arguments passed to |
Florian Detsch
mnth <- month.abb ## factor levels are being sorted fc_mnth <- factor(mnth) levels(fc_mnth) ## factor levels remain unsorted fc_mnth2 <- unsortedFactor(mnth) levels(fc_mnth2)
mnth <- month.abb ## factor levels are being sorted fc_mnth <- factor(mnth) levels(fc_mnth) ## factor levels remain unsorted fc_mnth2 <- unsortedFactor(mnth) levels(fc_mnth2)