Title: | Omnidirectional R Code Snippets |
Version: | 1.2.3 |
Maintainer: | Florian Detsch <fdetsch@web.de> |
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. |
License: | MIT + file LICENSE |
URL: | https://github.com/fdetsch/Orcs |
BugReports: | https://github.com/fdetsch/Orcs/issues |
Depends: | methods, R (≥ 2.10) |
Imports: | bookdown, grDevices, grid, knitr, lattice, latticeExtra, plotrix, Rcpp (≥ 0.11.3), remotes, sf, sp, stats, terra |
Suggests: | checkmate, raster, rmarkdown, tinytest |
LinkingTo: | Rcpp |
RoxygenNote: | 7.2.3 |
SystemRequirements: | GNU make, 7zip, unix2dos |
VignetteBuilder: | knitr |
Encoding: | UTF-8 |
NeedsCompilation: | yes |
Packaged: | 2023-01-04 09:29:20 UTC; fdetsch |
Author: | Florian Detsch [cre, aut], Tim Appelhans [aut], Baptiste Auguie [ctb], OpenStreetMap contributors [cph] |
Repository: | CRAN |
Date/Publication: | 2023-01-06 13:30:12 UTC |
Omnidirectional R Code Snippets.
Description
Omnidirectional R Code Snippets
Details
The package provides a variety of functions which I regularly use during my everyday work.
Author(s)
Florian Detsch, Tim Appelhans, Baptiste Auguie,
OpenStreetMap contributors
Maintainer: Florian Detsch fdetsch@web.de
Dimensions of a data.frame
Description
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
.
Usage
nrowC(x)
ncolC(x)
dimC(x)
Arguments
x |
A |
Value
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
.
Functions
-
nrowC()
: -
ncolC()
: -
dimC()
:
Author(s)
Florian Detsch
Examples
dat <- data.frame(a = 1:4, b = 2:5, c = 3:6)
nrowC(dat)
Assign SSH Key to Local Git Repository
Description
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.
Usage
assignSSH(user, repo)
Arguments
user |
GitHub user name as |
repo |
GitHub repository name as |
See Also
https://docs.github.com/articles/generating-an-ssh-key/.
Examples
## Not run:
## for an arbitrary git repository
assignSSH()
## for this very git repository
assignSSH(user = "fdetsch", repo = "Orcs")
## End(Not run)
Build a Book without Underscores
Description
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()
.
Usage
buildBook(output_dir = "book", ...)
Arguments
output_dir |
Output directory as |
... |
Arguments passed to |
Note
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.
Author(s)
Florian Detsch
Bump Package 'Version:' and 'Date:' in DESCRIPTION File
Description
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.
Usage
bumpVersion(
element = "patch",
pkg.repo = ".",
news = file.path(pkg.repo, "NEWS.md"),
plain_news = TRUE
)
Arguments
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 |
Author(s)
Tim Appelhans
See Also
Compare Two Density Distributions Side by Side
Description
This function will produce a plot of two density functions displayed side by side.
Usage
compareDistributions(
left,
right,
add.spread = TRUE,
print.stats = TRUE,
xlim = NULL,
ylim = NULL,
clrs = c("purple", "lightblue"),
xlab = "density",
ylab = "value",
...
)
Arguments
left |
|
right |
|
add.spread |
|
print.stats |
|
xlim , ylim |
|
clrs |
A |
xlab , ylab |
|
... |
Additional arguments passed to |
Value
A trellis
object.
Author(s)
Tim Appelhans
Examples
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)
Convert Points to SpatialLines*
Description
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()
.
Usage
## S4 method for signature 'matrix'
coords2Lines(coords, ID, data, match.ID = TRUE, ...)
## S4 method for signature 'Line'
coords2Lines(coords, ID, data, match.ID = TRUE, ...)
Arguments
coords |
|
ID |
|
data |
|
match.ID |
|
... |
Further arguments passed on to |
Value
If 'data' is missing, a SpatialLines
object; else a
SpatialLinesDataFrame
object.
Examples
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)
Convert Points to SpatialPolygons*
Description
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()
.
Usage
## 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, ...)
Arguments
coords |
|
hole |
|
ID |
|
data |
|
match.ID |
|
... |
Further arguments passed on to |
Value
If 'data' is missing, a SpatialPolygons
object; else a
SpatialPolygonsDataFrame
object.
Examples
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
Description
Compute selected evaluation metrics for binary (i.e. two-class) confusion matrices.
Usage
evalMetrics(mat, type = c("accuracy", "precision", "recall"))
Arguments
mat |
Binary confusion |
type |
Target evaluation metric as |
Value
A single numeric
.
Author(s)
Florian Detsch
References
University of Michigan (2017) Applied Machine Learning in Python. Available online: https://www.coursera.org/learn/python-machine-learning/home/welcome.
Examples
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 Spatial Extent to Polygon
Description
Convert a spatial extent to polygons.
Usage
ext2spy(x, crs = "EPSG:4326", as_sf = TRUE)
Arguments
x |
A |
crs |
Coordinate reference system set via |
as_sf |
|
Value
Depending on 'as_sf', either a c(sf, data.frame)
or SpatVector
object.
Author(s)
Florian Detsch
See Also
Examples
ext = terra::ext(c(25, 70, -5, 30))
ext2spy(ext) # 'sf' (default)
ext2spy(ext, as_sf = FALSE) # 'Spatial*'
Take Measures in Case of Nonexisting Target Files
Description
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.
Usage
ifMissing(ofl, fun0 = terra::rast, fun1 = terra::writeRaster, arg1, ...)
Arguments
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'. |
Value
If 'ofl' has already existed, the contents of 'ofl' derived from 'fun0'; else the output resultant from 'fun1'.
Author(s)
Florian Detsch
See Also
Examples
# 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)
Combine Multiple Lattice Plots in a Faceted Grid (Panels)
Description
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).
Usage
latticeCombineGrid(
trellis.list,
between = list(y = 0.3, x = 0.3),
as.table = TRUE,
...
)
Arguments
trellis.list |
A |
between |
Space between panels. |
as.table |
If |
... |
Additional arguments passed to |
Value
A single lattice plot object.
Author(s)
Tim Appelhans
See Also
Examples
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)
}
Combine Multiple Lattice Plots Layerwise
Description
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).
Usage
latticeCombineLayer(trellis.list, ...)
Arguments
trellis.list |
A |
... |
Additional arguments passed to |
Value
A single lattice plot object.
Author(s)
Tim Appelhans
See Also
Examples
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)
Convert Between DOS and UNIX Line Endings
Description
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.
Usage
lineEnding(infile, pattern = NULL, outfile = NULL, to = c("dos", "unix"), ...)
Arguments
infile |
Input filename(s). |
pattern |
See |
outfile |
Output filename. If not supplied, 'infile' will be overwritten. |
to |
Either |
... |
Additional arguments passed to |
Author(s)
Florian Detsch
Source
Dos2Unix/Unix2Dos Text file format converters.
See Also
Examples
## 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")
Create data.frame
from list
Description
Create a data.frame
from a list
directly, i.e. without being required to
explicitly call rbind()
first.
Usage
list2df(x, bind = c("rows", "cols"), ...)
Arguments
x |
A |
bind |
Binding direction. Available options are |
... |
Additional arguments passed to |
Value
A data.frame
object.
Examples
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()
Install and Load a Package from GitHub
Description
This function comprises multiple steps required to install and load a package directly from GitHub.
Usage
loadFromGit(repo = "fdetsch/Orcs", ...)
Arguments
repo |
Repository address as |
... |
Additional arguments passed to |
Author(s)
Florian Detsch
Examples
## Not run:
## install 'Orcs' from GitHub
loadFromGit("fdetsch/Orcs")
## End(Not run)
Load Multiple Packages
Description
Load and attach multiple packages at once.
Usage
loadPkgs(pkgs, ...)
Arguments
pkgs |
Packages to load as |
... |
Additional arguments passed to |
Note
Package start-up messages are automatically disabled.
Author(s)
Florian Detsch
Examples
loadPkgs(c("terra", "lattice"))
Calculate Mean Difference Between Two Datasets
Description
Calculate the mean difference between two datasets as suggested by Wang et al. (2012).
Usage
## S4 method for signature 'SpatRaster'
meanDifference(x, y)
## S4 method for signature 'numeric'
meanDifference(x, y)
Arguments
x , y |
Pairwise objects of class |
Value
The mean difference between the two inputs as numeric
.
Source
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.
Examples
x <- 1:10
y <- 2:11
meanDifference(x, y)
Merge Objects Stored in a List
Description
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.
Usage
## S4 method for signature 'list,missing'
merge(x, by = 1L, all = TRUE, ...)
Arguments
x |
A |
by , all |
See |
... |
Additional arguments passed to the underlying merge method (e.g.
arguments compatible with |
Value
A merged object (e.g. a new Spat*
object with a larger spatial extent).
Author(s)
Florian Detsch
See Also
Examples
## `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)
Convert Multiple R Markdown Files to Ordinary Markdown
Description
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
).
Usage
multiKnit(path_in = ".", path_out = path_in, pattern = "*.Rmd$", ...)
Arguments
path_in |
Input file path as |
path_out |
Output file path as |
pattern |
Passed to |
... |
Additional arguments passed to |
Value
Output filenames as character
.
Author(s)
Florian Detsch
Insert Offset Text Annotation into trellis
Plot
Description
This 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.
Usage
offsetGridText(
x,
y = NULL,
labels,
xlim = NULL,
ylim = NULL,
pos = NULL,
stext = FALSE,
offset = 0.02,
...
)
Arguments
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'). |
Author(s)
Florian Detsch
Examples
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))
}
Parallelized 7-Zip Compression
Description
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.
Usage
par7zip(outfile, nodes = 1L, ...)
Arguments
outfile |
Target file for compression as |
nodes |
Number of cores to use for parallelization as |
... |
Additional arguments passed to |
Value
Output filename(s) as character
.
Author(s)
Florian Detsch
See Also
Return File Name without Extension
Description
As opposed to basename()
, this function returns the pure basename of one or
multiple file names, i.e. without extension.
Usage
pureBasename(path, slash = FALSE)
Arguments
path |
File name(s) as |
slash |
A |
Value
File name(s) without extension as character
.
Author(s)
Florian Detsch
See Also
Examples
ifl = tempfile(fileext = ".tif")
pureBasename(ifl)
pureBasename(ifl, slash = TRUE)
Get p-Value from 'lm' Object
Description
Retrieve the p-value associated with a univariate linear regression.
Usage
pvalue(mod)
Arguments
mod |
An object of class |
Value
A numeric
p-value.
Source
retrieving p-values in lm on R-help mailing list.
See Also
Examples
## 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)
Convert an RGB Raster*
to Use with spplot()
Description
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()
.
Usage
rgb2spLayout(x, quantiles = c(0.02, 0.98), alpha = 1)
Arguments
x |
A 3-layered |
quantiles |
Upper and lower quantiles used for color stretching. |
alpha |
Level of transparency. |
Author(s)
Tim Appelhans, Florian Detsch
See Also
Examples
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)
}
Remove Duplicated Columns from data.frame
Description
Automatically detect and remove columns from a data.frame
based on
duplicated headers.
Usage
rmDuplCols(x, keep_first = TRUE, ...)
Arguments
x |
Input |
keep_first |
A |
... |
Currently not in use. |
Value
Revised data.frame
.
Author(s)
Florian Detsch
See Also
Examples
## 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)
Set Working Directory Dependent on Current OS
Description
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.
Usage
setwdOS(lin = "/media/permanent/", win = "C:/", ext = NULL)
Arguments
lin , win |
Absolute file paths to the Linux and Windows partition as
|
ext |
Optional file path extension as |
Author(s)
Florian Detsch
See Also
Examples
## Not run:
# desired partition
setwdOS()
# including file path extension
setwdOS(ext = "kilimanjaro/nubiscope")
## End(Not run)
Draw Shadow Text
Description
Create and draw shadow text by wrapping a textual expression into a colored framing.
Usage
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,
...
)
Arguments
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()]. |
Value
A text grob created by grid::gTree()
.
Author(s)
Baptiste Auguie, Florian Detsch
Examples
library(grid)
grid.newpage()
grid.rect(gp = gpar(fill = "grey"))
grid.stext("test")
Substrings of a Character Vector (C++ Style)
Description
Extract substrings from a character
vector in C++.
Usage
substrC(x, pos, len)
Arguments
x |
A |
pos |
The start point of the substring as |
len |
The length of the substring as |
Value
A character
vector of the same length as 'x'.
See Also
https://cplusplus.com/reference/string/string/substr/, substr()
.
Examples
substrC("Hello, world!", pos = 1, len = 5)
Remove Whitespace from Images
Description
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.
Usage
trimImages(path = ".", pattern = c(".png$", ".tiff$"))
Arguments
path |
File path leading to image files as |
pattern |
A regular expression as |
Value
A character
vector containing the names of the processed images.
Author(s)
Florian Detsch
Source
Ooms J (2018) The magick package: Advanced Image-Processing in R. Available online: https://cran.r-project.org/package=magick/vignettes/intro.html.
See Also
Examples
## 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)
Unlist the Outcome of strsplit()
Description
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.
Usage
unlistStrsplit(x, split, ...)
Arguments
x |
A |
split |
A |
... |
Additional arguments passed to |
Author(s)
Florian Detsch
Examples
## 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))
Factor with Unsorted Levels
Description
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.
Usage
unsortedFactor(x, ...)
Arguments
x |
A |
... |
Additional arguments passed to |
Author(s)
Florian Detsch
Examples
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)