Berryfunctions PDF
Berryfunctions PDF
R topics documented:
berryFunctions-package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
addAlpha . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
addFade . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
addRows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
almost.equal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
anhang . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1
2 R topics documented:
approx2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
around . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
betaPlot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
betaPlotComp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
between . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
checkFile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
ci . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
ciBand . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
circle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
classify . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
climateGraph . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
colPoints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
colPointsHist . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
colPointsLegend . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
combineFiles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
compareFiles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
convertUmlaut . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
createFun . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
createPres . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
dataStr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
distance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
divPal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
dupes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
exp4p . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
expReg . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
exTime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
funnelPlot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
funSource . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
funTinn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
getColumn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
getName . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
gof . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
googleLink2pdf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
groupHist . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
headtail . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
horizHist . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
insertRows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
instGit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
is.error . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
l2array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
l2df . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
legendmt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
library2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
lim0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
linLogHist . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
linLogTrans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
linReg . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
locArrow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
R topics documented: 3
locLine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
logAxis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
logHist . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
logSpaced . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
logVals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
lsc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
lsMem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
monthAxis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
monthLabs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
movAv . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
movAvLines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
mReg . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
na9 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
nameSample . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
newFilename . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
normalizePathCP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
normPlot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
openFile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
owa . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
packagePath . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
panelDim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
parallelCode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
pdfpng . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
popleaf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
pretty2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
quantileBands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
quantileMean . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
rainbow2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
removeSpace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
rescale . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
round0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128
roundedRect . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
runAxis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
seasonality . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
seqPal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134
seqR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136
showPal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
smallPlot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
smoothLines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
sortDF . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141
spiralDate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142
spiralDateAnim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144
superPos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
tableColVal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
textField . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
TFtest . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
timeAxis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153
timer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155
4 berryFunctions-package
toupper1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156
traceCall . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157
truncMessage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158
tryStack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159
unitHydrograph . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162
yearSample . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
Index 165
berryFunctions-package
Berry’s functions
Description
Collection of functions, mainly connected with graphics and hydrology.
- zoom in X11 graphics
- plot rainfall-runoff data and optimize parameters for the unit hydrograph in the linear storage cas-
cade
- write text to plots on top of colored fields in label size (halo-effect)
- draw scatterplots colored by 3rd dimension (as in image, which only deals with grids)
- draw histograms horizontally
- advancedly label date axes and logarithmic axes
- fit multiple functions (power, reciprocal, exponential, logarithmic, polynomial, rational) by re-
gression
- convert lists to data.frames
- and more...
Note
dataDWD and readDWD have moved to the package rdwd: https://github.com/brry/rdwd#
rdwd
Author(s)
Berry Boessenkool, <[email protected]>, 2011-2017
addAlpha 5
Examples
# see vignette("berryFunctions")
Description
Make existing colors semi-transparent (add alpha)
Usage
addAlpha(col, alpha = 0.3)
Arguments
col Vector of color names (colors), hexadecimal or integer that can be interpreted
by col2rgb
alpha Level of semi-transparency. between 0 (transparent) and 1 (intransparent). Can
also be a vector. DEFAULT: 0.3
Value
character vector with hexadecimal color codes.
Author(s)
Berry Boessenkool, <[email protected]>, June 2014 Based on suggestion by Mathias Seibert, Dec.
2013
See Also
addFade, rgb, colors, col2rgb
Examples
Description
Make existing colors fade away to white
Usage
addFade(col, fade = 0.3, target = "white", ...)
Arguments
col Vector of color names (colors), hexadecimal or integer that can be interpreted
by col2rgb
fade Level of fading towards target. between 0 (target) and 1 (col). Can also be a
vector. DEFAULT: 0.3
target Target color that should be faded into. DEFAULT: "white"
... Further arguments passed to colorRamp
Value
character matrix with hexadecimal color codes.
Author(s)
Berry Boessenkool, <[email protected]>, Feb 2016
See Also
addAlpha, colorRamp, colors
Examples
Description
Usage
Arguments
df Dataframe object
n Number of rows to add
values Values to be used in the new rows. DEFAULT: NA
Value
A data.frame
Author(s)
See Also
Examples
Description
Vectorized testing for near-equality with all.equal. Since elements are recycled, this will not
work for environments. You can use almost.equal directly in if expressions.
Usage
almost.equal(x, y, ...)
Arguments
x, y R objects to be compared with each other, recycled to max length
... Further arguments passed to all.equal
Value
Logical vector
Author(s)
Berry Boessenkool, <[email protected]>, Jan 2017
See Also
all.equal
Examples
# General usage:
x <- c(0.4-0.1, 0.5-0.2)
x
x==0.3 # FALSE TRUE # but mathematically, x is 0.3
all.equal(x, rep(0.3,2)) # TRUE
almost.equal(x,0.3) # TRUE TRUE # nice
# Testing vectorization
almost.equal(1:6, 3)
almost.equal(1:6, NA)
almost.equal(1:6, NULL)
anhang 9
# Testing the function for different data types (in order of coercion):
almost.equal(c(TRUE,FALSE,NA), c(TRUE,FALSE,NA)) # logical
almost.equal(as.factor(letters), as.factor(letters)) # factor
all.equal(1:6, 1:6)
almost.equal(1:6, 1:6) # integer numeric see above
0.4+0.4i - 0.1-0.1i == 0.3+0.3i
almost.equal(0.4+0.4i - 0.1-0.1i, 0.3+0.3i) # complex
all.equal(letters, tolower(LETTERS))
almost.equal(letters, tolower(LETTERS)) # character
almost.equal(Sys.Date()+1:4,Sys.Date()+1:4) # Date
x <- Sys.time()+0:2
all.equal(x,x)
almost.equal(x,x) # POSIXt
A <- list(a=1:5, b=0.5-0.2)
B <- list(a=1:5, b=0.4-0.1)
all.equal(A,B)
almost.equal(A,B) # list
Description
Open the Appendix of my R handbook found online at RclickHandbuch.wordpress.com
Usage
anhang()
Value
None, opens pdf in default viewer using system2
Author(s)
Berry Boessenkool, <[email protected]>, Jul 2016
See Also
funSource
Examples
# anhang() # excluded from cran check because of external browser opening policy
10 approx2
Description
Smart interpolation: as approx, approx2 fills NAs in a vector with linear interpolation, but unlike
approx, it can handle NAs at the ends of a vector (takes the first/last value available for those).
Also, approx2 returns a vector only.
Usage
Arguments
Details
The function fill is used to fill missing values at the ends of the vector. It could be mean or median,
for example, but must be a function that accepts na.rm=TRUE as an argument. The default (NULL)
means to use the first (or last) observation available.
Value
Author(s)
See Also
Examples
approx2(c(NA,NA, 6, 4, 8, 9, 3, 2, 1))
approx2(c(NA,NA, 6, 4, 8, 9, 3, 2, 1), fill=median) # first median, then linear
approx2(c(NA,NA, 6, 4, 8, 9, 3, 2, 1), fill=mean)
Description
View index rows of a data.frame with n surrounding rows
Usage
around(x, i, n1 = 2, n2 = n1, convert = is.logical(i))
Arguments
x Data.frame
i Index (logical or integers)
n1 Number of elements shown before each i. DEFAULT: 2
n2 Number of elements shown after each i. DEFAULT: n1
convert Use which to get the row numbers? DEFAULT: TRUE if i is boolean
Value
Nothing, calls View
Author(s)
Berry Boessenkool, <[email protected]>, Nov 2016
12 betaPlot
See Also
sortDF, View
Examples
## Not run: ## View should not be used in examples
myDF <- data.frame(A=1:30, B=cumsum(rnorm(30)))
myDF[c(5,7,23,29),1] <- NA
around(myDF, i=is.na(myDF$A))
around(myDF, i=c(11,19), n2=0)
## End(Not run)
Description
Quick and nice plot of beta density distribution based on just alpha and beta
Usage
betaPlot(shape1 = 1.5, shape2 = 5, lines = NA, fill = rgb(0, 0.3, 0.8,
0.4), cumulative = TRUE, mar = c(2, 3, 3, 3), keeppar = FALSE,
las = 1, main = paste("Beta density with\nalpha =", signif(shape1, 3),
"and beta =", signif(shape2, 3)), ylim = lim0(y), xlim = 0:1, ylab = "",
xlab = "", type = "l", lty = 1, col = par("fg"), ...)
Arguments
shape1 Alpha value as in dbeta. DEFAULT: 1.5
shape2 Beta value. DEFAULT: 5
lines Quantiles at which vertical lines should be plotted. DEFAULT: NA
fill Color passed to polygon. DEFAULT: rgb(0,0.3,0.8, 0.4)
cumulative Should cumulative density distribution be added? DEFAULT: TRUE
mar Margins for plot passed to par. DEFAULT: c(2,3,3,3)
keeppar Should margin parameters be kept instead of being restored to previous value?
DEFAULT: FALSE
las Label orientation, argument passed to plot. DEFAULT: 1
main main as in plot. DEFAULT: paste("Beta density with\nalpha =", shape1, "and
beta =", shape2)
ylim, xlim limit for the y and x axis. DEFAULT: lim0(y), 0:1
ylab, xlab labels for the axes. DEFAULT: ""
type, lty, col arguments passed to plot and lines.
... further arguments passed to plot like lwd, xaxs, cex.axis, etc.
betaPlotComp 13
Details
This function very quickly plots a beta distribution by just specifying alpha and beta.
Value
None. Used for plotting.
Author(s)
Berry Boessenkool, <[email protected]>, July 2014
See Also
betaPlotComp, normPlot, dbeta, https://cran.r-project.org/package=denstrip, https:
//cran.r-project.org/view=Distributions
Examples
betaPlot()
betaPlot(2,1)
betaPlot(0.5, 2)
Description
Visually understand the effect of the beta distribution parameters
Usage
betaPlotComp(shape1 = c(0.5, 1:4, 10, 20), shape2 = shape1,
cumulative = FALSE, cex = 0.8, las = 1, main = "", ylim = lim0(4),
mar = rep(0, 4), oma = c(2, 2, 4.5, 2), mgp = c(3, 0.7, 0),
keeppar = FALSE, textargs = NULL, ...)
14 betaPlotComp
Arguments
Value
Note
Tries to find suitable subplot for axis labels. This works only for increasing parameter values.
Author(s)
See Also
betaPlot
Examples
betaPlotComp()
betaPlotComp(oma=c(2,2,2,2), ylim=lim0(5.5), textargs=list(y=NA))
betaPlotComp(shape1=c(3,10,34), shape2=c(7,9,24))
between 15
Description
Are values within a certain interval? Basically a wrapper for x >= a & x <= b to save
repeating long x names twice.
Usage
between(x, a, b = a, incl = TRUE, aincl = incl, bincl = incl,
quiet = FALSE)
Arguments
x Numerical vector
a, b Numerical values/vectors specifying the borders of the interval. min and max are
used, so they can be a vector.
incl Logical. Include values on the borders? For x == border, TRUE will be returned.
Specify per left and right border separately with the arguments aincl and bincl.
DEFAULT: TRUE
aincl, bincl Logical. Include values on left and right border, respectively? DEFAULT: incl
quiet Logical. Suppress warning if a>b? DEFAULT: FALSE
Value
Logical (boolean) vector with TRUE/FALSE values
Author(s)
Berry Boessenkool, <[email protected]>, Aug 2017
See Also
findInterval
Examples
between(1:10, 4, 8)
between(1:10, 4:8) # range as vector
between(1:10, 8, 4) # warns about interval
Description
check whether files exist and give a useful error/warning/message
Usage
checkFile(file, warnonly = FALSE, trace = TRUE, pwd = TRUE)
Arguments
file Filename(s) as character string to be checked for existence.
warnonly Logical: Only issue a warning instead of an error with stop? DEFAULT:
FALSE
trace Logical: Add function call stack to the message? DEFAULT: TRUE
pwd Logical: Print working directory in message? DEFAULT: TRUE
Value
TRUE/FALSE, invisibly
Author(s)
Berry Boessenkool, <[email protected]>, May 2016
See Also
file.exists
Examples
is.error( checkFile("FileThatDoesntExist.txt") )
checkFile("FileThatDoesntExist.txt", warnonly=TRUE)
checkFile("FileThatDoesntExist.txt", warnonly=TRUE, trace=FALSE)
compareFiles("dummy.nonexist", "dummy2.nonexist")
checkFile("dummy.nonexist")
## End(Not run)
ci 17
Description
calculate the ends of the confidence interval around mean using t.test
Usage
Arguments
Details
Remember that CIs are used when insecurities about the inference from a sample to a general
population need quantification, not for hypothesis testing. If two confidence intervals overlap, the
difference between the two means still may be significantly different.
Value
A dataframe with the lower and upper confidence interval, as well as the level used.
Author(s)
References
For newbies: Charles Wheelan: naked statistics - stripping the dread from the data, 2013, Norton,
ISBN 978-0-393-07195-5.
For statisticians: any of your favorite statistics books should cover confidence intervals ;-)
http://en.wikipedia.org/wiki/Confidence_interval
Wolfe R, Hanley J (Jan 2002). "If we’re so different, why do we keep overlapping? When 1 plus 1
doesn’t make 2"
http://www.ecmaj.ca/content/166/1/65.full.pdf
Goldstein, H.; Healey, M.J.R. (1995). "The graphical presentation of a collection of means". Journal
of the Royal Statistical Society
http://www.jstor.org/stable/2983411
See Also
t.test
Examples
Description
Usage
Arguments
yu y values of upper confidence region boundary
yl y values of lower confidence region boundary
ym y values of middle/median/mean line. Only added if this argument is given.
DEFAULT: NULL
x x values (one ascending vector). DEFAULT: 1:length(yu)
na Method used at NA points. One of "interpolate" or "remove". DEFAULT: "in-
terpolate"
nastars If na="interpolate", should stars be drawn at places that used to be NA? DE-
FAULT: TRUE
singlepoints If na="remove", add points for places surrounded by NAs? can be a boolean
(T/F) vector of length three for upper, lower, median. Code to identify isolated
points is taken from wq::plotTs. DEFAULT: TRUE
args List of arguments passed to points for the previous two arguments. DEFAULT:
NULL
add Add to existing plot? If FALSE, plot is called before adding confidence interval.
DEFAULT: FALSE
lwd Line width of middle line. DEFAULT: 1
colm Color for median/mean line. DEFAULT: "green3"
colb Color of the confidence region band. DEFAULT: addAlpha(colm)
border polygon border. DEFAULT: NA
las LabelAxisStyle (axis labels turned upright, see par). DEFAULT: 1
ylim limits of plot. DEFAULT: range(yu,yl, finite=TRUE)
... Further arguments passed to plot - or maybe better polygon??
Value
None, currently. Used for drawing.
Author(s)
Berry Boessenkool, <[email protected]>, July 2015
See Also
quantileBands, polygon, approx2
Examples
y1 <- c(1,3,4,2,1,4,6,8,7)
y2 <- c(5,6,5,6,9,8,8,9,10)
y3 <- c(4,4,5,4,4,6,7,8,9)
ciBand(yl=y1, yu=y2, ym=y3)
20 circle
y1[6:7] <- NA
ciBand(yl=y1, yu=y2, ym=y3) # interpolation marked with stars if nastars=TRUE
ciBand(yl=y1, yu=y2, ym=y3, na="remove")
lines(y1, col=3, type="o")
lines(y2, col=3, type="o")
y2[1] <- NA
ciBand(yl=y1, yu=y2, ym=y3) # next observation carried backwards (NAs at begin)
# LOCF (last observation carried forwards if NAs at end)
# See ?approx2 for median/mean imputation in these cases
ciBand(yl=y1, yu=y2, ym=y3, na="remove")
y2[9] <- NA
ciBand(yl=y1, yu=y2, ym=y3)
ciBand(yl=y1, yu=y2, ym=y3, na="remove") # NAs at both ends
y2[1] <- 5
ciBand(yl=y1, yu=y2, ym=y3)
ciBand(yl=y1, yu=y2, ym=y3, na="remove") # NA only at end
Description
Draws a filled circle with a certain radius (in existing plot’s units) using polygon and sin
Usage
circle(x, y, r, locnum = 100, ...)
Arguments
x x coordinate of points, numeric value of length 1
y y coordinate
r radius of the circle in units of current plot
locnum number of calculated points on the circle (more means smoother but slower).
DEFAULT: 100
... further arguments passed to polygon, like col, border, lwd
classify 21
Value
Note
Author(s)
See Also
symbols, polygon
Examples
Description
Usage
Arguments
x Vector with numeric values
method Character string (partial matching is performed). Classification method (type
of binning) to compute the class breakpoints. See section Details. DEFAULT:
"linear"
breaks Specification for method, see Details. DEFAULT: NULL (different defaults for
each method)
Range Ends of intervals. DEFAULT: range(x, finite=TRUE)
sdlab Type of label and breakpoints if method=standarddeviation. 1 means -0.5 sd, 0.5 sd,
2 means -1 sd, mean, 1 sd, 3 means actual numbers for type 1, 4 means num-
bers for type 2. DEFAULT: 1
logbase base for logSpaced. Used only if not 1 and method="log". DEFAULT: 1
quiet Suppress warnings, eg for values outside Range? DEFAULT: FALSE
Details
Binning methods are explained very nicely in the link in the section References.
nbins indicates the number of classes (and thus, colors).
The default is set to equalinterval which makes sense for my original intent of plotting lake depth
(bathymetry measured at irregularly distributed points) on a linear color scale.
This is the workhorse for colPoints.
Value
list with class numbers (index) and other elements for colPoints
Author(s)
Berry Boessenkool, <[email protected]>, 2014
References
See this page on the effect of classification (binning) methods:
http://uxblog.idvsolutions.com/2011/10/telling-truth.html
climateGraph 23
See Also
colPoints
Examples
Description
Usage
Arguments
temp monthly temperature mean in degrees C
rain monthly rain sum in mm (12 values)
main location info as character string. can have \n. DEFAULT: "StatName\n52d 24’
N / 12d 58’ E\n42 m aSL"
units units used for labelling. DEFAULT: c("d C", "mm")
labs labels for x axis. DEFAULT: J,F,M,A,M,J,J,A,S,O,N,D
textprop proportion of graphic that is used for writing the values in a table to the right.
DEFAULT: 0.25
ylim limit for y axis in temp units. DEFAULT: range(temp, rain/2)
compress should rain>100 mm be compressed with adjusted labelling? (not recommended
for casual visualization!). DEFAULT: FALSE
ticklab positions for vertical labelling. DEFAULT: -8:30*10
ticklin positions for horizontal line drawing. DEFAULT: -15:60*5
box draw box along outer margins of graph? DEFAULT: TRUE
mar plot margins. DEFAULT: c(1.5,2.3,4.5,0.2)
keeppar Keep the changed graphical parameters? DEFAULT: TRUE
colrain Color for rain line and axis labels. DEFAULT: "blue"
coltemp color for temperature line and axis labels. DEFAULT: "red"
lwd line width of actual temp and rain lines. DEFAULT: 2
arghumi List of arguments for humid polygon, like density, angle. DEFAULT: NULL
(internal x,y, col, border)
argarid List of arguments for arid area. DEFAULT: NULL
argcomp List of arguments for compressed rainfall polygon. DEFAULT: NULL
arggrid List of arguments for background grid lines. DEFAULT: NULL
argtext List of arguments for text at right hand if textprop>0. DEFAULT: NULL
... further arguments passed to plot, like col.main
Value
None. Plots data and table.
Author(s)
Berry Boessenkool, <[email protected]>, June 2013
References
Heinrich Walter, Helmut Lieth: Klimadiagramm-Weltatlas. Gustav Fischer Verlag, Jena 1967
Examples:
https://www.hoelzel.at/__verlag/geojournal/archiv/klima/2006_01/lieth.gif
https://www.hoelzel.at/__verlag/geojournal/archiv/klima/istanbul/istanbul400.gif
http://www.ipb.uni-tuebingen.de/kurs/comp/1_excel2007/1_pic/2007diagramm_verbund02.
jpg
http://www.zivatar.hu/felhotar/albums/userpics/wldp.png
climateGraph 25
See Also
diagwl in package climatol
Examples
climateGraph(temp, rain)
climateGraph(temp, rain, textprop=0.6)
climateGraph(temp, rain, mar=c(2,3,4,3), textprop=0) # no table written to the right
# vertical lines instead of filled polygon:
climateGraph(temp, rain, arghumi=list(density=15, angle=90))
# fill color for arid without transparency:
climateGraph(temp, rain, argarid=list(col="gold"))
# for the Americans - axes should be different, though!:
climateGraph(temp, rain, units=c("\U{00B0}F","in"))
rain2 <- c(23, 11, 4, 2, 10, 53, 40, 15, 21, 25, 29, 22)
# fix ylim if you want to compare diagrams of different stations:
climateGraph(temp, rain2, ylim=c(-15, 50)) # works with two arid phases as well
rain <- c(54, 23, 5, 2, 5, 70, 181, 345, 265, 145, 105, 80) # with extrema
climateGraph(temp, rain) # August can be visually compared to June
climateGraph(temp, rain, compress=TRUE)
# compressing extrema enables a better view of the temperature,
# but heigths of rain cannot be visually compared anymore
climateGraph(temp, rain, compress=TRUE, ylim=c(-10, 90))
# needs ylim in linearly continued temp units
climateGraph(temp, rain, compress=TRUE, argcomp=list(density=30, col=6))
## Not run:
pdf("ClimateGraph.pdf")
climateGraph(temp, rain, main="Another Station\nlocated somewhere else")
dev.off()
openFile(ClimateGraph.pdf")
unlink("ClimateGraph.pdf")
browseURL(paste0(NOOAlink,"/station-inventories/allstations.txt"))
## End(Not run)
colPoints 27
Description
Draw colored points for 3D-data in a 2D-plane. Color is relative to third dimension, by different
classification methods. Can take 3 vectors or, as in image, 2 vectors and a matrix for z.
Adding points after smallPlot is called for the legend may be incorrect if the original function
messes with the graph margins, see the note in colPointsLegend.
Usage
colPoints(x, y, z, data, add = TRUE, col = seqPal(100), col2 = c(NA,
"grey", "black"), Range = range(z, finite = TRUE), method = "linear",
breaks = length(col), sdlab = 1, legend = TRUE, legargs = NULL,
lines = FALSE, nint = 30, xlab = gsub("\"", "",
deparse(substitute(x))), ylab = gsub("\"", "", deparse(substitute(y))),
zlab = gsub("\"", "", deparse(substitute(z))), axes = TRUE, log = "",
las = 1, bglines = NULL, pch = 16, x1 = 0.6, y1 = ifelse(horizontal,
0.88, 0.3), x2 = 0.99, y2 = 0.99, density = NULL, horizontal = TRUE,
quiet = FALSE, ...)
Arguments
x, y Vectors with coordinates of the points to be drawn
z z values belonging to coordinates. Vector or matrix with the color-defining
height values
data Optional: data.frame with the column names as given by x,y and z.
add Logical. Should the points be added to current (existing!) plot? If FALSE, a
new plot is started. DEFAULT: TRUE (It’s called colPoints, after all)
col Vector of colors to be used. DEFAULT: 100 colors from sequential palette
seqPal (color-blind safe, black/white-print safe)
col2 Color for points where z is NA, or lower / higher than Range. DEFAULT: c(NA,
1, 8)
Range Ends of color bar. If NULL, it is again the DEFAULT: range(z, finite=TRUE)
method Classification method (partial matching is performed), see classify. DEFAULT:
"linear"
breaks Specification for method, see classify. DEFAULT: different defaults for each
method
sdlab Type of label and breakpoints if method="sd", see classify. DEFAULT: 1
legend Logical. Should a colPointsLegend be drawn? DEFAULT: TRUE
legargs List. Arguments passed to colPointsLegend. DEFAULT: NULL, with some
defaults specified internally
28 colPoints
lines Logical. Should lines be drawn instead of / underneath the points? (color of each
segments is taken from starting point, last point is endpoint.) If lines=TRUE
and pch is not given, pch is set to NA. DEFAULT: FALSE
nint Numeric of length 1. Number of interpolation points between each coordinate
if lines=TRUE. nint=1 means no interpolation. Values below 10 will smooth
coordinates and might miss the original points. DEFAULT: 30
xlab, ylab, zlab
X axis label, y axis label, colPointsLegend title. DEFAULT: gsub("\"", "", deparse(substitute
axes, las Draw axes? Label Axis Style. Only used when add=FALSE. See par. DE-
FAULT: axes=TRUE, las=1 (all labels horizontal)
log Logarithmic axes with log="y", "xy" or "x". DEFAULT: ""
bglines If not NULL, passed to abline to draw background lines before adding colored
points. DEFAULT: NULL
pch Point CHaracter. See par. DEFAULT: 16
x1, x2, y1, y2 Relative coordinates [0:1] of inset plot, see smallPlot. Passed to colPointsLegend.
DEFAULT: x: 0.6-0.99, y: 0.88-0.98
density Arguments for density line in colPointsLegend, or FALSE to suppress drawing
it. DEFAULT: NULL
horizontal Logical passed to colPointsLegend. DEFAULT: TRUE
quiet Turn off warnings? DEFAULT: FALSE
... Further graphical arguments passed to plot, points and segments, eg cex, xlim
(when add=F), mgp, main, sub, asp (when add=F), etc. Note: col does not work,
as it is already another argument
Value
Invisible list of values that can be passed to colPointsLegend or colPointsHist.
Note
Rstudio scales graphics really badly, so don’t expect the right legend width out of the box if you
use Rstudio! Exporting via png("myplot.png", 600,400); colPoints(x,y,z); dev.off()
usually works much better
Author(s)
Berry Boessenkool, <[email protected]>, 2011-2014. I’d be interested in hearing what you used the
function for.
References
http://uxblog.idvsolutions.com/2011/10/telling-truth.html, http://www.theusrus.de/
blog/the-good-the-bad-22012/
See Also
classify, colPointsLegend, colPointsHist
colPoints 29
Examples
i <- c( 22, 40, 48, 60, 80, 70, 70, 63, 55, 48, 45, 40, 30, 32)
j <- c( 5, 10, 15, 20, 12, 30, 45, 40, 30, 36, 56, 33, 45, 23)
k <- c(175, 168, 163, 132, 120, 117, 110, 130, 131, 160, 105, 174, 190, 183)
# basic usage:
colPoints(i,j,k, cex=1.5, pch="+", add=FALSE)
# Add histogram:
cp <- colPoints(i,j,k, add=FALSE)
do.call(colPointsHist, cp[c("z","at","labels","bb","nbins")])
do.call(colPointsHist, owa(cp[c("z","at","labels","bb","nbins")],
list(bg=5, breaks=5)))
do.call(colPointsHist, owa(cp[c("z","at","labels","bb","nbins")],
list(mar=c(0,0,0,0), x1=0.5, x2=1, y1=0.8,
y2=0.99, yaxt="n")))
# histogram in lower panel:
layout(matrix(1:2), heights=c(8,4) )
colPoints(i,j,k, add=FALSE, y1=0.8, y2=1)
colPointsHist(z=k, x1=0.05, x2=1, y1=0, y2=0.4, mar=3, outer=TRUE)
30 colPointsHist
layout(1)
# highlight local character of points on a regular grid normally drawn with image:
z <- t(volcano) ; x <- 1:ncol(z) ; y <- 1:nrow(z)
colPoints(x,y,z, add=FALSE) # takes matrix for z
contour(x,y,t(z), add=TRUE)
# image only takes a regular matrix, but not scatterpoints...
image(x,y,t(z), col=rainbow2(100))
# add single newly measured points to image (fictional data):
mx <- c( 22, 40, 80, 45, 60, 63, 30, 70)
my <- c( 5, 33, 12, 56, 20, 40, 45, 45)
mz <- c(135, 155, 120, 105, 140, 130, 190, 110)
colPoints(mx,my,mz, cex=5, pch="*", Range=c(94, 195), col=rainbow2(100), col2=NA, legend=FALSE)
points(mx,my, cex=4)
text(mx,my,mz, adj=-0.5, font=2)
# santiago.begueria.es/2010/10/generating-spatially-correlated-random-fields-with-r
if(require(gstat)){
xyz <- gstat(formula=z~1, locations=~x+y, dummy=TRUE, beta=1,
model=vgm(psill=0.025,model="Exp",range=5), nmax=20)
xyz <- predict(xyz, newdata=data.frame(x=runif(200, 20,40),y=runif(200, 50,70)), nsim=1)
head(xyz)
colPoints(x,y,sim1, data=xyz, col=rainbow2(100), add=FALSE)
}
Description
Adds Histogram to plots created or enhanced with colPoints
Usage
colPointsHist(z, nbins = 40, colors = seqPal(nbins), bb = seqR(z,
length.out = nbins + 1), at = pretty2(z), labels = at, bg = "white",
x1 = 0, x2 = 0.4, y1 = 0, y2 = 0.3, outer = FALSE, mar = c(2, 2,
1, 0.5), mgp = c(1.8, 0.6, 0), sborder = NA, resetfocus = TRUE,
breaks = 20, freq = TRUE, col = par("fg"), border = NA, main = "",
ylab = "", xlab = "", las = 1, axes = TRUE, ...)
Arguments
z Values of third dimension used in colPoints
nbins Number of classes (thus, colors). DEFAULT: 40
colors Colors that are used for the background. DEFAULT: seqPal(nbins)
bb Borders of bins for the background. DEFAULT: seqR(z, length.out=nbins+1)
at Positions of x-axis labels. DEFAULT: pretty2(z)
labels X-axis labels themselves. DEFAULT: at
bg Background behind background and axis labels. DEFAULT: "white"
x1, x2, y1, y2 Relative coordinates [0:1] of inset plot, see smallPlot. DEFAULT: x: 0-0.3, y:
0-0.4
outer Logical: Should legend be relative to device instead of current figure? use
outer=TRUE when par(mfrow, oma) is set. DEFAULT: FALSE
mar Margins for smallPlot. DEFAULT: c(2, 2, 1, 0.5)
mgp MarGinPlacement: distance of xlab/ylab, numbers and line from plot margin, as
in par, but with different defaults. DEFAULT: c(1.8, 0.6, 0)
sborder Border around inset subplot. DEFAULT: par("fg")
resetfocus Reset focus to original plot? Specifies where further low level plot commands
are directed to. DEFAULT: TRUE
breaks Breaks as in hist, but with a different default. DEFAULT: 20
freq Plot count data in hist? (if FALSE, plot density instead). DEFAULT: TRUE
col Color of histogram bars. DEFAULT: par("fg")
border Border around each bar. DEFAULT: NA
main, ylab, xlab
Labels. DEFAULT: ""
las LabelAxisStyle. DEFAULT: 1
axes Draw axes?. DEFAULT: TRUE
... Further arguments passed to hist. NOT POSSIBLE: x, add
32 colPointsLegend
Value
invisible list of par of smallPlot, adds histogram to current plot
Author(s)
Berry Boessenkool, <[email protected]>, Aug 2014
See Also
colPointsLegend and colPoints for real life examples
Examples
z <- rnorm(50)
plot(1:10)
colPointsHist(z=z)
Description
Adds legends to plots created or enhanced with colPoints sf plots set par(mar=c(0,0,1.2,0)) but
then reset it to the values before. smallPlot will hence also reset to that, so points added after
calling colpointsLegend will be wrong, unless the margins are set BEFORE sf plot. sf:::plot.sf
alternatively uses c(2.1, 2.1, 1.2, 0) or c(1, 1, 1.2, 1).
Usage
colPointsLegend(z, Range = range(z, finite = TRUE), nbins = 100,
colors = seqPal(nbins), bb = seqR(Range, length.out = nbins + 1),
nlab = 5, at = pretty2(Range, nlab), labels = at, adj = 0.5,
x1 = 0.6, y1 = 0.88, x2 = 0.99, y2 = 0.99, outer = FALSE,
xpd = NA, mar, mgp = c(1.8, 0.6, 0), bg = par("bg"), sborder = NA,
resetfocus = TRUE, plottriangle = FALSE, triangle = 0.14,
tricol = c(8, 1), density = NULL, lines = TRUE, atminmax = FALSE,
horizontal = TRUE, labelpos = 1, titlepos = 3, title = "Legend",
las = 1, x, y, index, above, below, ...)
Arguments
z Values of third dimension used in colPoints, can be a matrix or a vector etc,
but must be numeric
Range Ends of color bar for method=equalinterval. DEFAULT: range(z, finite=TRUE)
colPointsLegend 33
nbins Number of classes (thus, colors). If colors is given, nbins is overwritten with
length(colors). DEFAULT: 100
colors Color vector. DEFAULT: seqPal from yellow (lowest) to blue (highest value in
Range)
bb Borders of bins for the legend (key). DEFAULT: seqR(Range, length.out=nbins+1)
nlab, at, labels
Number of legend labels, their positions and labels. DEFAULT: nlab=5, la-
bels=at=pretty2(Range,nlab)
adj label adjustment parallel to legend bar (only one number!). DEFAULT: 0.5
x1, x2, y1, y2 Relative coordinates [0:1] of inset plot, see smallPlot. DEFAULT: x: 0.6-0.99,
y: 0.88-0.99
outer Logical: Should legend be relative to device instead of current figure? use
outer=TRUE when par(mfrow, oma) is set. DEFAULT: FALSE
xpd Logical: should text be expanded outside of plotting region? Must be NA if
outer=TRUE. DEFAULT: NA
mar Margins for smallPlot. DEFAULT: internal calculations based on title, label-
pos and titlepos.
mgp MarGinPlacement: distance of xlab/ylab, numbers and line from plot margin, as
in par, but with different defaults. DEFAULT: c(1.8, 0.6, 0)
bg Background behind key, labels and title. DEFAULT: par("bg")
sborder Border around inset subplot. DEFAULT: NA
resetfocus Reset focus to original plot? Specifies where further low level plot commands
are directed to. DEFAULT: TRUE
plottriangle Should triangles be plotted at the end of the legend for values outside Range?
Vector of length two (for lower and upper, internally recycled). If this argument
is missing but triangle is given, this is set to TRUE. DEFAULT: FALSE
triangle Percentage of bar length at lower and upper end for triangles (can be a vector
with two different values). DEFAULT: 0.14
tricol Triangle colors for lower and upper end. DEFAULT: c(8,1)
density List of arguments passed to kernel density estimation. Can also be FALSE
to suppress KDE line drawing. DEFAULT: NULL
lines Plot black lines in the color bar at at? DEFAULT: TRUE
atminmax Should the extrema of the legend be added to at? DEFAULT: FALSE
horizontal Horizontal bar? if FALSE, a vertical bar is drawn. DEFAULT: TRUE
labelpos Position of labels relative to the bar. Possible: 1 (below), 2 (left), 3 (above), 4
(right), 5(on top of bar). DEFAULT: 1
titlepos Position of title -"-. DEFAULT: 3
title Legend title. DEFAULT: "Legend"
las LabelAxisStyle. DEFAULT: 1
x, y, index, above, below
Ignored arguments, so that you can pass the result from colPoints via do.call(colPointsLegend, cp_r
... Further arguments passed to text and strwidth, e.g. cex, srt, font, col. But
NOT adj!
34 combineFiles
Value
Note
Author(s)
See Also
Examples
z <- rnorm(50)
plot(1:10)
colPointsLegend(z=z)
colPointsLegend(z=z, titlepos=2)
colPointsLegend(z=z, horiz=FALSE) # note the different defaults
# positioning relative to plot:
colPointsLegend(z=z, x1=0.05, x2=0.3, y1=0.7,y2=0.9, title="Booh!", density=FALSE)
# Denote values outside of Range wit a triangle:
colPointsLegend(z=z, Range=c(-1,3), x1=0.2, y1=0.4, y2=0.6, triangle=0.2)
colPointsLegend(z=z, horiz=FALSE, x1=0.7, y1=0.6, plottriangle=TRUE, density=FALSE)
?colPoints # example section for actual usage
Description
Usage
Arguments
inFiles vector with names of input files, as can be read with scan. DEFAULT: dir()
outFile Character string: name of the file to be created. Passed to newFilename. DE-
FAULT: "combined_Textfiles.txt"
overwrite Logical: overwrite outFile? DEFAULT: FALSE
sep Character string: Separation between content of each file and the following.
DEFAULT: NULL, with which it uses an empty line, two lines with dashes, and
another line break.
names Should File names be included after sep? DEFAULT: TRUE
selection Index of rows that should be written. Can refer to each file separately, e.g.
substr(inFile_i,1,1)=="#". DEFAULT: all lines
progbar Should a progress bar be drawn? Useful if you combine many large files. DE-
FAULT: !quiet, i.e. TRUE
quiet Suppress message about number of files combined? DEFAULT: FALSE
... Arguments passed to scan, but not one of: file, what, blank.lines.skip, sep, quiet.
Value
Author(s)
See Also
compareFiles, and the functions used internally here, namely: paste, scan, write.
Examples
## These are skipped by rcmd check (writing to external places is not allowed)
## Not run:
cat("This is Sparta.\nKicking your face.", file="BujakashaBerry1.txt")
cat("Chuck Norris will roundhousekick you.", file="BujakashaBerry2.txt")
combineFiles(inFiles=paste0("BujakashaBerry", 1:2, ".txt"),
outFile="BujakashaBerry3.txt")
file.show("BujakashaBerry3.txt")
unlink(paste0("BujakashaBerry", 1:3, ".txt"))
## End(Not run)
36 compareFiles
Description
Usage
Arguments
Value
Author(s)
See Also
http://text-compare.com/ which I sadly only discovered after writing this function, dupes for
finding duplicate lines, combineFiles
Examples
Description
Convert German Umlaute (ae, oe, ue, ss) to ASCII. Conversion happens case sensitive for the first
three.
Usage
convertUmlaut(x)
Arguments
Value
Character strings
Author(s)
See Also
Examples
## Not run:
link <- paste0("ftp://ftp-cdc.dwd.de/pub/CDC/observations_germany/climate/",
"monthly/kl/recent/KL_Monatswerte_Beschreibung_Stationen.txt")
weatherstations <- read.fwf(link, widths=c(6,9,10,16,11,8,41,99), skip=3)
examples <- removeSpace(weatherstations[c(153, 509, 587, 2, 651, 851),7])
examples
convertUmlaut(examples) # note how lower and upper case is kept
## End(Not run)
38 createFun
Description
create a file with a complete (Roxygen) framework for a new function in a package
Usage
Arguments
fun Character string or unquoted name. Function that will be created with identical
filename.
path Path to package in development (including package name itself). Is passed to
packagePath. DEFAULT: "."
open Logical: open the file? If several instances of Rstudio are open, the last one (not
necessarily the active one) will be used. DEFAULT: TRUE
Details
Tries to open the file in the standard editor for .R files using system2
Value
Author(s)
See Also
Examples
#createFun("myNewFunction")
createPres 39
Description
Usage
Arguments
Author(s)
See Also
createFun
Examples
## Not run:
createPres("Berry_Conference")
## End(Not run)
40 distance
Description
Print the str of each dataset returned by data
Usage
dataStr(package = NULL, ...)
Arguments
package Package name. DEFAULT: NULL
... other arguments passed to data
Value
NULL. prints via message in a for loop.
Author(s)
Berry Boessenkool, <[email protected]>, November 2015, in search of good datasets for teaching
See Also
str
Examples
Description
Calculate distance between points on planar surface
Usage
distance(x, y, xref, yref, along = FALSE)
divPal 41
Arguments
x vector with x-coordinate(s) of point(s)
y ditto for y
xref single x coordinate of reference point
yref ditto for y
along Logical: Should distances be computed along vector (x,y)? If TRUE, (xref,yref)
are ignored. If both (xref,yref) are not given, along is set to TRUE.
Details
The function is quite simple: sqrt((xref - x)^2 + (yref - y)^2)
Value
vector with the distances
Author(s)
Berry Boessenkool, <[email protected]>, 2012
See Also
nndist in the package spatstat for distance to nearest neighbour
Examples
Description
Diverging color palette: brown to blue, light colors in the middle, darker at the extremes, good for
displaying values in two directions
42 divPal
Usage
divPal(n = 12, reverse = FALSE, alpha = 1, rwb = FALSE, ryb = FALSE,
gp = FALSE, br = FALSE, colors = NULL, ...)
Arguments
n Number of colors. DEFAULT: 12
reverse Reverse colors? DEFAULT: FALSE
alpha Transparency (0=transparent, 1=fully colored). DEFAULT: 1
rwb Should colors be in red-white-blue instead of brown-blue? DEFAULT: FALSE
ryb Use red-yellow-blue instead of the default, with "khaki" in the center. DE-
FAULT: FALSE
gp Use green-purple instead of the default. DEFAULT: FALSE
br Use blue-red instead of the default. DEFAULT: FALSE
colors If not NULL, a color vector used in colorRampPalette. DEFAULT: NULL
... Further arguments passed to colorRamp
Value
Character string vector with color names
Author(s)
Berry Boessenkool, <[email protected]>, Jan 2016
References
The default palette is originally in 12 shades in the IPCC Assessment Report 5 Chapter 12 Fig
12.22, http://www.ipcc.ch/report/ar5/wg1/.
The green-purple and blue-red palettes are from NYtimes (originally with 8 shades), https://
nyti.ms/2mL0o4J
See Also
showPal, seqPal, addAlpha, colorRampPalette, package RColorBrewer
Examples
Description
Number of duplicates per line of (text) file. Per default saved to file which can be loaded into excel
/ libreoffice. With conditional formatting of the first column, colors show for each line how often
it occurs in the file. A LibreOffice file is included. Note: OpenOffice does not provide color scales
based on cell values.
Usage
Arguments
Value
Either: a data.frame with line numbers of duplicate rows and the number of duplicates
Or: a file is written with the number of duplicates and the original file content.
Note
This has not been tested all that much - feedback is heavily welcome!
Author(s)
See Also
compareFiles
44 exp4p
Examples
## These are skipped by rcmd check (opening external places is not allowed):
## Not run: dupes(file)
Description
Fits an exponential function of the form a*e^(b*(x+c))+d
Usage
exp4p(x, y, digits = 2, plot = FALSE, las = 1, col = 1:6,
legarg = NULL, ...)
Arguments
x, y x and y Data
digits significant digits for rounding R^2. DEFAULT: 2
plot plot data and fitted functions? DEFAULT: FALSE
las label axis style, see par. DEFAULT: 1
col 6 colors for lines and legend texts. DEFAULT: 1:6
legarg Arguments passed to legend. DEFAULT: NULL
... further graphical parameters passed to plot
Details
This is mainly a building block for mReg
expReg 45
Value
Note
Optim can be slow! It refers to the functions rmse and rsquare, also in this package. L-BFGS-B
needs finite values. In case it doesn’t get any with the initial parameters (as in the first example
Dataset), it tries again with the parameters optimized via Nelder Mead.
Author(s)
See Also
mReg, lm
Examples
## Not run: ## Skip time consuming checks on CRAN
# exponential decline of temperature of a mug of hot chocolate
tfile <- system.file("extdata/Temp.txt", package="berryFunctions")
temp <- read.table(tfile, header=TRUE, dec=",")
head(temp)
plot(temp)
temp <- temp[-20,] # missing value - rmse would complain about it
x <- temp$Minuten
y <- temp$Temp
rm(tfile, temp)
exp4p(x,y, plot=TRUE)
# y=49*e^(-0.031*(x - 0 )) + 25 correct, judged from the model:
# Temp=T0 - Te *exp(k*t) + Te with T0=73.76, Tend=26.21, k=-0.031
# optmethod="Nelder-Mead" # y=52*e^(-0.031*(x + 3.4)) + 26 wrong
## End(Not run)
Description
uses lm; plots data if add=FALSE, draws the regression line with abline and confidence interval
with polygon and writes the formula with legend
46 expReg
Usage
expReg(x, y = NULL, data = NULL, logy = TRUE, predictnew = NULL,
interval = "confidence", plot = TRUE, digits = 2, inset = 0,
xpd = par("xpd"), pos1 = "top", pos2 = NULL, add = FALSE, pch = 16,
col = rgb(0, 0, 0, 0.5), modcol = 2, lwd = 1,
xlab = deparse(substitute(x)), ylab = deparse(substitute(y)),
main = "exponential regression", xlim = range(x), ylim = range(y), ...)
Arguments
x Numeric or formula (see examples). Vector with values of explanatory variable
y Numeric. Vector with values of dependent variable. DEFAULT: NULL
data Dataframe. If x is a formula, the according columns from data are used as x and
y. DEFAULT: NULL
logy Plot with a logarithmic y axis? Calls logAxis. DEFAULT: TRUE
predictnew Vector with values to predict outcome for. Passed as newdata to predict.lm.
DEFAULT: NULL
interval Interval for prediction. DEFAULT: "confidence"
plot Plot things at all? If FALSE, predictnew will still be returned. DEFAULT: TRUE
digits Numeric vector of length ≥ 1. Specifies number of digits a,b,r,e are rounded to
in the formula "y=a*log(x)+b, R^2, RMSE=e", respectively. If values are not
specified, they are set equal to the first. DEFAULT: 2
inset Numeric vector of length ≤ 2. inset distance(s) from the margins as a fraction
of the plot region when formula is placed by keyword. DEFAULT: 0
xpd Logical, specifying whether formula can be written only inside the plot region
(when FALSE) or inside the figure region including mar (when TRUE) or in the
entire device region including oma (when NA). DEFAULT: par("xpd")
pos1 xy.coords-acceptable position of the formula. DEFAULT: "top"
pos2 For numerical coordinates, this is the y-position. DEFAULT: NULL, as in
legend
add Logical. If TRUE, line and text are added to the existing graphic. DEFAULT:
FALSE (plots datapoints first and then the line.)
pch Point Character, see par. DEFAULT: 16
col Color of points, see par. DEFAULT: rgb(0,0,0, 0.5)
modcol color of model line. DEFAULT: 2
lwd Numeric. Linewidth, see par. DEFAULT: 1
xlab, ylab, main
Character / Expression. axis label and graph title if add=FALSE. DEFAULT:
internal from names
xlim, ylim graphic range. DEFAULT: range(x)
... Further arguments passed to plot and abline.
exTime 47
Value
predict.lm result.
Author(s)
Berry Boessenkool, <[email protected]>, Dec. 2014
See Also
lm, mReg, linReg.
Examples
Description
Time the execution of examples. Useful in package development to identify functions taking much
time.
Usage
exTime(topic = NA, package = NA, echo = FALSE, elapsed = FALSE,
imagefile = TRUE, quiet = FALSE, ...)
Arguments
topic Character string: the online help topic of which the examples should be run.
package Charstring: installed and loaded package from which all examples should be
run.
echo Show the R input when sourcing? DEFAULT: FALSE
elapsed Return *only* the third element (total elapsed time)? DEFAULT: FALSE
imagefile Reroute graphics to pdf device? Will message the tempfile location if quiet=FALSE.
DEFAULT: TRUE
48 funnelPlot
Value
Author(s)
See Also
example, system.time
Examples
exTime("plot")
exTime("yearSample", quiet=TRUE)
exTime(yearSample) # does NOT work, gives NULL and warning
exTime("yearSample", elapsed=TRUE, quiet=TRUE)
exTime("addFade", elapsed=TRUE, quiet=TRUE, run.dontrun=TRUE, run.donttest=TRUE)
## this takes quite some time if done for all functions in a package:
## Not run:
times <- exTime(package="rdwd")
as.matrix(sort(times))
system2("open", tempdir()) # to view the pdf graphics created by exTime
## End(Not run)
Description
Funnel plots for proportional data with confidence interval based on sample size. Introduced by
Stephen Few, 2013
funnelPlot 49
Usage
funnelPlot(x, n, labels = NULL, method = "classic", add = FALSE,
xlim = range(n, finite = TRUE), ylim = range(x/n * 100, finite = TRUE),
las = 1, xlab = "Sample size n", ylab = "Success rate [%]",
main = "Funnel plot for Proportions", a3 = NULL, a2 = NULL, am = NULL,
ap = NULL, at = NULL, al = NULL, ...)
Arguments
x Numeric vector with number of successes (cases).
n Numeric vector with number of trials (population).
labels Labels for points. DEFAULT: NULL
method Method to calculate Confidence interval, see "note" below. Can also be "wil-
son". DEFAULT: "classic"
add Add to existing plot instead of drawing new plot? DEFAULT: FALSE
xlim Graphical parameters, see par and plot. DEFAULT: range(n, finite=TRUE)
ylim y limit in [0:1] DEFAULT: range(x/n*100, finite=TRUE)
las DEFAULT: 1
xlab DEFAULT: "Sample size n"
ylab DEFAULT: "Success rate [%]"
main DEFAULT: "Funnel plot for Proportions"
a3 List with arguments for CI lines at 3*sd (eg: col, lty, lwd, lend, etc.). Over-
writes defaults that are defined within the function (if contentually possible).
DEFAULT: NULL
a2 Arguments for line of 2 sd. DEFAULT: NULL
am Arguments for mean line. DEFAULT: NULL
ap Arguments for the data points (cex, etc.). DEFAULT: NULL
at Arguments for text (labels of each point). DEFAULT: NULL
al Arguments for legend (text.col, bty, border, y.intersp, etc.). DEFAULT: NULL
... further arguments passed to plot only!
Value
Nothing - the function just plots
Note
the default for lty is not taken from par("lty"). This would yield "solid". Overwriting lty for one
of the three line categories then produces eg c("2", "solid", "solid"), which cannot be processed by
legend.
Wilson’s Method: algebraic approximation to the binomial distribution, very accurate, even for
very small numbers.
http://webarchive.nationalarchives.gov.uk/20170106081156/http://www.apho.org.uk/
resource/item.aspx?RID=39445 see "contains".
classic = Stephen Few’s Method = the way I knew it: sqrt( mu*(1-mu) / n )
http://www.jerrydallal.com/LHSP/psd.htm
http://commons.wikimedia.org/wiki/File:ComparisonConfidenceIntervals.png
The apho Wilson method first yielded wrong upper limits in my translation (it needs 0:1 instead of
%). Thus I added the wikipedia formula:
http://de.wikipedia.org/wiki/Konfidenzintervall_einer_unbekannten_Wahrscheinlichkeit#
Wilson-Intervall
http://en.wikipedia.org/wiki/Binomial_proportion_confidence_interval
Which other methods should I include? (That’s not the hard part anymore)
Author(s)
Berry Boessenkool, <[email protected]>, Oct 2013
References
https://www.perceptualedge.com/articles/visual_business_intelligence/variation_and_
its_discontents.pdf
http://sfew.websitetoolbox.com/post/variation-and-its-discontents-6555336?
Excellent explanation of bayesian take on proportions: http://varianceexplained.org/r/empirical_
bayes_baseball/
Examples
str(funnel)
X <- funnel$Incidents
N <- funnel$SampleSize
funSource 51
funnelPlot(X,N)
# arguments for subfunctions as text may be given this way:
funnelPlot(x=X, n=N, labels=funnel$Name, at=list(cex=0.7, col="red"))
# Labeling many points is not very clear...
funnelPlot(X,N)
sel <- c(1,4,10) # selection
text(N[sel], (X/N*100)[sel], funnel$Name[sel], cex=0.7)
# You could also pass a vector with partly empty strings to funnelPlot
funnelPlot(x=X, n=N, labels=replace(funnel$Name, c(2,3,5:9), ""), at=list(adj=0.5))
# Even though Jan is more successfull than Mary in succes rate terms, both are
# easily within random variation. Mary may just have had a bad start.
# That Mike is doing better than average is not random, but (with 95% confidence)
# actually due to him being a very good seller.
# The Wilson method yields slighty different (supposedly better) limits for small n:
funnelPlot(X,N, method="classic", al=list(title="Standard Method"))
funnelPlot(X,N, add=TRUE, method="wilson", a3=list(lty=2, col="red"),
a2=list(lty=2, col="blue"), al=list(x="bottomright", title="Wilson Method"))
Description
open source code of a function in a loaded or specified package on github.com/cran or github.com/wch/r-
source
Usage
funSource(x, character.only = is.character(x), trydirect = TRUE)
Arguments
x function name, with or without quotation marks
character.only If TRUE, look for SomeFun instead of MyFun if MyFun <- "SomeFun". DE-
FAULT: is.character(x)
trydirect If TRUE, try direct urls to files x.R and x.r. DEFAULT: TRUE
Value
links that are also opened with browseURL
Author(s)
Berry Boessenkool, <[email protected]>, Jan+Dec 2016
See Also
https://github.com/brry/rskey to add this as a keyboard shortcut
Examples
## Not run: ## browser windows should not be openend in CRAN checks
library("berryFunctions")
funSource(colPoints)
funSource("head")
funSource("require", trydirect=FALSE)
funSource(earthDist)
funSource(OSMscale::earthDist)
funSource("OSMscale::earthDist")
## End(Not run)
## End(Not run)
funTinn 53
Description
Opens function or object in external editor with an R command
Usage
funTinn(name)
Arguments
name Name of function or object to be opened with the program associated with .r-
files. In my case, the editor Tinn-R
Author(s)
Berry Boessenkool, <[email protected]>, Aug 2014
See Also
edit, http://stackoverflow.com/questions/13873528
Examples
## Not run:
## Rcmd check --as-cran doesn't allow opening external devices,
## so this example is excluded from running in the checks.
## funTinn(boxplot.default)
## End(Not run)
Description
(Try to) extract a column from a data frame with USEFUL warnings/errors.
Watch out not to define objects with the same name as x if you are using getColumn in a function!
Usage
getColumn(x, df, trace = TRUE, convnum = TRUE)
54 getColumn
Arguments
x Column name to be subsetted. The safest is to use character strings or substitute(input).
If there is an object "x" in a function environment, its value will be used as name!
(see upper2 example)
df dataframe object
trace Logical: Add function call stack to the message? DEFAULT: TRUE
convnum Logical: Convert numerical input (even if character) to Column name for that
number?
Value
Vector with values in the specified column
Author(s)
Berry Boessenkool, <[email protected]>, Sep 2016
See Also
subset, getElement, https://mran.revolutionanalytics.com/web/packages/car/vignettes/
embedding.pdf
Examples
head(stackloss)
getColumn(Air.Flow, stackloss)
getColumn("Air.Flow", stackloss)
getColumn(2, stackloss)
getColumn("2", stackloss) # works too...
# useful warnings:
getColumn(1, stackloss[0,])
getColumn(1, data.frame(AA=rep(NA,10)) )
Description
get the name of an input in nested function calls
Usage
getName(x)
56 getName
Arguments
Value
Author(s)
See Also
http://stackoverflow.com/a/26558733, substitute
Examples
# This does not work well:
upper("dummy")
upper(dummy) # works also for nonexistent objects
dummy <- 7
upper("dummy") # still stable
upper(dummy) # still stable
upper(stackloss[1:5,])
Description
Goodness of Fit measures (GOF) for two vectors.
gofNA: not exported, checks input for each of the functions:
rsquare: Coefficient of determination (R2)
rmse: Root Mean Square Error (for minimizing in optim)
nse: Nash-Sutcliffe efficiency, based on RHydro::eval.NSeff
kge: Kling-Gupta efficiency (better than NSE), based on hydroGOF::KGE, where there are many
more options
Usage
gofNA(a, b, quiet = FALSE, fun = "")
Arguments
a Numerical vector with observational data
b Simulated data (to be compared to a)
quiet Should NA-removal warnings be suppressed? This may be helpful within func-
tions. DEFAULT: FALSE
fun Character string with function name for error and warning messages
Value
Single numerical value
Note
NAs are omitted with warning.
Author(s)
Berry Boessenkool, <[email protected]>, Sept 2016
58 gof
See Also
cor, lm. http://en.wikipedia.org/wiki/R-squared, http://en.wikipedia.org/wiki/Mean_
squared_error
Examples
# R squared and RMSE --------------------------------------------------------
set.seed(123)
x <- rnorm(20)
y <- 2*x + rnorm(20)
plot(x,y)
legGOF <- function(a,b)
{
text(a,b, paste(c(" R2","RMSE"," NSE"," KGE"), collapse="\n"), adj=1.2)
text(a,b, paste(round(c(rsquare(x,y), rmse(x,y), nse(x,y), kge(x,y)),5),
collapse="\n"), adj=0)
}
legGOF(-1.5, 2) # R2 good, but does not check for bias (distance from 1:1 line)
# Input checks
is.error( rmse(1:6, 1:8) , tell=TRUE)
nse(replace(x,3,NA), y)
kge(rep(NA,20), y)
rmse(0,0, quiet=TRUE)
rsquare(1:6, tapply(chickwts$weight, chickwts$feed, mean) )
## End(Not run)
Description
restrict pdf link from a google search to actual link with text processing
Usage
googleLink2pdf(googlelink)
Arguments
googlelink Character string: A search result address
Value
Characterstring with only the basic link
Note
The function is not vectorized! If you have many links, use a loop around this function...
Author(s)
Berry Boessenkool, <[email protected]>, 2012
See Also
strsplit, gsub
60 groupHist
Examples
Description
Improvement of tapply(x, g, hist) with x and g taken from a data.frame
Usage
groupHist(df, x, g, xlab = "", ylab = "", las = 1, main = NULL,
unit = NA, ...)
Arguments
df data.frame object name
x column name of variable of interest
g column name of groups (INDEX in tapply, f in split)
xlab, ylab axis labels. DEFAULT: ""
las LabelAxisStyle, see par. DEFAULT: 1, means numbers on y-axis upright
main Main title, internal default based on d, x, unit and g. DEFAULT: NULL
unit Unit to be written into the default title. DEFAULT: NA
... further arguments passed to hist
Details
Uses split to categorize into groups.
headtail 61
Value
NULL, used for plotting
Author(s)
Berry Boessenkool, <[email protected]>, Jan 2015
See Also
hist, tapply
Examples
Description
show head and tail of an object with one command
Usage
headtail(x, n = 1, nh = n, nt = n, na = FALSE, ...)
Arguments
x Object
n Number of elements/rows/lines at begin and end of object to be returned. DE-
FAULT: 1
nh, nt Number for head and tail, respectively. DEFAULT: n
na Add NA values in between to emphasize visibly that there is something inbe-
tween the values? DEFAULT: FALSE
... Further arguments passed to head and tail
Details
Tries to find good methods of combining the two results according to codeclass(x).
Value
head result
62 horizHist
Author(s)
See Also
head
Examples
head(letters, n=3)
headtail(letters)
headtail(letters, n=3)
headtail(letters, n=3, na=TRUE)
head(letters, n=-10)
headtail(letters, n=-10, na=TRUE) # doesn't make sense for headtail
head(freeny.y, n=3)
headtail(freeny.y, n=3, na=TRUE)
head(library, n=3)
headtail(library, n=3, na=TRUE)
headtail(library, na=TRUE)
ftable(Titanic)
head(stats::ftable(Titanic), n=4)
headtail(stats::ftable(Titanic), n=4, na=TRUE)
Description
Usage
horizHist(Data, breaks = "Sturges", freq = TRUE, plot = TRUE,
col = par("bg"), border = par("fg"), las = 1, xlab = if (freq)
"Frequency" else "Density", main = paste("Histogram of",
deparse(substitute(Data))), ylim = range(HBreaks), labelat = pretty(ylim),
labels = labelat, ...)
Arguments
Data any data that hist would take.
breaks character or numerical as explained in hist. DEFAULT: "Sturges"
freq logical. if TRUE, the histogram graphic is a representation of frequencies, the
counts component of the result; if FALSE, probability densities, component den-
sity, are plotted (so that the histogram has a total area of one). DEFAULT: TRUE
plot logical. Should histogram be plotted? FALSE to get just the hpos function.
DEFAULT: TRUE
col color. DEFAULT: par("bg")
border color of borders of bars. DEFAULT: par("fg")
las integer. Label axis style. DEFAULT: 1
xlab character. Label for x-axis. DEFAULT: "absolute frequency"
main character. Title for graphic. DEFAULT: "Histogram of substitute(Data)"
ylim numerical vector of two elements. Y-axis limits. DEFAULT: range of data
labelat numerical vector. Position of Y-Axis labels. DEFAULT: pretty(ylim)
labels numerical or character. The labels themselves. DEFAULT: labelat
... further arguments passed to barplot and axis
Details
Uses barplot to draw the histogram horizontally.
Value
function to address y-coordinates
Note
Doesn’t work with breakpoints provided as a vector with different widths of the bars.
Please do not forget to use the function for vertical positioning from the current horizontal his-
togram. If It is not working correctly, you might have the function defined from some prior horizHist
result.
Author(s)
Berry Boessenkool, <[email protected]>, 2011-2012
64 insertRows
See Also
hist, barplot, axis
Examples
# Further arguments
horizHist(ExampleData, xlim=c(-8,20))
horizHist(ExampleData, ylab="the ... argument worked!", col.axis=3)
hist(ExampleData, xlim=c(-10,40)) # with xlim
horizHist(ExampleData, ylim=c(-10,40), border="red") # with ylim
hpos <- horizHist(ExampleData, breaks=20, col="orange")
axis(2, hpos(0:10), labels=FALSE, col=2) # another use of hpos()
Description
Insert (multiple) rows to a data.frame, possibly coming from another data.frame, with value and
row recycling
Usage
insertRows(df, r, new = NA)
Arguments
df data.frame
r Row number (not name!), at which the new row is to be inserted. Can be a vector
new Vector with data to be inserted, is recycled. Alternatively, a data.frame, whose
rows are put into the r locations. If it has more rows than length(r), the excess
rows are ignored. DEFAULT: NA
Value
data.frame
instGit 65
Note
Has not yet been tested with RWI (really weird input), so might not be absolutely foolproof
Author(s)
Berry Boessenkool, <[email protected]>, Oct 2015, based on code by Ari B. Friedmann (I added
the for loop, recycling, input controls and data.framification)
References
http://stackoverflow.com/questions/11561856/add-new-row-to-dataframe
See Also
addRows
Examples
Description
Quickly install a package from github without having to install devtools with all its dependencies.
Usage
instGit(pk, cleanup = TRUE, ...)
66 is.error
Arguments
pk Character string in the from of "user/package"
cleanup Remove downloaded zipfile and folder with source code. DEFAULT: TRUE
... Further arguments passed to install.packages, untested so far
Details
Works only for pure R package structure repositories from the master branch. Installs package de-
pendencies listed in ’Imports’ and ’Depends’, but ignores version requirements! Tested only on
windows 7 with R3.2.2. Note: devtools::install_github is much more extensive!
Note: drat is also much better than this quick hack. http://dirk.eddelbuettel.com/code/
drat.html, https://github.com/eddelbuettel/drat, http://eddelbuettel.github.io/drat/
DratForPackageAuthors.html Give your github users this code:
source("https://raw.githubusercontent.com/brry/berryFunctions/master/R/instGit.R")
instGit("brry/extremeStat")
library(extremeStat)
Author(s)
Berry Boessenkool, <[email protected]>, Dec 2015 + Mar/Apr 2016
See Also
funSource, install_github in each of the packages devtools, ghit, remotes
Examples
if(FALSE){
instGit("talgalili/installr")
instGit("talgalili/installr", FALSE)
instGit("hadley/readxl")
instGit("mages/googleVis") # many dependencies!
instGit("twitter/AnomalyDetection")
instGit("yihui/knitr")
instGit("ramnathv/slidify")
instGit("jrnold/ggthemes")
}
Description
Does a given expression return an error? Useful for tests where you want to make sure your function
throws an error.
l2array 67
Usage
is.error(expr, tell = FALSE, force = FALSE)
Arguments
expr Expression to be tested for returning an error
tell Logical: Should the error message be printed via message? DEFAULT: FALSE
force Logical: Should an error be returned if the expression is not an error? DE-
FAULT: FALSE
Value
TRUE/FALSE
Author(s)
Berry Boessenkool, <[email protected]>, May 2016
See Also
stop, try, inherits
Examples
is.error( log(3) )
is.error( log("a") )
is.error( log(3), tell=TRUE )
is.error( log("a"), tell=TRUE )
stopifnot( is.error( log("a") ) ) # or shorter:
is.error( log("a"), force=TRUE)
# is.error( log(3), force=TRUE)
stopifnot(is.error( is.error(log(3), force=TRUE) ))
Description
Convert a list of arrays to a single array, conserving names. If dimnames do not need to be checked,
you can also directly use
do.call(abind::abind, list(LIST, rev.along=0, use.dnns=TRUE))
Usage
l2array(x, ...)
68 l2array
Arguments
x List with arrays. The dimension of the first is target dimension.
... Further arguments passed to abind::abind
Value
array
Author(s)
Berry Boessenkool, <[email protected]>, Dec 2016
See Also
l2df, help, http://stackoverflow.com/a/4310747
Examples
# The old l2array (<1.13.14, 2017-01-06) was very slow on large lists.
# I then found abind, which is much much much faster and easier on memory!
# It now replaces the internal old actual conversion code
# l2array still checks the dimnames
LISTa2 <- do.call(abind::abind, list(LIST, rev.along=0, use.dnns=TRUE))
LISTa2
stopifnot(all(LISTa1==LISTa2))
rm(LIST, LISTa1, LISTa2)
# Selection:
A1[,,"n2"]
A1[,,1:2]
A1["row2",,] # result rotated against expectation -> transpose with t(...)
l2df 69
A1[,"A",]
# aggregation:
apply(A1, MARGIN=1:2, FUN=sum) # keep first two dimensions
apply(A1, MARGIN=c(1,3), FUN=sum) # aggregate over my_y -> row1: 6, 22, 38
A1["row1",,] # 1+5=6, 9+13=22, 17+21=38
as.vector(A1)
# l2array -----
A2 <- A1+2
A3 <- A1+4
LIST <- list(A1=A1, A2=A2, A3=A3) # list of arrays
LA <- l2array(LIST)
LA
str(LA)
LA[,,,"A2"]
LA["row2", ,"n2",]
avg <- apply(LA, MARGIN=1:3, mean)
stopifnot(all(avg==A2))
Description
Convert list with vectors of unequal length to dataframe, pad with NAs
Usage
l2df(list, byrow = TRUE)
Arguments
list List with vectors of irregular length.
byrow Transposed output? DEFAULT: TRUE
Value
data.frame
Author(s)
Berry Boessenkool, <[email protected]>, Jan 2014
References
http://stackoverflow.com/questions/5531471/combining-unequal-columns-in-r
http://stackoverflow.com/questions/15753091/convert-mixed-length-named-list-to-data-frame
http://stackoverflow.com/questions/5942760/most-efficient-list-to-data-frame-method
http://stackoverflow.com/questions/8799990/converting-given-list-into-dataframe
http://stackoverflow.com/questions/4227223/r-list-to-data-frame
See Also
l2array, sapply. If you have a LARGE list each with the same number of values, use the (much!)
faster: plyr::quickdf.
Examples
# Naming ----
# If you have a list with only data.frames, you could use the following:
eg6 <- list(AA=data.frame(BB=1:8, CC=4:-3), DD=data.frame(EE=23:24, FF=c(-3,2)))
eg6
do.call(cbind, eg6) # but this recycles the values of shorter tables!
names(eg6$DD) <- names(eg6$AA)
do.call(rbind, eg6)
# check some of the links above for more solutions...
72 legendmt
Description
Draw a legend with title spanning several lines (i.e. with line breaks). Note that this is in develop-
ment and not all inputs are correctly vectorized yet.
Usage
legendmt(x, y = NULL, legend, title, x.intersp = 1, fill = NA,
col = par("col"), border = NA, lty = NA, lwd = NA, pch = NA, ...)
Arguments
x, y, legend Arguments as in legend
title Character with linebreaks or vector of charstrings.
x.intersp, fill, col, border, lty, lwd, pch
Arguments as in legend
... Further arguments passed to legend. If vectorized, please remember to prepend
NAs or whatever.
Value
legend output
Author(s)
Berry Boessenkool, <[email protected]>, Apr 2017
See Also
legend
Examples
plot(1:10)
legend("topleft", letters[1:4], col=1:4, pch=1, title="very long title to be split up")
legendmt("topleft", letters[1:4], col=1:4, pch=1, title="very long title\nnow splat up")
# Alternative:
plot(1:10)
legend("topleft", "very long title to be split up")
legend("topleft", letters[1:4], col=1:4, pch=1, inset=c(0,0.09) )
library2 73
Description
install and load a package. If a package is not available, it is installed before being loaded
Usage
library2(name, libargs = NULL, ...)
Arguments
name Name of the package(s). Can be quoted, must not.
libargs List of arguments passed to library like lib.loc, quietly etc. DEFAULT:
NULL
... Arguments passed to install.packages like lib, repos etc.
Value
messages help instruction.
Note
Passing a vector with packages will work, but give some warnings.
Author(s)
Berry Boessenkool, <[email protected]>, 2014
See Also
install.packages, library
Examples
## Not run:
## Excluded fom CRAN checks. Package installation on server is unnecessary.
require2(ada)
library2("statmod")
## End(Not run)
74 lim0
Description
Calculates the range needed for ylim or xlim in plot, so that axis starts at zero and is extended by
4% at the other end
Usage
lim0(x, f = 1/27, curtail = TRUE)
Arguments
x Numeric. Vector with values
f Numeric. Extension factor. DEFAULT: 0.04 as in extendrange used eg. by
curve
curtail Logical. Should the range returned be trimmed by 4%? That way, plotting
doesn’t need the default par xaxs or yaxs changed. DEFAULT: TRUE
Value
Vector with two values: 0 and by 4
Author(s)
Berry Boessenkool, <[email protected]>, 6.6.2013
References
methods(plot), plot.default. Actually, I found extendrange via plot.function in curve
See Also
The extendrange() utility in package grDevices
Examples
# basic idea:
val <- c(3.2, 1.8, 4.5, 2.8, 0.1, 2.9) # just some numbers
plot(val, ylim=lim0(val) ) # you don't even have to set yaxs="i" ;-)
# "normal" plot:
plot(val)
par("usr") # -0.076 4.676
# if y-axis is not allowed to go below 0, and we're too lazy to set yaxs="i":
linLogHist 75
plot(val, ylim=lim0(val) )
round( par("usr") , digits=5) # 0.00000 4.66296
# with 0.04 extension as claimed by help page (1/27 in source code = 0.037):
plot(val, ylim=lim0(val, f=0.04) )
round( par("usr") , digits=5) # zero is not included on axis anymore
b <- -val
plot(b)
plot(b, ylim=lim0(b) ) # works with only negative values as well
Description
Draw histograms that gradually transform from a linear to a logarithmic axis (animation)
Usage
linLogHist(x, steps = 100, breaks = 20, col = "blue", las = 1,
xlab = deparse(substitute(x)), xlim = range(x, finite = TRUE),
box = TRUE, parexpr, endexpr, sleep = 0, axisargs = NULL,
axisargs2 = NULL, firstplot = TRUE, lastplot = TRUE, write_t = TRUE,
values_t = NULL, ...)
Arguments
x x values to be plotted in animation
steps Number of steps in transition. DEFAULT: 100
breaks hist breaks. DEFAULT: 20
col hist color. DEFAULT: "blue"
las par LabelAxisStyle (numbers upright). DEFAULT: 1
xlab Label for the x axis. DEFAULT: deparse(substitute(x))
xlim xlim range in non-log units. DEFAULT: range(x, finite=TRUE)
box Draw box at the end to overplot ablines crossing the box? DEFAULT: TRUE
parexpr Characterized Expression to set par, eg. parexpr='par(mar=c(2,0.5,1.5,0.5), mpg=c(1.8,1,0))'
endexpr Characterized Expression executed at the end of the plot, eg. endexpr='mtext("Probability Density"
sleep Pause time between frames, in seconds, passed to Sys.sleep. DEFAULT: 0
axisargs List of arguments passed to logVals, like base. DEFAULT: NULL
76 linLogHist
axisargs2 List of arguments passed to logAxis in the final plot. DEFAULT: NULL
firstplot plot on linear scale first? DEFAULT: TRUE
lastplot plot on logarithmic scale at the end? DEFAULT: TRUE
write_t write transformation value in lower right corner? DEFAULT: TRUE
values_t Supply vector with values for transformation (1/t). Overrides steps. If you have
a better algorithm than I do, please let me know! DEFAULT: NULL
... further arguments passed to hist, like freq, main, xlim, ylab. Excluded: x, xaxt,
possibly add
Value
Returned invisibly: transformation values used. Plotted: steps number of images.
Note
It’s best to save the plots into a pdf or wrap it within
png("Transition%03d"); linLogHist(x); dev.off()
Author(s)
Berry Boessenkool, <[email protected]>, April 2015
See Also
linLogTrans
Examples
op <- par()
linLogHist(x, steps=8, sleep=0.01) # 0.05 might be smoother
## Not run:
## Rcmd check --as-cran doesn't like to open external devices such as pdf,
## so this example is excluded from running in the checks.
pdf("LinLogTransitionAnimation.pdf")
linLogHist(x, main="Example Transition", steps=20, freq=FALSE)
dev.off()
# if you have FFmpeg installed, you can use the animation package like this:
library2(animation)
linLogTrans 77
## End(Not run)
Description
draw images that gradually transform from a linear to a logarithmic axis
Usage
linLogTrans(x, y, log = "x", steps = 100, base = 1, las = 1,
plot = TRUE, xlim = range(x, finite = TRUE), ylim = range(y, finite =
TRUE), box = TRUE, parexpr, endexpr, sleep = 0, firstplot = TRUE,
lastplot = TRUE, write_t = TRUE, values_t = NULL, pointsarg = NULL,
...)
Arguments
x x values to be plotted in animation
y Vector with corresponding y values
log Which axis is logarithmic, "x" or "y". DEFAULT: "x"
steps Number of steps (images) in transition (About 30% are taken out). DEFAULT:
100
base Base passed to logVals. DEFAULT: 1
las par LabelAxisStyle (numbers upright). DEFAULT: 1
plot Plot animations at all? False to just get the t-vector (used in linLogHist). DE-
FAULT: TRUE
xlim xlim range in non-log units. DEFAULT: range(x, finite=TRUE)
ylim ylim range in non-log units. DEFAULT: range(y, finite=TRUE)
box Draw box at the end to overplot ablines crossing the box? DEFAULT: TRUE
parexpr Characterized Expression to set par, eg. parexpr='par(mar=c(2,0.5,1.5,0.5), mpg=c(1.8,1,0))'
endexpr Characterized Expression executed at the end of the plot, eg. endexpr='mtext("Probability density"
sleep Pause time between frames, in seconds, passed to Sys.sleep. DEFAULT: 0
firstplot Plot data on linear axis as additional first image? DEFAULT: TRUE
lastplot Plot data on logarithmic axis as additional last image? DEFAULT: TRUE
write_t Write transformation value in lower right corner? DEFAULT: TRUE
78 linLogTrans
values_t Supply vector with values for transformation (1/t). Overrides steps. If you have
a better algorithm than I do, please let me know! DEFAULT: NULL for internal
calculation based on size of steps.
pointsarg List of further arguments passed to points, like pch, cex, col. DEFAULT: NULL
... Further arguments passed only to plot, like main, xlim, ylab. Excluded: x, y, las,
xaxt, type
Value
Returned invisibly: transformation values used. Plotted: steps number of images.
Note
if(steps>1000) steps <- 1000. In the unlikely case you need more steps, please let me know and I’ll
change the code.
It’s best to save the plots into a pdf (see the example) or wrap it within
png("Transition%03d"); linLogTrans(x,y); dev.off()
Author(s)
Berry Boessenkool, <[email protected]>, June 2014
References
x^(1/t) is based on the first comment on http://stackoverflow.com/questions/15994442/
besides the nice graphic properties of logtransformations, check this page for the implications on
rates of change:
http://sfew.websitetoolbox.com/post/show_single_post?pid=1282690259&postcount=4
http://sfew.websitetoolbox.com/post/show_single_post?pid=1282691799&postcount=5
See Also
logVals
Examples
## Not run:
## Rcmd check --as-cran doesn't like to open external devices such as pdf,
## so this example is excluded from running in the checks.
pdf("LinLogTransitionAnimation.pdf")
linLogTrans(x,y, main="Example Transition")
dev.off()
# if you have FFmpeg installed, you can use the animation package like this:
library2(animation)
linLogTrans 79
plot(d$x[-1], diff(d$t), type="l", ylim=c(3e-3,10), yaxt="n", log="y", main="t value growth rate")
logAxis(2) ; lines(d$x[-1], diff(d$t))
d2 <- findt(1000)
lines(d2$x[-1], diff(d2$t), col=2)
lines(2:1000, diff(linLogTrans(1,1, steps=1000, plot=F)), col=4)
d <- findt(300)
pdf("degreepoly.pdf")
for(i in 5:30)
{
plot(d, log="y", type="l", lwd=3, main=i, xlim=c(0,300), ylim=c(1,2))
modell <- lm(t ~ poly(x,i, raw=T), data=d)
lines(x2, predict(modell, data.frame(x=1:1300)), col=2)
}
dev.off() # 17 is good
cf <- coef(lm(t ~ poly(x,17, raw=T), data=d)) # these are currently used in the function
x <- 1:1000
y <- rowSums(sapply(1:18, function(i) cf[i]*x^(i-1)), na.rm=TRUE)
lines(x, y, lwd=3)
y[1] <- 1
plot(x, round(y, 3), ylim=c(1,3), xlim=c(0,500), type="l", log="")
dput(round(y, 3))
## End(Not run)
Description
uses lm; plots data if add=FALSE, draws the regression line with abline and writes the formula
with legend
Usage
linReg(x, y = NULL, data = NULL, add = FALSE, digits = 2, pch = 16,
col = 2, colband = addAlpha(col), level = 0.95,
plotrange = par("usr")[1:2], lwd = 1, xlab = deparse(substitute(x)),
ylab = deparse(substitute(y)), main = "linear regression", pos1 = "top",
pos2 = NULL, inset = 0, legargs = NULL, ...)
Arguments
x Numeric or formula (see examples). Vector with values of explanatory variable
y Numeric. Vector with values of dependent variable. DEFAULT: NULL
data Dataframe. If x is a formula, the according columns from data are used as x and
y. DEFAULT: NULL
add Logical. If TRUE, line and text are added to the existing graphic. DEFAULT:
FALSE (plots datapoints first and then the line.)
digits Numeric vector of length ≥ 1. Specifies number of digits a,b,r,e are rounded to
in the formula "y=a*x+b \n R^2=r \n RMSE=e", respectively. If values are not
specified, they are set equal to the first. DEFAULT: 2
pch Point Character of datapoints, see par. DEFAULT: 16
col Color of the regression line, see par. DEFAULT: 2
colband Color of the confidence region band. DEFAULT: addAlpha(col)
level Confidence level, see predict.lm. DEFAULT: 0.95
plotrange x range for which regression line and uncertainty band should be plotted. Is
passed to seqR and can hence be a vector. DEFAULT: par("usr")[1:2]
lwd Numeric. Linewidth, see par. DEFAULT: 1
xlab Axis label if add=FALSE. DEFAULT: deparse(substitute(x))
ylab Axis label if add=FALSE. DEFAULT: deparse(substitute(y))
main Title if add=FALSE. Changed (if not specified) for x=formula with data. DE-
FAULT: "linear regression"
linReg 81
Value
Author(s)
See Also
Examples
a <- 1:30
b <- a/2.345+rnorm(30,0,3)
linReg(a,b)
linReg(a,b, ylab="Hallo", pch=1, col=3, main="Regression by Berry")
linReg(a, b, pos1=15, pos2=0) # position of topleft corner of legend
linReg(a, b, pos1=NA, col="orange") # to suppress legend
linReg(a, b, plotrange=5:20) # only for plotting, all data points are used!
# Formula specification:
linReg(b~a)
linReg(Volume~Height, data=trees)
# For more flexibility with the datapoints, plot first, then use linReg with add=TRUE:
plot(a,b, xlim=c(-5,45))
linReg(a, b, pos1="bottomright", add=TRUE, inset=.1) # inset: distance from plot border
linReg(a, b, digits=c(7,4,3), add=TRUE, col=3, lty=2, lwd=4, level=0.8)
linReg(a, b, pos1="topleft", inset=c(-0.1, 0.3), legargs=list(xpd=TRUE), add=TRUE)
82 locArrow
Description
Draw arrow at positions in a graph located by clicking and return the code to recreate it
Usage
Arguments
Details
Value
Author(s)
See Also
Examples
plot(cumsum(rnorm(60)), type="l")
## locArrow() # only do this manually in interactive() mode
## locArrow(col="blue", lwd=3)
locLine 83
Description
Usage
Arguments
Details
Value
locator result
Author(s)
See Also
locator, abline
Examples
plot(cumsum(rnorm(60)), type="l")
## locLine() # only do this manually in interactive() mode
84 logAxis
Description
Shortcut to calling logVals, axis and abline
Usage
logAxis(side = 1, log = NULL, lcol = "grey", lty = 1, lwd = 1,
labels = NULL, allticks = FALSE, allargs = NULL, expr, las = 1, from,
to, Range, base = NA, big.mark = "'", decimal.mark = ".",
scientific = FALSE, exponent = 5, expobase1 = FALSE, allbase = 1:9,
box = TRUE, ...)
Arguments
side Which axis are to be labeled? Can be a vector within 1:4. DEFAULT: 1
log Is the axis logarithmic by plot(log="x")? internal DEFAULT: par("xlog") or
"ylog". DEFAULT: NULL
lcol Color of gridlines drawn in the graph with abline, NA to suppress. DEFAULT:
"grey"
lty, lwd Type of gridlines. DEFAULT: 1
labels Labels passed to axis. "FALSE" to suppress labeling. DEFAULT: NULL (in-
ternally, logVals$labs
allticks Place all intermediate ticklines at the axis (without labeling). DEFAULT: FALSE
allargs List of arguments passed to axis for allticks=TRUE. DEFAULT: NULL
expr Expression drawing over the ablines, like (points(x,y). Can be code within
braces.
las LabelAxisStyle for the orientation of the labels. DEFAULT: 1
from Lower exponent OR vector with data, as in logVals. DEFAULT based on
par("usr")
to High end exponent. DEFAULT: internally based on par("usr")
Range Override from and to as range.
base Bases to be used in logVals. DEFAULT: NA -> c(1,2,5) or 1, depending on
from and to.
big.mark Symbol separating thousands, eg. space, comma, dot, etc. see "format" and
"prettyNum". DEFAULT: "’"
decimal.mark Character separating comma values, see "format" and "prettyNum". DEFAULT:
"."
scientific See format. DEFAULT: FALSE
logAxis 85
exponent Starting at which exponent should logVals return an expression with expo-
nents? DEFAULT: 5
expobase1 Should "n * " be appended before 10^exp if n=1? DEFAULT: FALSE
allbase base for $all (for horizontal lines). DEFAULT: 1:9
box Draw box at the end to overplot ablines crossing the box? DEFAULT: TRUE
... Further arguments passed to axis, like lwd, col.ticks, hadj, lty, ...
Value
An invisible list with
Author(s)
Berry Boessenkool, <[email protected]>, Sept 2014
See Also
logVals, log10
Examples
plot(1:3, axes=FALSE)
logAxis(1:2, allticks=TRUE, lcol=NA)
par(mar=c(3,3,1,4))
plot(8:15) ; logAxis(4) # with exponents if they are above 5
plot(10^(1:4), ylim=10^c(4,1), type="o", log="y") # reverse axis:
86 logHist
Description
Draw histogram of values on a logarithmic scale with nice axis labels
Usage
logHist(x, logargs = NULL, main = xmain, xlab = xname, col = "tan",
add = FALSE, las = 1, ylim = NULL, freq = TRUE, quiet = FALSE, ...)
Arguments
x Vector of numerical values
logargs A list of arguments passed to logAxis. DEFAULT: NULL
main Title of graph, internally from x. DEFAULT: internal name representation
xlab X axis label. DEFAULT: internal: name of x
col Color of histogram bars
add Logical: add to existing plot?
las Integer: label axis style. DEFAULT: 1 (numbers upright)
ylim 2 Numbers: y-axis range. DEFAULT: NULL
freq Logical: counts instead of density? DEFAULT: TRUE
quiet Logical: suppress warning about non-positive values? DEFAULT: FALSE
... further arguments passed to hist like breaks, xlim=c(-1,3), ..., but not xaxt
Value
none
Author(s)
Berry Boessenkool, <[email protected]>, Feb 2016
See Also
logAxis, hist
logSpaced 87
Examples
Description
Calculates values that are in logarithmic distance from each other e.g. to produce logarithmic
interval borders.
For exact logarithmic spacing, use 10^seq(from=log10(1), to=log10(100), len=100)
Usage
logSpaced(base = 1.1708, n = 20, min = 1, max = n, plot = TRUE,
pch = 3, las = 1, ylab = "base", ...)
Arguments
base Base for calculations, can be a vector to compare several bases. DEFAULT:
1.1708
n Number of values to be calculated. DEFAULT: 30
min, max Range where n values are to be distributed, single values each. DEFAULT: 1,n
plot Should the points be plotted on a line? DEFAULT: TRUE
pch, las PointCharacter and Label Axis Style. DEFAULT: 3,1
ylab Y axis label. DEFAULT: "base"
... Further arguments passed to plot
Value
Vector or matrix, depending on base input
Note
base >1 concentrates points at low values, base<1 at high values. base does not relate to base in
log!
88 logVals
Author(s)
Berry Boessenkool, <[email protected]>, Oct 2014
See Also
classify, log
Examples
logSpaced()
logSpaced(base=c(1.1, 1.5, 2), n=6, min=5, max=10)
d <- logSpaced(seq(0.8, 1.2, 0.025), main="logarithmically spaced points")
# the default base for the default n (20) will give an approximately equal
# bin width across the range on a logarithmic scale:
d <- logSpaced()
plot(d, rep(1,20), log="x")
Description
Create nice values and labels to write at logarithmic axes
Usage
logVals(from = -7, to = 7, Range, base = 1, big.mark = "'",
decimal.mark = ".", scientific = FALSE, exponent = Inf,
expobase1 = FALSE, allbase = 1:9, ...)
Arguments
from Lower exponent OR vector with data
to High end
Range Or give from and to as range
base Bases to be used, eg. c(1,2,5). Use base=NA to switch between 1 and c(1,2,5)
depending on range. DEFAULT 1
big.mark Symbol separating thousands, eg. space, comma, dot, etc. see format and
prettyNum
decimal.mark Character separating comma values, see format and prettyNum
logVals 89
Value
A list with
vals Values for lines and label positions
labs Formatted values for labels
all Values for lines
Author(s)
Berry Boessenkool, <[email protected]>, Feb 2014
See Also
log10, logAxis, http://r.789695.n4.nabble.com/expression-exponent-labeling-td4661174.
html
Examples
# Default arguments:
lv <- logVals()
str(lv) # values, formatted labels, all 10^x values for lines
plot(1, ylim=c(1e-3, 1e4), log="y", yaxt="n", yaxs="i")
abline(h=lv$all, col=8 )
box("plot")
axis(2, lv$vals, lv$labs, las=1)
lines(seq(0.5, 1.5, len=50), 10^runif(50, -3, 4), col=2)
# Formatting labels:
logVals( )$labs
logVals(scient=TRUE )$labs
logVals(exponent=5 )$labs # expression with exponent, see logAxis
logVals(big.mark=" " )$labs
90 lsc
Description
Optimize the parameters for unit hydrograph as in the framework of the linear storage cascade. Plot
observed & simulated data
Usage
lsc(P, Q, area = 50, Qbase = Q[1], n = 2, k = 3, x = 1:length(P),
fit = 1:length(Q), plot = TRUE, main = "Precipitation and discharge",
plotsim = TRUE, returnsim = FALSE, type = c("o", "l"),
legx = "center", legy = NULL, ...)
Arguments
P Vector with precipitation values in mm in hourly spacing
Q Vector with observed discharge (runoff) in m^3/s with the same length as pre-
cipitation.
area Single numeric. Catchment area in km^2
Qbase baseflow that is added to UH-induced simulated Q, thus cutting off baseflow in
a very simple manner.
n Numeric. Initial number of storages in cascade. not necessarily integer. DE-
FAULT: 2
k Numeric. Initial storage coefficient (resistance to let water run out). High damp-
ing, slowly reacting landscape, high k. DEFAULT: 3
x Vector for the x-axis of the plot. DEFAULT: sequence along P
fit Integer vector. Indices for a subset of Q that Qsim is fitted to. DEFAULT: all of
Q
plot Logical. plot input data? DEFAULT: TRUE
main Character string. DEFAULT: "Precipitation and discharge"
plotsim Logical. add best fit to plot? DEFAULT: TRUE
returnsim Logical. Return simulated Q instead of parameters of UH? DEFAULT: FALSE
type Vector with two characters: type as in plot, repeated if only one is given. 1st
for obs, 2nd for sim. DEFAULT: c("o","l")
legx legend position. DEFAULT: "center"
legy legend position. DEFAULT: NULL
... arguments passed to optim
lsc 91
Value
Either vector with optimized n and k and the Nash-Sutcliffe Index, or simulated discharge, depend-
ing on the value of returnsim
Author(s)
Berry Boessenkool, <[email protected]>, July 2013
References
http://ponce.sdsu.edu/onlineuhcascade.php
Skript ’Abflusskonzentration’ zur Vorlesungsreihe Abwasserentsorgung I von Prof. Krebs an der
TU Dresden
http://tu-dresden.de/die_tu_dresden/fakultaeten/fakultaet_forst_geo_und_hydrowissenschaften/
fachrichtung_wasserwesen/isiw/sww/lehre/dateien/abwasserbehandlung/uebung_ws09_10/
uebung_awe_1_abflusskonzentration.pdf
http://www.uni-potsdam.de/fs-g3/file.php?fileserver=klausuren&file=%2FMaster_of_
Science%2FHydroII_Lernzettel.pdf
See Also
unitHydrograph, superPos, nse, rmse. deconvolution.uh in the package hydromad, http:
//hydromad.catchment.org
Examples
## End(Not run)
Description
Show memory size of the biggest objects in MB. Helps you find the biggest memory killers.
Usage
lsMem(n = 6, pos = 1, ...)
Arguments
n Number of Objects to be shown separately. The rest is combined into "sum rest".
DEFAULT: 6
pos Environment where ls looks for objects.
... Further arguments passed to ls
Value
Named vector with object sizes in MB (MegaBytes)
Author(s)
Berry Boessenkool, <[email protected]>, Feb 2014
References
http://stackoverflow.com/questions/1358003/tricks-to-manage-the-available-memory-in-an-r-session
See Also
object.size, ls
Examples
## Not run:
## excluded from CRAN check - I forgot why, but there's probably a good reason
lsMem()
## End(Not run)
94 monthAxis
Description
Labels date axes at sensible monthly intervals in the time domain of years to decades.
Usage
monthAxis(side = 1, time = NA, origin = "1970-01-01",
mlabels = substr(month.abb, 1, 1), yformat = "%Y", nmonths = 3,
nym_half = 3.5, nym_none = 5, mcex = 0.7, ycex = 1,
mtcl = par("tcl"), ytcl = par("tcl") - 1.7, mline = -1, yline = 0.2,
las = 1, lrange = NA, ym = TRUE, mgp = c(3, 1, 0), mt = NULL,
ml = NULL, yt = NULL, yl = NULL, quiet = FALSE, ...)
Arguments
side Which axis is to be labeled? DEFAULT: 1
time Logical indicating whether the axis is POSIXct, not Date. DEFAULT: NA,
meaning axis value >1e5
origin Origin foras.Date and as.POSIXct. DEFAULT: "1970-01-01"
mlabels Labels for the months. DEFAULT: J,F,M,A,M,J,J,A,S,O,N,D
yformat Format of year labels, see details in strptime. Use yformat=" " (with space)
to suppress year labeling. DEFAULT: "%Y"
nmonths Minimum number of months required before a year at the axis boundary is la-
beled. DEFAULT: 3
nym_half Number of years on axis above which only every second month is labeled. DE-
FAULT: 3.5
nym_none Number of years on axis above which the months are not labeled. DEFAULT: 5
mcex cex.axis (letter size) for month labels. DEFAULT: 0.7
ycex cex.axis (letter size) for year labels. DEFAULT: 1
mtcl Month tick length (negative text line height units). 0 to suppress ticks. DE-
FAULT: par("tcl") = -0.5
ytcl Year tick length (negative text line height units). 0 to suppress ticks. DEFAULT:
par("tcl")-1.7 = -2.2
mline Line of month labels. DEFAULT: -1
yline Line of year labels. DEFAULT: 0.2
las LabelAxisStyle for orientation of labels. DEFAULT: 1 (upright)
lrange Label range (two Date values). DEFAULT: NA = internally computed from
par("usr")
ym Kept for back reference. DEFAULT: TRUE
monthAxis 95
mgp MarGin Placement. Suggested not to change this, since _tcl and _line defaults
are chosen for the DEFAULT: c(3,1,0)
mt, ml, yt, yl Lists with further arguments passed to axis, like lwd, col.ticks, lwd.ticks, hadj, lty,
separately for month ticks, month labels, year ticks, year labels. DEFAULT:
NULL
quiet Suppress warning about short time axis? DEFAULT: FALSE
... Arguments passed to axis for all 4 elements.
Value
List with locations of month and year labels and ticks, each a Date vector.
Author(s)
Berry Boessenkool, <[email protected]>, Feb + Dec 2015, Oct 2017
See Also
monthLabs for the numbercrunching itself, timeAxis for shorter or longer time frames, axis.Date
with defaults that are less nice.
Examples
timePlot(1100)
monthAxis()
monthAxis(1, nmonths=6, col.axis="red") # 2013 not labeled anymore
monthAxis(side=3, nym_half=2) # if axis > 2 years, label only partially
timePlot(2e3)
monthAxis() # long time series (>nym_none) only have years labeled
monthAxis(side=3, font=2)
timePlot(900)
monthAxis(side=3, mtcl=0) # no tick lines between months
monthAxis(ycex=1.4, ytcl=2, lwd.ticks=2)
monthAxis(yline=1, col.axis=4, col=4)
monthAxis(mcex=1, col.axis="red", yformat=" ") # no years labeled
timePlot(800)
monthAxis()
monthAxis(mgp=c(2,1,0)) # the same. element 2 is relevant here
monthAxis(mgp=c(3,0,0)) # requires change in mline andy yline placement
timePlot(400)
ma <- monthAxis(lwd=3, yl=list(col.axis=3), mlabels=letters[1:12], mcex=1)
96 monthLabs
timePlot(80)
monthAxis(mlabels=month.abb, mcex=1) # short time series give a warning
timePlot(80, "2013-11-14")
monthAxis(mlabels=month.abb, mcex=1, nmonths=0, quiet=TRUE)
timePlot(800, "2015-01-01")
monthAxis()
timePlot(900, "2015-01-01", xaxs="i")
monthAxis()
timePlot(300, "2015-01-01", xaxs="i")
monthAxis() # if less than a full year is covered, the year label is centered
Description
Create dates of certain days of the month for labeling
Usage
monthLabs(startyear = 2002, stopyear = 2018, npm = 2, npy = NA)
Arguments
startyear Integer. starting year. DEFAULT: 2002
stopyear Integer. ending year. DEFAULT: 2018
npm Integer, one of 1,2,3,6 or 31. Number of labels per month. DEFAULT: 2
npm : days of the month
1 : first day of each month within the given years
2 : 1st and 15th day
3 : 1, 10, 20
6 : 1, 5, 10, 15, 20, 25. 31 : each day
npy Integer, one of 1,2,3,4 or 6. Number of labels per year at equally spaced month-
beginnings. If specified, npm is not considered at all. DEFAULT: NA
Value
Vector with Dates as returned by as.Date.
movAv 97
Note
Spacing of days is not equal, but set to certain days of the month! This was originally developed for
time series movie frames
Author(s)
Berry Boessenkool, <[email protected]>, early 2013
See Also
timeAxis for nice labeling, timeAxis for automatic determination of npm/npy, as.Date, paste
Examples
Description
Weighted moving average (running mean) with overlapping windows
Usage
movAv(dat, width = 7, weights = rep(1, width), quiet = FALSE)
Arguments
dat Vector with regularly spaced data
width Odd integer specifying window width. DEFAULT: 7
weights Vector with weights. Sum is normalized to 1. DEFAULT: rep(1,width)
quiet Logical: suppress allNA message and even width warning? DEFAULT: FALSE
Details
Width has to be odd, so there is a defined middle point of each window. Even inputs will be changed
with a warning (unless quiet=TRUE).
Weights doesn’t have to be symmetrical, but is always mapped to the middle of each window!
If there are NAs in the window, the corresponding weight is distributed evenly to the other weights.
98 movAv
Value
Vector of the same length as the original input. Padded with NAs at width/2 margin elements
Note
You can specify just one of weights or width.
Author(s)
Berry Boessenkool, <[email protected]>, ca 2012
See Also
filter, decompose, smooth, loess, rollapply (no overlapping!)
Examples
# general usage -------------------------------------------------------------
set.seed(29); a <- runif(40, 5,50)
data.frame(a, movAv(a))
# final and commencing NAs are kept, middle ones are filled:
a[c(1:10, 18:26, 32:40)] <- NA
data.frame(a, movAv(a))
# Weights:
plot(a, type="o", pch=16, las=1)
lines(movAv(a), col=2, lwd=3) # uniform weight within running window
# Triangular weights react stronger to extrema:
lines(movAv(a, weights=c(1,2,4,6,4,2,1)), col=4, lwd=3)
plot(c(Nile), type="l")
lines(movAv(Nile,20), col=4, lwd=4)
lines(movAv(Nile,21), col=3) # even widths are changed to a higher value
for(i in 1:30*2-1)
{
plot(a, type="o", pch=16, las=1, main=paste("moving average, width =", i))
lines(movAv(a, i), col=2, lwd=4)
}
# How to lie with moving averages: compare width 29 with 49 - the "trend"
movAvLines 99
Description
Add moving average lines with different window widths to a plot
Usage
movAvLines(x = 1:length(y), y, widths = c(3, 5, 7, 9, 11, 13), weights,
col = "blue", alpha = 0.3, add = TRUE, las = 1, ...)
Arguments
x x values of data. DEFAULT: 1:length(y)
y y values that are smoothed with several window widths
widths widths of movAv windows. DEFAULT: 2:7*2-1
weights weights within each window
col color passed to addAlpha. DEFAULT: "blue"
100 mReg
Author(s)
See Also
movAv, addAlpha
Examples
set.seed(42)
movAvLines(y=cumsum(rnorm(50)), add=FALSE, lwd=3)
Description
Multiple regression fitting various function types including e.g. linear, cubic, logarithmic, exponen-
tial, power, reciprocal. Quick way to find out what function type fits the data best. Plots data and
fitted functions and adds a legend with the functions (or their types=structure) sorted by R squared.
Returns the fitted functions with their parameters and R^2 values in a data.frame.
Usage
Arguments
x Vector with x coordinates or formula (like y~x), the latter is passed to model.frame
y Vector with y values. DEFAULT: NULL (to enable x to be a formula)
data data.frame in which formula is applied. DEFAULT: NULL
Poly45 Logical. Should 4th and 5th degree polynomials also be fitted? DEFAULT:
FALSE, as the formulas are very long.
exp_4 Logical. Return 4-parametric exponential distribution fits (via exp4p) in the
output table? (only best fit is plotted). exp_4par_ini has the initial values of
exponential fitting with the data relocated to first quadrant. The others are opti-
mized with the methods of optim. DEFAULT: FALSE
xf Character. x name for Formula. DEFAULT: substitute(x) before replacing zeros
in x and y
yf Ditto for y
ncolumns Number of columns in output. Set lower to avoid overcrowding the console.
DEFAULT: 9
plot Logical. plot data and fitted functions? DEFAULT: TRUE
add Logical. add lines to existing plot? DEFAULT: FALSE
nbest Integer. Number of best fitting functions to be plotted (console output table
always has all). DEFAULT: 12
R2min Numerical. Minimum Rsquared value for function type to be plotted. Sugges-
tion: 0.6 (2/3 of variation of y is explained by function of x). DEFAULT: empty
selection Integers of functions to be plotted, assigned as in list in section "note". DE-
FAULT: NULL, meaning all
digits Integer. number of significant digits used for rounding formula parameters and
R^2 displayed. DEFAULT: 2
extend Numerical. Extention of axis ranges (proportion of range). DEFAULT: 0.4
xlim Numerical vector with two values, defining the x-range of the lines to be plotted.
DEFAULT: extended range(x)
ylim Ditto for Y-axis
xlab Character. default labels for axis labeling and for formulas. DEFAULT: substi-
tute(x) before replacing zeros in x and y
ylab Ditto for y axis.
las Integer in 0:4. label axis style. See par. DEFAULT: 1
lwd Numerical of length 12. line width for lines. DEFAULT: rep(1,12)
lty Numerical of length 12. line type. DEFAULT: rep(1,12)
col Numerical of length 12. line colors. DEFAULT: NULL, means they are speci-
fied internally
pcol Color used for the data-points themselves. DEFAULT: par(’col’)
pch Integer or single character. Point CHaracter for the data points. See par. DE-
FAULT: 16
102 mReg
Details
legendform : example
full : 7.8*x + 6.31
form : a*x+b
nameform : linear a*x+b
name : linear
Value
data.frame with rounded R squared, formulas, and full R^2 and parameters for further use. Row-
names are the names (types) of function. Sorted decreasingly by R^2
warning
A well fitting function does NOT imply correct causation!
A good fit does NOT mean that you describe the behaviour of a system adequately!
Extrapolation can be DANGEROUS!
Always extrapolate to see if a function fits the expected results there as well.
Avoid overfitting: Poly45 will often yield good results (in terms of R^2), but can be way overfitted.
And outside the range of values, they act wildly.
Note
If you’re adjusting the appearance (lwd, lty, col) of single lines, set parameters in the following
order:
# 1 linear a*x + b
# 2 quadratic (parabola) a*x^2 + b*x + c
# 3 cubic a*x^3 + b*x^2 + c*x + d
# 4 Polynom 4th degree a*x^4 + b*x^3 + c*x^2 + d*x + e
# 5 Polynom 5 a*x^5 + b*x^4 + c*x^3 + d*x^2 + e*x + f
# 6 logarithmic a*log(x) + b
# 7 exponential a*e^(b*x)
# 8 power/root a*x^b
# 9 reciprocal a/x + b
# 10 rational 1 / (a*x + b)
mReg 103
Negative values are not used for regressions containing logarithms; with warning.
exp_4par was originally developed for exponential temperature decline in a cup of hot water.
Author(s)
Berry Boessenkool, <[email protected]>, Dec 2012, updated April and Aug 2013, sept 2015
References
Listed here: http://rclickhandbuch.wordpress.com/rpackages
See Also
glm, lm, optim
Examples
set.seed(12)
x <- c(runif(100,0,3), runif(200, 3, 25)) # random from uniform distribution
y <- 12.367*log10(x)+7.603+rnorm(300) # random from normal distribution
plot(x,y, xlim=c(0,40))
mReg(x,y) # warning comes from negative y-values (suppress with quiet=TRUE)
# Formula specification:
mReg(Volume~Height, data=trees)
# NA management
x[3:20] <- NA
mReg(x,y)
mReg(x,y, col=rainbow2(11))
mReg(x,y, extend=0.2) # less empty space around data points
mReg(x,y, nbest=4) # only 4 distributions plotted
mReg(x,y, legargs=list(x=7, y=8, bty="o", cex=0.6)) # Legend position as coordinates
## End(Not run)
# optim methods often yield different results, so be careful using this.
# I might insert a possibility to specify initial values for optim.
# 4 Parameters allow several combinations to yield similarly good results!
plot( 0:10, 3.5*exp(0.8*( 0:10 + 2 )) + 15 , type="l")
lines(0:10, 18*exp(0.8*( 0:10 - 2.5e-05)) - 5, col=2)
104 mReg
# only plot a subset: best n fits, minimum fit quality, or user selection
mReg(x,y, pcol=8, ncol=2, nbest=4)
mReg(x,y, pcol=8, ncol=2, R2min=0.7)
mReg(x,y, pcol=8, ncol=2, selection=c(2,5,8))
# selecting the fifth degree polynomial activates Poly45 (in the output table)
x <- temp$Minuten
y <- temp$Temp
mReg 105
## End(Not run)
Description
Returns a number of useful character strings with varying amount of spaces prepended. It can be
used as na.strings=na9() in read.table.
Usage
na9(nspace = 5, base = c(-9999, -999, -9.99, -9.999), sep = c(",", "."),
digits = 0:4, more = NULL, ...)
Arguments
nspace number of spaces prepended. DEFAULT: 5
base Numeric: basic na.string numbers
sep Separator string (comma or decimal point or both). DEFAULT: c(",",".")
digits Number(s) of zeros to be appended. DEFAULT: 0:4
more More structures added to base, like "NA", "–". digits and sep is not added to
this! DEFAULT: NULL
... Arguments passed to nothing currently
Value
Character strings
Author(s)
Berry Boessenkool, <[email protected]>, Jan 2016
See Also
paste
Examples
na9()
na9(nspace=0, sep=".")
na9(nspace=0, sep=".", more=c(NA,"-"))
nameSample 107
Description
Find the seed necessary to produce a character sequence by using sample
Usage
nameSample(name, progress = FALSE, estimatetime = nc > 4,
continue = FALSE)
Arguments
name Character string. long strings (»5) will compute a VERY long time!
progress Logical. Monitor progress by printing a dot every 10000 tries? DEFAULT:
TRUE for long names (nchar(name)>3).
estimatetime Estimate computation time? DEFAULT: nc>4
continue Continue without asking? DEFAULT: FALSE
Value
cats command into the console that can be copypasted to anyone’s R script.
Note
nameSample may take a lot of time, due to nchar^26 possibilities. That’s why it warns about strings
longer than 5 characters
Author(s)
Berry Boessenkool, <[email protected]>, April 2014
See Also
yearSample to wish a happy new year, set.seed, sample, letters
Examples
# calculation time
# on my slow laptop: # on PC
108 newFilename
system.time(nameSample("berr")) # 25 s # berry: 57 s 10 23
system.time(nameSample("berr", FALSE)) # 23 s 53 s 9 20
## End(Not run)
Description
Check if files already exist and append _1 or _2, etc to the filename if needed, thereby giving useful
messages.
Usage
newFilename(filename, ignore = FALSE, overwrite = FALSE,
tellignore = TRUE, pre = "", mid = "\n", end = "", quiet = FALSE,
ntrunc = 3)
Arguments
filename Char (vector): file name(s).
ignore Logical (vector, recycled): Ignore file? DEFAULT: FALSE
overwrite Logical (vector, recycled): overwrite file? DEFAULT: FALSE
tellignore Logical: Message about ignored files? DEFAULT: TRUE
pre, mid, end Char: strings to append after traceback / message / filenames. DEFAULT: "",
"\n ", ""
quiet Logical: Suppress messages about creating file(s)? DEFAULT: FALSE
ntrunc Integer: Number of filenames printed in messages before they get truncated with
message "(and xx more)". DEFAULT: 3
normalizePathCP 109
Value
newFilename returns the input with an added "_n" in the filename for each file that already existed.
Author(s)
Berry Boessenkool, <[email protected]>, Oct 2016 + Jan 2017
See Also
file.exists
Examples
Description
normalizePath Cross Platform: Returns absolute path even for not (yet) existing files even on
Linux. On Windows, this is the default behaviour.
Usage
normalizePathCP(path, winslash = "/", mustWork = FALSE)
Arguments
path Character vector of file paths
winslash Path separator on Windows. DEFAULT: "/" (unlike normalizePath)
mustWork Logical for normalizePath. DEFAULT: FALSE
Value
path character string(s)
110 normPlot
Author(s)
Berry Boessenkool, <[email protected]>, Nov 2017
See Also
normalizePath, newFilename
Examples
checknp("notexist.file")
checknp("../notexist.file", "notexist.file", dirname(getwd()))
checknp("notexistfolder/notexist.file")
#checknp("/home/berry/notexist.file", d="") # fails on windows
#checknp("S:/Dropbox/notexist.file",d="") # fails on linux
Description
Nice plot of normal density distribution
Usage
normPlot(mean = 0, sd = 1, width = 3, lines = TRUE, quant = TRUE,
fill = addAlpha("blue", c(2:6, 7:2)/10), cumulative = TRUE, las = 1,
main = paste("Normal density with\nmean =", signif(mean, 2), "and sd =",
signif(sd, 2)), ylim = lim0(dnorm(mean, mean, sd)), ylab = "",
xlab = "", type = "n", lty = 1, col = par("fg"), mar = c(2, 3, 3,
3), keeppar = FALSE, ...)
normPlot 111
Arguments
mean average value as in dnorm. DEFAULT: 0
sd standard deviation. DEFAULT: 1
width distance (in sd) from plot ends to mean. DEFAULT: 3
lines Should vertical lines be plotted at mean +- n*sd? DEFAULT: TRUE
quant should quantile regions be drawn with fill colors? DEFAULT: TRUE
fill color(s) passed to polygon. DEFAULT: addAlpha("blue",c(2:6,7:2)/10)
cumulative Should cumulative density distribution be added? DEFAULT: TRUE
las arguments passed to plot. DEFAULT: 1
main main as in plot. DEFAULT: paste("Normal density with\nmean =", mean, "and
sd =", sd)
ylim limit for the y axis. DEFAULT: lim0(y)
ylab, xlab labels for the axes. DEFAULT: ""
type, lty, col arguments passed to lines. type="l" to add pdf line
mar margins for plot passed to par. DEFAULT: c(2,3,3,3)
keeppar should margin parameters be kept instead of being restored to previous value?
DEFAULT: FALSE
... further arguments passed to plot like lwd, xaxs, cex.axis, etc.
Details
This function finds some nice defaults for very quickly plotting a normal distribution by just speci-
fying mean and sd.
Value
None. Used for plotting.
Author(s)
Berry Boessenkool, <[email protected]>, July 2014
See Also
betaPlot, dnorm, https://cran.r-project.org/package=denstrip, https://cran.r-project.
org/view=Distributions
Examples
normPlot()
normPlot(81.7, 11.45)
normPlot(180, 11, quant=FALSE, width=2)
112 openFile
Description
open a file using system2 with command based on operating system. Tries to open the file with the
program associated with its file extension.
Usage
openFile(file, ...)
Arguments
file Filename to be opened, as character string.
... Further arguments passed to system2
Value
Result of try(system2, ...), invisibly
Author(s)
Berry Boessenkool, <[email protected]>, Aug 2017
References
https://askubuntu.com/questions/15354, https://apple.stackexchange.com/questions/
212583
See Also
system2, checkFile
Examples
## Not run: # excluded from CRAN checks, file opening not wanted
openFile("README.md")
openFile("Tests.R")
openFile("dummydummydoesntexist.R")
openFile(tempdir())
## End(Not run)
#' # To open folders with system2:
# "nautilus" on linux ubuntu
# "open" or "dolphin" on mac
# "explorer" or "start" on windows
owa 113
Description
Second ellipsis (three dots) passed to particular functions, combining default and user-specified ar-
gument lists.
owa can be used in functions that pass argument lists separately to several functions. Internal de-
faults can be set per function (eg. one list for plot and one for legend).
You can specify which defaults can be overwritten and which should be left unchanged. See the
example section on how to implement this.
Usage
Arguments
Value
Author(s)
References
http://stackoverflow.com/questions/3057341
http://stackoverflow.com/questions/5890576
http://stackoverflow.com/questions/4124900
http://stackoverflow.com/questions/16774946
114 packagePath
Examples
# The motivation behind owa:
testfun <- function(...) {plot(7:11, ...) ; legend("top", "some text", ...)}
testfun()
is.error( testfun(type="o") , tell=TRUE)
# Error: legend doesn't have the argument 'type'!
testfun()
testfun(type="l", col="blue")
testfun(type="o", legargs=list(col="blue", pch=16, lty=3) )
# color in legargs is ignored, as it is defined as unchangeable
#----------------------------------------------------------------------------
Description
Base path of package (with DESCRIPTION file), per default at current getwd. Derived from dev-
tools::package_file
Usage
packagePath(path = ".", warnonly = FALSE)
panelDim 115
Arguments
path Path to (or below) package directory. DEFAULT: "."
warnonly Logical: if no part of the path is a package, give a warning and return the original
input instead of stopping with an error. DEFAULT: FALSE
Value
Path character string
Author(s)
Berry Boessenkool, <[email protected]>, Sep 2017
See Also
getwd
Examples
# packagePath() # may fail on cran checks
Description
Returns the optimum where deviation from ncol=nrow and number of panels left empty have a
minimum sum.
Usage
panelDim(n, weight = c(1, 1), maxempty = round(n/4), landscape = FALSE,
all = FALSE, plot = FALSE, mfcol = FALSE)
Arguments
n Number of panels to be arranged
weight Weights to avoid empty panels and discrepancy between ncol and nrow, respec-
tively. DEFAULT: c(1,1)
maxempty Maximum number of panels that are allowed to be left empty. If maxempty=0,
no panel is left blank, so 11 plots would be beneath each other instead of in a
4x3 grid with one panel left blank. DEFAULT: round(n/4)
landscape Use landscape orientation instead of portrait? DEFAULT: FALSE
all Show all reasonable possibilities in a data.frame? DEFAULT: FALSE
plot Show the panel layout result? (the 4 best options are compared if all=TRUE).
DEFAULT: FALSE
mfcol use mfcol instead of mfrow. DEFAULT: FALSE
116 panelDim
Details
There probably are other ways to find the optimal way to arrange panels, so if you find anything,
please give me a hint.
Value
vector with 2 values, can be passed to par(mfrow), or a data.frame if all=TRUE.
Author(s)
Berry Boessenkool, <[email protected]>, Dec 2014, Jan 2015
See Also
groupHist, which is using this function
Examples
# basic usage
op <- par(mfrow=panelDim(6))
for(i in 1:6) plot(i:10, main=i)
par(op)
# Adcanced options
panelDim(7)
g <- panelDim(7, all=TRUE)
panelDim(7, plot=TRUE)
panelDim(7, plot=TRUE, all=TRUE) # compares 4 best options
panelDim(26, all=TRUE)
panelDim(26, plot=TRUE, all=TRUE) # compares 4 best options
panelDim(26, plot=TRUE, all=TRUE, weight=c(3,0) ) # fewer empty panels
# effect of maxempty:
panelDim(13, plot=TRUE) # 4 x 4
panelDim(13, maxempty=2, plot=TRUE) # 5 x 3
panelDim(13, maxempty=1, plot=TRUE) # 7 x 2
panelDim(13, maxempty=0, plot=TRUE) # 13 x 1
# Orientation of plot:
panelDim(45, plot=TRUE) # good for portrait orientation of plot
panelDim(45, landscape=TRUE, plot=TRUE) # better if plot width > height
## Not run:
## Rcmd check --as-cran doesn't like to open external devices,
## so this example is excluded from running in the checks.
plot of several n with defaults
parallelCode 117
dev.new(record=TRUE)
for(i in 1:50) panelDim(i, plot=TRUE)
## End(Not run)
Description
message a code chunk template for parallelization with progress bar on windows. On Linux, just
use pblapply(X, cl=8, FUN=fun)
Usage
parallelCode()
Author(s)
Berry Boessenkool, <[email protected]>, Aug 2017
Examples
parallelCode()
Description
Create both a pdf and a png file with a graph, with custom size default values. To iteratively create
pdfs without closing and reopening the pdf viewer, you might want to use e.g. Sumatra, which
comes with Rstudio. It can be found e.g. in C:/Program Files/RStudio/bin/sumatra
Usage
pdfpng(expr, file, pdf = TRUE, png = TRUE, overwrite = FALSE,
open = TRUE, quiet = FALSE, tracewarnmes = !quiet, filargs = NULL,
width = 7, height = 5, units = "in", res = 500, seed = runif(1,
-1e+09, 1e+09), envlevel = 1, pdfargs = NULL, pngargs = NULL, ...)
118 pdfpng
Arguments
expr Expression creating the plot, can be included in curly braces.
file Character: Filename without pdf/png extension. Unless overwrite=TRUE, files
will not be overwritten, but "_1" will be appended instead, see newFilename. If
expr creates several plots, use file="fname%02d", otherwise the png will only
contain the last figure. Note: this overwrites files as the % notation is not cap-
tured by newFilename. You may also have to run dev.off().
pdf Logical: Create pdf? DEFAULT: TRUE
png Logical: Create png? DEFAULT: TRUE
overwrite Logical: Overwrite existing file? Can be a vector for pdf and png separately.
DEFAULT: FALSE (_n appended in filename)
open Logical: open file(s) after creation using openFile? DEFAULT: TRUE
quiet Logical: suppress file creation messages and expr execution error tracing? DE-
FAULT: FALSE
tracewarnmes Logical: trace warnings and messages in expr execution? Errors are always
traced. Default: !quiet
filargs List of other arguments passed to newFilename. DEFAULT: NULL
width, height Graph dimensions. DEFAULT: 7x5 inches
units, res Graph quality arguments passed only to png. DEFAULT: inches ("in"), 500 ppi
seed Seed passed to set.seed before each call. DEFAULT: runif(1,-1e9,1e9)
envlevel Environment level passed to eval.parent. Never needs to be changed, as far
as I can tell. DEFAULT: 1
pdfargs List of arguments only passed to pdf.
pngargs List of arguments only passed to png.
... Further arguments passed to both pdf and png
Value
Nothing
Author(s)
Berry Boessenkool, <[email protected]>, March 2017
See Also
pdf, png
Examples
## Not run: # excluded from CRAN checks, file opening not wanted
pdfpng( plot(rnorm(500), type="l") , file="dummyplot", png=FALSE)
## End(Not run)
popleaf 119
Description
combine data.frame columns into a leaflet popup-box compatible format
Usage
popleaf(df, sel = colnames(df))
Arguments
df Data.frame
sel Columns to be selected (Names or index or TRUE/FALSE vector). DEFAULT:
colnames(df)
Value
Vector with character strings
Author(s)
Berry Boessenkool, <[email protected]>, Apr 2017
120 pretty2
See Also
paste
Examples
dat <- data.frame(a=14:16, b=letters[14:16], c=LETTERS[14:16],
lat=c(52.58,53.45,52.4), lon=c(6.34,7.23,13.05))
popleaf(dat)
dat$display <- popleaf(dat, 1:4)
## End(Not run)
Description
pretty with no values outside of x range
Usage
pretty2(x, n = 5, force = FALSE, ...)
Arguments
x object with numeric values
n desired number of values in pretty. DEFAULT: 5
force Must output length equal n exactly? DEFAULT: FALSE
... all other arguments in pretty.
Details
calculates pretty(x), then removes the values that do not lie within range(x).
If force=TRUE, range(x) is reduced step by step in a while loop until the condition is met. This is
useful if you want exactly 2 labels on an axis. In order not to get stuck, the outer values are taken
if there are more than n values within range(x).
Author(s)
Berry Boessenkool, <[email protected]>, Aug 2014
quantileBands 121
See Also
pretty , logVals
Examples
Description
Quantile bands with optional smoothing, e.g. for visualizing simulations
Usage
quantileBands(mat, x = 1:ncol(mat), col = rgb(0, 0, 1, alpha = c(0.5, 0.7)),
add = FALSE, main = "Quantile Bands", ylab = "", xlab = "",
probs = 0:4/4, na.rm = FALSE, type = 7, smooth = NA, medargs = NULL,
meanargs = NULL, txi, textargs = NULL, ...)
Arguments
mat Matrix or data.frame with columns of data
x X-axis positions for each column. DEFAULT: 1:ncol(mat)
col Vector of colors for each quantile group, recycled reversely if necessary. DE-
FAULT: rgb(0,0,1, alpha=c(0.5, 0.7))
add Add to existing plot? Allows to add to highly customized plot. DEFAULT:
FALSE
main, xlab, ylab
plot labels. DEFAULT: "Quantile Bands", ""
probs Probabilities passed to quantile. DEFAULT: 0:4/4
na.rm Remove NAs before computing quantiles, median and mean? DEFAULT:
FALSE
type Which of the 9 quantile algorithms should be used. DEFAULT: 7
smooth If(!is.na), width passed to movAv smoothing quantiles. DEFAULT: NA
122 quantileBands
medargs List of arguments passed to lines drawing median. Not drawn if NULL. DE-
FAULT: NULL
meanargs List of arguments passed to lines drawing mean. Not drawn if NULL. DE-
FAULT: NULL
txi Text x position index (along columns of mat), recycled if necessary. NA to
suppress. INTERNAL DEFAULT: middle of the plot for all.
textargs List of arguments passed to text, like col, adj, ... DEFAULT: NULL
... Further arguments passed to polygon, like border, lty, ...
Value
Quantiles of each column, invisible. Smoothed if smooth is given!
Note
This is the first version and is not tested very well yet.
Author(s)
Berry Boessenkool, <[email protected]>, Sept 2014
See Also
quantile, quantileMean, ciBand, polygon, https://cran.r-project.org/package=fanplot
Examples
library(RColorBrewer)
Description
Weighted average of R’s quantile methods
Usage
quantileMean(x, probs = seq(0, 1, 0.25), weights = rep(1, 9),
names = TRUE, truncate = 0, ...)
Arguments
x Numeric vector whose sample quantiles are wanted
probs Numeric vector of probabilities with values in [0,1]. DEFAULT: seq(0, 1, 0.25)
weights Numeric vector of length 9 with weight for each quantile method. Recycled
if shorter. DEFAULT: unweighted mean. DEFAULT: rep(1,9)
names If TRUE, the resulting vector has a names attribute. DEFAULT: TRUE
truncate Number between 0 and 1. Censored quantile: fit to highest values only (truncate
lower proportion of x). Probabilities are adjusted accordingly. DEFAULT: 0
... further arguments passed to quantile, except for type
Details
weights are internally normalized to sum 1
Value
numeric named vector, as returned by apply
Author(s)
Berry Boessenkool, <[email protected]>, Sept 2014
See Also
quantile
Examples
## Not run:
# #Excluded from CRAN Checks because of the long computing time
# median of 500 simulations:
qmm <- function(size, truncate=0) median(replicate(n=500,
expr=quantileMean(rbeta(size, 2,9), probs=0.999, names=FALSE, truncate=truncate)))
#dev.new(record=TRUE)
#pqmm(30, plot=TRUE)
## End(Not run)
Description
Reversed rainbow with different defaults, resulting in a color vector from blue (good) to red (bad)
Usage
rainbow2(n = 10, s = 1, v = 1, start = 0, end = 0.7, alpha = 1)
Arguments
n number of colors. DEFAULT: 10
s, v saturation and value as in rainbow. DEFAULT: 1
start start color. DEFAULT: 0
end end color. DEFAULT: 0.7
alpha transparency. DEFAULT: 1)
Value
A character vector of color names.
Author(s)
Berry Boessenkool, <[email protected]>, Sept 2014
See Also
seqPal for a better palette, rainbow
Examples
Description
Remove leading and/or trailing white space from character strings
Usage
removeSpace(x, begin = TRUE, end = TRUE, all = FALSE, ...)
Arguments
x Character string, can be a vector
begin Logical. Remove leading spaces at the beginning of the character string? DE-
FAULT: TRUE
end Logical. Remove trailing spaces at the end? DEFAULT: TRUE
all Logical. Remove all spaces anywhere in the string? DEFAULT: FALSE
... Further arguments passed to sub or gsub, like ignore.case, perl, fixed, useBytes.
Value
Character string (vector)
Note
If all arguments are FALSE, the string is returned unchanged.
Not extensively tested yet, please mail me any problems...
Author(s)
Berry Boessenkool, <[email protected]>, Dec 2014
See Also
sub
Examples
s <- c("space at end ", " white at begin", " both ", " special ^ ")
removeSpace(s)
Description
rescale a numeric vector: map values linearly onto a given range
Usage
rescale(x, from = 0, to = 1)
Arguments
x Numerical vector of values to be mapped to a given range
from output minimum. DEFAULT: 0
to output maximum. DEFAULT: 1
Value
numeric vector, rescaled onto output range
Author(s)
Berry Boessenkool, <[email protected]>, Jan 2016
References
http://stackoverflow.com/a/18303620
See Also
scales::rescale
Examples
Description
Round numbers and add leading + trailing zeros
Usage
round0(x, digits = 0, pre = 2, width = digits + pre + ifelse(digits == 0,
0, 1), flag = 0, ...)
Arguments
x Value(s)
digits Number of digits (after decimal separator) to keep. DEFAULT: 0
pre Minimum number of characters before the decimal separator. DEFAULT: 2
width Total width (number of characters including dot). DEFAULT: digits+pre (+1 if
needed)
flag Flag. Could be "" for spaces. DEFAULT: "0"
... Further arguments passed to formatC, except for "format".
Value
Character string vector
Author(s)
Berry Boessenkool, <[email protected]>, Jun 2017
See Also
formatC, sprintf
Examples
round0( pi*10^(-3:5), 2)
stopifnot(round0(17.3, 2) == "17.30")
round0(7.3)
round0(c(7.3,777.1234), 2)
round0(c(0.2,7.3,12.8), 2, pre=1)
round0(c(0.2,7.3,12.8), 1, pre=3, flag="") # spaces instead of zeros
roundedRect 129
Description
Draw rectangles with rounded corners via polygon
Usage
roundedRect(xleft, ybottom, xright, ytop, rounding = 0.25, bothsame = TRUE,
aspcorrect = bothsame, devcorrect = bothsame, corfactor = 1.3,
factorpoints = FALSE, corners = 1:4, npoints = 200, plot = TRUE, ...)
Arguments
xleft, ybottom, xright, ytop
Single numbers with the outer end locations of the rectangle.
rounding Proportion of the box to round. Recommended to be between 0 and 1. DE-
FAULT: 0.25
bothsame Set the visual amount of rounding to the same in both x and y direction? If
TRUE (the default), the proportion relates to the shortest rectangle side. This is
visually correct only if aspcorrect and devcorrect are both left at TRUE and
corfactor is set correctly. bothsame DEFAULT: TRUE
aspcorrect Correct for graph aspect ratio? DEFAULT: bothsame
devcorrect Correct for device aspect ratio? DEFAULT: bothsame
corfactor Aspect correction factor. I found this by trial and error. More elegant solutions
are welcome! DEFAULT 1.3, works well for 7x5 (width x height) graphs
factorpoints Logical: plot points at inset locations to determine the exact value for corfactor
by measuring on screen. DEFAULT: FALSE
corners Vector with integers indicating which corners to round. Starting bottom left,
going clockwise. Zero to suppress rounding. DEFAULT: 1:4
npoints Total number of vertices for the corners. DEFAULT: 200
plot Logical. Plot the polygon? FALSE to only compute coordinates. DEFAULT:
TRUE
... Further arguments passed to polygon, like col, border, ...
Value
Final coordinates, invisible
Author(s)
Berry Boessenkool, <[email protected]>, Dec 2017
130 runAxis
See Also
textField
Examples
plot(1:10) ; rect(4,2,7,8, border=8)
roundedRect(4,2,7,8, rounding=0.1)
roundedRect(4,2,7,8, rounding=0.25) # default
roundedRect(4,2,7,8, rounding=0.5)
roundedRect(4,2,7,8, rounding=-0.1, border="red")
roundedRect(4,2,7,8, rounding=1.1, border="blue")
roundedRect(2,2,8,4, rounding=0.5) # in long boxes, 0.5 is max
roundedRect(2,2,8,4, rounding=0.5, bothsame=FALSE, corfactor=1, border=3)
## End(Not run)
Description
Label a numerical axis (in minutes) with time units that are typical for running times (10 sec inter-
vals)
seasonality 131
Usage
runAxis(t = 3 * 60, int1 = 10, int2 = 5, side = 1, linarg = NULL, ...)
Arguments
t Maximum time in minutes
int1 Primary interval (for labels)
int2 Secondary interval (for lines)
side Side of the plot to draw axis (1,2,3,4 = bottom, left, top, right)
linarg List of arguments passed to abline
... Further arguments passed to axis
Value
List with the positions and labels
Author(s)
Berry Boessenkool, <[email protected]>, Jun 2016
See Also
logAxis, monthAxis
Examples
plot(1:200, xaxt="n")
runAxis(t=200, int1=20, int2=10)
Description
Examine time series for seasonality of high (low) values
Usage
seasonality(dates, values, data, drange = NA, vrange = NA, shift = 0,
janline = TRUE, hlines = FALSE, nmax = 0, maxargs = NULL, plot = 1,
add = FALSE, nmin = 100, probs = c(0, 25, 50, 75, 95, 99.9)/100,
width = 3, text = TRUE, texti = seq(200, 20, length.out =
length(probs)), textargs = NULL, months = substr(month.abb, 1, 1),
slab = "Month", tlab = "Year", vlab = NA, xlim = NA, ylim = NA,
xaxs = NA, yaxs = NA, main = "Seasonality", adj = 0.2, mar = c(3, 3,
4, 1), mgp = c(1.7, 0.7, 0), keeppar = TRUE, legend = TRUE,
legargs = NULL, returnall = FALSE, quiet = FALSE, ...)
132 seasonality
Arguments
dates Dates in ascending order. Can be character strings or strptime results, as ac-
cepted (and coerced) by as.Date
values Values to be mapped in color with colPoints
data Optional: data.frame with the column names as given by dates and values
drange Optional date range (analogous to xlim), can be a vector like dates. Can also be
numerical years, in which case "-01-01" is appended. DEFAULT: NA (computed
from dates internally)
vrange Optional value range (analogous to ylim), can be a vector like values. DE-
FAULT: NA (computed from values internally)
shift Number of days to move the year-break to. E.g. shift=61 for German hydrolog-
ical year (Nov to Oct). DEFAULT: 0
janline Logical: Should horizontal line be plotted at January 1st if shift!=0? DE-
FAULT: TRUE
hlines Draw horizontal background lines in plot 1? Either FALSE (the default), TRUE
to draw gray background lines at each month start, or a list of arguments passed
to abline with owa. DEFAULT: FALSE
nmax Number of annual maxima to be marked, plotted and returned. Currently, only
0 and 1 are implemented. DEFAULT: 0
maxargs List of arguments passed to lines for annual maxima, e.g. maxargs=list(type="l", col="red", lty=
DEFAULT: NULL (several internal defaults are used, but can be overridden)
plot Integer specifying the type of plot. Can be a vector to produce several plots.
0: none, only return the data.frame with annual maxima.
1: color coded doy (day of the year) over year (the default).
2: Color coded spiral graph with spiralDate.
3: Spaghetti line plot with discharge over doy, one line per year.
4: probs quantileMean over doy, with optional aggregation window (width)
around each doy.
5: Annmax over time for crude trend analysis.
DEFAULT: 1
add Logical. Add to existing plot? DEFAULT: FALSE
nmin Minimum number of values that must be present per (hydrological) year to be
plotted in plot type 5. DEFAULT: 100
probs Probabilities passed to quantileMean for plot=4. DEFAULT: c(0,25,50,75,95,99)/100
width Numeric: window width for plot=4. Used as sd in gaussian weighting. Support
(number of values around a DOY passed to quantile function at least once) is
ca 4.9*width. The value at doy itself is used 10 times. Larger values of width
require more computing time. DEFAULT: 3
text Logical. Call textField if plot=4? DEFAULT: TRUE
texti Numerical (vector): indices at which to label the lines. DEFAULT: seq(200,20,length.out=length(probs))
textargs List of arguments passed to textField for plot=4. DEFAULT: NULL
months Labels for the months. DEFAULT: J,F,M,A,M,J,J,A,S,O,N,D
seasonality 133
Value
The output is always invisible, don’t forget to assign it. If returnall=FALSE: Data.frame with year,
number of nonNA entries, max value + doy of annual maxima. Please note that the column year
does not match the calendrical year if shift!=0.
if returnall=TRUE: a list with annmax (df from above) as well as:
data: data.frame(doy, values, year) and optionally:
plot1, plot3, plot4, plot5: outputs from colPoints
plot2: output list from spiralDate
and other elements depending on plot type, like data3, data4, probs4, width4.
Author(s)
Berry Boessenkool, <[email protected]>, Jul-Oct 2016
See Also
spiralDate, colPoints, https://waterdata.usgs.gov/nwis
Examples
# browseURL("http://nrfa.ceh.ac.uk/data/station/meanflow/39072")
qfile <- system.file("extdata/discharge39072.csv", package="berryFunctions")
Q <- read.table(qfile, skip=19, header=TRUE, sep=",", fill=TRUE)[,1:2]
rm(qfile)
colnames(Q) <- c("date","discharge")
134 seqPal
# Be careful with your interpretation. This looks normal up to 2007, but then BAM!:
seasonality(date, discharge, data=Q[Q$date<as.Date("2007-07-15"),], plot=3, shift=100, nmax=1)
seasonality(date, discharge, data=Q[Q$date<as.Date("2007-08-15"),], plot=3, shift=100, nmax=1)
# Shift is important. You don't want to have this event included twice:
seasonality(date, discharge, data=Q[850:950,], plot=3, nmax=1, quiet=TRUE, shift=100)
## End(Not run)
## Not run:
dev.new(noRStudioGD=TRUE, record=TRUE) # large graph on 2nd monitor
par(mfrow=c(2,2))
seasonality(date, discharge, data=Q, plot=(1:5)[-4], shift=100)
seasonality(date, discharge, data=Q, plot=(1:5)[-4], lwd=2)
seasonality(date, discharge, data=Q, plot=(1:5)[-4], nmax=1, shift=100)
seasonality(date, discharge, data=Q, plot=(1:5)[-4], col=divPal(100, ryb=TRUE))
dev.off()
## End(Not run)
Description
Sequential color palette from yellow to red or yellow to blue or custom colors.
Usage
seqPal(n = 12, reverse = FALSE, alpha = 1, extr = FALSE, yb = FALSE,
yr = FALSE, gb = FALSE, b = FALSE, colors = NULL, logbase = 1, ...)
seqPal 135
Arguments
n Number of colors. DEFAULT: 12
reverse Reverse colors? DEFAULT: FALSE
alpha Transparency (0=transparent, 1=fully colored). DEFAULT: 1
extr Should colors span possible range more extremely? If TRUE, it has very light
yellow and very dark blue values included, using the result from RColorBrewer::brewer.pal(9, "YlGnB
DEFAULT: FALSE
yb Should colors be in yellow-blue instead of the internal (nice) default? DE-
FAULT: FALSE
yr Should colors be in yellow-red instead of the default? DEFAULT: FALSE
gb Should colors be in green-blue instead of the default? DEFAULT: FALSE
b Should colors be in an increasingly saturated blue? DEFAULT: FALSE
colors If not NULL, a color vector used in colorRampPalette. DEFAULT: NULL
logbase If !=1, this is passed to classify and logSpaced. DEFAULT: 1
... Further arguments passed to colorRamp
Value
Character string vector with color names
Author(s)
Berry Boessenkool, <[email protected]>, Jan 2016
See Also
showPal, divPal, addAlpha, colorRampPalette, package RColorBrewer
Examples
# nonlinear color scale (use colPoints + see classify for more options):
v <- rescale(volcano^30)
image(v, col=seqPal(1000), asp=1); colPointsLegend(v, nbins=1000)
image(v, col=seqPal(1000, logbase=1.007), asp=1)
colPointsLegend(v, col=seqPal(1000, logbase=1.007))
plot( rep(1, 1000), pch=15, cex=3, col=seqPal(1000), ylim=c(0.99, 1.01), ylab="logbase", las=1)
for(b in seq(0.99, 1.01, len=30))
points(rep(b, 1000), pch=15, cex=1, col=seqPal(1000, logbase=b))
136 seqR
Description
sequence given by range or vector of values.
Usage
seqR(range, from = 1, to = 1, extend = 0, ...)
Arguments
range vector with 2 values (1st taken as from, 2nd as to) or more (the result is then
always ascending).
from start value of sequence. DEFAULT:1
to end value of sequence. DEFAULT:1
extend Factor f passed to extendrange. DEFAULT:0
... further arguments passed to seq.
Value
Numeric vector.
Author(s)
Berry Boessenkool, <[email protected]>, Feb 2014
See Also
seq, range, http://r.789695.n4.nabble.com/seq-range-argument-td4684627.html
Examples
seqR(range=c(12,6), by=-2)
m <- c(41, 12, 38, 29, 50, 39, 22)
seqR(m, len=6)
# Takes min and max of range if the vector has more than two elements.
Description
Plot examples of the sequential and diverging color palettes in this package. Do not use rainbow:
https://eagereyes.org/basics/rainbow-color-map
Usage
showPal(cex = 4, ...)
Arguments
cex Character EXpansion size (width of color bar). DEFAULT: 4
... Arguments passed to par
Author(s)
Berry Boessenkool, <[email protected]>, Apr 2016
See Also
seqPal, divPal, package RColorBrewer
Examples
showPal()
Description
multipanel-compatible inset plot with margins, background and border Adding points after smallPlot
is called may be incorrect if the original function messes with the graph margins, see the note in
colPointsLegend.
Usage
smallPlot(expr, x1 = 0.05, x2 = 0.7, y1 = 0.5, y2 = 1, outer = FALSE,
xpd = NA, mar = c(3, 3, 1, 1), mgp = c(1.8, 0.8, 0), bg = par("bg"),
border = par("fg"), las = 1, resetfocus = TRUE, colwise = FALSE, ...)
138 smallPlot
Arguments
expr expression creating a plot. Can be code within braces.
x1, x2, y1, y2 Position of small plot, relative to current figure region [0:1]. DEFAULT: x: 0.05-
0.7, y: 0.5-1
outer Logical. Should inset plot be placed in the device outer margin region instead of
relative to the current figure region? Useful in multipanel plots with par(oma).
outer here does not have exactly the same meaning as in title. DEFAULT:
FALSE
xpd Plotting and notation clipped to plot region (if xpd=FALSE), figure region (TRUE)
or device region (xpd=NA). DEFAULT: NA
mar Margin vector in (approximate) number of lines. It is internally multiplied with
strheight to convert it to relative units [0:1], thus the behaviour is a bit different
from par(mar). It’s recycled, so you can use mar=0. DEFAULT: c(3,3,1,1)
mgp MarGinPlacement: distance of xlab/ylab, numbers and line from plot margin, as
in par, but with different defaults. DEFAULT: c(1.8, 0.8, 0)
bg Background. DEFAULT: par("bg")
border Border around inset plot. DEFAULT: par("fg")
las LabelAxisStyle. DEFAULT: 1
resetfocus Reset focus to original plot? Specifies where further low level plot commands
are directed to. DEFAULT: TRUE
colwise Logical: Continue next plot below current plot? If you had par(mfcol=...),
you must use colwise=TRUE, otherwise the next plot will be to the right of the
current plot (as with par(mfrow=...)). DEFAULT: FALSE
... further arguments passed to par. This may mess things up - please tell me
for which arguments! You can do par(las=1, las=2) (the last will be set),
so smallPlot(plot(1), new=FALSE) works, but may not yield the intended
result.
Value
parameters of small plot, invisible.
Warning
setting mai etc does not work!
Author(s)
Berry Boessenkool, <[email protected]>, 2014-2016
See Also
colPointsLegend for an example of usage. subplot and add.scatter for alternative solutions to
this problem that do not set margins.
smallPlot 139
Examples
# Basic usage:
op <- par(no.readonly=TRUE) # original parameters
plot(1:10)
smallPlot(plot(5:1, ylab="Yo man!"), bg="lightgreen" )
smallPlot(plot(5:1), x1=0.5,x2=1, y1=0.3,y2=0.6, bg="yellow", yaxt="n")
# if R warns "figure margins too large", try dragging the plot viewer bigger
par(mfcol=c(3,4))
new_plt <- par("plt")
plot(1:10)
plot(1:10)
smallPlot(plot(5:1), bg="lightblue", colwise=TRUE)
points(3, 2, pch="+", cex=2, col=2)
plot(1:10) # canot keep mfcol, only mfrow, if colwise is left FALSE.
smallPlot(plot(5:1), bg="bisque", resetfocus=FALSE )
points(3, 2, pch="+", cex=2, col=2)
plot(1:10) # in smallPlot space
par(plt=old_plt)
plot(1:10) # too large
smallPlot(plot(5:1), bg="palegreen")
points(3, 2, pch="+", cex=2, col=2, xpd=NA) # not drawn with default xpd
par(plt=new_plt)
plot(1:10) # canot keep mfcol, only mfrow, if colwise is left FALSE.
smallPlot(plot(5:1), bg="yellow")
points(3, 2, pch="+", cex=2, col=2) # everything back to normal
par(op)
Description
draw smoothed lines with an n-level partially transparent haze
Usage
smoothLines(x, y, lwd = 1, col = 1, n = 5, alpha = 0.1, ...)
Arguments
x numerical. x-coordinates. x can be a matrix, then the y coordinates are taken
from the second column
y numerical. y-coordinates
lwd single integer. line width
col color. DEFAULT: 1 (black)
sortDF 141
n single integer. number of transparent lines overlayed with sinking line widths.
DEFAULT: 5
alpha Transparency of color. DEFAULT: 0.1 (very transparent)
... further arguments as in lines
Value
none, draws lines
Author(s)
Berry Boessenkool, <[email protected]>, 2011/2012
See Also
lines, col2rgb, rgb
Examples
#dev.off()
Description
sort a data.frame by column - basically just a wrapper for order
Usage
sortDF(df, col, decreasing = TRUE, ...)
142 spiralDate
Arguments
df Data.frame to be sorted
col Column (index or (un)quoted name) to be sorted by
decreasing Logical: should highest value be on top? DEFAULT: TRUE (unlike order!)
... Further arguments passed to order, like eg na.last or method
Value
data.frame
Author(s)
Berry Boessenkool, <[email protected]>, June 2015
See Also
sort, order
Examples
sortDF(USArrests[USArrests$Murder>11,], Assault)
sortDF(USArrests[USArrests$Murder>11,], "Assault") # safer within functions
sortDF(USArrests[USArrests$Murder>11,], 3)
Description
Plot seasonality of (daily) time series along spiral
Usage
spiralDate(dates, values, data, drange = NA, vrange = NA,
months = substr(month.abb, 1, 1), add = FALSE, shift = 0, prop = NA,
zlab = substitute(values), format = "%Y", nint = 1, ...)
Arguments
dates Dates in ascending order. Can be character strings or strptime results, as ac-
cepted (and coerced) by as.Date
values Values to be mapped in color with colPoints along seasonal spiral
data Optional: data.frame with the column names as given by dates and values
drange Optional date range (analogous to xlim), can be a vector like dates. DEFAULT:
NA
spiralDate 143
vrange Optional value range (analogous to ylim), can be a vector like values. DE-
FAULT: NA
months Labels for the months. DEFAULT: J,F,M,A,M,J,J,A,S,O,N,D
add Add to existing plot? DEFAULT: FALSE
shift Number of days to move January 1st clockwise. DEFAULT: 0
prop Proportion of the data to be actually plotted, used in spiralDateAnim. DE-
FAULT: NA (ignored)
zlab Title of colPointsLegend
format Format of date labels see details in strptime. DEFAULT: "%Y"
nint Number of interpolation segments between points, only used if lines=TRUE
(passed to colPoints). DEFAULT: 1 (with long time series, the colPoints de-
fault of 30 is too high!)
... Further arguments passed to colPoints, but not Range (use vrange)
Value
invisible data.frame with date, vals, and the plotting coordinates
Author(s)
Berry Boessenkool, <[email protected]>, May 2016
See Also
seasonality, colPoints, as.Date
Examples
# synthetic seasonal Data
set.seed(42)
fakeData <- data.frame(time = as.Date("1985-01-01")+0:5000,
vals = cumsum(rnorm(5001))+50 )
fakeData$vals <- fakeData$vals + sin(0:5000/366*2*pi)*max(abs(fakeData$vals))
par(mfrow=c(1,1))
## Real data:
#library2("waterData")
#data(exampleWaterData)
#spiralDate(dates, val, data=q05054000LT, lines=TRUE, lwd=3)
Description
Animation of (daily) time series along spiral
Usage
spiralDateAnim(dates, values, data, steps = 100, sleep = 0,
progbar = TRUE, ...)
Arguments
dates, values, data
Input as in spiralDate
steps Number of steps (images) in animation. DEFAULT: 100
sleep Pause time between frames, in seconds, passed to Sys.sleep. DEFAULT: 0
progbar Should a progress bar be drawn? Useful if you have a large dataset or many
steps. DEFAULT: TRUE
... Further arguments passed to spiralDate
Author(s)
Berry Boessenkool, <[email protected]>, May 2016
See Also
spiralDate, linLogHist
superPos 145
Examples
set.seed(42)
x <- as.Date("1985-01-01")+0:5000
y <- cumsum(rnorm(5001))+50
y <- y + sin(0:5000/366*2*pi)*max(abs(y))/2
plot(x,y)
## Not run:
## Rcmd check --as-cran doesn't like to open external devices such as pdf,
## so this example is excluded from running in the checks.
pdf("spiralDateAnimation.pdf")
spiralDateAnim(x,y, main="Example Transition", col=divPal(100), format=" ")
dev.off()
# if you have FFmpeg installed, you can use the animation package like this:
library2(animation)
saveVideo(spiralDateAnim(x,y, steps=300), video.name="spiral_anim.mp4", interval=0.1,
ffmpeg="C:/Program Files/R/ffmpeg/bin/ffmpeg.exe")
## End(Not run)
Description
superposition of precipitation along unit hydrograph (to simulate Q from P)
Usage
superPos(P, UH)
Arguments
P Vector with precipitation values
UH Vector with discrete values of the Unit Hydrograph. This can be any UH sum-
ming to one, not just the storage cascade model.
Value
Vector of streamflow values
146 superPos
Author(s)
Berry Boessenkool, <[email protected]>, July 2013
See Also
lsc where superPos is used, unitHydrograph
Examples
superPos(N, UH)
# If catchment area = 34 km^2 and precipitation is homogenous:
superPos(N/10^3, UH) * 34*10^6 / 3600 # m^3/s # Add baseflow and you're done...
Description
Table with numbers and corresponding color in the background of each cell. (heatmap)
Usage
tableColVal(mat, main = deparse(substitute(mat)), nameswidth = 0.3,
namesheight = 0.1, palette = seqPal(100), Range = range(mat, finite =
TRUE), digits = 2, ..., classargs = NULL, cellargs = NULL,
colargs = NULL, rowargs = NULL, mainargs = NULL)
Arguments
mat Matrix with values and row/column names
main Title for topleft space. DEFAULT: name of mat object.
nameswidth Relative width of row names at the left, as a percentage of plot. DEFAULT: 0.3
namesheight Relative height of column names at the top. DEFAULT: 0.1
palette Color palette for the heatmap. DEFAULT: seqPal(100)
Range Range mapped to color palette. DEFAULT: range(mat)
digits Number of digits rounded to for writing. DEFAULT: 2
... Further arguments passed to all text like cex, col, srt, ...
148 tableColVal
classargs List of arguments specifying how to call classify, e.g. method. DEFAULT:
NULL
cellargs, colargs, rowargs, mainargs
List of arguments passed to text only for the cells, column labels, row labels or
title, respectively. DEFAULTS: NULL
Details
Create tables with corresponding color in the background of each cell. (heatmap)
Value
List of locations in plot.
Author(s)
Berry Boessenkool, <[email protected]>, Nov 2012 + Nov 2016
See Also
pdf, heatmap
Examples
( tableColVal(Bsp) )
tableColVal(Bsp, nameswidth=0.1) # relative to plot width
tableColVal(Bsp, namesheight=0.5, srt=45)
tableColVal(Bsp, namesheight=0.5, colargs=c(srt=45))
## Not run:
## Rcmd check --as-cran doesn't like to open external devices such as pdf,
## so this example is excluded from running in the checks.
pdf("TableColVal.pdf", height=5); tableColVal(Bsp); dev.off()
openFile("TableColVal.pdf")
unlink("TableColVal.pdf")
textField 149
## End(Not run)
Description
Write text to plot. A field the size of each label is drawn beneath it, so the text can be read easily
even if there are many points in the plot. Fields can be rectangular, elliptic or rectangular with
rounded edges.
Usage
textField(x, y, labels = seq_along(x), fill = "white", border = NA,
expression = NA, margin = 0.3, field = "rounded", nv = 500,
rounding = 0.25, rrarg = NULL, lty = par("lty"), lwd = par("lwd"),
cex = par("cex"), xpd = par("xpd"), adj = par("adj"), pos = NULL,
offset = 0.5, quiet = TRUE, ...)
Arguments
x X coordinates, if necessary, they are recycled
y Y coordinates
labels labels to be placed at the coordinates, as in text. DEFAULT: seq_along(x)
fill fill is recycled if necessary. With a message when quiet = FALSE. DEFAULT:
"white"
border ditto for border. DEFAULT: NA
expression If TRUE, labels are converted to expression for better field positioning through
expression bounding boxes. If NA, it is set to TRUE for labels without line
breaks (Newlines, "\n"). If FALSE, no conversion happens. DEFAULT: NA
margin added field space around words (multiple of em/ex). DEFAULT: 0.3
field ’rectangle’, ’ellipse’, or ’rounded’, partial matching is performed. DEFAULT:
"rounded"
nv number of vertices for field = "ellipse" or "rounded". low: fast drawing. high:
high resolution in vector graphics as pdf possible. DEFAULT: 500
rounding between 0 and 0.5: portion of height that is cut off rounded at edges when field
= "rounded". DEFAULT: 0.25
rrarg List of arguments passed to roundedRect. DEFAULT: NULL
lty line type. DEFAULT: par("lty")
lwd line width. DEFAULT: par("lwd")
cex character expansion. DEFAULT: par("cex")
150 textField
Details
Specifying pos and offset will currently change the position of the text, but not of the field.
srt is not supported yet.
lend, ljoin and lmitre can not be specified for rect, to keep argument number low.
density (crosshatch etc.) is not supported, as this would distract from the text. # Search Engine
Keywords: R Text visible on top R labeling with color underneath R Creating text with a halo R
Text with shadow
Value
None
Author(s)
Berry Boessenkool, <[email protected]>, April 2013 + March 2014
References
with inspiration taken from ordilabel in package vegan and thanks to Jari Oksanen for his com-
ments
See Also
text, roundedRect; shadowtext in package TeachingDemos, see http://blog.revolutionanalytics.
com/2009/05/make-text-stand-out-with-outlines.html, and http://stackoverflow.com/
questions/25631216.
s.label in package ade4, which is not so versatile and doesn’t work with logarithmic axes
Examples
# Field type can be abbreviated (partial matching), margin may need adjustment:
textField(90, 5, "short", field="ell", fill=7, border=4, mar=-0.4)
# In most devices, vertical adjustment is slightly off when the character string
# contains no descenders. The default is for centered text: adj = c(0.5, NA).
# For drawing the field, adj[2] is in this case set to 0.5.
# Text positioning is different for NA than for 0.5, see details of ?text
# I'm working on it through expression, which does not work with newlines yet
Description
Check if logical expressions return what you expect with a truth table
Usage
TFtest(..., na = TRUE)
Arguments
... Expression(s) with logical operators to be evaluated, with single letters for vari-
ables. Each expression is to be separated with a comma
na Logical: should NAs be included in the truth table? DEFAULT: TRUE
Details
Value
Truth table as data.frame with TRUE and FALSE (and NA) combinations
Author(s)
See Also
logical
Examples
Description
Labels date axes at sensible intervals in the time domain of weeks to decades.
Usage
timeAxis(side = 1, timeAxis = NA, origin = "1970-01-01",
startyear = NULL, stopyear = NULL, n = 5, npm = NULL, npy = NA,
format = "%d.%m.\n%Y", yformat = "%Y", labels = format.Date(d,
format), ym = FALSE, mcex = 0.6, mmgp = c(3, 0, 0), midyear = FALSE,
midmonth = FALSE, midargs = NULL, mgp = c(3, 1.5, 0), cex.axis = 1,
tick = TRUE, tcl = par("tcl"), las = 1, ...)
Arguments
side Which axis are to be labeled? (can be several). DEFAULT: 1
timeAxis Logical indicating whether the axis is POSIXct, not date. DEFAULT: NA, mean-
ing axis value >1e5
origin Origin foras.Date and as.POSIXct. DEFAULT: "1970-01-01"
startyear Integer. starting year. DEFAULT: NULL = internally computed from par("usr")
stopyear Ditto for ending year. DEFAULT: NULL
n Approximate number of labels that should be printed (as in pretty). DEFAULT:
5
npm Number of labels per month, overrides n. DEFAULT: NULL = internally com-
puted.
npy Number of labels per year, overrides npm and n. DEFAULT: NA
format Format of date, see details in strptime. DEFAULT: "%d.%m.\n%Y"
yformat Format of year if ym=TRUE. Use yformat=" " (with space) to suppress year
labeling. DEFAULT: "%Y"
labels labels. DEFAULT: format.Date(d, format)
ym Label months with first letter at the center of the month and year at center below.
Sets midyear and midmonth to TRUE. Uses labels and format for the years,
but ignores them for the months. DEFAULT: FALSE
mcex cex.axis for month labels if ym=TRUE. DEFAULT: 0.6
mmgp mgp for month labels if ym=TRUE. DEFAULT: 3,0,0
midyear Place labels in the middle of the year? if TRUE, format default is "%Y". DE-
FAULT: FALSE
midmonth Place labels in the middle of the month? if TRUE, format default is "%m\n%Y".
DEFAULT: FALSE
154 timeAxis
midargs List of arguments passed to axis for the year-start lines without labels. DE-
FAULT: NULL
mgp MarGinPlacement, see par. The second value is for label distance to axis. DE-
FAULT: c(3,1.5,0)
cex.axis Character EXpansion (letter size). DEFAULT: 1
tick Draw tick lines? DEFAULT: TRUE
tcl Tick length (negative to go below axis) in text line height units like mgp[2]
Changed to -2.5 for year borders if ym=TRUE. DEFAULT: par("tcl")
las LabelAxisStyle for orientation of labels. DEFAULT: 1 (upright)
... Further arguments passed to axis, like lwd, col.ticks, hadj, lty, ...
Value
The dates that were labeled
Author(s)
Berry Boessenkool, <[email protected]>, Feb 2015, update labels and midyear Dec 2015
See Also
monthLabs for the numbercrunching itself, axis.Date with defaults that are less nice.
Examples
# mid-year labels:
plot(Date3, cumsum(rnorm(50)), type="l", xaxt="n", ann=FALSE)
timeAxis(midyear=TRUE, midargs=list(tcl=-1.2))
# mid-month labels:
plot(Date1, cumsum(rnorm(30)), type="l", xaxt="n", ann=FALSE)
timeAxis(midmonth=TRUE)
Description
Beeps in a given interval and gives a progress bar in the console
Usage
timer(interval = 20, n = 15, write = FALSE)
Arguments
interval alarm interval in seconds. DEFAULT: 20
n number of alarm signals to be given. DEFAULT: 15
write Should the actual estimated time be written for overhead computing time control
purposes? DEFAULT: FALSE
Details
defaults to practice useR lightning talks: 15 slides, each shown 20 secs, change automatically
Value
none
156 toupper1
Author(s)
Berry Boessenkool, <[email protected]>, June 2015
References
http://user2015.math.aau.dk/lightning_talks
See Also
alarm, Sys.sleep, txtProgressBar
Examples
## End(Not run)
Description
capitalizes the first letter of character strings using toupper
Usage
toupper1(x)
Arguments
x Character vector
Details
Basically just a one-liner using toupper
Value
character string vector
Author(s)
Berry Boessenkool, <[email protected]>, Jul 2016
traceCall 157
See Also
toupper, substr
Examples
toupper1("berry")
toupper1(c("berRy","likes to code"))
Description
trace the call stack e.g. for error checking and format output for do.call levels
Usage
Arguments
Value
Author(s)
See Also
Examples
lower <- function(a, s) {warning(traceCall(s), "stupid berry warning: ", a+10); a}
upper <- function(b, skip=0) lower(b+5, skip)
upper(3)
upper(3, skip=1) # traceCall skips last level (warning)
upper(3, skip=4) # now the stack is empty
d <- tryStack(upper("four"), silent=TRUE)
inherits(d, "try-error")
cat(d)
Description
truncate long vectors for messages
Usage
truncMessage(x, ntrunc = 3, prefix = "s", midfix = " ", altnix = "'",
sep = ", ")
Arguments
x Character vector
ntrunc Integer: number of elements printed before truncation. DEFAULT: 3
prefix Character: Prefix added if length(x)>1. DEFAULT: "s"
midfix Character: string added after prefix OR before first altnix. DEFAULT: " "
altnix Character: Alternative string padded around x if length(x)==1. DEFAULT: "’"
sep Character: Separator between elements. DEFAULT: ", "
Value
Character string
Author(s)
Berry Boessenkool, <[email protected]>, Nov 2016
See Also
message
tryStack 159
Examples
truncMessage("hi")
message("listing name", truncMessage( "hi" ), ".")
message("listing name", truncMessage(paste0("hi",1:10)), ".")
truncMessage(paste0("hi",1:10), ntrunc=1)
truncMessage(paste0("hi",1:10), ntrunc=2, prefix="", midfix="")
truncMessage(paste0("hi",1:10), ntrunc=8, prefix="files _ ")
Description
As in try, the result of an expression if it works. If it fails, execution is not halted, but an invisible
try-error class object is returned and (unless silent=TRUE) a message catted to the console.
Unlike try, tryStack also returns the calling stack to trace errors and warnings and ease debugging.
Usage
tryStack(expr, silent = FALSE, warn = TRUE, short = TRUE, file = "",
removetry = TRUE, skip = NULL)
Arguments
expr Expression to try, potentially wrapped in curly braces if spanning several com-
mands.
silent Logical: Should printing of error message + stack be suppressed? Does not
affect warnings and messages. DEFAULT: FALSE
warn Logical: trace warnings and messages also? They are still handled like regu-
lar warnings / messages unless file !="", when they are catted into that file.
DEFAULT: TRUE
short Logical: should trace be abbreviated to upper -> middle -> lower? If NA, it is
set to TRUE for warnings and messages, FALSE for errors. DEFAULT: TRUE
file File name passed to cat. If given, Errors will be appended to the file after
two empty lines. if warn=T and file!="", warnings and messages will not be
shown, but also appended to the file. This is useful in lapply simulation runs.
DEFAULT: "" (catted to the console)
removetry Logical: should all stack entries matching typical tryCatch expressions be re-
moved? Unless the call contains customized tryCatch code, this can be left to
the DEFAULT: TRUE
skip Character string(s) to be removed from the stack. e.g. "eval(expr, p)". Use
short=F to find exact matches. DEFAULT: NULL
160 tryStack
Value
Value of expr if evaluated successfully. If not, an invisible object of class "try-error" as in try with
the stack in object[2]. For nested tryStack calls, object[3], object[4] etc. will contain "–
empty error stack –"
Author(s)
Berry Boessenkool, <[email protected]>, Nov 2016
See Also
try, traceCall, http://r.789695.n4.nabble.com/Stack-trace-td4021537.html, http://
stackoverflow.com/questions/15282471/get-stack-trace-on-trycatched-error-in-r, http:
//stackoverflow.com/questions/1975110/printing-stack-trace-and-continuing-after-error-occurs-in-r,
http://stackoverflow.com/questions/16879821/save-traceback-on-error-using-trycatch
Examples
# Functions -----
## End(Not run)
d <- tryStack(upper("42") ) # like try, but with traceback, even for warnings
cat(d)
d <- tryStack(upper("42"), silent=TRUE, warn=0) # don't trace warnings
d <- tryStack(upper("42"), short=FALSE)
stopifnot(inherits(d, "try-error"))
stopifnot(tryStack(upper(42))==52)
## End(Not run)
op <- options(warn=2)
d <- try(upper("42") )
cat(d)
d <- tryStack(upper("42") )
d <- tryStack(upper("42"), warn=FALSE)
cat(d)
options(op) ; rm(op)
cat( tryStack(upper("42")) )
f <- function(k) tryStack(stop("oh oh"))
d <- f(42) ; cat("-----\n", d, "\n-----\n") ; rm(d) # level 4 not helpful, but OK
Description
Calculate continuous unit hydrograph with given n and k (in the framework of the linear storage
cascade)
Usage
unitHydrograph(n, k, t, force = FALSE)
Arguments
n Numeric. Number of storages in cascade.
k Numeric. Storage coefficient [1/s] (resistance to let water run out). High damp-
ing = slowly reacting landscape = high soil water absorbtion = high k.
t Numeric, possibly a vector. Time [s].
force Logical: Force the integral of the hydrograph to be 1? DEFAULT: FALSE
Value
Vector with the unit hydrograph along t
Note
The sum under the UH should always be 1 (if t is long enough). This needs yet to be checked...
Author(s)
Berry Boessenkool, <[email protected]>, July 2013
See Also
lsc on how to estimate n and k for a given discharge dataset. deconvolution.uh in the package
hydromad, http://hydromad.catchment.org
Examples
# Some n and k values are cut off at the left, that explains the shift from the
# median of simulations relative to the n2k8 line.
Description
Nerdy way to wish someone a happy new year by using sample
Usage
yearSample(year)
Arguments
year 4 digit numerical year.
Details
Nerdy way to wish someone a happy new year, eg:
Have a great
set.seed(1244); sample(0:9,4,T)
164 yearSample
Value
cats command into the console that can be copypasted to anyone’s R script.
Author(s)
Berry Boessenkool, <[email protected]>, April 2014
See Also
nameSample to impress with "randomly" finding a name, set.seed, sample, letters
Examples
yearSample(2016)
# Have a nerdy
set.seed(12353); sample(0:9, 4, replace=TRUE)
Index
∗Topic IO insertRows, 64
combineFiles, 34 l2array, 67
compareFiles, 36 panelDim, 115
dupes, 43 ∗Topic character
getName, 55 combineFiles, 34
na9, 106 compareFiles, 36
∗Topic aplot convertUmlaut, 37
ciBand, 18 dupes, 43
circle, 20 getName, 55
colPoints, 27 googleLink2pdf, 59
colPointsHist, 30 nameSample, 107
colPointsLegend, 32 removeSpace, 126
expReg, 45 toupper1, 156
funnelPlot, 48 truncMessage, 158
legendmt, 72 ∗Topic chron
linReg, 80 monthAxis, 94
locArrow, 82 monthLabs, 96
locLine, 83 spiralDate, 142
logAxis, 84 spiralDateAnim, 144
logHist, 86 timeAxis, 153
logVals, 88 timer, 155
monthAxis, 94 ∗Topic classif
mReg, 100 classify, 21
popleaf, 119 ∗Topic color
quantileBands, 121 addAlpha, 5
roundedRect, 129 addFade, 6
runAxis, 130 colPoints, 27
seasonality, 131 colPointsHist, 30
smallPlot, 137 colPointsLegend, 32
smoothLines, 140 divPal, 41
spiralDate, 142 rainbow2, 125
spiralDateAnim, 144 seqPal, 134
textField, 149 showPal, 137
timeAxis, 153 spiralDate, 142
∗Topic arith spiralDateAnim, 144
approx2, 10 ∗Topic connection
logSpaced, 87 funTinn, 53
sortDF, 141 ∗Topic datagen
∗Topic array seqR, 136
165
166 INDEX
curve, 74 image, 27
inherits, 67
data, 40 insertRows, 7, 64
data.frame, 7 install.packages, 66, 73
dataStr, 40 instGit, 65
Date, 94 is.character, 52
dbeta, 12–14 is.error, 66
decompose, 98
density, 33 kge (gof), 57
distance, 40
divPal, 41, 135, 137 l2array, 67, 70
dnorm, 111 l2df, 68, 69
dupes, 36, 43 legend, 44–46, 49, 72, 80, 81, 102, 113
legendmt, 72
edit, 53 letters, 107, 164
eval.parent, 118 library, 73
example, 48 library2, 73
exp4p, 44, 101 lim0, 74
expReg, 45, 81 lines, 12, 100, 111, 132, 141
extendrange, 74, 136 linLogHist, 75, 77, 144
exTime, 47 linLogTrans, 76, 77
linReg, 47, 80
file.exists, 16, 109
lm, 45, 47, 58, 80, 81, 103
filter, 98
locArrow, 82
findInterval, 15
locator, 82, 83
format, 84, 88, 89
locLine, 82, 83
formatC, 128
loess, 98
funnelPlot, 48
log, 87, 88
funSource, 9, 38, 51, 66
log10, 85, 87, 89
funTinn, 53
logAxis, 46, 76, 84, 86, 89, 131
getColumn, 53 logHist, 86
getElement, 54 logical, 152
getName, 55 logSpaced, 22, 87, 135
getwd, 115 logVals, 75, 77, 78, 84, 85, 88, 121
glm, 103 ls, 93
gof, 57 lsc, 90, 146, 162
gofNA (gof), 57 lsMem, 93
googleLink2pdf, 59
matrix, 7
groupHist, 60, 116
mean, 121, 122
gsub, 37, 59, 126
median, 121, 122
head, 36, 61, 62 message, 40, 47, 67, 73, 113, 158, 159
headtail, 61 min, 15
heatmap, 148 model.frame, 101
help, 47, 68 monthAxis, 94, 131
hist, 31, 60, 61, 63, 64, 75, 76, 86 monthLabs, 95, 96, 154
horizHist, 62 movAv, 97, 99, 100, 121
movAvLines, 99
iconv, 37 mReg, 45, 47, 81, 100
INDEX 169
suppressWarnings, 48
symbols, 21
Syntax, 152
Sys.sleep, 75, 77, 144, 156
system.time, 48
system2, 9, 38, 112
t.test, 17, 18
tableColVal, 147
tail, 61
tapply, 60, 61
tempfile, 47
text, 33, 122, 147–150
textField, 14, 130, 132, 149
TFtest, 151
timeAxis, 95, 97, 153
timer, 155
title, 133, 138
toupper, 156, 157
toupper1, 156
traceback, 157
traceCall, 157, 160
truncMessage, 158
try, 67, 159, 160
tryCatch, 159
tryStack, 157, 159
txtProgressBar, 156
View, 11, 12
xy.coords, 46, 81