| Title: | Dendrochronology Program Library in R |
|---|---|
| Description: | Perform tree-ring analyses such as detrending, chronology building, and cross dating. Read and write standard file formats used in dendrochronology. |
| Authors: | Andy Bunn [aut, cph, cre, trl], Mikko Korpela [aut, cph, trl], Franco Biondi [aut, cph], Filipe Campelo [aut, cph], Stefan Klesse [aut, cph], Pierre Mérian [aut, cph], Fares Qeadan [aut, cph], Christian Zang [aut, cph], Allan Buras [ctb], Alice Cecile [ctb], Manfred Mudelsee [ctb], Michael Schulz [ctb], David Frank [ctb], Ronald Visser [ctb], Ed Cook [ctb], Kevin Anchukaitis [ctb] |
| Maintainer: | Andy Bunn <bunna@wwu.edu> |
| License: | GPL (>= 2) |
| Version: | 1.8.1 |
| Built: | 2026-10-13 23:28:07 UTC |
| Source: | https://github.com/opendendro/dplr |
This package contains functions for performing some standard tree-ring analyses.
| Package: | dplR |
| Type: | Package |
| License: | GPL (>= 2) |
Main Functions
read.rwlreads rwl files
detrenddetrends raw ring widths
chronbuilds chronologies
corr.rwl.segcrossdating function
Andy Bunn andy.bunn@wwu.edu with major additions from Mikko
Korpela and other significant contributions from Franco Biondi, Filipe
Campelo, Pierre Mérian, Fares Qeadan and Christian
Zang. Function redfit is an improved translation of
program REDFIT which is original work of Manfred Mudelsee and Michael
Schulz. Jacob Cecile contributed a bug fix to
detrend.series. Allan Buras came up with the revised
formula of glk in dplR >= 1.6.1.
Cook, E. R. and Kairiukstis, L. A., editors (1990) Methods of Dendrochronology: Applications in the Environmental Sciences. Springer. ISBN-13: 978-0-7923-0586-6.
Fritts, H. C. (2001) Tree Rings and Climate. Blackburn. ISBN-13: 978-1-930665-39-2.
Applies an age-dependent smoothing spline to y.
ads(y, nyrs0 = 50, pos.slope = TRUE)ads(y, nyrs0 = 50, pos.slope = TRUE)
y |
a |
nyrs0 |
a number greater than one, affecting the rigidity of the
initial spline. A larger |
pos.slope |
a |
This implements the age-dependent smoothing spline similar to that described by Melvin (2004). In this implementation a cubic smoothing spline (caps) is fit to y with an initial stiffness of nyrs0. For each succesive measurement, the siffness is incremented by that ring index. This results in a spline is nyrs0 flexible at the start of the series and grows progressively stiffer. This can help capture the initial fast growth of a juvinielle tree with a flexible spline that then progresses to a stiffer spline that can better model the constant growth commonly found in mature trees. In its details, the cubic smoothing spline follows the Cook and Peters (1981) spline with a 50% frequency cutoff. See Cook and Kairiukstis (1990) for more information.
The default setting for nyrs0 is 50 years which is approprite for trees with a classic growth model but a value of 10 or 20 might be more appropriate for a Hugershoff-like initial increase in growth. Cook (pers comm) suggests a value of 20 for RCS.
If pos.slope is FALSE, the function will attempt to prevent a positive slope at the end of the series. In some cases when ads is used for detrending, a positive slope can be considered biologically unlikely. In those cases, the user can constrain the positive slope in the spline. This works by calculating the spline and taking the first difference. Then the function finds the last (outside) index where the spline changes slope and fixes the spline values from the that point to the end. Finally the spline is rerun along this constrained curve. See examples for details. The wisdom of constraining the slope in this manner depends very much on expert knowledge of the system.
A filtered vector.
Fortran code provided by Ed Cook. Ported and adapted for dplR by Andy Bunn.
Cook, E. R. and Kairiukstis, L. A., editors (1990) Methods of Dendrochronology: Applications in the Environmental Sciences. Springer. ISBN-13: 978-0-7923-0586-6.
Melvin, T. M. (2004) Historical Growth Rates and Changing Climatic Sensitivity of Boreal Conifers. PhD Thesis, Climatic Research Unit, School of Environmental Sciences, University of East Anglia.
Cook, E. R. and Peters, K. (1981) The Smoothing Spline: A New Approach to Standardizing Forest Interior Tree-Ring Width Series for Dendroclimatic Studies. Tree-Ring Bulletin, 41, 45-53.
# fit a curve data(co021) aSeries <- na.omit(co021$`641114`) plot(aSeries,type="l",col="grey50") lines(ads(y = aSeries),col="blue",lwd=2) # show an artificial series with a Hugershoff-like curve. a <- 0.5 b <- 1 g <- 0.1 d <- 0.25 n <- 300 x <- 1:n y <- I(a*x^b*exp(-g*x)+d) # add some noise y <- y + runif(n=length(y),min = 0,max = 0.5) # Plot with two different splines. plot(y,type="l",col="grey50") lines(ads(y,50),col="darkgreen",lwd=2) # bad lines(ads(y,10),col="darkblue",lwd=2) # good # now repeat with a positive slope to constrain y <- I(a*x^b*exp(-g*x)+d) y[251:300] <- y[251:300] + seq(0,0.25,length.out=50) y <- y + runif(n=length(y),min = 0,max = 0.5) plot(y,type="l",col="grey50") lines(ads(y,10),col="darkgreen",lwd=2) #bad? lines(ads(y,10,pos.slope=FALSE),col="darkgreen",lwd=2,lty="dashed")# fit a curve data(co021) aSeries <- na.omit(co021$`641114`) plot(aSeries,type="l",col="grey50") lines(ads(y = aSeries),col="blue",lwd=2) # show an artificial series with a Hugershoff-like curve. a <- 0.5 b <- 1 g <- 0.1 d <- 0.25 n <- 300 x <- 1:n y <- I(a*x^b*exp(-g*x)+d) # add some noise y <- y + runif(n=length(y),min = 0,max = 0.5) # Plot with two different splines. plot(y,type="l",col="grey50") lines(ads(y,50),col="darkgreen",lwd=2) # bad lines(ads(y,10),col="darkblue",lwd=2) # good # now repeat with a positive slope to constrain y <- I(a*x^b*exp(-g*x)+d) y[251:300] <- y[251:300] + seq(0,0.25,length.out=50) y <- y + runif(n=length(y),min = 0,max = 0.5) plot(y,type="l",col="grey50") lines(ads(y,10),col="darkgreen",lwd=2) #bad? lines(ads(y,10,pos.slope=FALSE),col="darkgreen",lwd=2,lty="dashed")
This data set gives the raw ring widths for Norway spruce Picea
abies at Rothenburg ob der Tauber, Bavaria, Germany. There are 20
series from 10 trees. Data set was created using
read.rwl and saved to an .rda file using
save.
data(anos1)data(anos1)
A data.frame containing 20 tree-ring series from 10 trees
in columns and 98 years in rows. The correct stc mask for use with
read.ids is c(5, 2, 1).
Zang, C. (2010) Growth reaction of temperate forest tree species to summer drought – a multispecies tree-ring network approach. Ph.D. thesis, Technische Universität München.
Class "bai" holds basal area increment: the area of each ring,
with one series per column and one year per row, as made by
bai.in and bai.out. as.bai labels
a data.frame or matrix of ring areas as one.
as.bai(x) ## S3 method for class 'bai' x[i, j, drop] ## S3 method for class 'bai' subset(x, subset, select, drop = FALSE, ...) ## S3 method for class 'bai' time(x, ...) ## S3 method for class 'bai' summary(object, ...) ## S3 method for class 'bai' plot(x, plot.type = c("seg", "spag"), ...)as.bai(x) ## S3 method for class 'bai' x[i, j, drop] ## S3 method for class 'bai' subset(x, subset, select, drop = FALSE, ...) ## S3 method for class 'bai' time(x, ...) ## S3 method for class 'bai' summary(object, ...) ## S3 method for class 'bai' plot(x, plot.type = c("seg", "spag"), ...)
x, object
|
for |
i, j, subset, select, drop
|
as for |
plot.type |
|
... |
for |
A "bai" object has the same shape as an "rwl" object and
makes the same promise: the row names are the years, consecutive and
increasing. It inherits from neither "rwl" nor "rwi",
so that areas, widths and indices can be told apart.
dplR's functions use the class to check what they are given. Those
that want ring-width indices, such as chron and
rwi.stats, take a "bai" object without a word:
a mean of basal area increment by year is a BAI chronology.
So do the crossdating functions, the plots,
common.interval, and detrend, since
fitting a curve to basal area increment is established practice.
Functions that want ring widths, such as bai.in,
rcs, cms and rwl.report,
warn and treat the areas as widths. If the values really are widths,
relabel them with as.rwl.
Two attributes travel with it. attr(x, "dplR.bai") says how
the areas were made: the function (fun) and whether the
distance to pith (d2pith, for bai.in) or the diameters
(diam, for bai.out) were given rather than estimated
from the widths. attr(x, "dplR.provenance") is the provenance
record of the ring widths the areas were made from, if they had one
(see read.tucson). Neither is set by as.bai,
which only labels the object.
Subsetting works as for "rwl" objects ([.rwl),
and window takes a span of years
(window.rwl). summary gives the per-series
statistics of rwl.stats, in the units of the areas.
as.bai: an object of class c("bai", "data.frame").
x is returned unchanged if it already has that class.
time: a numeric vector of years.
summary: a data.frame, as from rwl.stats.
Andy Bunn
bai.in, bai.out,
as.rwl, as.rwi, chron
library(utils) data(gp.rwl) data(gp.d2pith) gp.bai <- bai.in(rwl = gp.rwl, d2pith = gp.d2pith) class(gp.bai) str(attr(gp.bai, "dplR.bai")) head(summary(gp.bai)) ## A BAI chronology gp.bai.crn <- chron(gp.bai) plot(gp.bai.crn, add.spline = TRUE, nyrs = 32) plot(gp.bai[, 1:5])library(utils) data(gp.rwl) data(gp.d2pith) gp.bai <- bai.in(rwl = gp.rwl, d2pith = gp.d2pith) class(gp.bai) str(attr(gp.bai, "dplR.bai")) head(summary(gp.bai)) ## A BAI chronology gp.bai.crn <- chron(gp.bai) plot(gp.bai.crn, add.spline = TRUE, nyrs = 32) plot(gp.bai[, 1:5])
Class "rwi" holds ring-width indices: detrended series with one
series per column and one year per row, as made by
detrend, rcs and cms.
as.rwi labels a data.frame or matrix of indices
as one.
as.rwi(x) ## S3 method for class 'rwi' x[i, j, drop] ## S3 method for class 'rwi' subset(x, subset, select, drop = FALSE, ...) ## S3 method for class 'rwi' time(x, ...) ## S3 method for class 'rwi' summary(object, ids = NULL, pcrit = 0.05, ...) ## S3 method for class 'summary.rwi' print(x, max.print = 10, ...) ## S3 method for class 'summary.rwi' as.data.frame(x, ...) ## S3 method for class 'rwi' plot(x, plot.type = c("spag", "seg", "image"), ...)as.rwi(x) ## S3 method for class 'rwi' x[i, j, drop] ## S3 method for class 'rwi' subset(x, subset, select, drop = FALSE, ...) ## S3 method for class 'rwi' time(x, ...) ## S3 method for class 'rwi' summary(object, ids = NULL, pcrit = 0.05, ...) ## S3 method for class 'summary.rwi' print(x, max.print = 10, ...) ## S3 method for class 'summary.rwi' as.data.frame(x, ...) ## S3 method for class 'rwi' plot(x, plot.type = c("spag", "seg", "image"), ...)
x, object
|
for |
ids |
an optional |
pcrit |
the significance level below which a series is taken to correlate with the others. |
max.print |
the most series to list as not correlating. |
i, j, subset, select, drop
|
as for |
plot.type |
|
... |
for |
An "rwi" object has the same shape as an "rwl" object
and makes the same promise: the row names are the years, consecutive
and increasing. It does not inherit from "rwl", so that
indices and ring widths can be told apart.
dplR's functions use the class to check what they are given. Those
that want ring widths – detrend, rcs,
cms, i.detrend, bai.in,
bai.out, pointer,
strip.rwl, ssf and
rwl.report – warn when given an "rwi" object,
and say what goes wrong: detrend on indices, for instance,
divides out a growth curve that has already been removed. Those that
want indices – chron, chron.ars,
chron.stabilized, rwi.stats,
rwi.stats.running and sss – warn when
given an "rwl" object: rwi.stats(ca533) gives an
rbar.eff of 0.350 from the widths against 0.423 from the
Spline indices, and nothing about the number says it is wrong. They
still take a plain data.frame or matrix without a word, and a
"bai" object of basal area increment (see
as.bai). The
crossdating functions, the plots, common.interval,
sgc and rwl.stats take either class
quietly. Each warning is only a warning, and the function goes on:
if the class is what is wrong – indices read from a file with
read.rwl come back as class "rwl" – relabel
them with as.rwi, or relabel widths with as.rwl.
Two attributes travel with it. attr(x, "dplR.detrend") is a
list that says how the indices were made: the function
(fun), the method and its settings, and always
difference, which is TRUE when the indices are
differences from the fitted curve (centred on 0) rather than ratios
(centred on 1). attr(x, "dplR.provenance") is the provenance
record of the ring widths the indices were made from, if they had one
(see read.tucson). Neither is set by as.rwi,
which only labels the object.
Subsetting works as for "rwl" objects ([.rwl):
the class and both records are kept, dropping series trims the years
that none of the remaining series cover, and a row subset that leaves
the years out of order or with holes returns a plain
data.frame, with a warning. subset and
window.rwi drop series left with no values and name
them in a message; [ keeps them, on purpose, so that its
columns stay lined up with anything indexed alongside them.
summary describes the indices as a collection. It gives how
they were made (from attr(x, "dplR.detrend")), their span and
common interval, the collection statistics from
rwi.stats (including rbar.eff, EPS and SNR), and for
each series its first and last years, length, mean, standard
deviation, first-order autocorrelation, and its correlation with the
mean of the other series, with the p-value, from
interseries.cor with its defaults. Printing it shows
the collection and lists the series that do not correlate with the
others at pcrit; as.data.frame gives the per-series
table. The collection statistics count each series as its own tree
unless ids is given, and the print says which. The print ends
by pointing to summary with ids (when it was not
given),
rwi.stats.running (rbar and EPS through time, which
usually fall off where sample depth does) and
corr.rwl.seg (where in a series the fit breaks down).
A series with no values at all is listed and left out of the
collection statistics, the correlations and the common interval. With
fewer than two series with values there is no collection, and the
statistics and correlations are NULL and NA.
plot draws, by default, spag.plot, which draws
indices around 1 (or 0 for differences) and not around each series'
mean, so the grey line under each series is the value the indices
should sit at. plot.type = "image" draws each index as a
coloured cell, with years across and series down, earliest-starting
at the bottom. Colours are brown below 1 (or 0) and green above it.
Each side is scaled separately and clipped at the clip
quantile of its departures, since ratio indices cannot fall below 0
but can run well above 2; the key gives the clips. A run of one
colour at the start or end of a series is a growth trend the
detrending did not remove, and a vertical stripe is a year the series
agree on.
Arithmetic on an "rwi" object (e.g. x + 1) returns a
plain data.frame, as it does for any data.frame
subclass. Use as.rwi on the result if it is still a set of
indices.
as.rwi: an object of class c("rwi", "data.frame").
x is returned unchanged if it already has that class.
time: a numeric vector of years.
summary: an object of class "summary.rwi", a list with
how (the dplR.detrend record), n.series,
first, last, common (the first and last years
in which every series has a value, or NA), stats (from
rwi.stats), ids.given, empty (the names of series with no values),
series (the per-series data.frame)
and pcrit.
Andy Bunn
detrend, rcs, cms,
as.rwl, chron, rwi.stats
library(utils) data(ca533) ca533.rwi <- detrend(ca533, method = "Spline") class(ca533.rwi) str(attr(ca533.rwi, "dplR.detrend")) summary(ca533.rwi) ## Group cores by tree, from the series IDs summary(ca533.rwi, ids = autoread.ids(ca533)) head(as.data.frame(summary(ca533.rwi))) plot(ca533.rwi[, 1:5]) data(co021) ## The growth trend "Mean" leaves in: a run of green at the start of ## nearly every series. plot(detrend(co021, method = "Mean"), plot.type = "image")library(utils) data(ca533) ca533.rwi <- detrend(ca533, method = "Spline") class(ca533.rwi) str(attr(ca533.rwi, "dplR.detrend")) summary(ca533.rwi) ## Group cores by tree, from the series IDs summary(ca533.rwi, ids = autoread.ids(ca533)) head(as.data.frame(summary(ca533.rwi))) plot(ca533.rwi[, 1:5]) data(co021) ## The growth trend "Mean" leaves in: a run of green at the start of ## nearly every series. plot(detrend(co021, method = "Mean"), plot.type = "image")
Attempts to turn its argument into a rwl object.
as.rwl(x)as.rwl(x)
x |
a |
This tries to coerce x into class c("rwl","data.frame"). Failable.
An object of class c("rwl", "data.frame") with the series in
columns and the years as rows. The series IDs are the
column names and the years are the row names.
Andy Bunn. Patched and improved by Mikko Korpela.
library(graphics) library(stats) library(utils) ## Toy n <- 100 ## Make a data.frame that is tree-ring like base.series <- 0.75 + exp(-0.2 * 1:n) foo <- data.frame(x1 = base.series + abs(rnorm(n, 0, 0.25)), x2 = base.series + abs(rnorm(n, 0, 0.25)), x3 = base.series + abs(rnorm(n, 0, 0.25)), x4 = base.series + abs(rnorm(n, 0, 0.25)), x5 = base.series + abs(rnorm(n, 0, 0.25)), x6 = base.series + abs(rnorm(n, 0, 0.25))) # coerce to rwl and use plot and summary methods foo <- as.rwl(foo) class(foo) plot(foo, plot.type="spag") summary(foo)library(graphics) library(stats) library(utils) ## Toy n <- 100 ## Make a data.frame that is tree-ring like base.series <- 0.75 + exp(-0.2 * 1:n) foo <- data.frame(x1 = base.series + abs(rnorm(n, 0, 0.25)), x2 = base.series + abs(rnorm(n, 0, 0.25)), x3 = base.series + abs(rnorm(n, 0, 0.25)), x4 = base.series + abs(rnorm(n, 0, 0.25)), x5 = base.series + abs(rnorm(n, 0, 0.25)), x6 = base.series + abs(rnorm(n, 0, 0.25))) # coerce to rwl and use plot and summary methods foo <- as.rwl(foo) class(foo) plot(foo, plot.type="spag") summary(foo)
Convert multiple ring-width series to basal area increment (i.e., ring area) going from the pith to the bark.
bai.in(rwl, d2pith = NULL)bai.in(rwl, d2pith = NULL)
rwl |
a |
d2pith |
an optional |
This converts ring-width series (mm) to ring-area series (mm squared)
(aka basal area increments) based on the distance between the
innermost measured ring and the pith of the tree. It is related to
bai.out, which calculates each ring area starting from
the outside of the tree and working inward. Both methods assume a
circular cross section (Biondi 1999). See the references below for
further details.
An object of class c("bai", "data.frame") containing the ring
areas for each series with the column names, row names and dimensions
of rwl. It carries the provenance record of
rwl, if it has one, and records how it was made in
attr(x, "dplR.bai"): the function (fun) and whether
d2pith was given (d2pith). See as.bai
for which functions take it.
DendroLab website: https://dendrolaborg.wordpress.com/
Code by Andy Bunn based on work from DendroLab, University of Nevada Reno, USA. Patched and improved by Mikko Korpela.
Biondi, F. (1999) Comparing tree-ring chronologies and repeated timber inventories as forest monitoring tools. Ecological Applications, 9(1), 216–227.
Biondi, F. and Qeadan, F. (2008) A theory-driven approach to tree-ring standardization: Defining the biological trend from expected basal area increment. Tree-Ring Research, 64(2), 81–96.
library(graphics) library(stats) library(utils) ## Toy n <- 100 ## Make three fake tree-ring series to show that these funcs work on rwl objects base.series <- 0.75 + exp(-0.2 * 1:n) rwl <- data.frame(x1 = base.series + abs(rnorm(n, 0, 0.05)), x2 = base.series + abs(rnorm(n, 0, 0.05)), x3 = base.series + abs(rnorm(n, 0, 0.05))) ## The inside out method foo <- bai.in(rwl = rwl) ## The outside in method bar <- bai.out(rwl = rwl) ## Identical head(bar) head(foo) ## Use gp data data(gp.rwl) data(gp.d2pith) foo <- bai.in(rwl = gp.rwl, d2pith = gp.d2pith) foo.crn <- chron(foo) yrs <- time(foo.crn) plot(yrs, foo.crn[, 1], type = "n", xlab = "Year", ylab = expression(mm^2)) lines(yrs, foo.crn[, 1], col = "grey", lty = "dashed") lines(yrs, caps(foo.crn[, 1], nyrs = 32), col = "red", lwd = 2)library(graphics) library(stats) library(utils) ## Toy n <- 100 ## Make three fake tree-ring series to show that these funcs work on rwl objects base.series <- 0.75 + exp(-0.2 * 1:n) rwl <- data.frame(x1 = base.series + abs(rnorm(n, 0, 0.05)), x2 = base.series + abs(rnorm(n, 0, 0.05)), x3 = base.series + abs(rnorm(n, 0, 0.05))) ## The inside out method foo <- bai.in(rwl = rwl) ## The outside in method bar <- bai.out(rwl = rwl) ## Identical head(bar) head(foo) ## Use gp data data(gp.rwl) data(gp.d2pith) foo <- bai.in(rwl = gp.rwl, d2pith = gp.d2pith) foo.crn <- chron(foo) yrs <- time(foo.crn) plot(yrs, foo.crn[, 1], type = "n", xlab = "Year", ylab = expression(mm^2)) lines(yrs, foo.crn[, 1], col = "grey", lty = "dashed") lines(yrs, caps(foo.crn[, 1], nyrs = 32), col = "red", lwd = 2)
Convert multiple ring-width series to basal area increment (i.e., ring area) going from the bark to the pith.
bai.out(rwl, diam = NULL)bai.out(rwl, diam = NULL)
rwl |
a |
diam |
an optional |
This converts ring-width series (mm) to ring-area series (mm squared)
(aka basal area increments) based on the diameter of the tree and the
width of each ring moving towards the pith of the tree. It is related
to bai.in, which calculates each ring area starting from
the inside of the tree and working outward. Both methods assume a
circular cross section (Biondi 1999). See the references below for
further details.
An object of class c("bai", "data.frame") containing the ring
areas for each series with the column names, row names and dimensions
of rwl. It carries the provenance record of
rwl, if it has one, and records how it was made in
attr(x, "dplR.bai"): the function (fun) and whether
diam was given (diam). See as.bai
for which functions take it.
DendroLab website: https://dendrolaborg.wordpress.com/
Code by Andy Bunn based on work from DendroLab, University of Nevada Reno, USA. Patched and improved by Mikko Korpela.
Biondi, F. (1999) Comparing tree-ring chronologies and repeated timber inventories as forest monitoring tools. Ecological Applications, 9(1), 216–227.
Biondi, F. and Qeadan, F. (2008) A theory-driven approach to tree-ring standardization: Defining the biological trend from expected basal area increment. Tree-Ring Research, 64(2), 81–96.
library(graphics) library(utils) ## Not run: library(stats) ## Toy n <- 100 ## Make three fake tree-ring series to show that these funcs work on rwl objects base.series <- 0.75 + exp(-0.2 * 1:n) rwl <- data.frame(x1 = base.series + abs(rnorm(n, 0, 0.05)), x2 = base.series + abs(rnorm(n, 0, 0.05)), x3 = base.series + abs(rnorm(n, 0, 0.05))) ## The inside out method foo <- bai.in(rwl = rwl) ## The outside in method bar <- bai.out(rwl = rwl) ## Identical head(bar) head(foo) ## End(Not run) ## Use gp data data(gp.rwl) data(gp.dbh) ## dbh (minus the bark) from cm to mm gp.dbh2 <- gp.dbh[, 1:2] gp.dbh2[, 2] <- (gp.dbh[, 2] - gp.dbh[, 3]) * 10 bar <- bai.out(rwl = gp.rwl, diam = gp.dbh2) bar.crn <- chron(bar) yrs <- time(bar.crn) plot(yrs, bar.crn[, 1], type = "n", xlab = "Year", ylab = expression(mm^2)) lines(yrs, bar.crn[, 1], col = "grey", lty = "dashed") lines(yrs, caps(bar.crn[, 1], nyrs = 32), col = "red", lwd = 2)library(graphics) library(utils) ## Not run: library(stats) ## Toy n <- 100 ## Make three fake tree-ring series to show that these funcs work on rwl objects base.series <- 0.75 + exp(-0.2 * 1:n) rwl <- data.frame(x1 = base.series + abs(rnorm(n, 0, 0.05)), x2 = base.series + abs(rnorm(n, 0, 0.05)), x3 = base.series + abs(rnorm(n, 0, 0.05))) ## The inside out method foo <- bai.in(rwl = rwl) ## The outside in method bar <- bai.out(rwl = rwl) ## Identical head(bar) head(foo) ## End(Not run) ## Use gp data data(gp.rwl) data(gp.dbh) ## dbh (minus the bark) from cm to mm gp.dbh2 <- gp.dbh[, 1:2] gp.dbh2[, 2] <- (gp.dbh[, 2] - gp.dbh[, 3]) * 10 bar <- bai.out(rwl = gp.rwl, diam = gp.dbh2) bar.crn <- chron(bar) yrs <- time(bar.crn) plot(yrs, bar.crn[, 1], type = "n", xlab = "Year", ylab = expression(mm^2)) lines(yrs, bar.crn[, 1], col = "grey", lty = "dashed") lines(yrs, caps(bar.crn[, 1], nyrs = 32), col = "red", lwd = 2)
Convert multiple ring-width series to basal area increment (i.e., ring area) following the proportional method of Bakker (2005).
bakker(rwl, ancillary)bakker(rwl, ancillary)
rwl |
a |
ancillary |
A |
This converts ring-width series (mm) to ring-area series (mm squared) (aka basal area increments) based on the diameter of the tree, the missing distance to the pith and the missing number of rings to the pith, following the proportional method for reconstructing historical tree diameters by Bakker (2005).
It prevents bai.out transformations from producing negative increments when the sum of all ring widths in a series is larger than DBH/2. It prevents bai.in transformations from producing too small values when the sum of all ring widths in a series is smaller than DBH/2.
A list containing the following objects:
DBHhist_raw |
|
baiBakker_raw |
|
Code by Stefan Klesse. Adapted for dplR by Andy Bunn.
Bakker, J.D., 2005. A new, proportional method for reconstructing historical tree diameters. Canadian Journal of Forest Research 35, 2515–2520. https://doi.org/10.1139/x05-136
data(zof.rwl) data(zof.anc) zof.bakker <- bakker(rwl = zof.rwl,ancillary = zof.anc) zof.bai <- zof.bakker$baiBakker_raw # first series bai yrs <- time(zof.rwl) plot(yrs,zof.bai[,1],type="l", xlab="Year", ylab=expression(BAI~(mm^2)), main = colnames(zof.bai)[1])data(zof.rwl) data(zof.anc) zof.bakker <- bakker(rwl = zof.rwl,ancillary = zof.anc) zof.bai <- zof.bakker$baiBakker_raw # first series bai yrs <- time(zof.rwl) plot(yrs,zof.bai[,1],type="l", xlab="Year", ylab=expression(BAI~(mm^2)), main = colnames(zof.bai)[1])
This data set gives the raw ring widths for bristlecone pine
Pinus longaeva at Campito Mountain in California,
USA. There are 34 series. Data set was created using
read.rwl and saved to an .rda file using
save.
data(ca533)data(ca533)
A data.frame containing 34 tree-ring series in columns and 1358
years in rows.
International tree-ring data bank, Accessed on 20-April-2021 at https://www.ncei.noaa.gov/pub/data/paleo/treering/measurements/northamerica/usa/ca533.rwl
Graybill, D. A. and LaMarche, Jr., V. C. (1983) Campito Mountain Data Set. IGBP PAGES/World Data Center for Paleoclimatology Data Contribution Series 1983-CA533.RWL. NOAA/NCDC Paleoclimatology Program, Boulder, Colorado, USA.
library(utils) data(ca533) ## Where the data came from. read.tucson() records what it saw and attaches ## it to what it returns; this data set carries that record. prov <- attr(ca533, "dplR.provenance") prov$file # the archived file it was read from prov$precision # the precision each series was measured at prov$gaps # interior gaps, if any -- this file has none prov$events # problems found while reading -- none here either ## rwl.report() puts the file and precision at the head of its report rwl.report(ca533)library(utils) data(ca533) ## Where the data came from. read.tucson() records what it saw and attaches ## it to what it returns; this data set carries that record. prov <- attr(ca533, "dplR.provenance") prov$file # the archived file it was read from prov$precision # the precision each series was measured at prov$gaps # interior gaps, if any -- this file has none prov$events # problems found while reading -- none here either ## rwl.report() puts the file and precision at the head of its report rwl.report(ca533)
This data set gives the standard chronology for white spruce
Picea glauca at Twisted Tree Heartrot Hill in Yukon,
Canada. Data set was created using read.crn and saved to
an .rda file using save.
data(cana157)data(cana157)
A data.frame containing the standard chronology in column one
and the sample depth in column two. There are 463 years
(1530–1992) in the rows.
International tree-ring data bank, Accessed on 20-April-2021 at https://www.ncei.noaa.gov/pub/data/paleo/treering/chronologies/northamerica/canada/cana157.crn
Jacoby, G., D’Arrigo, R. and Buckley, B. (1992) Twisted Tree Heartrot Hill Data Set. IGBP PAGES/World Data Center for Paleoclimatology Data Contribution Series 1992-CANA157.CRN. NOAA/NCDC Paleoclimatology Program, Boulder, Colorado, USA.
Applies a smoothing spline to y with rigidity determined
by two parameters: frequency response f at a wavelength
of nyrs years.
caps(y, nyrs = 32, f = 0.5)caps(y, nyrs = 32, f = 0.5)
y |
a |
nyrs |
a number greater than zero, affecting the rigidity of the spline. If |
f |
a number between 0 and 1 giving the frequency response at a wavelength of |
This applies the classic smoothing spline from Cook and Peters (1981). The rigidity of the spline has a frequency response of 50% at a wavelength of nyrs. The references, of course, have more information.
This function was introduced to dplR in version 1.7.3 and replaces the now defunct ffcsaps. Where ffcsaps was written entirely in R, caps is a wrapper for a Fortran subroutine from Ed Cook's ARSTAN program that is hundreds of times faster.
The default value of nyrs was changed to 32 from 2/3 length of y in version 1.7.8 based on a suggestion from Klesse (2021).
Note: nyrs is passed to the Fortran subroutine as an
integer, so a fractional nyrs is truncated. This matters
when nyrs is given as a proportion of series length, which
is rarely a whole number. The effect on the fitted curve is small but not
zero; see the “Mathematical Details” vignette for a worked
comparison.
Note: caps stops if there are any NA values in y. A smoothing spline through a series with missing values is not defined, and the caller has to decide what to do about the gap rather than have one chosen silently. Before version 1.8.0 such a call returned a vector of NA, which looked like an answer and was not. See examples, and fill.internal.NA.
A filtered vector.
The mathematical relationship between nyrs,
f and the spline's smoothing parameter, together with an
empirical check of the frequency response and a demonstration that
caps reproduces the deprecated ffcsaps, is
given in the vignette: vignette("math-dplR", package = "dplR").
Fortran code provided by Ed Cook and adapted for dplR by Andy Bunn.
Cook, E. R. and Kairiukstis, L. A., editors (1990) Methods of Dendrochronology: Applications in the Environmental Sciences. Springer. ISBN-13: 978-0-7923-0586-6.
Cook, E. R. and Peters, K. (1981) The Smoothing Spline: A New Approach to Standardizing Forest Interior Tree-Ring Width Series for Dendroclimatic Studies. Tree-Ring Bulletin, 41, 45-53.
Klesse, S. (2021) Critical Note on the Application of the "Two-Third"" Spline. Dendrochronologia Volume 65: 125786
library(graphics) library(utils) ## Use first series from the Mesa Verde data set data(co021) series <- co021[, 1] series <- series[!is.na(series)] plot(series, type = "l", ylab = "Ring Width (mm)", col = "grey") lines(caps(series, nyrs = 10), col = "red", lwd = 2) lines(caps(series, nyrs = 100), col = "green", lwd = 2) # The default, a 32-year spline since version 1.7.8 lines(caps(series), col = "blue", lwd = 2) legend("topright", c("Series", "nyrs=10", "nyrs=100", "Default nyrs (32)"), fill=c("grey", "red", "green", "blue")) ## caps() needs a series with no missing values. Note that the example ## above drops the NA padding before fitting. A gap inside the measured ## span has to be dealt with deliberately: drop the series, or close the ## gap with fill.internal.NA(). y <- c(NA, NA, rnorm(100)) try(caps(y)) ## fit over the measured values instead head(caps(y[!is.na(y)]))library(graphics) library(utils) ## Use first series from the Mesa Verde data set data(co021) series <- co021[, 1] series <- series[!is.na(series)] plot(series, type = "l", ylab = "Ring Width (mm)", col = "grey") lines(caps(series, nyrs = 10), col = "red", lwd = 2) lines(caps(series, nyrs = 100), col = "green", lwd = 2) # The default, a 32-year spline since version 1.7.8 lines(caps(series), col = "blue", lwd = 2) legend("topright", c("Series", "nyrs=10", "nyrs=100", "Default nyrs (32)"), fill=c("grey", "red", "green", "blue")) ## caps() needs a series with no missing values. Note that the example ## above drops the NA padding before fitting. A gap inside the measured ## span has to be dealt with deliberately: drop the series, or close the ## gap with fill.internal.NA(). y <- c(NA, NA, rnorm(100)) try(caps(y)) ## fit over the measured values instead head(caps(y[!is.na(y)]))
Computes cross-correlations between a tree-ring series and a master chronology built from a rwl object at user-specified lags and segments.
ccf.series.rwl(rwl, series, series.yrs = as.numeric(names(series)), seg.length = 50, bin.floor = 100, n = NULL, nyrs = NULL, prewhiten = TRUE, ar.order.max = NULL, biweight = TRUE, pcrit = 0.05, lag.max = 5, make.plot = TRUE, floor.plus1 = FALSE, series.x = FALSE, ...)ccf.series.rwl(rwl, series, series.yrs = as.numeric(names(series)), seg.length = 50, bin.floor = 100, n = NULL, nyrs = NULL, prewhiten = TRUE, ar.order.max = NULL, biweight = TRUE, pcrit = 0.05, lag.max = 5, make.plot = TRUE, floor.plus1 = FALSE, series.x = FALSE, ...)
rwl |
a |
series |
a |
series.yrs |
a |
seg.length |
an even integral value giving length of segments in years (e.g., 20, 50, 100 years). |
bin.floor |
a non-negative integral value giving the base for locating the first segment (e.g., 1600, 1700, 1800 AD). Typically 0, 10, 50, 100, etc. |
n |
|
nyrs |
|
prewhiten |
|
ar.order.max |
|
biweight |
|
pcrit |
a number between 0 and 1 giving the critical value for the correlation test. |
lag.max |
an integral value giving the maximum lag at which to
calculate the |
make.plot |
|
floor.plus1 |
|
series.x |
|
... |
other arguments passed to plot. |
This function calculates the cross-correlation function between a
tree-ring series and a master chronology built from rwl
looking at correlations lagged positively and negatively using
ccf at overlapping segments set by
seg.length. For instance, with lag.max set
to 5, cross-correlations would be calculated at for each segment with
the master lagged at k = -5:5 years.
The cross correlations are calculated calling
ccf as ccf(x=master, y=series, lag.max=lag.max, plot=FALSE) if series.x is
FALSE and as ccf(x=series, y=master, lag.max=lag.max, plot=FALSE) if
series.x is TRUE. This argument was introduced in dplR version 1.7.0.
Different users have different expectations about how missing or extra rings are
notated. If series.x = FALSE the behavior will be like COFECHA where a missing
ring in a series produces a negative lag in the plot rather than a positive lag.
Correlations are calculated for the first segment, then the second segment and so on. Correlations are only calculated for segments with complete overlap with the master chronology.
Each series (including those in the rwl object) is
optionally detrended as the residuals from a hanning
filter with weight n. The filter is not applied if
n is NULL. Detrending can also be done via
prewhitening where the residuals of an ar model are
added to each series mean. This is the default. The master chronology
is computed as the mean of the rwl object using
tbrm if biweight is TRUE and
rowMeans if not. Note that detrending typically changes the
length of the series. E.g., a hanning filter will
shorten the series on either end by floor(n/2). The
prewhitening default will change the series length based on the
ar model fit. The effects of detrending can be seen with
series.rwl.plot.
A list containing matrices ccf and
bins. Matrix ccf contains the correlations
between the series and the master chronology at the lags window given
by lag.max. Matrix bins contains the years
encapsulated by each bin.
Andy Bunn. Patched and improved by Mikko Korpela.
Bunn, A. G. (2010) Statistical and visual crossdating in R using the dplR library. Dendrochronologia, 28(4), 251–258.
corr.rwl.seg, corr.series.seg,
skel.plot, series.rwl.plot
library(utils) data(co021) dat <- co021 ## Create a missing ring: delete the 1500 ring of series 641143 and ## drop the original from the master. Dated from the bark, every ring ## before 1500 now sits one year late. flagged <- dat$"641143" names(flagged) <- rownames(dat) flagged <- delete.ring(flagged, year = 1500) dat$"641143" <- NULL ccf.100 <- ccf.series.rwl(rwl = dat, series = flagged, seg.length = 100) ## Not run: flagged2 <- co021$"641143" names(flagged2) <- rownames(dat) ccf.100.1 <- ccf.series.rwl(rwl = dat, seg.length = 100, series = flagged2) ## Select series by name or column position ccf.100.2 <- ccf.series.rwl(rwl = co021, seg.length = 100, series = "641143") ccf.100.3 <- ccf.series.rwl(rwl = co021, seg.length = 100, series = which(colnames(co021) == "641143")) identical(ccf.100.1, ccf.100.2) # TRUE identical(ccf.100.2, ccf.100.3) # TRUE ## End(Not run)library(utils) data(co021) dat <- co021 ## Create a missing ring: delete the 1500 ring of series 641143 and ## drop the original from the master. Dated from the bark, every ring ## before 1500 now sits one year late. flagged <- dat$"641143" names(flagged) <- rownames(dat) flagged <- delete.ring(flagged, year = 1500) dat$"641143" <- NULL ccf.100 <- ccf.series.rwl(rwl = dat, series = flagged, seg.length = 100) ## Not run: flagged2 <- co021$"641143" names(flagged2) <- rownames(dat) ccf.100.1 <- ccf.series.rwl(rwl = dat, seg.length = 100, series = flagged2) ## Select series by name or column position ccf.100.2 <- ccf.series.rwl(rwl = co021, seg.length = 100, series = "641143") ccf.100.3 <- ccf.series.rwl(rwl = co021, seg.length = 100, series = which(colnames(co021) == "641143")) identical(ccf.100.1, ccf.100.2) # TRUE identical(ccf.100.2, ccf.100.3) # TRUE ## End(Not run)
Checks that an object is a valid rwl and, if not, attempts
coercion via as.rwl. Warns about internal NA
values found within any series.
check.rwl(rwl, why = NULL, bai.ok = FALSE)check.rwl(rwl, why = NULL, bai.ok = FALSE)
rwl |
an |
why |
|
bai.ok |
logical. If |
check.rwl is for functions that want ring widths. If
rwl is an "rwi" object of ring-width indices (see
as.rwi), a warning names the calling function, says
that it wants widths, adds why, and suggests
as.rwl if the values really are widths. The object is
then relabelled as class "rwl" and checked as below. A
"bai" object of basal area increment (see as.bai)
is treated the same way, unless bai.ok is TRUE, when it
is relabelled without a warning.
If rwl is not already of class "rwl", coercion is
attempted using as.rwl. If coercion succeeds, a warning
is issued. If coercion fails (e.g., because row names are not
consecutive integers, columns are not numeric, or the input is not a
data.frame or matrix), the function stops with a single
informative message that describes both the class problem and the
reason coercion failed.
After class validation, each series is checked for internal
NA values, defined as NA values that are sandwiched
between non-NA values within a series (as opposed to leading
or trailing NAs, which are standard in rwl objects).
If any are found, a warning names the affected series and suggests
fill.internal.NA.
This function is called at the top of the dplR functions that want
ring widths, providing uniform validation across the package.
Functions that take widths or indices alike, and those that want
indices, use internal checks of their own (see as.rwi).
An object of class c("rwl", "data.frame") with series in
columns and years as row names. The series IDs are the
column names. The returned object is identical to the input when the
input is already a valid rwl.
Andy Bunn
as.rwl, as.rwi, read.rwl,
fill.internal.NA
library(utils) data(ca533) ## A proper rwl passes silently and is returned unchanged ca533.checked <- check.rwl(ca533) identical(ca533, ca533.checked) ## A plain data.frame is coerced with a warning. ## suppressWarnings() is used here to keep R CMD check clean since the ## warning is expected. Remove it to see the coercion warning. ca533.df <- ca533 class(ca533.df) <- "data.frame" ca533.rwl <- suppressWarnings(check.rwl(ca533.df)) #ca533.rwl <- check.rwl(ca533.df) class(ca533.rwl)library(utils) data(ca533) ## A proper rwl passes silently and is returned unchanged ca533.checked <- check.rwl(ca533) identical(ca533, ca533.checked) ## A plain data.frame is coerced with a warning. ## suppressWarnings() is used here to keep R CMD check clean since the ## warning is expected. Remove it to see the coercion warning. ca533.df <- ca533 class(ca533.df) <- "data.frame" ca533.rwl <- suppressWarnings(check.rwl(ca533.df)) #ca533.rwl <- check.rwl(ca533.df) class(ca533.rwl)
This function builds a mean value chronology, typically from a
data.frame of detrended ring widths as produced by
detrend.
chron(rwi, biweight = TRUE, prewhiten = FALSE, ...)chron(rwi, biweight = TRUE, prewhiten = FALSE, ...)
rwi |
a |
biweight |
|
prewhiten |
|
... |
Arguments passed to |
This either averages the rows of the data.frame using a mean or
a robust mean (the so-called standard chronology) or can do so from
the residuals of an AR process (the residual chronology).
The residual chronology here is the mean of series that were each
whitened with their own AR model, the order chosen for each series by
ar. Each whitened series is free of autocorrelation but
their mean need not be. Where much of the persistence belongs to the
individual trees and is not shared among them, whitening each series
removes more than the series have in common, and the residual
chronology comes out negatively autocorrelated. For wa082
detrended with a spline its lag-one autocorrelation is about -0.2. It
is worth checking, for example with acf.
The residual chronology from chron.ars is built
differently and will not have the same values. It uses one AR order
for all the series, taken from a pooled model, and whitens the mean a
second time, which removes the autocorrelation that averaging leaves
behind. Use it when the residual chronology from this function is not
close to white.
An object of of class crn and data.frame with the standard chronology, residual chronology (if prewhitening was performed), and the sample depth. The years are stored as row numbers.
Andy Bunn. Patched and improved by Mikko Korpela.
Cook, E. R. and Kairiukstis, L. A., editors (1990) Methods of Dendrochronology: Applications in the Environmental Sciences. Springer. ISBN-13: 978-0-7923-0586-6.
Fritts, H. C. (2001) Tree Rings and Climate. Blackburn. ISBN-13: 978-1-930665-39-2.
read.rwl, detrend,
chron.ars, ar, crn.plot
library(graphics) library(utils) data(ca533) ca533.rwi <- detrend(rwl = ca533, method = "ModNegExp") ca533.crn <- chron(ca533.rwi) plot(ca533.crn,xlab="Year",ylab="RWI") ## With residual chron ca533.crn2 <- chron(ca533.rwi, prewhiten = TRUE) plot(ca533.crn2,xlab="Year",ylab="RWI")library(graphics) library(utils) data(ca533) ca533.rwi <- detrend(rwl = ca533, method = "ModNegExp") ca533.crn <- chron(ca533.rwi) plot(ca533.crn,xlab="Year",ylab="RWI") ## With residual chron ca533.crn2 <- chron(ca533.rwi, prewhiten = TRUE) plot(ca533.crn2,xlab="Year",ylab="RWI")
This function builds three varieties of the mean-value chronology, including
the ARSTAN chronology, typically from a
data.frame of detrended ring widths as produced by
detrend.
chron.ars(rwi, biweight=TRUE, maxLag=10, firstAICmin=TRUE, verbose=TRUE, prewhitenMethod=c("ar.yw","arima.CSS-ML"))chron.ars(rwi, biweight=TRUE, maxLag=10, firstAICmin=TRUE, verbose=TRUE, prewhitenMethod=c("ar.yw","arima.CSS-ML"))
rwi |
a |
biweight |
|
maxLag |
an |
firstAICmin |
|
verbose |
|
prewhitenMethod |
a |
This produces three mean-value chronologies: standard, residual, and ARSTAN. Users unfamiliar with the concept behind the ARSTAN method should look to Cook (1985) for background and inspiration.
The standard chronology is the (biweight) mean value across rows and
identical to chron.
The residual chronology is the prewhitened chronology as described by
Cook (1985) and uses multivariate autoregressive modeling to determine
the order of the AR process. It is important to note that the residual
chronology produced here is different from the simple residual
chronology produced by chron, which returns the
residuals of an AR process using a naive call to ar. In
practice the results will be similar. For more on the residual
chronology in this function, see pp. 153-154 in Cook's 1985
dissertation.
The ARSTAN chronology is the residual chronology with the pooled AR coefficients from the multivariate autoregressive modeling put back in. The residual chronology is whitened a second time after the whitened series are averaged, because whitening each series with its own coefficients can remove more persistence than the series share and leave their mean negatively autocorrelated. The pooled model is added to that twice-whitened chronology, so the ARSTAN chronology has missing values in the same years as the residual chronology. Through dplR 1.8.0 the pooled model was instead added to each whitened series before averaging, which skipped the second whitening and could give an ARSTAN chronology with negative autocorrelation where the persistence is mostly within trees. See references for details.
The order of the AR model is selected from the pooled AR coefficients
by AIC using either the first local AIC minimum
(firstAICmin = TRUE, the default) or the overall minimum across
all lags up to maxLag (firstAICmin = FALSE). When
firstAICmin = TRUE and the AIC decreases monotonically across
all tested lags without reaching a local minimum, the function stops
with an error. This can occur when maxLag is too small for the
data or when the series have persistence structures that are not
well-suited to this approach (e.g., non-stationary or very long-memory
series). In such cases, consider increasing maxLag or reviewing
the data preparation steps described in Cook (1985). When
firstAICmin = FALSE the function always selects an order and
does not stop in this way.
If the selected AR order is zero (no detectable common autocorrelation among the series), no prewhitening or post-reddening is applied and all three returned chronologies are identical to the standard chronology.
Once the AR order is determined an AR(p) model is fit to each series
using either ar via the Yule-Walker method or by
arima via conditional-sum-of-squares to find starting
values, then maximum likelihood. It is possible that the model will
not converge in which case a warning is produced. The AR fitting is
determined via prewhitenMethod and defaults to using
ar.
A data.frame of class "crn" with the following columns:
std |
the standard chronology: the (biweight) mean ring-width index across all series for each year. |
res |
the residual chronology: the standard chronology after multivariate autoregressive prewhitening to remove common persistence. |
ars |
the ARSTAN chronology: the residual chronology with the
pooled autoregression reintroduced. When the selected AR order is
zero, |
samp.depth |
the number of series with non-missing values in each year. |
Row names are the years taken from rownames(rwi).
Andy Bunn with contributions from Kevin Achukaitis and Ed Cook. Much of the function is a port of Cook's FORTRAN code.
Cook, E. R. and Kairiukstis, L. A., editors (1990) Methods of Dendrochronology: Applications in the Environmental Sciences. Springer. ISBN-13: 978-0-7923-0586-6.
Cook, E. R. (1985). A Time Series Analysis Approach to Tree Ring Standardization. PhD thesis, The University of Arizona.
library(graphics) library(utils) data(co021) co021.rwi <- detrend(rwl = co021, method = "AgeDepSpline") co021.crn <- chron.ars(co021.rwi) plot(co021.crn,xlab="Year",ylab="RWI",add.spline=TRUE,nyrs=20) cor(co021.crn)library(graphics) library(utils) data(co021) co021.rwi <- detrend(rwl = co021, method = "AgeDepSpline") co021.crn <- chron.ars(co021.rwi) plot(co021.crn,xlab="Year",ylab="RWI",add.spline=TRUE,nyrs=20) cor(co021.crn)
This function builds a mean value chronology with bootstrapped confidence
intervals, typically from a data.frame of detrended ring widths as produced by
detrend.
chron.ci(x, biweight=TRUE, conf=0.95, R=100)chron.ci(x, biweight=TRUE, conf=0.95, R=100)
x |
a |
biweight |
|
conf |
|
R |
|
This either averages the rows of the data.frame using a mean or
a robust mean (the so-called standard chronology) and calculates boostrapped confidence intervals using the normal approximation. The function will fail if there are any rows in x that contain only one sample and in practice there should be several samples in a row. One of the guiding principles of bootstrapping is that the population is to the sample as the sample is to the bootstrap samples.
An object of of class data.frame with the standard chronology, the upper and lower confidence interval, and the sample depth. The years are stored as row numbers.
Andy Bunn.
read.rwl, detrend,
boot, boot.ci
library(graphics) library(utils) data(wa082) # truncate to a sample depth of five wa082Trunc <- wa082[rowSums(!is.na(wa082))>4,] # detrend wa082RWI <- detrend(wa082Trunc, method="AgeDepSpline") # bootstrap the chronology and wa082Crn <- chron.ci(wa082RWI, biweight = TRUE, R = 100, conf = 0.99) head(wa082Crn) # plot (this is so much easier in ggplot!) wa082Crn$yrs <- time(wa082Crn) xx <- c(wa082Crn$yrs,rev(wa082Crn$yrs)) yy <- c(wa082Crn$lowerCI,rev(wa082Crn$upperCI)) plot(wa082Crn$yrs,wa082Crn$std,type="n",ylim=range(yy), ylab="RWI",xlab="Year",main="Chronology with CI") polygon(x=xx,y=yy,col = "grey",border = NA) lines(wa082Crn$yrs,wa082Crn$std)library(graphics) library(utils) data(wa082) # truncate to a sample depth of five wa082Trunc <- wa082[rowSums(!is.na(wa082))>4,] # detrend wa082RWI <- detrend(wa082Trunc, method="AgeDepSpline") # bootstrap the chronology and wa082Crn <- chron.ci(wa082RWI, biweight = TRUE, R = 100, conf = 0.99) head(wa082Crn) # plot (this is so much easier in ggplot!) wa082Crn$yrs <- time(wa082Crn) xx <- c(wa082Crn$yrs,rev(wa082Crn$yrs)) yy <- c(wa082Crn$lowerCI,rev(wa082Crn$upperCI)) plot(wa082Crn$yrs,wa082Crn$std,type="n",ylim=range(yy), ylab="RWI",xlab="Year",main="Chronology with CI") polygon(x=xx,y=yy,col = "grey",border = NA) lines(wa082Crn$yrs,wa082Crn$std)
This function builds a variance stabilized mean-value chronology, typically from a
data.frame of detrended ring widths as produced by
detrend.
chron.stabilized(x, winLength, biweight = TRUE, running.rbar = FALSE)chron.stabilized(x, winLength, biweight = TRUE, running.rbar = FALSE)
x |
a |
winLength |
a odd |
biweight |
|
running.rbar |
|
The variance of a mean chronology depends on the variance of the individual samples, the number of series averaged together, and their interseries correlation (Wigley et al. 1984). As the number of series commonly decreases towards the beginning of a chronology averaging introduces changes in variance that are a solely an effect of changes in sample depth.
Additionally, time-dependent changes in interseries correlation can cause artificial variance changes of the final mean chronology. The function chron.stabilized accounts for both temporal changes in the interseries correlation and sample depth to produce a mean value chronology with stabilized variance.
The basic correction centers around the use of the effective independent sample size, Neff, which considers sample replication and mean interseries correlation between the samples at every time. This is defined as: Neff = n(t) / 1+(n(t)-1)rbar(t)
where n(t) is the number of series at time t, and rbar is the interseries correlation (see interseries.cor). Multiplication of the mean time series with the square root of Neff at every time t theoretically results in variance that is independent of sample size. In the limiting cases, when the rbar is zero or unity, Neff obtains values of the true sample size and unity, respectively.
An object of of class crn and data.frame with the variance stabilized chronology, running interseries correlation ('if running.rbar=TRUE), and the sample depth.
Original code by David Frank and adapted for dplR by Stefan Klesse. Patched and improved by Andy Bunn.
Frank, D, Esper, J, Cook, E, (2006) On variance adjustments in tree-ring chronology development. Tree rings in archaeology, climatology and ecology, TRACE 4, 56–66
Frank, D, Esper, J, Cook, E, (2007) Adjustment for proxy number and coherence in a large-scale temperature reconstruction. Geophysical Research Letters 34
Wigley, T, Briffa K, Jones P (1984) On the Average Value of Correlated Time Series, with Applications in Dendroclimatology and Hydrometeorology. J. Climate Appl. Meteor., 23, 201–213
library(graphics) library(utils) data(co021) co021.rwi <- detrend(co021,method = "Spline") co021.crn <- chron(co021.rwi) co021.crn2 <- chron.stabilized(co021.rwi, winLength=101, biweight = TRUE, running.rbar = FALSE) yrs <- time(co021) plot(yrs,co021.crn$std,type="l",col="grey") lines(yrs,co021.crn2$adj.crn,col="red")library(graphics) library(utils) data(co021) co021.rwi <- detrend(co021,method = "Spline") co021.crn <- chron(co021.rwi) co021.crn2 <- chron.stabilized(co021.rwi, winLength=101, biweight = TRUE, running.rbar = FALSE) yrs <- time(co021) plot(yrs,co021.crn$std,type="l",col="grey") lines(yrs,co021.crn2$adj.crn,col="red")
Detrend multiple ring-width series simultaneously using the C-method.
cms(rwl, po, c.hat.t = FALSE, c.hat.i = FALSE)cms(rwl, po, c.hat.t = FALSE, c.hat.i = FALSE)
rwl |
a |
po |
a |
c.hat.t |
a |
c.hat.i |
a |
This method detrends and standardizes tree-ring series by calculating a growth curve based on constant annual basal area increment. The method is based on the “assumption that constant growth is expressed by a constant basal area increment distributed over a growing surface” (Biondi and Qeadan 2008). The detrending is the estimation and removal of the tree’s natural biological growth trend. The standardization is done by dividing each series by the growth trend to produce units in the dimensionless ring-width index (RWI).
This attempts to remove the low frequency variability that is due to biological or stand effects.
A series with no values at all is dropped, with a message naming it,
and the rest are standardized as if it had never been there.
po must still have a row for every series in
rwl, empty or not.
See the reference below for further details.
An object of class c("rwi", "data.frame") (see
as.rwi) containing the dimensionless and detrended
ring-width indices with column names, row names and dimensions of
rwl if c.hat.t is FALSE and
c.hat.i is FALSE.
Otherwise a list of length 2 or 3 containing the RWI
data.frame, a data.frame containing the C-curves for
each tree (c.hat.t), and/or a vector containing the
C-values for each tree (c.hat.i) depending on the output
flags. See Eq. 12 in Biondi and Qeadan (2008) for more detail on
c.hat.t, and c.hat.i.
DendroLab website: https://dendrolaborg.wordpress.com/
Code provided by DendroLab based on programming by F. Qeadan and F. Biondi, University of Nevada Reno, USA and adapted for dplR by Andy Bunn. Patched and improved by Mikko Korpela.
Biondi, F. and Qeadan, F. (2008) A theory-driven approach to tree-ring standardization: Defining the biological trend from expected basal area increment. Tree-Ring Research, 64(2), 81–96.
library(graphics) library(utils) data(gp.rwl) data(gp.po) gp.rwi <- cms(rwl = gp.rwl, po = gp.po) gp.crn <- chron(gp.rwi) crn.plot(gp.crn, add.spline = TRUE) ## c.hat gp.rwi <- cms(rwl = gp.rwl, po = gp.po, c.hat.t = TRUE, c.hat.i = TRUE) dotchart(gp.rwi$c.hat.i, ylab = "Series", xlab = expression(hat(c)[i])) tmp <- gp.rwi$c.hat.t plot(tmp[, 1], type = "n", ylim = range(tmp, na.rm = TRUE), xlab = "Cambial Age", ylab = expression(hat(c)[t])) apply(tmp, 2, lines)library(graphics) library(utils) data(gp.rwl) data(gp.po) gp.rwi <- cms(rwl = gp.rwl, po = gp.po) gp.crn <- chron(gp.rwi) crn.plot(gp.crn, add.spline = TRUE) ## c.hat gp.rwi <- cms(rwl = gp.rwl, po = gp.po, c.hat.t = TRUE, c.hat.i = TRUE) dotchart(gp.rwi$c.hat.i, ylab = "Series", xlab = expression(hat(c)[i])) tmp <- gp.rwi$c.hat.t plot(tmp[, 1], type = "n", ylim = range(tmp, na.rm = TRUE), xlab = "Cambial Age", ylab = expression(hat(c)[t])) apply(tmp, 2, lines)
This data set gives the raw ring widths for Douglas fir
Pseudotsuga menziesii at Mesa Verde in Colorado, USA.
There are 35 series. Data set was created using read.rwl
and saved to an .rda file using save.
data(co021)data(co021)
A data.frame containing 35 tree-ring series in columns and 788
years in rows.
International tree-ring data bank, Accessed on 20-April-2021 at https://www.ncei.noaa.gov/pub/data/paleo/treering/measurements/northamerica/usa/co021.rwl
Schulman, E. (1963) Schulman Old Tree No. 1 Data Set. IGBP PAGES/World Data Center for Paleoclimatology Data Contribution Series 1983-CO021.RWL. NOAA/NCDC Paleoclimatology Program, Boulder, Colorado, USA.
library(utils) data(co021) ## Where the data came from. read.tucson() records what it saw and attaches ## it to what it returns; this data set carries that record. prov <- attr(co021, "dplR.provenance") prov$file # the archived file it was read from prov$precision # the precision each series was measured at prov$gaps # interior gaps, if any -- this file has none prov$events # problems found while reading -- none here either ## rwl.report() puts the file and precision at the head of its report rwl.report(co021)library(utils) data(co021) ## Where the data came from. read.tucson() records what it saw and attaches ## it to what it returns; this data set carries that record. prov <- attr(co021, "dplR.provenance") prov$file # the archived file it was read from prov$precision # the precision each series was measured at prov$gaps # interior gaps, if any -- this file has none prov$events # problems found while reading -- none here either ## rwl.report() puts the file and precision at the head of its report rwl.report(co021)
This function combines any number of data.frames of
tree-ring data into one data.frame.
combine.rwl(x, y = NULL)combine.rwl(x, y = NULL)
x |
either a |
y |
a |
The sequence of years in each data.frame must be
increasing and continuous. The output produced by the function
also fulfills this condition. If the input is differently formatted,
the result will be wrong.
An object of class c("rwl", "data.frame") with the series in
columns and the years as
rows. The keycodes are the column names and the years are the row
names.
Christian Zang. Patched by Mikko Korpela.
library(utils) data(ca533) data(co021) combi1 <- combine.rwl(list(ca533, co021)) ## or alternatively for data.frames to combine combi2 <- combine.rwl(ca533, co021) identical(combi1, combi2) # TRUElibrary(utils) data(ca533) data(co021) combi1 <- combine.rwl(list(ca533, co021)) ## or alternatively for data.frames to combine combi2 <- combine.rwl(ca533, co021) identical(combi1, combi2) # TRUE
This function finds the common interval on a set of tree-ring widths
such as that produced by read.rwl.
common.interval(rwl, type=c("series", "years", "both"), make.plot=TRUE)common.interval(rwl, type=c("series", "years", "both"), make.plot=TRUE)
rwl |
a |
type |
a |
make.plot |
a |
This trims an rwl object to a common interval that maximizes
the number of series (type="series"), the number of years
(type="years"), or a compromise between the two
(type="both"). A modified seg.plot can be drawn
as well.
Series with no values are left out. A single series is its own common interval, and its measured years are returned. If there are two or more series and no year in which any two of them overlap, or no series has any values, there is no common interval and that is an error.
A data.frame with colnames(x) and
rownames(x), with no missing values. It has the class
of rwl: ring-width indices (class "rwi", see
as.rwi) come back as indices. If the years kept are
not consecutive, which type = "years" can give when a series
has an interior gap, the result is a plain data.frame, with a
warning (see [.rwl).
Filipe Campelo, Andy Bunn and Mikko Korpela
library(utils) data(co021) co021.s <- common.interval(co021, type="series", make.plot=TRUE) co021.y <- common.interval(co021, type="years", make.plot=TRUE) co021.b <- common.interval(co021, type="both", make.plot=TRUE) dim(co021) dim.s <- dim(co021.s) dim.s # the highest number of series prod(dim.s) # (33 series x 288 years = 9504) dim.y <- dim(co021.y) dim.y # the highest number of years prod(dim.y) # (27 series x 458 years = 12366) dim.b <- dim(co021.b) dim.b # compromise solution prod(dim.b) # (28 series x 435 years = 12180)library(utils) data(co021) co021.s <- common.interval(co021, type="series", make.plot=TRUE) co021.y <- common.interval(co021, type="years", make.plot=TRUE) co021.b <- common.interval(co021, type="both", make.plot=TRUE) dim(co021) dim.s <- dim(co021.s) dim.s # the highest number of series prod(dim.s) # (33 series x 288 years = 9504) dim.y <- dim(co021.y) dim.y # the highest number of years prod(dim.y) # (27 series x 458 years = 12366) dim.b <- dim(co021.b) dim.b # compromise solution prod(dim.b) # (28 series x 435 years = 12180)
Computes the correlation between each tree-ring series in a rwl object.
corr.rwl.seg(rwl, seg.length = 50, bin.floor = 100, n = NULL, nyrs = NULL, prewhiten = TRUE, ar.order.max = NULL, pcrit = 0.05, biweight = TRUE, method = c("spearman", "pearson","kendall"), make.plot = TRUE, label.cex = 1, floor.plus1 = FALSE, master = NULL, lag.max = 0, master.yrs = as.numeric(if (is.null(dim(master))) { names(master) } else { rownames(master) }), ...)corr.rwl.seg(rwl, seg.length = 50, bin.floor = 100, n = NULL, nyrs = NULL, prewhiten = TRUE, ar.order.max = NULL, pcrit = 0.05, biweight = TRUE, method = c("spearman", "pearson","kendall"), make.plot = TRUE, label.cex = 1, floor.plus1 = FALSE, master = NULL, lag.max = 0, master.yrs = as.numeric(if (is.null(dim(master))) { names(master) } else { rownames(master) }), ...)
rwl |
a |
seg.length |
an even integral value giving length of segments in years (e.g., 20, 50, 100 years). |
bin.floor |
a non-negative integral value giving the base for locating the first segment (e.g., 1600, 1700, 1800 AD). Typically 0, 10, 50, 100, etc. |
n |
|
nyrs |
|
prewhiten |
|
ar.order.max |
|
pcrit |
a number between 0 and 1 giving the critical value for the correlation test. |
biweight |
|
method |
Can be either |
make.plot |
|
label.cex |
|
floor.plus1 |
|
master |
|
lag.max |
a non-negative whole number less than
|
master.yrs |
a |
... |
other arguments passed to plot. |
This function calculates correlation serially between each tree-ring
series and a master chronology built from all the other series in the
rwl object (leave-one-out principle). Optionally, the
user may give a master chronology (a vector) as an
argument. In the latter case, the same master chronology is used for
all the series in the rwl object. The user can also
choose to give a master data.frame (series as
columns, years as rows), from which a single master chronology is
built.
Correlations are done for each segment of the series where segments
are lagged by half the segment length (e.g., 100-year segments would
be overlapped by 50-years). The first segment is placed according to
bin.floor. The minimum bin year is calculated as
ceiling(min.yr/bin.floor)*bin.floor where
min.yr is the first year in either the rwl
object or the user-specified master chronology, whichever
is smaller. For example if the first year is 626 and
bin.floor is 100 then the first bin would start in 700.
If bin.floor is 10 then the first bin would start in 630.
Correlations are calculated for the first segment, then the second
segment and so on. Correlations are only calculated for segments with
complete overlap with the master chronology. For now, correlations are
Spearman’s rho calculated via cor.test using
method = "spearman".
Each series (including those in the rwl object) is optionally
detrended as the residuals from a hanning filter with
weight n. The filter is not applied if n is
NULL. Detrending can also be done via prewhitening where the
residuals of an ar model are added to each series
mean. This is the default. The master chronology is computed as the
mean of the rwl object using tbrm if
biweight is TRUE and rowMeans if not. Note
that detrending can change the length of the series. E.g., a
hanning filter will shorten the series on either end by
floor(n/2). The prewhitening default will change the
series length based on the ar model fit. The effects of
detrending can be seen with series.rwl.plot.
As an alternative to the hanning filter, nyrs
divides each series by a smoothing spline, which removes no years from
the ends of the series. COFECHA uses a 32-year spline. The spline
alone does not usually save years at the start of a series, because
the ar model is then fitted to a high-pass filtered series,
and AIC tends to choose a high order for it. Setting
ar.order.max to a small value (e.g., 3) limits the years
lost to prewhitening, and after a spline a low-order model loses little
of the fit.
With neither filter, each series is divided by its mean before the
master is built, so every series counts equally. Data that can be
negative, such as indices from detrend with
difference = TRUE, log widths or isotope values, have
the mean subtracted instead, since dividing by a negative mean would
flip the series. The n and nyrs filters
divide by a smooth curve, so they refuse such data. The same applies
to the other crossdating functions.
The function is typically invoked to produce a plot where each segment for each series is colored by its correlation to the master chronology. Green segments are those that do not overlap completely with the width of the bin. Blue segments are those that correlate above the user-specified critical value. Red segments are those that correlate below the user-specified critical value and might indicate a dating problem.
A segment that correlates well where it is dated can still correlate
better somewhere else. With lag.max greater than 0, each
segment is also correlated against the master at every shift from
-lag.max to lag.max years. Each year of the
segment is paired with the master value k years away, so the
correlation at lag k is that of series[t] with
master[t + k]. The sign follows ccf.series.rwl
with series.x = FALSE: a negative lag means missing rings
in the series, a positive lag means false (extra) rings. The dated
position wins ties.
This gives the two kinds of flag COFECHA reports. An ‘A’
segment correlates below the critical value, but its dated position
is still the best one tested: it is weak, not misdated. A
‘B’ segment correlates better at some other position,
whether or not it is significant as dated. The letters are not
stored; they follow from the returned matrices as
best.lag != 0 for B and
best.lag == 0 & p.val >= pcrit for A (see Examples). When
lag.max is greater than 0, the plot draws B segments in
purple and leaves red for the rest of the segments below the critical
value.
A B flag is a hypothesis about the dating, not a verdict. A one-year
shift that gains 0.05 in correlation is noise as often as it is a
missing ring, which is why the size of the gain is returned
(best.rho - spearman.rho) alongside the lag, so that it can be
thresholded. Check any B segment against the wood, for example with
ccf.series.rwl and xskel.ccf.plot.
Read the lags along a series rather than one bin at a time. Dating
runs from the bark inward, so a missing ring moves every ring before
it one year late: every complete bin before the missing ring has
best.lag of -1 and every bin after it has 0. A false ring
does the same with +1. The error therefore lies where the lag
changes, not in the bin with the largest gain. The bin that
straddles it holds some shifted and some unshifted years, and may
show either lag with a small gain. A run of -1 with correctly dated
bins on both sides is a different fault: the ring count is right, but
a ring is missing at the later end of the run and there is an extra
ring at the earlier end. A locally absent ring entered as a zero in
too early a year looks exactly like this. A test on the whole series,
such as RWL_DATING_LAG in rwl.check, usually cannot
see it, because most of the series is dated correctly. The Examples
show both patterns.
The shifted correlations follow the same complete-overlap rule as the
dated one: a lag is tested only if the master has a value for every
year of the shifted window. Near the start and end of the record
(and of the master), the lags that run off the record cannot be
tested, and a segment that lies within lag.max years of
an end is only searched in one direction. A segment that is not
complete at its dated position is not tested at all. Floating series
and series with dating errors near their ends sit exactly where the
test is blind, so the absence of a flag there says little. Worse, a
segment misdated in the direction that runs off the record can still
be flagged B, at whichever of the remaining lags happens to correlate
best, so the lag reported for a B near either end can be noise even
when the segment really is misdated.
A list containing matrices spearman.rho,
p.val, overall, bins,
rwi, vector avg.seg.rho,
numeric seg.lag, seg.length, pcrit,
label.cex, matrices best.lag,
best.rho and numeric lag.max. An additional character
flags is also returned if any segments fall below the
critical value. Matrix spearman.rho contains the
correlations for each series by bin. Matrix p.val
contains the p-values on the correlation for each series by
bin. Matrix overall contains the average correlation and
p-value for each series. Matrix bins contains the years
encapsulated by each bin. The vector avg.seg.rho
contains the average correlation for each bin. Matrix rwi
contains the detrended rwl data, the numerics seg.lag,
seg.length, pcrit, label.cex
are from the oroginal call and used to pass into plot.crs.
Matrices best.lag and best.rho have the same
shape and names as spearman.rho. best.lag
gives, for each series and bin, the lag (in years) at which the
segment correlates best with the master, and best.rho
gives that correlation. Both are NA where
spearman.rho is. With lag.max = 0,
best.lag is 0 and best.rho equals
spearman.rho. lag.max is from the original
call. Flags in flags depend on the p-value only and are
the same whatever lag.max is.
Andy Bunn. Patched and improved by Mikko Korpela.
corr.series.seg, skel.plot,
series.rwl.plot, ccf.series.rwl,
plot.crs
library(utils) data(co021) crs <- corr.rwl.seg(co021, seg.length = 100, label.cex = 1.25) names(crs) ## Average correlation and p-value for the first few series head(crs$overall) ## Average correlation for each bin crs$avg.seg.rho ## Plant a missing ring and follow it through the bins: delete the ## 1500 ring of series 641143, the same fault as in the examples for ## ccf.series.rwl(), corr.series.seg() and xskel.ccf.plot(). Dated ## from the bark, every ring before 1500 now sits one year late. dat <- co021 x <- dat$"641143" names(x) <- rownames(dat) dat$"641143" <- delete.ring(x, year = 1500) crs <- corr.rwl.seg(dat, lag.max = 5) ## -1 in every complete bin before 1500 (drawn in purple), 0 from 1500 ## on, and a large gain in each shifted bin ok <- !is.na(crs$best.lag["641143", ]) rbind(lag = crs$best.lag["641143", ok], rho = round(crs$spearman.rho["641143", ok], 2), best.rho = round(crs$best.rho["641143", ok], 2)) ## The same missing ring with a false ring inserted at 1400. The ring ## count is right again, and only the rings between the two errors are ## one year late. dat$"641143" <- insert.ring(delete.ring(x, year = 1500), year = 1400) crs <- corr.rwl.seg(dat, lag.max = 5, make.plot = FALSE) ## -1 between the two errors only, 0 on both sides crs$best.lag["641143", ok] ## COFECHA-style A and B flags for every series flag <- ifelse(crs$best.lag != 0, "B", ifelse(crs$p.val >= crs$pcrit, "A", "")) flag[is.na(flag)] <- "" ## B segments with their lag and the gain in correlation idx <- which(flag == "B", arr.ind = TRUE) data.frame(series = rownames(flag)[idx[, 1]], bin = colnames(flag)[idx[, 2]], lag = crs$best.lag[idx], rho = round(crs$spearman.rho[idx], 3), best.rho = round(crs$best.rho[idx], 3))library(utils) data(co021) crs <- corr.rwl.seg(co021, seg.length = 100, label.cex = 1.25) names(crs) ## Average correlation and p-value for the first few series head(crs$overall) ## Average correlation for each bin crs$avg.seg.rho ## Plant a missing ring and follow it through the bins: delete the ## 1500 ring of series 641143, the same fault as in the examples for ## ccf.series.rwl(), corr.series.seg() and xskel.ccf.plot(). Dated ## from the bark, every ring before 1500 now sits one year late. dat <- co021 x <- dat$"641143" names(x) <- rownames(dat) dat$"641143" <- delete.ring(x, year = 1500) crs <- corr.rwl.seg(dat, lag.max = 5) ## -1 in every complete bin before 1500 (drawn in purple), 0 from 1500 ## on, and a large gain in each shifted bin ok <- !is.na(crs$best.lag["641143", ]) rbind(lag = crs$best.lag["641143", ok], rho = round(crs$spearman.rho["641143", ok], 2), best.rho = round(crs$best.rho["641143", ok], 2)) ## The same missing ring with a false ring inserted at 1400. The ring ## count is right again, and only the rings between the two errors are ## one year late. dat$"641143" <- insert.ring(delete.ring(x, year = 1500), year = 1400) crs <- corr.rwl.seg(dat, lag.max = 5, make.plot = FALSE) ## -1 between the two errors only, 0 on both sides crs$best.lag["641143", ok] ## COFECHA-style A and B flags for every series flag <- ifelse(crs$best.lag != 0, "B", ifelse(crs$p.val >= crs$pcrit, "A", "")) flag[is.na(flag)] <- "" ## B segments with their lag and the gain in correlation idx <- which(flag == "B", arr.ind = TRUE) data.frame(series = rownames(flag)[idx[, 1]], bin = colnames(flag)[idx[, 2]], lag = crs$best.lag[idx], rho = round(crs$spearman.rho[idx], 3), best.rho = round(crs$best.rho[idx], 3))
Compute correlation between a tree-ring series and a master chronology by segment.
corr.series.seg(rwl, series, series.yrs = as.numeric(names(series)), seg.length = 50, bin.floor = 100, n = NULL, nyrs = NULL, prewhiten = TRUE, ar.order.max = NULL, biweight = TRUE, method = c("spearman", "pearson","kendall"), pcrit = 0.05, make.plot = TRUE, floor.plus1 = FALSE, ...)corr.series.seg(rwl, series, series.yrs = as.numeric(names(series)), seg.length = 50, bin.floor = 100, n = NULL, nyrs = NULL, prewhiten = TRUE, ar.order.max = NULL, biweight = TRUE, method = c("spearman", "pearson","kendall"), pcrit = 0.05, make.plot = TRUE, floor.plus1 = FALSE, ...)
rwl |
a |
series |
a |
series.yrs |
a |
seg.length |
an even integral value giving length of segments in years (e.g., 20, 50, 100 years). |
bin.floor |
a non-negative integral value giving the base for locating the first segment (e.g., 1600, 1700, 1800 AD). Typically 0, 10, 50, 100, etc. |
n |
|
nyrs |
|
prewhiten |
|
ar.order.max |
|
biweight |
|
method |
Can be either |
pcrit |
a number between 0 and 1 giving the critical value for the correlation test. |
make.plot |
|
floor.plus1 |
|
... |
other arguments passed to plot. |
This function calculates the correlation between a tree-ring series and a
master chronology built from a rwl object. Correlations are done by
segment (see below) and with a moving correlation with length equal to
the seg.length. The function is typically invoked to
produce a plot.
A list containing matrices bins,
moving.rho, and vectors spearman.rho,
p.val, and overall.
Matrix bins contains the years encapsulated by each bin
(segments). Matrix moving.rho contains the moving
correlation and p-value for a moving average equal to
seg.length. Vector spearman.rho contains
the correlations by bin and p.val contains
the p-values. Vector overall contains the average
correlation and p-value.
Andy Bunn. Patched and improved by Mikko Korpela.
corr.series.seg, skel.plot,
series.rwl.plot, ccf.series.rwl
library(utils) data(co021) dat <- co021 ## Create a missing ring: delete the 1500 ring of series 641143 and ## drop the original from the master. Dated from the bark, every ring ## before 1500 now sits one year late. flagged <- dat$"641143" names(flagged) <- rownames(dat) flagged <- delete.ring(flagged, year = 1500) dat$"641143" <- NULL seg.100 <- corr.series.seg(rwl = dat, series = flagged, seg.length = 100, biweight = FALSE) ## Not run: flagged2 <- co021$"641143" names(flagged2) <- rownames(dat) seg.100.1 <- corr.series.seg(rwl=dat, seg.length=100, biweight=FALSE, series = flagged2) ## Select series by name or column position seg.100.2 <- corr.series.seg(rwl=co021, seg.length=100, biweight=FALSE, series = "641143") seg.100.3 <- corr.series.seg(rwl=co021, seg.length=100, biweight=FALSE, series = which(colnames(co021) == "641143")) identical(seg.100.1, seg.100.2) # TRUE identical(seg.100.2, seg.100.3) # TRUE ## End(Not run)library(utils) data(co021) dat <- co021 ## Create a missing ring: delete the 1500 ring of series 641143 and ## drop the original from the master. Dated from the bark, every ring ## before 1500 now sits one year late. flagged <- dat$"641143" names(flagged) <- rownames(dat) flagged <- delete.ring(flagged, year = 1500) dat$"641143" <- NULL seg.100 <- corr.series.seg(rwl = dat, series = flagged, seg.length = 100, biweight = FALSE) ## Not run: flagged2 <- co021$"641143" names(flagged2) <- rownames(dat) seg.100.1 <- corr.series.seg(rwl=dat, seg.length=100, biweight=FALSE, series = flagged2) ## Select series by name or column position seg.100.2 <- corr.series.seg(rwl=co021, seg.length=100, biweight=FALSE, series = "641143") seg.100.3 <- corr.series.seg(rwl=co021, seg.length=100, biweight=FALSE, series = which(colnames(co021) == "641143")) identical(seg.100.1, seg.100.2) # TRUE identical(seg.100.2, seg.100.3) # TRUE ## End(Not run)
This is a wrapper for detrend.series to detrend many
ring-width series at once.
detrend(rwl, y.name = names(rwl), make.plot = FALSE, method = "Spline", nyrs = NULL, f = 0.5, pos.slope = FALSE, constrain.nls = c("never", "when.fail", "always"), verbose = FALSE, return.info = FALSE, wt, span = "cv", bass = 0, difference = FALSE)detrend(rwl, y.name = names(rwl), make.plot = FALSE, method = "Spline", nyrs = NULL, f = 0.5, pos.slope = FALSE, constrain.nls = c("never", "when.fail", "always"), verbose = FALSE, return.info = FALSE, wt, span = "cv", bass = 0, difference = FALSE)
rwl |
a |
y.name |
a |
make.plot |
a |
method |
a |
nyrs |
a number giving the rigidity of the smoothing spline,
defaults to 0.67 of series length if |
f |
a number between 0 and 1 giving the frequency response or wavelength cutoff. Defaults to 0.5. |
pos.slope |
a |
constrain.nls |
a |
verbose |
|
return.info |
a |
wt |
a |
span |
a |
bass |
a |
difference |
a |
See detrend.series for details on detrending
methods. Setting make.plot = TRUE will cause plots of
each series to be produced. These could be saved using
Devices if desired.
A series with no values at all is dropped, with a message naming it,
and the rest are detrended as if it had never been there; its name
is dropped from y.name too. x[rows, ] and
head can leave such a series (see [.rwl).
If no series has any values, that is an error. A series with
NA inside its measured span stops the call, with a message
naming the series; see fill.internal.NA.
If one detrending method is used, an object of class
c("rwi", "data.frame") containing the
dimensionless detrended ring widths with the column names, row names
and dimensions of rwl, less any series with no values. It records how it was made in
attr(x, "dplR.detrend") and carries the provenance record of
rwl, if it has one; see as.rwi.
If more methods are used, a list with
ncol(rwl) elements each containing a data.frame
with the detrended ring widths in each column.
If return.info is TRUE, the return value is a
list with four parts:
series |
the main result described above ( |
curves |
the curve or line used to detrend |
model.info |
Information about the models corresponding to each
output series. A |
data.info |
Information about the input series. A |
This function uses the foreach looping
construct with the %dopar% operator.
For parallel computing and a potential speedup, a parallel backend
must be registered before running the function. If
verbose is TRUE, parallel computation is disabled.
Andy Bunn. Improved by Mikko Korpela.
library(utils) data(ca533) ## Detrend using modified exponential decay. Returns an rwi object ca533.rwi <- detrend(rwl = ca533, method = "ModNegExp") ## Detrend using splines and compute ## residuals via subtraction ca533.rwi <- detrend(rwl = ca533, method = "Spline", difference = TRUE) ## Detrend using modified Hugershoff curve and return info on the model ## fits. Returns a list with: series, curves, modelinfo and data.info data(co021) co021.rwi <- detrend(rwl = co021, method = "ModHugershoff", return.info=TRUE) ## Not run: library(grDevices) ## Detrend using all methods. Returns a list ca533.rwi <- detrend(rwl = ca533, method = c("Spline", "ModNegExp", "Mean", "Ar", "Friedman", "ModHugershoff", "AgeDepSpline")) ## Save a pdf of all series fname <- tempfile(fileext=".pdf") print(fname) # tempfile used for output pdf(fname) ca533.rwi <- detrend(rwl = ca533, method = c("Spline", "ModNegExp"), make.plot = TRUE) dev.off() unlink(fname) # remove the file ## End(Not run)library(utils) data(ca533) ## Detrend using modified exponential decay. Returns an rwi object ca533.rwi <- detrend(rwl = ca533, method = "ModNegExp") ## Detrend using splines and compute ## residuals via subtraction ca533.rwi <- detrend(rwl = ca533, method = "Spline", difference = TRUE) ## Detrend using modified Hugershoff curve and return info on the model ## fits. Returns a list with: series, curves, modelinfo and data.info data(co021) co021.rwi <- detrend(rwl = co021, method = "ModHugershoff", return.info=TRUE) ## Not run: library(grDevices) ## Detrend using all methods. Returns a list ca533.rwi <- detrend(rwl = ca533, method = c("Spline", "ModNegExp", "Mean", "Ar", "Friedman", "ModHugershoff", "AgeDepSpline")) ## Save a pdf of all series fname <- tempfile(fileext=".pdf") print(fname) # tempfile used for output pdf(fname) ca533.rwi <- detrend(rwl = ca533, method = c("Spline", "ModNegExp"), make.plot = TRUE) dev.off() unlink(fname) # remove the file ## End(Not run)
Detrend a tree-ring series by one of two methods, a smoothing spline or a statistical model. The series and fits are plotted by default.
detrend.series(y, y.name = "", make.plot = TRUE, method = "Spline", nyrs = NULL, f = 0.5, pos.slope = FALSE, constrain.nls = c("never", "when.fail", "always"), verbose = FALSE, return.info = FALSE, wt, span = "cv", bass = 0, difference = FALSE)detrend.series(y, y.name = "", make.plot = TRUE, method = "Spline", nyrs = NULL, f = 0.5, pos.slope = FALSE, constrain.nls = c("never", "when.fail", "always"), verbose = FALSE, return.info = FALSE, wt, span = "cv", bass = 0, difference = FALSE)
y |
a |
y.name |
an optional |
make.plot |
a |
method |
a |
nyrs |
a number controlling the smoothness of the fitted curve in methods. See Details. |
f |
a number between 0 and 1 giving the frequency response or
wavelength cutoff in method |
pos.slope |
a |
constrain.nls |
a |
verbose |
a |
return.info |
a |
wt |
a |
span |
a |
bass |
a |
difference |
a |
This detrends and standardizes a tree-ring series. The detrending is the estimation and removal of the tree’s natural biological growth trend. The default standardization is done by dividing each series by the growth trend to produce units in the dimensionless ring-width index (RWI). If difference is TRUE, the index is calculated by subtraction. Values of zero (typically missing rings) in y are set to 0.001 when dividing.
A curve that is divided by must be positive, so when difference is FALSE a fit that is not all positive is replaced by a straight line or the mean (or, for "Ar", its negative values are set to zero) with a warning. Subtraction has no such need, so with difference = TRUE the fits are used as they are, zeros are left alone, and y may be negative, as log widths or isotope values are.
There are currently seven methods available for
detrending although more are certainly possible. The methods
implemented are an age-dependent spline via ads
(method = "AgeDepSpline"), the residuals of an AR model
(method = "Ar"), Friedman's Super Smoother
(method = "Friedman"), a simple horizontal line
(method = "Mean"), or a modified Hugershoff
curve (method = "ModHugershoff"), a modified negative exponential
curve (method = "ModNegExp"), and a smoothing spline via caps (method = "Spline").
The "AgeDepSpline" approach uses an age-dependent spline with an initial
stiffness of 50 (nyrs=50). See ads. If some of the fitted
values are not positive then method "Mean" is used. However, this is
extremely unlikely.
The "Ar" approach is also known as prewhitening where the detrended
series is the residuals of an ar model divided by the
mean of those residuals to yield a series with white noise and a mean of one.
This method removes all but the high frequency variation in the series
and should only be used as such.
The "Friedman" approach uses Friedman’s ‘super
smoother’ as implemented in supsmu. The parameters
wt, span and bass can be
adjusted, but periodic is always set to FALSE. If some of
the fitted values are not positive then method "Mean" is used.
The "Mean" approach fits a horizontal line using the mean of
the series. This method is the fallback solution in cases where the
"Spline" or the linear fit (also a fallback solution itself)
contains zeros or negative values, which would lead to invalid
ring-width indices.
The "ModHugershoff" approach attempts to fit a Hugershoff
model of biological growth of the form , where the argument of the function is time, using
nls. See Fritts (2001) for details about the
parameters. Option constrain.nls gives a
possibility to constrain the parameters of the modified negative
exponential function. If the constraints are enabled, the nonlinear
optimization algorithm is instructed to keep the parameters in the
following ranges: , and
. The default is to not constrain the parameters
(constrain.nls = "never") for nls but
warn the user when the parameters go out of range.
If a suitable nonlinear model cannot be fit
(function is non-decreasing or some values are not positive) then a
linear model is fit. That linear model can have a positive slope
unless pos.slope is FALSE in which case method
"Mean" is used.
The "ModNegExp" approach attempts to fit a classic nonlinear
model of biological growth of the form , where the argument of the function is time, using
nls. See Fritts (2001) for details about the
parameters. Option constrain.nls gives a
possibility to constrain the parameters of the modified negative
exponential function. If the constraints are enabled, the nonlinear
optimization algorithm is instructed to keep the parameters in the
following ranges: , and
. The default is to not constrain the parameters
(constrain.nls = "never") for nls but
warn the user when the parameters go out of range.
If a suitable nonlinear model cannot be fit
(function is non-decreasing or some values are not positive) then a
linear model is fit. That linear model can have a positive slope
unless pos.slope is FALSE in which case method
"Mean" is used.
The "Spline" approach uses a spline where the frequency
response is 0.50 at a wavelength of 0.67 * “series length in
years”, unless specified differently using nyrs and
f in the function caps. If some of the fitted
values are not positive then method "Mean" is used.
These methods are chosen because they are commonly used in
dendrochronology. There is a rich literature on detrending
and many researchers are particularly skeptical of the use of the
classic nonlinear model of biological growth () for detrending. It is, of course, up to the
user to determine the best detrending method for their data.
Note that the user receives a warning if a series has negative values in the fitted curve. This happens fairly commonly with with the ‘Ar’ method on high-order data. It happens less often with method ‘Spline’ but isn't unheard of (see ‘Examples’). If this happens, users should look carefully at their data before continuing. Automating detrending and not evaluating each series individually is folly. Remember, frustration over detrending is the number one cause of dendros going to live as hermits in the tallgrass prairie, where there are no trees to worry about.
See the references below for further details on detrending. It's a dark art.
If several methods are used, returns a data.frame containing
the detrended series (y) according to the methods used.
The columns are named and ordered to match method. If
only one method is selected, returns a vector.
If return.info is TRUE, the return value is a
list with four parts:
series |
the main result described above ( |
curves |
the curve or line used to detrend |
model.info |
Information about the models corresponding to each
output series. Whereas
|
data.info |
Information about the input series: number
( |
dirtDog |
A logical flag indicating whether the requested method resulted in negative values for the curve fit, what Cook's ARSTAN called a Dirty Dog. |
Andy Bunn. Patched and improved by Mikko Korpela. A bug fix related to negative output values is based on work by Alice Cecile.
Cook, E. R. and Kairiukstis, L. A., editors (1990) Methods of Dendrochronology: Applications in the Environmental Sciences. Springer. ISBN-13: 978-0-7923-0586-6.
Fritts, H. C. (2001) Tree Rings and Climate. Blackburn. ISBN-13: 978-1-930665-39-2.
library(stats) library(utils) ## Use series CAM011 from the Campito data set data(ca533) series <- ca533[, "CAM011"] names(series) <- rownames(ca533) # all seven methods series.rwi <- detrend.series(y = series, y.name = "CAM011", verbose=TRUE, method = c("Spline", "ModNegExp", "Mean", "Ar", "Friedman", "ModHugershoff", "AgeDepSpline")) # see plot with three methods series.rwi <- detrend.series(y = series, y.name = "CAM011", method=c("Spline", "ModNegExp","Friedman"), difference=TRUE) # see plot with two methods # interesting to note difference from ~200 to 250 years # in terms of what happens to low frequency growth series.rwi <- detrend.series(y = series, y.name = "CAM011", method=c("Spline", "ModNegExp")) # see plot with just one method and change the spline # stiffness to 50 years (which is not neccesarily a good choice!) series.rwi <- detrend.series(y = series, y.name = "CAM011", method="Spline",nyrs=50) # note that method "Ar" doesn't get plotted in first panel # since this approach doesn't approximate a growth curve. series.rwi <- detrend.series(y = series, y.name = "CAM011", method="Ar") # note the difference between ModNegExp and ModHugershoff at the # start of the series. Also notice how curves, etc. are returned # via return.info data(co021) series <- co021[, 4] names(series) <- rownames(co021) series.rwi <- detrend.series(y = series, y.name = names(co021)[4], method=c("ModNegExp", "ModHugershoff"), verbose = TRUE, return.info = TRUE, make.plot = TRUE) # A dirty dog. # In the case of method=="Spline" the function carries-on # and applies method=="Mean" as an alternative. data(nm046) series <- nm046[,8] names(series) <- rownames(nm046) series.rwi <- detrend.series(y = series, y.name = names(nm046)[8], method="Spline", make.plot = FALSE)library(stats) library(utils) ## Use series CAM011 from the Campito data set data(ca533) series <- ca533[, "CAM011"] names(series) <- rownames(ca533) # all seven methods series.rwi <- detrend.series(y = series, y.name = "CAM011", verbose=TRUE, method = c("Spline", "ModNegExp", "Mean", "Ar", "Friedman", "ModHugershoff", "AgeDepSpline")) # see plot with three methods series.rwi <- detrend.series(y = series, y.name = "CAM011", method=c("Spline", "ModNegExp","Friedman"), difference=TRUE) # see plot with two methods # interesting to note difference from ~200 to 250 years # in terms of what happens to low frequency growth series.rwi <- detrend.series(y = series, y.name = "CAM011", method=c("Spline", "ModNegExp")) # see plot with just one method and change the spline # stiffness to 50 years (which is not neccesarily a good choice!) series.rwi <- detrend.series(y = series, y.name = "CAM011", method="Spline",nyrs=50) # note that method "Ar" doesn't get plotted in first panel # since this approach doesn't approximate a growth curve. series.rwi <- detrend.series(y = series, y.name = "CAM011", method="Ar") # note the difference between ModNegExp and ModHugershoff at the # start of the series. Also notice how curves, etc. are returned # via return.info data(co021) series <- co021[, 4] names(series) <- rownames(co021) series.rwi <- detrend.series(y = series, y.name = names(co021)[4], method=c("ModNegExp", "ModHugershoff"), verbose = TRUE, return.info = TRUE, make.plot = TRUE) # A dirty dog. # In the case of method=="Spline" the function carries-on # and applies method=="Mean" as an alternative. data(nm046) series <- nm046[,8] names(series) <- rownames(nm046) series.rwi <- detrend.series(y = series, y.name = names(nm046)[8], method="Spline", make.plot = FALSE)
These are functions no longer included in dplR
| Function: | plotRings |
| Function: | ffcsaps, use caps instead
|
Subset a rwl object by series (columns) and years (rows), keeping
the class and the provenance record of the data.
## S3 method for class 'rwl' x[i, j, drop] ## S3 method for class 'rwl' subset(x, subset, select, drop = FALSE, ...)## S3 method for class 'rwl' x[i, j, drop] ## S3 method for class 'rwl' subset(x, subset, select, drop = FALSE, ...)
x |
an object of class |
i, j
|
indices for the rows (years) and columns (series), used
exactly as in |
drop |
logical. As in |
subset, select
|
for the |
... |
Not used. |
Subsetting an rwl object works as it does for a
data.frame, with i indexing years and j
indexing series. Four things are different.
Dropping series returns the years the remaining series cover. A
collection is ragged, and the years at the ends of an rwl object
usually belong to a few long series, so dropping some of the series
ordinarily leaves years in which nothing that remains was measured. The result runs
from the first year to the last year in which any of the selected series
has a measurement. Empty years between those two are kept: an
rwl object holds one row per year, and an interior year cannot be
dropped without breaking the sequence.
This applies to calls that drop series without indexing years –
x[, j], x[j], and subset given only select.
Two kinds of call leave the years alone. A call that indexes years
returns exactly the years it asks for, measured or not: x[i, ],
x[i, j], head, tail,
common.interval, and subset with its subset
argument. A year window is how an rwl object is aligned with
something else, such as a climate series or a second collection, and
returning fewer years than were asked for would put that alignment out.
And a call that keeps every series, such as the reordering
x[, order(names(x))] or x[], has dropped nothing to trim
for, whatever empty years the object already held.
Two results are not trimmed. A subset holding no measurement in any year
is returned whole rather than emptied, and rwl.check reports
it. A single series taken with drop = TRUE is a numeric
vector, which carries no years at all, so it is returned at full length
and stays aligned with the object it came from; use drop = FALSE
for a one-series rwl object trimmed to its own years.
subset drops empty series; [ keeps them. Taking
years can leave a series with no values at all: in
ca533[time(ca533) %in% 1800:1899, ], the series CAM132, CAM152,
CAM161 and CAM201 end before 1800 and are left as columns of nothing
but NA. An empty column is not a series. chron,
rwi.stats and the plots skip it, and
summary.rwi, interseries.cor,
corr.rwl.seg and detrend either drop it or
fail on it.
subset and window.rwl therefore drop any series
left with no values, and a message names the series dropped. If no
series is left with values, that is an error. Use one of these to
take a span of years for analysis.
[ keeps every series it is asked for, empty or not, on purpose.
x[i, j] always returns the columns that j names, in that
order, so the result stays lined up with anything indexed alongside it:
a vector of series names, an ids table from
read.ids, or a second object with the same series. If
[ dropped columns, those would fall out of step without a word,
and code that indexes with [ – dplR's own included – could no
longer count on names(x[, j]) being the series it asked for.
So row subsets made with [, and head and
tail, can return empty series. Drop them with
window or subset, or find them with
colSums(!is.na(x)) == 0.
Years must stay consecutive. An rwl object holds one row
per year in increasing order, and dplR reads the year of a measurement
from its row name, so time.rwl, plot.rwl,
detrend, chron, rwl.stats and
the crossdating functions all take the next row to be the next year. A
subset such as x[c(1, 5, 9), ] leaves that untrue. Where row
subsetting leaves years that are not consecutive and increasing, because
rows were taken from the middle, repeated, or reordered, the result is
returned as a plain data.frame, with a warning, and without the
provenance record. The measurements are unchanged; what is withdrawn is
the claim that they are a set of dated series.
The provenance record is carried and cut to fit. The
"dplR.provenance" attribute attached by read.tucson
follows the subset. What describes the file – its name, the reader, the
header lines – is kept. What describes series – the precision of each,
the renames, the interior gaps, the problems found while parsing – is
kept for the series that remain, and gaps are dropped where they fall
outside the years that remain. mixed.precision is recomputed,
since a file measured at two precisions can be subset down to series
measured at one. A subset element is added, holding the series in
the result, its first and last year, and all.series, which is
TRUE when every series the file held is still present. A record
that cannot be matched to a series in the result is dropped rather than
kept, so an object whose series have been renamed since it was read
carries a record that says nothing about them in preference to one that
says something wrong.
common.interval cuts an object down to the years its series
share, which is a different question from the years they cover
between them.
An object of class c("rwl", "data.frame"), or a numeric
vector when one column is selected and drop is TRUE, or a
data.frame when row subsetting has left the years no longer
consecutive. When series are dropped and years are not indexed, the
result runs only over the years the remaining series cover. [
returns every series asked for, including any with no values;
subset drops those, with a message.
Andy Bunn
read.rwl, read.tucson, rwl.check,
common.interval, time.rwl,
subset.data.frame
library(utils) data(ca533) ## Series are columns and years are rows. Selecting series drops the years ## that none of them covers: ca533 begins in 626, but these five series do ## not. ca533.sub <- ca533[, 1:5] class(ca533.sub) range(time(ca533)) range(time(ca533.sub)) ## Naming years returns those years, whether or not they hold data. dim(ca533[time(ca533) %in% 1000:1099, 1:5]) ## subset() works the same way. range(time(subset(ca533, select = 1:5))) ## Years are subset by name or by time(). ca533.1800s <- ca533[time(ca533) %in% 1800:1899, ] range(time(ca533.1800s)) ## Four series end before 1800. `[` keeps them as empty columns, so the ## result still has the 34 series asked for; subset() and window() drop ## them and say which. ncol(ca533.1800s) names(ca533.1800s)[colSums(!is.na(ca533.1800s)) == 0] ncol(subset(ca533, time(ca533) %in% 1800:1899)) ncol(window(ca533, 1800, 1899)) ## A single series comes back as a vector unless drop is FALSE. class(ca533[, 1]) class(ca533[, 1, drop = FALSE]) ## The provenance record of the data follows the subset. data(wa082) gap.series <- attr(wa082, "dplR.provenance")$gaps$series wa082.sub <- wa082[, gap.series, drop = FALSE] attr(wa082.sub, "dplR.provenance")$gaps attr(wa082.sub, "dplR.provenance")$subset$all.series ## Rows taken out of the middle break the one-row-per-year promise that ## dplR relies on. This warns, and gives back a data.frame. not.rwl <- ca533[c(1, 5, 9), ] class(not.rwl)library(utils) data(ca533) ## Series are columns and years are rows. Selecting series drops the years ## that none of them covers: ca533 begins in 626, but these five series do ## not. ca533.sub <- ca533[, 1:5] class(ca533.sub) range(time(ca533)) range(time(ca533.sub)) ## Naming years returns those years, whether or not they hold data. dim(ca533[time(ca533) %in% 1000:1099, 1:5]) ## subset() works the same way. range(time(subset(ca533, select = 1:5))) ## Years are subset by name or by time(). ca533.1800s <- ca533[time(ca533) %in% 1800:1899, ] range(time(ca533.1800s)) ## Four series end before 1800. `[` keeps them as empty columns, so the ## result still has the 34 series asked for; subset() and window() drop ## them and say which. ncol(ca533.1800s) names(ca533.1800s)[colSums(!is.na(ca533.1800s)) == 0] ncol(subset(ca533, time(ca533) %in% 1800:1899)) ncol(window(ca533, 1800, 1899)) ## A single series comes back as a vector unless drop is FALSE. class(ca533[, 1]) class(ca533[, 1, drop = FALSE]) ## The provenance record of the data follows the subset. data(wa082) gap.series <- attr(wa082, "dplR.provenance")$gaps$series wa082.sub <- wa082[, gap.series, drop = FALSE] attr(wa082.sub, "dplR.provenance")$gaps attr(wa082.sub, "dplR.provenance")$subset$all.series ## Rows taken out of the middle break the one-row-per-year promise that ## dplR relies on. This warns, and gives back a data.frame. not.rwl <- ca533[c(1, 5, 9), ] class(not.rwl)
This function fills internal NA values (i.e., those with numeric data
above and below a small data gap) in each column of a
data.frame such as a data set of ring widths as produced by
read.rwl.
fill.internal.NA(x, fill = c("Mean", "Spline", "Linear", "Chron"), series = names(x), nyrs = 20, min.series = 3)fill.internal.NA(x, fill = c("Mean", "Spline", "Linear", "Chron"), series = names(x), nyrs = 20, min.series = 3)
x |
a |
fill |
a |
series |
a |
nyrs |
a number greater than 1. Used only by
|
min.series |
a number, 1 or greater. Used only by
|
There are occasionally data gaps within a tree-ring series. Some of
the functions in dplR will fail
when an internal NA is encountered (e.g. caps). This
function fills internal NA values with either a given numeric value
(e.g., 0) or through crude imputation. The latter can be calculated as
the mean of the series (fill="Mean") or calculated by fitting a cubic spline
(fill="Spline") using the spline function or calculated
by linear approximation (fill="Linear") using the function
approx. Those three look only at the series being
filled. fill="Chron" takes the value from the other series
in x and is described in its own section below.
Editorial: Having internal NA in a tree-ring series is
often bad practice and filling those values should be done with
caution. For instance, some users code missing rings as NA
instead of 0. And missing values (i.e., NA) are
sometimes present in maximum latewood density data when the rings are
small. A common, but not recommended, practice is to leave stretches
of NA values in places where it has been impossible to
accurately measure rings (perhaps because of a break in the core). It
is often better to treat that core as two separate series (e.g., "01A"
and "01B" rather than have internal NA values. As with all
processing, the analyst should make a decision based on their
experience with the wood and not rely on software to make a choice for
them!
x, with the internal NAs of the series named in
series filled as above. It keeps the class and attributes
of x: an rwl object comes back as an rwl
object, with the record read.tucson attached to it.
Before dplR 1.8.1 the result was a plain data.frame.
fill = "Chron")A mean, a line or a spline through one series can say what size of
ring to expect in a gap, but nothing about whether the missing years
were wide or narrow ones. The other trees at the site can.
fill = "Chron" estimates each missing ring from them.
The method is in the spirit of the one in the program
ARSTAN (Cook and Krusic), whose subroutine fillin
fills every gap in a data set before detrending. It follows the same
outline:
A spline of nyrs years (caps) is
fitted to every series in x and each series is divided
by its spline, giving indices. The default of 20 years is
ARSTAN's.
For the series being filled, the indices of all the
other series are averaged year by year with a robust mean
(tbrm).
In each gap year, the departure of that mean from its own average is expressed in standard deviations, and then given the mean and standard deviation of the indices of the series being filled.
The result is multiplied by the spline of the series being filled, to return to ring width. An estimate below zero is set to zero.
It is not a port of fillin and will not reproduce
ARSTAN's numbers. The differences are deliberate:
ARSTAN fits a weighted spline that ignores the gap years. Here the gap is first bridged with a straight line and the spline is fitted to the bridged series.
ARSTAN's mean includes the series being filled. Here it is left out.
ARSTAN detrends the mean a second time and stabilises its variance. Neither is done here.
ARSTAN fills from a single series if that is all
there is and leaves the value missing if there is none. Here a
year with fewer than min.series other series stops
the call.
ARSTAN treats any negative value as a gap, and
zero as well when the data are transformed. Here only NA
is a gap.
Assumptions:
The data are ring widths or another quantity for which a ratio to a growth curve makes sense: no negative values, and a curve that stays above zero.
The series share a common year-to-year signal. The method assumes the series being filled would have followed the others in the years it is missing. Where the series do not crossdate, the filled values are noise with a convincing shape.
The series are correctly dated. A dating error in the series being filled, or in several of the others, puts the wrong year's signal in the gap.
The gap is short relative to nyrs. The
growth curve across a gap comes from a straight line between the
rings either side of it, so over a long gap the level of the filled
values is a guess, whatever their year-to-year pattern.
Limitations:
The filled values are estimates, not measurements, and nothing in the returned object marks which they are. Keep the unfilled data.
The fill is circular. The values come from the other series
and then sit beside them, so statistics that measure agreement
among series (rwi.stats,
interseries.cor, corr.rwl.seg)
are biased upwards in the filled years, and sample depth counts
series that were not measured there. Do not crossdate with filled
values.
The filled values are given the full year-to-year variance of the series, as if it tracked the others perfectly. That keeps the variance of the series from dropping in the gap, at the cost of filled values that vary more than a regression estimate would.
An estimate that falls below zero is returned as zero, with a warning naming the series and years. A zero ring width reads as a locally absent ring everywhere else in dplR.
A year can be filled only if at least
min.series other series were measured in it. If any
gap year falls short, the call stops, names the series and years,
and fills nothing. With min.series of 1 or 2 the
“mean” is one tree or the average of two.
The series being filled and the mean of the others need at least three years in common to set the scale, and a scale set from a few years is poor. Short series are filled badly.
A series with fewer than three measurements, or whose spline reaches zero, has no usable growth curve. If it is one of the series to be filled the call stops. If it is one of the others it is left out of the mean without comment.
Gaps are not filled from each other: a year that is missing in several series is estimated for each from the series that have it.
Filled values do not fall on the measurement grid of the data (0.01 or 0.001 mm). They are not rounded.
Andy Bunn. Patched and improved by Mikko Korpela.
Cook, E. R. and Krusic, P. J. Program ARSTAN: a tree-ring
standardization program based on detrending and autoregressive time
series modeling, with interactive graphics. Tree-Ring Laboratory,
Lamont-Doherty Earth Observatory of Columbia University. The
"Chron" method follows the outline of subroutine
fillin in version 49v1 of the Fortran source.
library(graphics) library(stats) foo <- data.frame(x1=c(rnorm(5), NA, NA, rnorm(3)), x2=c(rnorm(10)), x3=c(NA, NA, rnorm(3), NA, rnorm(4)), x4=c(NA, NA, rnorm(3), NA, rnorm(3), NA), x5=c(NA, NA, rnorm(8)), x6=c(NA, rnorm(9)), x7=c(NA, rnorm(5), NA, rnorm(3)), x8=c(rnorm(8), NA, NA), x9=c(rnorm(5), NA, rnorm(3), NA)) row.names(foo) <- 1901:1910 class(foo) <- c("rwl","data.frame") fill.internal.NA(foo, fill=0) bar <- fill.internal.NA(foo, fill="Spline") baz <- fill.internal.NA(foo, fill="Linear") ## note differences in method "Spline" vs. "Linear" yrs <- time(foo) plot(yrs, foo$x7, type="b", lwd=3) lines(yrs, bar$x7, col="red", lwd=2) lines(yrs, baz$x7, col="green", lwd=1) ## fill = "Chron" uses the other series. Remove ten rings from one ## series of co021 and compare the estimates with what was measured. data(co021) gap <- 1701:1710 gap2 <- as.character(gap) dat <- co021 dat[gap2, "641114"] <- NA chr <- fill.internal.NA(dat, fill="Chron", series="641114") lin <- fill.internal.NA(dat, fill="Linear", series="641114") plot(gap, co021[gap2, "641114"], type="b", lwd=3, xlab="Year", ylab="Ring width (mm)", ylim = c(0.1,0.75)) lines(gap, chr[gap2, "641114"], col="darkred", lwd=2) lines(gap, lin[gap2, "641114"], col="darkgreen", lwd=2)library(graphics) library(stats) foo <- data.frame(x1=c(rnorm(5), NA, NA, rnorm(3)), x2=c(rnorm(10)), x3=c(NA, NA, rnorm(3), NA, rnorm(4)), x4=c(NA, NA, rnorm(3), NA, rnorm(3), NA), x5=c(NA, NA, rnorm(8)), x6=c(NA, rnorm(9)), x7=c(NA, rnorm(5), NA, rnorm(3)), x8=c(rnorm(8), NA, NA), x9=c(rnorm(5), NA, rnorm(3), NA)) row.names(foo) <- 1901:1910 class(foo) <- c("rwl","data.frame") fill.internal.NA(foo, fill=0) bar <- fill.internal.NA(foo, fill="Spline") baz <- fill.internal.NA(foo, fill="Linear") ## note differences in method "Spline" vs. "Linear" yrs <- time(foo) plot(yrs, foo$x7, type="b", lwd=3) lines(yrs, bar$x7, col="red", lwd=2) lines(yrs, baz$x7, col="green", lwd=1) ## fill = "Chron" uses the other series. Remove ten rings from one ## series of co021 and compare the estimates with what was measured. data(co021) gap <- 1701:1710 gap2 <- as.character(gap) dat <- co021 dat[gap2, "641114"] <- NA chr <- fill.internal.NA(dat, fill="Chron", series="641114") lin <- fill.internal.NA(dat, fill="Linear", series="641114") plot(gap, co021[gap2, "641114"], type="b", lwd=3, xlab="Year", ylab="Ring width (mm)", ylim = c(0.1,0.75)) lines(gap, chr[gap2, "641114"], col="darkred", lwd=2) lines(gap, lin[gap2, "641114"], col="darkgreen", lwd=2)
This function calculates the Gini coefficient on raw or detrended ring-width series.
gini.coef(x)gini.coef(x)
x |
a |
This calculates the Gini coefficient of inequality which is used as an all-lag measure of diversity in tree-ring records – typically detrended series. Lower values indicate lower diversity. The use of the Gini coefficient in dendrochronology is described by Biondi and Qeadan (2008). See Handcock and Morris (1999) for more information.
the Gini coefficient.
The equivalence between the Lorenz-curve formula used in the C code and
the relative-mean-difference definition of the Gini coefficient is
derived in the vignette:
vignette("math-dplR", package = "dplR").
Mikko Korpela, based on original by Andy Bunn
Biondi, F. and Qeadan, F. (2008) Inequality in Paleorecords. Ecology, 89(4), 1056–1067.
Handcock, M. S. and Morris, M. (1999) Relative Distribution Methods in the Social Sciences. Springer. ISBN: 0-387-98778-9.
library(utils) data(ca533) ca533.rwi <- detrend(rwl = ca533, method = "ModNegExp") ca533.crn <- chron(ca533.rwi) gini.coef(ca533.crn)library(utils) data(ca533) ca533.rwi <- detrend(rwl = ca533, method = "ModNegExp") ca533.crn <- chron(ca533.rwi) gini.coef(ca533.crn)
This function calculates the Gleichläufigkeit and related measures for a given set of tree-ring records.
glk(x, overlap = 50, prob = TRUE) glk.legacy(x)glk(x, overlap = 50, prob = TRUE) glk.legacy(x)
x |
a |
overlap |
integer value with minimal length of overlapping growth changes (compared number of tree rings - 1). Comparisons with less overlap are not compared. |
prob |
if |
Gleichläufigkeit is a classical agreement test based on sign tests (Eckstein and Bauch, 1969). This function implements Gleichläufigkeit as the pairwise comparison of all records in data set. This vectorized implementation is faster than the previous version and follows the original definition (Huber 1942), instead of the incorrect interpretation that has been used in the past (Schweingruber 1988, see Buras/Wilmking 2015 for the correction).
The probability of exceedence (p) for the Gleichläufigkeit expresses the chance that the Gleichläufigkeit is incorrect. The observed value of the Gleichläufigkeit is converted to a z-score and based on the standard normal curve the probability of exceedence is calculated. The result is a matrix of all p-values (Jansma 1995, 60-61, see also Visser 2020).
Note that prior to dplR version 1.7.2, glk did not have the overlap or prob and returned a matrix with just the Gleichläufigkeit for all possible combinations of records. That function can still be accessed via glk.legacy.
The funtions returns a named list of two or three matrices (p_mat is optional if prob = TRUE):
glk_mat: matrix with Gleichläufigkeit
overlap: matrix with number of overlapping growth changes.This is the number of overlapping years minus one.
p_mat: matrix of all probabilities of exceedence for all observed Gleichläufigkeit values.
The matrices can be extracted from the list by selecting the name or index number. If two curves have less than 3 years of overlap, Gleichläufigkeit cannot be computed, and NA is returned.
To calculate the global glk of the dataset mean(x$glk_mat, na.rm = TRUE). See examples for calculating the the global glk without self-similarities (i.e., the ones on the diagonal).
Christian Zang. Patched and improved by Mikko Korpela. Improved by Allan Buras. Further improved and expanded by Ronald Visser and Andy Bunn
Buras, A. and Wilmking, M. (2015) Correcting the calculation of Gleichläufigkeit, Dendrochronologia 34, 29-30. DOI: https://doi.org/10.1016/j.dendro.2015.03.003
Eckstein, D. and Bauch, J. (1969) Beitrag zur Rationalisierung eines dendrochronologischen Verfahrens und zur Analyse seiner Aussagesicherheit. Forstwissenschaftliches Centralblatt, 88(1), 230-250.
Huber, B. (1943) Über die Sicherheit jahrringchronologischer Datierung. Holz als Roh- und Werkstoff 6, 263-268. DOI: https://doi.org/10.1007/BF02603303
Jansma, E., 1995. RemembeRINGs; The development and application of local and regional tree-ring chronologies of oak for the purposes of archaeological and historical research in the Netherlands, Nederlandse Archeologische Rapporten 19, Rijksdienst voor het Oudheidkundig Bodemonderzoek, Amersfoort
Schweingruber, F. H. (1988) Tree rings: basics and applications of dendrochronology, Kluwer Academic Publishers, Dordrecht, Netherlands, 276 p.
Visser, R.M. (2020) On the similarity of tree-ring patterns: Assessing the influence of semi-synchronous growth changes on the Gleichläufigkeit for big tree-ring data sets,Archaeometry, 63, 204-215 DOI: https://doi.org/10.1111/arcm.12600
sgc sgc is an alternative for glk)
library(utils) data(ca533) ca533.glklist <- glk(ca533) ca533.glk_mat <- ca533.glklist$glk_mat # calculating the mean GLK including self-similarities mean(ca533.glk_mat, na.rm = TRUE) # calculating the mean GLK excluding self-similarities mean(ca533.glk_mat[upper.tri(ca533.glk_mat)], na.rm = TRUE)library(utils) data(ca533) ca533.glklist <- glk(ca533) ca533.glk_mat <- ca533.glklist$glk_mat # calculating the mean GLK including self-similarities mean(ca533.glk_mat, na.rm = TRUE) # calculating the mean GLK excluding self-similarities mean(ca533.glk_mat[upper.tri(ca533.glk_mat)], na.rm = TRUE)
gp.rwl This data set gives the distance to pith for each series (in mm) that
matches the ring widths for gp.rwl – a data set of
ponderosa pine (Pinus ponderosa) from the Gus Pearson Natural
Area (GPNA) in northern Arizona, USA. Data are
further described by Biondi and Qeadan (2008) and references therein.
data(gp.d2pith)data(gp.d2pith)
A data.frame with 58 rows, one for each series of
gp.rwl and in the order of its columns, containing
series IDs in column 1
(series) and the distance (in mm) from the innermost ring
to the pith of the tree (d2pith). This can be used
together with the ring widths to calculate the area of each ring.
DendroLab, University of Nevada Reno, USA. https://dendrolaborg.wordpress.com/
Biondi, F. and Qeadan, F. (2008) A theory-driven approach to tree-ring standardization: Defining the biological trend from expected basal area increment. Tree-Ring Research, 64(2), 81–96.
gp.rwl) This data set gives the diameter at breast height for each series that
matches the series in gp.rwl – a data set of ponderosa
pine (Pinus ponderosa) from the Gus Pearson Natural Area
(GPNA) in northern Arizona, USA. Data are further
described by Biondi and Qeadan (2008) and references therein.
data(gp.dbh)data(gp.dbh)
A data.frame with 58 rows, one for each series of
gp.rwl and in the order of its columns, containing
series IDs in column 1 (ID), tree diameter (in cm)
at breast height (DBH), and the bark thickness (in cm,
BARK). The two cores of a tree have the same diameter. This
can be used together with the ring widths to calculate the area of
each ring: see the example in bai.out.
DendroLab, University of Nevada Reno, USA. https://dendrolaborg.wordpress.com/
Biondi, F. and Qeadan, F. (2008) A theory-driven approach to tree-ring standardization: Defining the biological trend from expected basal area increment. Tree-Ring Research, 64(2), 81–96.
gp.rwl, gp.po,
gp.d2pith, bai.out
gp.rwl This data set gives the pith offsets that match the ring widths for
gp.rwl – a data set of ponderosa pine (Pinus
ponderosa) from the Gus Pearson Natural Area (GPNA) in
northern Arizona, USA. Data are further described by Biondi
and Qeadan (2008) and references therein.
data(gp.po)data(gp.po)
A data.frame with 58 rows, one for each series of
gp.rwl and in the order of its columns, and two
variables:
series the series ID, a factor. It
matches names(gp.rwl).
pith.offset an integer: the number of years
between the beginning of that series in gp.rwl and the
pith of the tree. The values run from 1 to 249.
A pith offset says how old the tree was, at the height of the core, when the first measured ring was laid down. An offset of 1 means the first ring of the series is the first ring of the tree. Added to the position of a ring in its series, it gives the cambial age of that ring: the first ring of a series with an offset of 79 has a cambial age of 79.
This is the form of po that rcs and
cms take, and the data can be used as they are with
gp.rwl. See the examples.
The two cores of a tree have offsets of their own.
DendroLab, University of Nevada Reno, USA. https://dendrolaborg.wordpress.com/
Biondi, F. and Qeadan, F. (2008) A theory-driven approach to tree-ring standardization: Defining the biological trend from expected basal area increment. Tree-Ring Research, 64(2), 81–96.
gp.rwl, gp.d2pith,
gp.dbh, rcs, cms
data(gp.rwl) data(gp.po) head(gp.po) summary(gp.po$pith.offset) ## the offsets are in the order of the series identical(as.character(gp.po$series), names(gp.rwl)) ## cambial age of each ring of the first series age <- gp.po$pith.offset[1] - 1 + seq_len(sum(!is.na(gp.rwl[[1]]))) range(age) ## as the po argument of cms() and rcs() gp.rwi <- cms(rwl = gp.rwl, po = gp.po)data(gp.rwl) data(gp.po) head(gp.po) summary(gp.po$pith.offset) ## the offsets are in the order of the series identical(as.character(gp.po$series), names(gp.rwl)) ## cambial age of each ring of the first series age <- gp.po$pith.offset[1] - 1 + seq_len(sum(!is.na(gp.rwl[[1]]))) range(age) ## as the po argument of cms() and rcs() gp.rwi <- cms(rwl = gp.rwl, po = gp.po)
This data set includes ring-width measurements for ponderosa pine (Pinus ponderosa) increment cores collected at the Gus Pearson Natural Area (GPNA) in northern Arizona, USA. There are 58 series from 29 trees (2 cores per tree). Data are further described by Biondi and Qeadan (2008) and references therein.
data(gp.rwl)data(gp.rwl)
An object of class c("rwl", "data.frame") containing 58
ring-width series in columns and 421 years in rows, 1570 to 1990.
Each series is named by a two-digit tree number and a letter for the
core, A or B: "01A" and "01B" are the two
cores of tree 1. The tree numbers run from 1 to 59 with gaps.
Ring widths are in mm, to 0.01 mm. The series hold 16,408 ring widths in all, of which 194 are zero. Series are between 92 and 418 rings long. All end in 1990 but one, which ends in 1987. No series has a year without a measurement inside its span.
Three other data sets hold one row for each series of gp.rwl,
in the order of its columns:
With two cores for every tree, these data are useful for anything
that separates agreement within trees from agreement between them.
read.ids(gp.rwl, stc = c(0, 2, 1)) gives the tree and core of
each series for rwi.stats, sss and
summary.rwi.
The Gus Pearson Natural Area is a permanent plot of 800 by 400 m, established in 1908 in ponderosa pine forest near Flagstaff, Arizona. Its history, and the growth of its trees through the twentieth century, are described by Biondi (1996, 1999).
DendroLab, University of Nevada Reno, USA. https://dendrolaborg.wordpress.com/
Biondi, F. (1996) Decadal-scale dynamics at the Gus Pearson Natural Area: evidence for inverse (a)symmetric competition? Canadian Journal of Forest Research, 26(8), 1397–1406.
Biondi, F. (1999) Comparing tree-ring chronologies and repeated timber inventories as forest monitoring tools. Ecological Applications, 9(1), 216–227.
Biondi, F. and Qeadan, F. (2008) A theory-driven approach to tree-ring standardization: Defining the biological trend from expected basal area increment. Tree-Ring Research, 64(2), 81–96.
gp.po, gp.d2pith,
gp.dbh, read.ids
data(gp.rwl) summary(gp.rwl)[1:6, ] ## which series are cores of the same tree gp.ids <- read.ids(gp.rwl, stc = c(0, 2, 1)) head(gp.ids) ## two cores for each of 29 trees table(table(gp.ids$tree)) ## the pith offsets, distances to pith and diameters are in the ## order of the series data(gp.po) identical(as.character(gp.po$series), names(gp.rwl))data(gp.rwl) summary(gp.rwl)[1:6, ] ## which series are cores of the same tree gp.ids <- read.ids(gp.rwl, stc = c(0, 2, 1)) head(gp.ids) ## two cores for each of 29 trees table(table(gp.ids$tree)) ## the pith offsets, distances to pith and diameters are in the ## order of the series data(gp.po) identical(as.character(gp.po$series), names(gp.rwl))
Applies a Hanning filter of length n to x.
hanning(x, n = 7)hanning(x, n = 7)
x |
a vector |
n |
length of the Hanning filter, defaults to 7 |
This applies a low frequency Hanning (a.k.a. Hann) filter to
x with weight set to n.
A filtered vector.
Andy Bunn. Patched and improved by Mikko Korpela.
Oppenheim, A. V., Schafer, R. W., and Buck, J. R. (1999) Discrete-Time Signal Processing. Prentice-Hall, 2nd edition. ISBN-13: 978-0-13-754920-7.
library(graphics) library(utils) data(ca533) yrs <- time(ca533) y <- ca533[, 1] not.na <- !is.na(y) yrs <- yrs[not.na] y <- y[not.na] plot(yrs, y, xlab = "Years", ylab = "Series1 (mm)", type = "l", col = "grey") lines(yrs, hanning(y, n = 9), col = "red", lwd = 2) lines(yrs, hanning(y, n = 21), col = "blue", lwd = 2) legend("topright", c("Series", "n=9", "n=21"), fill=c("grey", "red", "blue"))library(graphics) library(utils) data(ca533) yrs <- time(ca533) y <- ca533[, 1] not.na <- !is.na(y) yrs <- yrs[not.na] y <- y[not.na] plot(yrs, y, xlab = "Years", ylab = "Series1 (mm)", type = "l", col = "grey") lines(yrs, hanning(y, n = 9), col = "red", lwd = 2) lines(yrs, hanning(y, n = 21), col = "blue", lwd = 2) legend("topright", c("Series", "n=9", "n=21"), fill=c("grey", "red", "blue"))
Interactively detrend multiple tree-ring series by one of two methods, a
smoothing spline or a statistical model. This is a wrapper for
detrend.series.
i.detrend(rwl, y.name = names(rwl), nyrs = NULL, f = 0.5, pos.slope = FALSE)i.detrend(rwl, y.name = names(rwl), nyrs = NULL, f = 0.5, pos.slope = FALSE)
rwl |
a |
y.name |
a |
nyrs |
a number giving the rigidity of the smoothing spline,
defaults to 0.67 of series length if |
f |
a number between 0 and 1 giving the frequency response or wavelength cutoff. Defaults to 0.5. |
pos.slope |
a |
This function allows a user to choose detrending curves based on plots
that are produced by detrend.series for which it is
essentially a wrapper. The user enters their choice of detrended
method via keyboard at a prompt for each ring width series in
rwl. See detrend.series for examples and
details on the detrending methods.
A series with no values at all is dropped, with a message naming it,
before any series is shown, and its name is dropped from
y.name too.
An object of class c("rwi", "data.frame") (see
as.rwi) containing each detrended series according to
the method used as columns and rownames set to
colnames(y). These are typically years. The method
chosen for each series is recorded, named by series, in
attr(x, "dplR.detrend")$method. Plots are also
produced as the user chooses the detrending methods through keyboard
input.
This function is kept for old scripts. For interactive detrending use the iDetrend app (https://github.com/OpenDendro/iDetrend), part of openDendro. There the curve for each series can be adjusted and compared with others on screen, series that need attention are pointed out, and the app writes R code that reproduces the indices. Here the choice is made once per series from a static plot, the parameters of the curves cannot be changed series by series, and only the name of the method chosen is recorded. The function says so, once in a session, when it is called.
Andy Bunn
Interactively detrend a tree-ring series by one of three methods, a
smoothing spline, a linear model, or the mean. This is a wrapper for
detrend.series.
i.detrend.series(y, y.name = NULL, nyrs = NULL, f = 0.5, pos.slope = FALSE)i.detrend.series(y, y.name = NULL, nyrs = NULL, f = 0.5, pos.slope = FALSE)
y |
a |
y.name |
an optional |
nyrs |
a number giving the rigidity of the smoothing spline,
defaults to 0.67 of series length if |
f |
a number between 0 and 1 giving the frequency response or wavelength cutoff. Defaults to 0.5. |
pos.slope |
a |
This function allows a user to choose a detrending method based on a
plot that is produced by detrend.series for which it is
essentially a wrapper. The user enters their choice of detrended
method via keyboard at a prompt. See detrend.series for
examples and details on the detrending methods.
A vector containing the detrended series (y) according to
the method used with names set to colnames(y). These are
typically years. The name of the method chosen is attached as
attr(x, "method"). A plot is also produced and the user
chooses a method through keyboard input.
This function is kept for old scripts. For interactive detrending use the iDetrend app (https://github.com/OpenDendro/iDetrend), part of openDendro. There the curve for each series can be adjusted and compared with others on screen, series that need attention are pointed out, and the app writes R code that reproduces the indices. Here the choice is made once per series from a static plot, the parameters of the curves cannot be changed series by series, and only the name of the method chosen is recorded. The function says so, once in a session, when it is called.
Andy Bunn. Patched and improved by Mikko Korpela.
Insert or delete rings from a ring-width series, given either as a
vector or as one series of an rwl object.
insert.ring(rw.vec, ...) delete.ring(rw.vec, ...) ## Default S3 method: insert.ring(rw.vec, rw.vec.yrs = as.numeric(names(rw.vec)), year, ring.value = mean(rw.vec, na.rm = TRUE), fix.last = TRUE, fix.length = TRUE, ...) ## Default S3 method: delete.ring(rw.vec, rw.vec.yrs = as.numeric(names(rw.vec)), year, fix.last = TRUE, fix.length = TRUE, ...) ## S3 method for class 'rwl' insert.ring(rw.vec, series, year, ring.value = mean(rw.vec[[series]], na.rm = TRUE), fix.last = TRUE, ...) ## S3 method for class 'rwl' delete.ring(rw.vec, series, year, fix.last = TRUE, ...)insert.ring(rw.vec, ...) delete.ring(rw.vec, ...) ## Default S3 method: insert.ring(rw.vec, rw.vec.yrs = as.numeric(names(rw.vec)), year, ring.value = mean(rw.vec, na.rm = TRUE), fix.last = TRUE, fix.length = TRUE, ...) ## Default S3 method: delete.ring(rw.vec, rw.vec.yrs = as.numeric(names(rw.vec)), year, fix.last = TRUE, fix.length = TRUE, ...) ## S3 method for class 'rwl' insert.ring(rw.vec, series, year, ring.value = mean(rw.vec[[series]], na.rm = TRUE), fix.last = TRUE, ...) ## S3 method for class 'rwl' delete.ring(rw.vec, series, year, fix.last = TRUE, ...)
rw.vec |
a vector of ring widths, or an object of class
|
rw.vec.yrs |
the years for |
series |
for an |
year |
for |
ring.value |
the value to add |
fix.last |
logical. If TRUE the last year of the series is fixed and the first year changes. |
fix.length |
logical. If TRUE the length of the output will be the length of the input. Vectors only. |
... |
not used. |
Simple editing of ring widths. A missing ring is corrected by
inserting one, a false ring by deleting one. With fix.last =
TRUE (the default) the outermost ring keeps its year, as for a core
with a known bark date, and every ring before the edit moves one year.
For a vector, fix.length = TRUE keeps the output the length of
the input, so that it can be put back into the rwl object it
came from. Inserting a ring then drops a value from one end. If that
value is a measurement, because the series starts (or, with
fix.last = FALSE, ends) on the first (last) year of
rw.vec, it is lost, and insert.ring warns.
For an rwl object, the series named in series is
edited and the whole object returned. Nothing is dropped: the series
is edited from its first to its last measurement and put back, and
years are added to or removed from the ends of the object as needed.
Gaps inside the series (internal NA) keep their place among the
rings around them. The other series, the class and the attributes of
the object (such as the record attached by
read.tucson) are unchanged.
For a vector, a named vector. For an rwl object, the edited
rwl object.
Andy Bunn. Patched and improved by Mikko Korpela.
library(utils) data(gp.rwl) dat <- gp.rwl # insert a value of zero for the year 1950 in series 50A # fix the last year of growth and maintain the length of the series tmp <- insert.ring(rw.vec=dat$"50A",rw.vec.yrs = time(dat), year=1950,ring.value=0,fix.length = TRUE) # with fix.length=TRUE this can be merged back into the rwl object: data.frame(dat$"50A",tmp) dat$"50A" <- tmp # note that if fix.last = FALSE and fix.length = FALSE inserting a ring causes the # ending year of the series to be pushed forward and the length of the output to # be longer than the original series. tmp <- insert.ring(rw.vec=dat$"50A",rw.vec.yrs = time(dat), year=1950,ring.value=0, fix.last = FALSE, fix.length = FALSE) # with fix.length=FALSE this can't be merged back into the rwl object the # same way as above tail(tmp) length(tmp) nrow(dat) # the same logic applies to deleting rings. dat <- gp.rwl # delete the year 1950 in series 50A # fix the last year of growth and maintain the length of the series tmp <- delete.ring(rw.vec=dat$"50A",rw.vec.yrs = time(dat), year=1950,fix.last = TRUE, fix.length = TRUE) # with fix.length=TRUE this can be merged back into the rwl object: data.frame(dat$"50A",tmp) dat$"50A" <- tmp # note that if fix.last = FALSE and fix.length = FALSE inserting a ring causes the # ending year of the series to be pushed forward and the length of the output to # be longer than the original series. tmp <- delete.ring(rw.vec=dat$"50A", rw.vec.yrs = time(dat), year=1950, fix.last = FALSE, fix.length = FALSE) # with fix.length=FALSE this can't be merged back into the rwl object the # same way as above tail(tmp) length(tmp) nrow(dat) # An rwl object can be edited directly, one series at a time. # Plant a missing ring in series 50A by deleting its 1950 ring. With # fix.last = TRUE every earlier ring moves one year later, so the ring # that was 1949 is now dated 1950 and the gap follows it. Put the ring # back by inserting it after 1950 dat <- gp.rwl dat2 <- delete.ring(dat, series = "50A", year = 1950) dat3 <- insert.ring(dat2, series = "50A", year = 1950, ring.value = dat$"50A"[time(dat) == 1950]) all.equal(dat3$"50A", dat$"50A") # edits can be chained, and the result is still an rwl object class(dat3)library(utils) data(gp.rwl) dat <- gp.rwl # insert a value of zero for the year 1950 in series 50A # fix the last year of growth and maintain the length of the series tmp <- insert.ring(rw.vec=dat$"50A",rw.vec.yrs = time(dat), year=1950,ring.value=0,fix.length = TRUE) # with fix.length=TRUE this can be merged back into the rwl object: data.frame(dat$"50A",tmp) dat$"50A" <- tmp # note that if fix.last = FALSE and fix.length = FALSE inserting a ring causes the # ending year of the series to be pushed forward and the length of the output to # be longer than the original series. tmp <- insert.ring(rw.vec=dat$"50A",rw.vec.yrs = time(dat), year=1950,ring.value=0, fix.last = FALSE, fix.length = FALSE) # with fix.length=FALSE this can't be merged back into the rwl object the # same way as above tail(tmp) length(tmp) nrow(dat) # the same logic applies to deleting rings. dat <- gp.rwl # delete the year 1950 in series 50A # fix the last year of growth and maintain the length of the series tmp <- delete.ring(rw.vec=dat$"50A",rw.vec.yrs = time(dat), year=1950,fix.last = TRUE, fix.length = TRUE) # with fix.length=TRUE this can be merged back into the rwl object: data.frame(dat$"50A",tmp) dat$"50A" <- tmp # note that if fix.last = FALSE and fix.length = FALSE inserting a ring causes the # ending year of the series to be pushed forward and the length of the output to # be longer than the original series. tmp <- delete.ring(rw.vec=dat$"50A", rw.vec.yrs = time(dat), year=1950, fix.last = FALSE, fix.length = FALSE) # with fix.length=FALSE this can't be merged back into the rwl object the # same way as above tail(tmp) length(tmp) nrow(dat) # An rwl object can be edited directly, one series at a time. # Plant a missing ring in series 50A by deleting its 1950 ring. With # fix.last = TRUE every earlier ring moves one year later, so the ring # that was 1949 is now dated 1950 and the gap follows it. Put the ring # back by inserting it after 1950 dat <- gp.rwl dat2 <- delete.ring(dat, series = "50A", year = 1950) dat3 <- insert.ring(dat2, series = "50A", year = 1950, ring.value = dat$"50A"[time(dat) == 1950]) all.equal(dat3$"50A", dat$"50A") # edits can be chained, and the result is still an rwl object class(dat3)
This function calculates the correlation between a series and a master chronology.
interseries.cor(rwl, n = NULL, nyrs = NULL, prewhiten = TRUE, ar.order.max = NULL, biweight = TRUE, method = c("spearman", "pearson", "kendall"))interseries.cor(rwl, n = NULL, nyrs = NULL, prewhiten = TRUE, ar.order.max = NULL, biweight = TRUE, method = c("spearman", "pearson", "kendall"))
rwl |
a |
n |
|
nyrs |
|
prewhiten |
|
ar.order.max |
|
biweight |
|
method |
Can be either |
This function calculates correlation serially between each tree-ring
series and a master chronology built from all the other series in the
rwl object (leave-one-out principle).
Each series in the rwl object is optionally
detrended as the residuals from a hanning filter with
weight n. The filter is not applied if n is
NULL. Detrending can also be done via prewhitening where the
residuals of an ar model are added to each series
mean. This is the default. The master chronology is computed as the
mean of the rwl object using tbrm if
biweight is TRUE and rowMeans if not. Note
that detrending can change the length of the series. E.g., a
hanning filter will shorten the series on either end by
floor(n/2). The prewhitening default will change the
series length based on the ar model fit. The effects of
detrending can be seen with series.rwl.plot.
This function produces the same output of the overall portion of
corr.rwl.seg. The mean correlation value given is sometimes
referred to as the “overall interseries correlation” or the “COFECHA
interseries correlation”. This output differs from the rbar
statistics given by rwi.stats in that rbar is
the average pairwise correlation between series where this is the
correlation between a series and a master chronology.
a data.frame with correlation values and p-values given from
cor.test
Andy Bunn, patched and improved by Mikko Korpela
library(utils) data(gp.rwl) foo <- interseries.cor(gp.rwl) # compare to: # corr.rwl.seg(rwl=gp.rwl,make.plot=FALSE)$overall # using pearson's r foo <- interseries.cor(gp.rwl,method="pearson") # two measures of interseries correlation # compare interseries.cor to rbar from rwi.stats gp.ids <- read.ids(gp.rwl, stc = c(0, 2, 1)) bar <- rwi.stats(gp.rwl, gp.ids, prewhiten=TRUE) bar$rbar.eff mean(foo[,1])library(utils) data(gp.rwl) foo <- interseries.cor(gp.rwl) # compare to: # corr.rwl.seg(rwl=gp.rwl,make.plot=FALSE)$overall # using pearson's r foo <- interseries.cor(gp.rwl,method="pearson") # two measures of interseries correlation # compare interseries.cor to rbar from rwi.stats gp.ids <- read.ids(gp.rwl, stc = c(0, 2, 1)) bar <- rwi.stats(gp.rwl, gp.ids, prewhiten=TRUE) bar$rbar.eff mean(foo[,1])
Fits an autoregressive model whose coefficients are allowed to change
through time, using the Kalman filter and a fixed-interval smoother.
The result goes to kalman.spec for an evolutive spectrum:
a spectrum for every year.
kalman.ar(y, yrs = NULL, order, prior = c("rw1", "rw2"), lambda = NULL, variance = c("constant", "varying"), nu = NULL) ## S3 method for class 'kalman.ar' print(x, digits = 4, ...)kalman.ar(y, yrs = NULL, order, prior = c("rw1", "rw2"), lambda = NULL, variance = c("constant", "varying"), nu = NULL) ## S3 method for class 'kalman.ar' print(x, digits = 4, ...)
y |
a |
yrs |
|
order |
the order of the autoregression, a whole number. There is no default. See ‘Details’. |
prior |
how the coefficients move from year to year.
|
lambda |
the variance of the yearly change in the coefficients
( |
variance |
|
nu |
with |
x |
an object of class |
digits |
number of significant digits to print. |
... |
not used. |
The model for a series with its mean removed is
where is white noise with variance
. This is the ordinary AR() model
except that the coefficients carry a time index. They are treated as
the unobserved state of a state-space model and estimated for each
year from the whole series (Kitagawa and Gersch 1985).
One number, lambda, sets how freely the coefficients
move. At zero under "rw1" they do not move and the model is
the ordinary one. At zero under "rw2" they change along
straight lines. As lambda grows the coefficients follow
the series more closely, and eventually follow its noise.
Choosing order and lambda is the user’s
job. Maximum likelihood for lambda is a sound starting
point, but it answers a narrow question: whether one-step predictions
improve when the coefficients move. It can return zero, as it does
for the sunspot numbers in the examples. A larger value set by hand
will always show a spectrum that changes; a series with fixed
coefficients shows the same when fitted that way, so such a picture
is not by itself evidence of change. Ed Cook, who suggested this method for
dplR, reports that trying several orders served him better than
a criterion such as AIC, and that orders well above what
AIC would pick can be needed to resolve a cycle (30 for the
roughly 11-year sunspot cycle). If a cycle of known period is the
target, the lags should span a few cycles of it, and
order should stay well below the number of years: for
the 289 years of sunspot numbers, order 30 spans nearly three cycles,
while order 60 leaves fewer than five years for each coefficient and
fills the spectrum with peaks that the series cannot support. A
picture that depends on the
setting should be reported with the setting. profile
on a fit shows the likelihood over a range of lambda.
The log-likelihood is that of the one-step prediction errors, with
the coefficients given a vague starting distribution and the first
prediction errors, as many as there are elements in the state
(order for "rw1", twice that for "rw2"),
left out. It is given for the fitted model and for the ordinary
AR model with fixed coefficients over the same years, so the two can
be compared. AIC counts and, if
they were estimated, lambda and nu. Log-likelihoods from different
orders or different priors are over different years and cannot be
compared.
By default the innovation variance is constant. A series whose
year-to-year scatter changes, as a chronology’s can where
sample depth is low, is then at risk of having that change read as a
change in the coefficients. With variance = "varying" the
innovation variance of year is
, where the logarithm of
is a random walk with step variance nu
and averages zero. It is estimated from the squared one-step
prediction errors, whose logarithms are the log variance plus noise of
known variance (Harvey et al. 1994); the filter is then run
again with the new variances, and the two steps repeat until the
variances settle. nu is chosen by a quasi-likelihood,
and when that gives zero the variance is constant and a message says
so. The path is smooth: an abrupt or short-lived change in variance
is spread out and understated.
The innovation variance is the size of what cannot be predicted one
year ahead. It is not the variance of the series, and it does not
respond to a slow, large swing in a strongly autocorrelated series,
which needs only a run of ordinary innovations of the same sign.
Such events show in a wavelet analysis (morlet) and
not here.
The variance path is estimated from the prediction errors and then
treated as known. The log-likelihood of a fit with
variance = "varying" is therefore somewhat too high when set
against a fit with constant variance. The comparison with fixed
coefficients inside one fit is not affected: both use the same path.
A residual chronology has had its autocorrelation removed and is seldom what is wanted here.
A year enters the fit only if it and the order years
before it all have values. One NA inside the series therefore
takes order + 1 years out of the fit; a message gives
the count. Coefficients are still returned for those years, carried
across from the years on either side.
Nothing forces the coefficients of a year to be those of a stationary
process. The number of years in which they are not is printed, and
stationary in the result identifies them. A spectrum is still
computed for such years but its peaks should not be trusted. Many
such years suggest that lambda or order is
too high.
Memory use grows with the number of years times the square of the length of the state.
An object of class "kalman.ar", a list with elements:
coef |
|
se |
|
yrs |
the years of the rows of |
order, prior
|
as given. |
lambda |
the value used. |
lambda.estimated |
|
sigma2 |
innovation variance, in the units of |
sigma2.t |
innovation variance of each year, one per row of
|
variance |
as given. |
nu, nu.estimated
|
the value used and whether it was
estimated. |
loglik, aic
|
log-likelihood and AIC. |
fixed |
a |
stationary |
|
n, n.used, n.lik, n.skipped
|
years in the series, years that entered the fit, years in the likelihood, and years left out because of missing values. |
y, y.yrs, mean
|
the series, its years and its mean. |
call |
the call. |
This function is experimental and may change in future releases:
arguments, defaults and the object returned. How to choose
order and lambda is not settled.
Written from the published method at the suggestion of Ed Cook. It is not a port of his programs and will not reproduce their numbers.
Andy Bunn
Harvey, A., Ruiz, E. and Shephard, N. (1994) Multivariate stochastic variance models. Review of Economic Studies, 61(2), 247–264.
Kitagawa, G. and Gersch, W. (1985) A smoothness priors time-varying AR coefficient modeling of nonstationary covariance time series. IEEE Transactions on Automatic Control, 30(1), 48–56.
Kitagawa, G. and Gersch, W. (1996) Smoothness Priors Analysis of Time Series. Lecture Notes in Statistics 116. Springer.
kalman.spec, profile.kalman.ar,
morlet,
redfit, ar
## Annual sunspot numbers. Maximum likelihood finds no gain from ## letting the coefficients move: ss <- datasets::sunspot.year fit <- kalman.ar(as.numeric(ss), yrs = as.numeric(time(ss)), order = 30) fit ## Setting lambda by hand lets them move fit2 <- kalman.ar(as.numeric(ss), yrs = as.numeric(time(ss)), order = 30, lambda = 1e-3) fit2 matplot(fit2$yrs, fit2$coef[, 1:3], type = "l", lty = 1, xlab = "Year", ylab = "Coefficient") ## A chronology data(ca533) ca533.rwi <- detrend(rwl = ca533, method = "Spline") ca533.crn <- chron(ca533.rwi) kalman.ar(ca533.crn, order = 10) ## The same, letting the innovation variance change fit3 <- kalman.ar(ca533.crn, order = 10, variance = "varying") fit3 plot(fit3$yrs, sqrt(fit3$sigma2.t), type = "l", xlab = "Year", ylab = "Innovation sd")## Annual sunspot numbers. Maximum likelihood finds no gain from ## letting the coefficients move: ss <- datasets::sunspot.year fit <- kalman.ar(as.numeric(ss), yrs = as.numeric(time(ss)), order = 30) fit ## Setting lambda by hand lets them move fit2 <- kalman.ar(as.numeric(ss), yrs = as.numeric(time(ss)), order = 30, lambda = 1e-3) fit2 matplot(fit2$yrs, fit2$coef[, 1:3], type = "l", lty = 1, xlab = "Year", ylab = "Coefficient") ## A chronology data(ca533) ca533.rwi <- detrend(rwl = ca533, method = "Spline") ca533.crn <- chron(ca533.rwi) kalman.ar(ca533.crn, order = 10) ## The same, letting the innovation variance change fit3 <- kalman.ar(ca533.crn, order = 10, variance = "varying") fit3 plot(fit3$yrs, sqrt(fit3$sigma2.t), type = "l", xlab = "Year", ylab = "Innovation sd")
Computes the autoregressive spectrum of every year from the
coefficients estimated by kalman.ar, and plots the result as
a surface in time and period.
kalman.spec(x, nfreq = 200, freq = NULL) ## S3 method for class 'kalman.spec' plot(x, log.power = TRUE, col = NULL, key = TRUE, xlab = gettext("Time", domain = "R-dplR"), ylab = gettext("Period", domain = "R-dplR"), ...) ## S3 method for class 'kalman.spec' print(x, ...)kalman.spec(x, nfreq = 200, freq = NULL) ## S3 method for class 'kalman.spec' plot(x, log.power = TRUE, col = NULL, key = TRUE, xlab = gettext("Time", domain = "R-dplR"), ylab = gettext("Period", domain = "R-dplR"), ...) ## S3 method for class 'kalman.spec' print(x, ...)
x |
for |
nfreq |
number of frequencies. They are spaced evenly in the logarithm of period, from 2 years to half the length of the series. |
freq |
|
log.power |
|
col |
colours for the surface, low to high. A viridis ramp if
|
key |
|
xlab, ylab
|
axis labels. |
... |
arguments passed to |
The spectrum in year at frequency is
which is the usual AR spectrum, scaled as in
spec.ar, with the coefficients of that year.
If the fit had variance = "varying",
is that of the year as well, so the whole spectrum of a year rises
and falls with its innovation variance.
There is no test of significance. The surface shows what the fitted
model implies and is only as good as the choice of order and
lambda in kalman.ar; see the details there. The
spectrum of the model with fixed coefficients is returned as
spec.fixed for comparison.
The first order years of the series have no spectrum.
kalman.spec returns an object of class "kalman.spec", a
list with elements:
yrs |
the years. |
freq |
frequencies in cycles per year. |
period |
the same as periods in years. |
spec |
|
spec.fixed |
spectrum of the AR model with fixed coefficients, at the innovation variance of that model (its geometric mean if the variance varies). |
sigma2.t |
innovation variance of each year. |
order, prior, lambda, variance
|
from the fit. |
The plot method returns x invisibly.
This function is experimental and may change in future releases, as
may kalman.ar.
Andy Bunn
Kitagawa, G. and Gersch, W. (1985) A smoothness priors time-varying AR coefficient modeling of nonstationary covariance time series. IEEE Transactions on Automatic Control, 30(1), 48–56.
ss <- datasets::sunspot.year fit <- kalman.ar(as.numeric(ss), yrs = as.numeric(time(ss)), order = 30, lambda = 1e-3) sp <- kalman.spec(fit) sp plot(sp) ## The period with the most power between 7 and 16 years, by year band <- sp$period > 7 & sp$period < 16 peak <- sp$period[band][apply(sp$spec[, band], 1, which.max)] plot(sp$yrs, peak, type = "l", xlab = "Year", ylab = "Period (years)")ss <- datasets::sunspot.year fit <- kalman.ar(as.numeric(ss), yrs = as.numeric(time(ss)), order = 30, lambda = 1e-3) sp <- kalman.spec(fit) sp plot(sp) ## The period with the most power between 7 and 16 years, by year band <- sp$period > 7 & sp$period < 16 peak <- sp$period[band][apply(sp$spec[, band], 1, which.max)] plot(sp$yrs, peak, type = "l", xlab = "Year", ylab = "Period (years)")
This is a simple convenience function that returns a date in the format used by ‘\today’ in LaTeX. A possible use case is fixing the date shown in a vignette at weaving time.
latexDate(x = Sys.Date(), ...)latexDate(x = Sys.Date(), ...)
x |
any object for which an |
... |
other arguments to |
A character vector
Mikko Korpela
latexDate() # today latexDate(Sys.Date() + 5) # today + 5 days latexDate(c("2013-12-06", "2014-09-19")) # fixed dates ## [1] "December 6, 2013" "September 19, 2014" latexDate(5*60*60*24, origin=Sys.Date()) # today + 5 dayslatexDate() # today latexDate(Sys.Date() + 5) # today + 5 days latexDate(c("2013-12-06", "2014-09-19")) # fixed dates ## [1] "December 6, 2013" "September 19, 2014" latexDate(5*60*60*24, origin=Sys.Date()) # today + 5 days
Some characters cannot be entered directly into a LaTeX document.
This function converts the input character vector to a form
suitable for inclusion in a LaTeX document in text mode. It can be
used together with ‘\Sexpr’ in vignettes.
latexify(x, doublebackslash = TRUE, dashdash = TRUE, quotes = c("straight", "curved"), packages = c("fontenc", "textcomp"))latexify(x, doublebackslash = TRUE, dashdash = TRUE, quotes = c("straight", "curved"), packages = c("fontenc", "textcomp"))
x |
a |
doublebackslash |
a |
dashdash |
a |
quotes |
a |
packages |
a |
The function is intended for use with unformatted inline text.
Newlines, tabs and other whitespace characters ("[:space:]" in
regex) are converted to spaces. Control characters
("[:cntrl:]") that are not whitespace are removed. Other more
or less special characters in the ASCII set are ‘{’,
‘}’, ‘\’, ‘#’, ‘$’, ‘%’,
‘^’, ‘&’, ‘_’, ‘~’, double quote,
‘/’, single quote, ‘<’, ‘>’, ‘|’, grave
and ‘-’. They are converted to the corresponding LaTeX
commands. Some of the conversions are affected by user options,
e.g. dashdash.
Before applying the substitutions described above, input elements with
Encoding set to "bytes" are printed and the
output is stored using captureOutput. The result of
this intermediate stage is ASCII text where some characters
are shown as their byte codes using a hexadecimal pair prefixed with
"\x". This set includes tabs, newlines and control
characters. The substitutions are then applied to the intermediate
result.
The quoting functions sQuote and dQuote
may use non-ASCII quote characters, depending on the locale.
Also these quotes are converted to LaTeX commands. This means that
the quoting functions are safe to use with any LaTeX input encoding.
Similarly, some other non-ASCII characters, e.g. letters,
currency symbols, punctuation marks and diacritics, are converted to
commands.
Adding "eurosym" to packages enables the use of the
euro sign as provided by the "eurosym" package (‘\euro’).
The result is converted to UTF-8 encoding, Normalization Form C (NFC).
Note that this function will not add any non-ASCII
characters that were not already present in the input. On the
contrary, some non-ASCII characters, e.g. all characters in
the "latin1" (ISO-8859-1) Encoding
(character set), are removed when converted to LaTeX commands. Any
remaining non-ASCII character has a good chance of working
when the document is processed with XeTeX or LuaTeX, but the Unicode
support available with pdfTeX is limited.
Assuming that ‘pdflatex’ is used for compilation, suggested package loading commands in the document preamble are:
\usepackage[T1]{fontenc} % no '"' in OT1 font encoding
\usepackage{textcomp} % some symbols e.g. straight single quote
\usepackage[utf8]{inputenx} % UTF-8 input encoding
\input{ix-utf8enc.dfu} % more supported characters
A character vector
Mikko Korpela
INRIA. Tralics: a LaTeX to XML translator, HTML documentation of all TeX commands. http://www-sop.inria.fr/marelle/tralics/.
Levitt, N., Persch, C., and Unicode, Inc. (2013) GNOME Character Map, application version 3.10.1.
Mittelbach, F., Goossens, M., Braams, J., Carlisle, D., and Rowley, C. (2004) The LaTeX Companion. Addison-Wesley, second edition. ISBN-13: 978-0-201-36299-2.
Pakin, S. (2009) The Comprehensive LaTeX Symbol List. https://www.ctan.org/tex-archive/info/symbols/comprehensive.
The Unicode Consortium. The Unicode Standard. https://home.unicode.org/.
x1 <- "clich\xe9\nma\xf1ana" Encoding(x1) <- "latin1" x1 x2 <- x1 Encoding(x2) <- "bytes" x2 x3 <- enc2utf8(x1) testStrings <- c("different kinds\nof\tspace", "control\a characters \ftoo", "{braces} and \\backslash", '#various$ %other^ &characters_ ~escaped"/coded', x1, x2, x3) latexStrings <- latexify(testStrings, doublebackslash = FALSE) ## All should be "unknown" Encoding(latexStrings) cat(latexStrings, sep="\n") ## Input encoding does not matter identical(latexStrings[5], latexStrings[7])x1 <- "clich\xe9\nma\xf1ana" Encoding(x1) <- "latin1" x1 x2 <- x1 Encoding(x2) <- "bytes" x2 x3 <- enc2utf8(x1) testStrings <- c("different kinds\nof\tspace", "control\a characters \ftoo", "{braces} and \\backslash", '#various$ %other^ &characters_ ~escaped"/coded', x1, x2, x3) latexStrings <- latexify(testStrings, doublebackslash = FALSE) ## All should be "unknown" Encoding(latexStrings) cat(latexStrings, sep="\n") ## Input encoding does not matter identical(latexStrings[5], latexStrings[7])
This function performs a continuous wavelet transform on a time series.
morlet(y1, x1 = seq_along(y1), p2 = NULL, dj = 0.25, siglvl = 0.95)morlet(y1, x1 = seq_along(y1), p2 = NULL, dj = 0.25, siglvl = 0.95)
y1 |
|
x1 |
|
p2 |
|
dj |
|
siglvl |
|
This performs a continuous wavelet transform of a time series. This
function is typically invoked with wavelet.plot.
A list containing:
y |
|
x |
|
wave |
|
coi |
|
period |
|
Scale |
|
Signif |
|
Power |
|
This is a port of Torrence’s IDL code, which can be accessed through the Internet Archive Wayback Machine.
Andy Bunn. Patched and improved by Mikko Korpela.
Torrence, C. and Compo, G. P. (1998) A practical guide to wavelet analysis. Bulletin of the American Meteorological Society, 79(1), 61–78.
library(utils) data(ca533) ca533.rwi <- detrend(rwl = ca533, method = "ModNegExp") ca533.crn <- chron(ca533.rwi, prewhiten = FALSE) Years <- time(ca533.crn) CAMstd <- ca533.crn[, 1] out.wave <- morlet(y1 = CAMstd, x1 = Years, dj = 0.1, siglvl = 0.99)library(utils) data(ca533) ca533.rwi <- detrend(rwl = ca533, method = "ModNegExp") ca533.crn <- chron(ca533.rwi, prewhiten = FALSE) Years <- time(ca533.crn) CAMstd <- ca533.crn[, 1] out.wave <- morlet(y1 = CAMstd, x1 = Years, dj = 0.1, siglvl = 0.99)
Computes the parameter for a set of tree-ring
records or other time-series data.
net(x, weights = c(v = 1, g = 1))net(x, weights = c(v = 1, g = 1))
x |
A |
weights |
A |
This function computes the parameter (Esper et
al., 2001). The overall is an average of all
(non-NA) yearly values , which are
computed as follows:
The yearly variation is the standard deviation of the
measurements of a single year divided by their mean.
Gegenläufigkeit is based
on one definition of Gleichläufigkeit
, similar to but not the same as what glk
computes. Particularly, in the formula used by this function (Esper
et al., 2001), simultaneous zero differences in two series are not
counted as a synchronous change.
The weights of and in the sum can
be adjusted with the argument weights (see above). As a
rather extreme example, it is possible to isolate variation or
Gegenläufigkeit by setting one of the weights
to zero (see ‘Examples’).
A list with the following components, in the same order as
described here:
all |
a |
average |
a |
Mikko Korpela
Esper, J., Neuwirth, B., and Treydte, K. (2001) A new parameter to evaluate temporal signal strength of tree-ring chronologies. Dendrochronologia, 19(1), 93–102.
library(utils) data(ca533) ca533.rwi <- detrend(rwl = ca533, method = "ModNegExp") ca533.net <- net(ca533.rwi) tail(ca533.net$all) ca533.net$average ## Not run: ## Isolate the components of NET ca533.v <- net(ca533.rwi, weights=c(v=1,0)) ca533.g <- net(ca533.rwi, weights=c(g=1,0)) ## End(Not run)library(utils) data(ca533) ca533.rwi <- detrend(rwl = ca533, method = "ModNegExp") ca533.net <- net(ca533.rwi) tail(ca533.net$all) ca533.net$average ## Not run: ## Isolate the components of NET ca533.v <- net(ca533.rwi, weights=c(v=1,0)) ca533.g <- net(ca533.rwi, weights=c(g=1,0)) ## End(Not run)
This data set gives the raw ring widths for Douglas fir
Pseudotsuga menziesii near Los Alamos New Mexico,
USA. There are 8 series. Data set was created using
read.rwl and saved to an .rda file using
save.
data(nm046)data(nm046)
A data.frame containing 8 tree-ring series in columns and 289
years in rows.
International tree-ring data bank, Accessed on 20-April-2021 at https://www.ncei.noaa.gov/pub/data/paleo/treering/measurements/northamerica/usa/nm046.rwl
O'Brien, D (2002) Los Alamos Data Set. IGBP PAGES/World Data Center for Paleoclimatology Data Contribution Series 2002-NM046.RWL. NOAA/NCDC Paleoclimatology Program, Boulder, Colorado, USA.
library(utils) data(nm046) ## Where the data came from. read.tucson() records what it saw and attaches ## it to what it returns; this data set carries that record. prov <- attr(nm046, "dplR.provenance") prov$file # the archived file it was read from prov$precision # the precision each series was measured at prov$gaps # interior gaps, if any -- this file has none prov$events # problems found while reading -- none here either ## rwl.report() puts the file and precision at the head of its report rwl.report(nm046)library(utils) data(nm046) ## Where the data came from. read.tucson() records what it saw and attaches ## it to what it returns; this data set carries that record. prov <- attr(nm046, "dplR.provenance") prov$file # the archived file it was read from prov$precision # the precision each series was measured at prov$gaps # interior gaps, if any -- this file has none prov$events # problems found while reading -- none here either ## rwl.report() puts the file and precision at the head of its report rwl.report(nm046)
Applies low-pass, high-pass, band-pass, or stop-pass filtering to y with frequencies (or periods) supplied by the user.
pass.filt(y, W, type = c("low", "high", "stop", "pass"), method = c("Butterworth", "ChebyshevI"), n = 4, Rp = 1)pass.filt(y, W, type = c("low", "high", "stop", "pass"), method = c("Butterworth", "ChebyshevI"), n = 4, Rp = 1)
y |
a |
W |
a |
type |
a |
method |
a |
n |
a |
Rp |
a |
This function applies either a Butterworth or a Chebyshev type I filter of order n to a signal and is nothing more than a wrapper for functions in the signal package. The filters are designed via butter and cheby1. The filter is applied via filtfilt.
The input data (y) has the mean value subtracted and is then padded via reflection at the start and the end to a distance of twice the maximum period. The padded data and the filter are passed to filtfilt after which the data are unpadded and returned afer the mean is added back.
The argumement W can be given in either frequency between 0 and 0.5 or, for convenience, period (minimum value of 2). For low-pass and high-pass filters, W must have a length of one. For low-pass and high-pass filters W must be a two-element vector (c(low, high)) specifying the lower and upper boundaries of the filter.
Because this is just a wrapper for casual use with tree-ring data the frequencies and periods assume a sampling frequency of one. Users are encouraged to build their own filters using the signal package.
A filtered vector.
Andy Bunn. Patched and improved by Mikko Korpela.
data("co021") x <- na.omit(co021[, 1]) # 20-year low-pass filter -- note freq is passed in bSm <- pass.filt(x, W=0.05, type="low", method="Butterworth") cSm <- pass.filt(x, W=0.05, type="low", method="ChebyshevI") plot(x, type="l", col="grey") lines(bSm, col="red") lines(cSm, col="blue") # 20-year high-pass filter -- note period is passed in bSm <- pass.filt(x, W=20, type="high") plot(x, type="l", col="grey") lines(bSm, col="red") # 20 to 100-year band-pass filter -- note freqs are passed in bSm <- pass.filt(x, W=c(0.01, 0.05), type="pass") cSm <- pass.filt(x, W=c(0.01, 0.05), type="pass", method="ChebyshevI") plot(x, type="l", col="grey") lines(bSm, col="red") lines(cSm, col="blue") # 20 to 100-year stop-pass filter -- note periods are passed in cSm <- pass.filt(x, W=c(20, 100), type="stop", method="ChebyshevI") plot(x, type="l", col="grey") lines(cSm, col="red")data("co021") x <- na.omit(co021[, 1]) # 20-year low-pass filter -- note freq is passed in bSm <- pass.filt(x, W=0.05, type="low", method="Butterworth") cSm <- pass.filt(x, W=0.05, type="low", method="ChebyshevI") plot(x, type="l", col="grey") lines(bSm, col="red") lines(cSm, col="blue") # 20-year high-pass filter -- note period is passed in bSm <- pass.filt(x, W=20, type="high") plot(x, type="l", col="grey") lines(bSm, col="red") # 20 to 100-year band-pass filter -- note freqs are passed in bSm <- pass.filt(x, W=c(0.01, 0.05), type="pass") cSm <- pass.filt(x, W=c(0.01, 0.05), type="pass", method="ChebyshevI") plot(x, type="l", col="grey") lines(bSm, col="red") lines(cSm, col="blue") # 20 to 100-year stop-pass filter -- note periods are passed in cSm <- pass.filt(x, W=c(20, 100), type="stop", method="ChebyshevI") plot(x, type="l", col="grey") lines(cSm, col="red")
This function makes a default plot of a tree-ring chronology from a
data.frame of the type produced by chron,
chron.ars, chron.stabilized, ssf.
## S3 method for class 'crn' plot(x, add.spline = FALSE, nyrs = NULL, xlab = "", ylab = NULL, ...)## S3 method for class 'crn' plot(x, add.spline = FALSE, nyrs = NULL, xlab = "", ylab = NULL, ...)
x |
a |
add.spline |
a |
nyrs |
a number giving the rigidity of the smoothing spline.
Defaults to 1/3 times the length of the first chronology if
|
xlab |
a label for the x axis, drawn under the bottom panel. Empty by default. |
ylab |
a label for the y axis. A single label is used for
every chronology panel and leaves the sample depth and running
rbar panels with their own labels. A vector with one element per
panel labels each panel in turn. If |
... |
Additional arguments to pass to |
This makes a crude plot of one or more tree-ring chronologies.
None. Invoked for side effect (plot).
Andy Bunn. Patched and improved by Mikko Korpela.
library(graphics) data(wa082) # Truncate the RW data to a sample depth at least 5 wa082Trunc <- wa082[rowSums(!is.na(wa082))>4,] # Detrend with age-dependent spline wa082RWI <- detrend(wa082Trunc,method = "AgeDep") # make several chronologies wa082CRN1 <- chron(wa082RWI) wa082CRN2 <- chron.stabilized(wa082RWI, winLength=51, biweight = TRUE, running.rbar = TRUE) wa082CRN3 <- chron.ars(wa082RWI) wa082CRN4 <- ssf(wa082Trunc) # and plot plot.crn(wa082CRN1,add.spline = TRUE,nyrs=20) plot.crn(wa082CRN2,add.spline = TRUE,nyrs=20) plot(wa082CRN3,add.spline = TRUE,nyrs=20) plot(wa082CRN4,add.spline = TRUE,nyrs=20) # a custom crn foo <- data.frame(wa082CRN1,sfc=wa082CRN4$sfc) foo <- foo[,c(1,3,2)] class(foo) <- c("crn","data.frame") plot.crn(foo,add.spline = TRUE,nyrs=20) # axis labels plot(wa082CRN1, xlab = "Year", ylab = "Ring-width index") # one label per panel plot(wa082CRN1, xlab = "Year", ylab = c("Ring-width index", "Series"))library(graphics) data(wa082) # Truncate the RW data to a sample depth at least 5 wa082Trunc <- wa082[rowSums(!is.na(wa082))>4,] # Detrend with age-dependent spline wa082RWI <- detrend(wa082Trunc,method = "AgeDep") # make several chronologies wa082CRN1 <- chron(wa082RWI) wa082CRN2 <- chron.stabilized(wa082RWI, winLength=51, biweight = TRUE, running.rbar = TRUE) wa082CRN3 <- chron.ars(wa082RWI) wa082CRN4 <- ssf(wa082Trunc) # and plot plot.crn(wa082CRN1,add.spline = TRUE,nyrs=20) plot.crn(wa082CRN2,add.spline = TRUE,nyrs=20) plot(wa082CRN3,add.spline = TRUE,nyrs=20) plot(wa082CRN4,add.spline = TRUE,nyrs=20) # a custom crn foo <- data.frame(wa082CRN1,sfc=wa082CRN4$sfc) foo <- foo[,c(1,3,2)] class(foo) <- c("crn","data.frame") plot.crn(foo,add.spline = TRUE,nyrs=20) # axis labels plot(wa082CRN1, xlab = "Year", ylab = "Ring-width index") # one label per panel plot(wa082CRN1, xlab = "Year", ylab = c("Ring-width index", "Series"))
Plots objects returned from corr.rwl.seg.
## S3 method for class 'crs' plot(x, ...)## S3 method for class 'crs' plot(x, ...)
x |
An object of class |
... |
Additional arguments passed to |
Each segment is drawn in blue if it correlates above the critical
value, red if it does not, and green where it does not overlap the bin
completely. If corr.rwl.seg was run with
lag.max greater than 0, segments that correlate better at
another lag (COFECHA’s B flag) are drawn in purple instead,
whatever their correlation as dated.
None. A plot is produced.
Andy Bunn
library(graphics) data(co021) foo <- corr.rwl.seg(co021, make.plot = FALSE) plot(foo)library(graphics) data(co021) foo <- corr.rwl.seg(co021, make.plot = FALSE) plot(foo)
Plots rwl objects.
## S3 method for class 'rwl' plot(x, plot.type=c("seg","spag"), ...)## S3 method for class 'rwl' plot(x, plot.type=c("seg","spag"), ...)
x |
An object of class |
plot.type |
Character. Type "seg" calls |
... |
Additional arguments for each |
None. A plot is produced.
Andy Bunn
library(graphics) library(utils) data(co021) plot(co021, plot.type="seg") plot(co021, plot.type="spag") plot(co021, plot.type="spag", zfac=2)library(graphics) library(utils) data(co021) plot(co021, plot.type="seg") plot(co021, plot.type="spag") plot(co021, plot.type="spag", zfac=2)
This function creates a partial wood completeness data structure based on pith offset data.
po.to.wc(po)po.to.wc(po)
po |
A |
Uses pith.offset - 1 as the number of missing heartwood
rings.
A data.frame containing one variable of wood completeness data:
n.missing.heartwood (integer type). This can be
used as input to write.tridas.
Mikko Korpela
## Not run: library(utils) data(gp.po) all(wc.to.po(po.to.wc(gp.po)) == gp.po) ## End(Not run)## Not run: library(utils) data(gp.po) all(wc.to.po(po.to.wc(gp.po)) == gp.po) ## End(Not run)
This function calculates pointer years on a data.frame of
ring-width series using the Becker algorithm. The pointer years are
computed with adjustable thresholds of relative radial growth
variation and number of series displaying similar growth pattern
(i.e. positive or negative variations).
pointer(rwl, rgv.thresh = 10, nseries.thresh = 75, round.decimals = 2)pointer(rwl, rgv.thresh = 10, nseries.thresh = 75, round.decimals = 2)
rwl |
a |
rgv.thresh |
a |
nseries.thresh |
a |
round.decimals |
an |
This calculates pointer years from ring-width series for each year
t of the time period covered by the series using the
Becker algorithm. This algorithm is based on, first, the calculation
of the individual relative radial growth variation by comparison of
ring-width of year t to that of year t-1 for
each series, and second, the inter-series comparison of both sign and
magnitude of these variations.
For example, if rgv.thresh and
nseries.thresh are set at 10 and 75 respectively, pointer
years will be defined as those years when at least 75% of the series
present an absolute relative radial growth variation higher than 10%.
Users unfamiliar with the Becker algorithm should refer to Becker et al. (1994) and Mérian and Lebourgeois (2011) for further details.
A data.frame containing the following columns (each row
corresponds to one position of the window):
Year |
Considered year (t). |
Nb.series |
Number of available series. |
Perc.pos |
Percentage of series displaying a significant positive radial growth variation. |
Perc.neg |
Percentage of series displaying a significant negative radial growth variation. |
Nature |
Number indicating whether the year is a positive pointer year (1), a negative pointer year (-1) or a regular year (0). |
RGV_mean |
Mean radial growth variations over the available series. |
RGV_sd |
Standard deviation of the radial growth variations over the available series. |
Pierre Mérian. Improved by Mikko Korpela and Andy Bunn.
Becker, M., Nieminen, T. M., and Gérémia, F. (1994) Short-term variations and long-term changes in oak productivity in northeastern France – the role of climate and atmospheric CO2. Annals of Forest Science, 51(5), 477–492.
Mérian, P. and Lebourgeois, F. (2011) Size-mediated climate–growth relationships in temperate forests: A multi-species analysis. Forest Ecology and Management, 261(8), 1382–1391.
## Pointer years calculation on ring-width series. Returns a data.frame. library(utils) data(gp.rwl) py <- pointer(rwl=gp.rwl, rgv.thresh=10, nseries.thresh=75, round.decimals=2) tail(py)## Pointer years calculation on ring-width series. Returns a data.frame. library(utils) data(gp.rwl) py <- pointer(rwl=gp.rwl, rgv.thresh=10, nseries.thresh=75, round.decimals=2) tail(py)
Power transformation of tree-ring width.
powt(rwl, method = "universal", rescale = FALSE, return.power=FALSE)powt(rwl, method = "universal", rescale = FALSE, return.power=FALSE)
rwl |
a |
method |
a |
rescale |
|
return.power |
|
In dendrochronology, ring width series are sometimes power transformed to address heteroscedasticity.
The classic procedure used by method="cook"
is a variance stabilization technique implemented after
Cook & Peters (1997): for each series a linear model is fitted on the
logs of level and spread, where level is defined as the local mean
with
ring widths R, and spread S is the local standard deviation defined as
. The
regression coefficient b from a linear model
is then used for the
power transform .
The procedure above is modified with method="universal" where all samples
are used simultaneously in a linear mixed-effects model with time (year)
as a random effect: lmer(log S ~ log M + (1|year). This "universal" or
"signal free" approach accounts for the common year effect across all of the
series in rwl and should address that not every year has the same
change in environmental conditions to the previous year.
The rescale argument will return the series with a mean and standard
deviation that matches the input data. While this is a common convention,
users should note that this can produce negative values which can be confusing
if thought of as "ring widths."
Either an object of class c("rwl", "data.frame") containing the
power transformed ring width series with the series in columns and the years
as rows or in the case of a single series, a possibly named vector of the same.
With class rwl, the series IDs are the column names and the
years are the row names.
If return.power=TRUE the returned
object is a list containing the power transformed data and a
numeric with the power estimate(s) used to transform the data.
Christian Zang implemented the Cook and Peters method. Stefan Klesse conceived and wrote the universal method. Patched and improved by Mikko Korpela and Andy Bunn.
Cook, E. R. and Peters, K. (1997) Calculating unbiased tree-ring indices for the study of climatic and environmental change. The Holocene, 7(3), 361–370.
library(utils) data(zof.rwl) powtUniversal <- powt(zof.rwl, method = "universal") powtCook <- powt(zof.rwl, method = "cook") op <- par(no.readonly = TRUE) par(mfcol = c(1, 3)) hist(summary(zof.rwl)$skew, breaks = seq(-2.25,2.25,by=0.25), main="Raw Data",xlab="Skew") hist(summary(powtUniversal)$skew, breaks = seq(-2.25,2.25,by=0.25), main="Universal POWT",xlab="Skew") hist(summary(powtCook)$skew, breaks = seq(-2.25,2.25,by=0.25), main="Cook POWT",xlab="Skew") par(op) # restore graphical parameterslibrary(utils) data(zof.rwl) powtUniversal <- powt(zof.rwl, method = "universal") powtCook <- powt(zof.rwl, method = "cook") op <- par(no.readonly = TRUE) par(mfcol = c(1, 3)) hist(summary(zof.rwl)$skew, breaks = seq(-2.25,2.25,by=0.25), main="Raw Data",xlab="Skew") hist(summary(powtUniversal)$skew, breaks = seq(-2.25,2.25,by=0.25), main="Universal POWT",xlab="Skew") hist(summary(powtCook)$skew, breaks = seq(-2.25,2.25,by=0.25), main="Cook POWT",xlab="Skew") par(op) # restore graphical parameters
Print information contained in or derived from a redfit object.
## S3 method for class 'redfit' print(x, digits = NULL, csv.out = FALSE, do.table = FALSE, prefix = "", row.names = FALSE, file = "", ...)## S3 method for class 'redfit' print(x, digits = NULL, csv.out = FALSE, do.table = FALSE, prefix = "", row.names = FALSE, file = "", ...)
x |
An object of class |
digits |
Specifies the desired number of significant digits in
the output. The argument is passed to |
csv.out |
A |
do.table |
A |
prefix |
A prefix to be used on every output line except the
large information table. REDFIT (see |
row.names |
A |
file |
A writable connection or a character string naming a
file. Used for setting the output destination when
|
... |
Arguments to |
Invisibly returns x.
Mikko Korpela
This function is based on the Fortran program REDFIT, which is in the public domain.
Schulz, M. and Mudelsee, M. (2002) REDFIT: estimating red-noise spectra directly from unevenly spaced paleoclimatic time series. Computers & Geosciences, 28(3), 421–426.
library(utils) data(ca533) tm <- time(ca533) x <- ca533[[1]] idx <- which(!is.na(x)) redf <- redfit(x[idx], tm[idx], "time", nsim = 100, iwin = 0, ofac = 1, n50 = 1) print(redf) fname <- tempfile(fileext=".csv") print(fname) # tempfile used for output print(redf, csv.out = TRUE, file = fname) redftable <- read.csv(fname) unlink(fname) # remove the filelibrary(utils) data(ca533) tm <- time(ca533) x <- ca533[[1]] idx <- which(!is.na(x)) redf <- redfit(x[idx], tm[idx], "time", nsim = 100, iwin = 0, ofac = 1, n50 = 1) print(redf) fname <- tempfile(fileext=".csv") print(fname) # tempfile used for output print(redf, csv.out = TRUE, file = fname) redftable <- read.csv(fname) unlink(fname) # remove the file
This function prints the results of rwl.report
## S3 method for class 'rwl.report' print(x, ...)## S3 method for class 'rwl.report' print(x, ...)
x |
a |
... |
not implemented |
This function formats the list from rwl.report for the
user to have a summary report of the number of series, the mean length
of all the series, the first year, last year, the mean first-order
autocorrelation (via summary.rwl), the mean interseries
correlation (via interseries.cor), the years where a series has
a missing ring (zero), internal NA, or a very small ring (<0.005).
Invisible
Andy Bunn. Patched and improved by Mikko Korpela.
rwl.report, summary.rwl,
interseries.cor
data("gp.rwl") rwl.report(gp.rwl) foo <- gp.rwl foo[177,1] <- NA foo[177:180,3] <- NA foo[185,4] <- 0.001 rwl.report(foo)data("gp.rwl") rwl.report(gp.rwl) foo <- gp.rwl foo[177,1] <- NA foo[177:180,3] <- NA foo[185,4] <- 0.001 rwl.report(foo)
Computes the log-likelihood of a kalman.ar model over a
range of lambda, keeping the series, order and prior of the
fit. It shows how well the data determine lambda and what a
value set by hand costs.
## S3 method for class 'kalman.ar' profile(fitted, lambda = 10^seq(-14, 0, by = 0.5), ...) ## S3 method for class 'kalman.profile' plot(x, drop = 20, ylim = NULL, xlab = expression(lambda), ylab = gettext("Log-likelihood", domain = "R-dplR"), ...) ## S3 method for class 'kalman.profile' print(x, digits = 4, ...)## S3 method for class 'kalman.ar' profile(fitted, lambda = 10^seq(-14, 0, by = 0.5), ...) ## S3 method for class 'kalman.profile' plot(x, drop = 20, ylim = NULL, xlab = expression(lambda), ylab = gettext("Log-likelihood", domain = "R-dplR"), ...) ## S3 method for class 'kalman.profile' print(x, digits = 4, ...)
fitted |
an object of class |
lambda |
|
x |
an object of class |
drop |
|
ylim |
limits of the vertical axis, in place of
|
xlab, ylab
|
axis labels. |
digits |
number of significant digits to print. |
... |
for |
The model is fitted again at each value of lambda. If
the fit had variance = "varying", its variance path is kept
as it is and not estimated again. The
plot shows the log-likelihood against lambda on a log
scale, with a dashed line at the log-likelihood of the ordinary AR
model with fixed coefficients and a circle at the fit that was
profiled.
A curve that is nearly level over several powers of ten says that the
series holds little information about lambda. The
maximum likelihood value then deserves little weight, and so does a
comparison of AIC with the fixed model. A curve that falls
away steeply above some value says that larger values make the
one-step predictions clearly worse.
The number of years in which the coefficients are not those of a
stationary process is given for each lambda. It usually
rises with lambda and is another guide to how far it can
be pushed.
Under prior = "rw2" the model at lambda = 0 has
coefficients that change along straight lines, and its log-likelihood,
loglik.zero, is not that of the fixed model.
An object of class "kalman.profile", a list with elements:
lambda |
the values, sorted. |
loglik |
log-likelihood at each. |
n.nonstationary |
years with non-stationary coefficients at each. |
loglik.zero |
log-likelihood at |
loglik.fixed |
log-likelihood of the AR model with fixed coefficients. |
fit.lambda, fit.loglik, lambda.estimated
|
from the fit. |
order, prior
|
from the fit. |
n.lik |
years in the likelihood. |
n.yrs |
years with coefficients. |
This function is experimental and may change in future releases, as
may kalman.ar.
Andy Bunn
ss <- datasets::sunspot.year fit <- kalman.ar(as.numeric(ss), yrs = as.numeric(time(ss)), order = 30, lambda = 1e-3) pr <- profile(fit) pr plot(pr)ss <- datasets::sunspot.year fit <- kalman.ar(as.numeric(ss), yrs = as.numeric(time(ss)), order = 30, lambda = 1e-3) pr <- profile(fit) pr plot(pr)
This function takes plotting commands and uses a temporary bitmap graphics device to capture their output. The resulting raster image is drawn in the plot or figure region of the active high-level plot. A new plot is started if one does not exist.
rasterPlot(expr, res = 150, region = c("plot", "figure"), antialias, bg = "transparent", interpolate = TRUE, draw = TRUE, Cairo = FALSE, ...)rasterPlot(expr, res = 150, region = c("plot", "figure"), antialias, bg = "transparent", interpolate = TRUE, draw = TRUE, Cairo = FALSE, ...)
expr |
Low-level plotting commands ( |
res |
Resolution in points per inch (ppi). A numeric value. Suggested
values for different types of display media are given in
|
region |
The function can draw in the |
antialias |
Antialiasing argument passed to |
bg |
Background color of the raster plot, an argument passed to
the bitmap device. If the default |
interpolate |
Argument passed to |
draw |
A |
Cairo |
A |
... |
The appropriate graphical parameters of the current graphics device are copied to the temporary bitmap device. Therefore the appearance of the raster contents should be almost the same as when directly drawn.
The call or expression expr is evaluated in the
environment of the caller.
It is possible that the raster contents will maintain a constant size
when the graphics device is resized. If resizing works, however, the
image may become distorted. For example, circle symbols will turn
into ellipses if the width to height ratio is not maintained (see
‘Examples’). This is in contrast to a standard plot in a
display graphics device, e.g. x11, where text and
symbols maintain their size when the device is resized.
If draw is TRUE, there is no return value. The
function is used for the side effects.
If draw is FALSE, an object of class
"nativeRaster" is returned. The object can be used as input
for rasterImage or grid.raster. See
readPNG. If no bitmap device is available
(see ‘Note’), NULL is returned.
The graphics device used for the output must have support for
including raster images. See "rasterImage" in
dev.capabilities.
The R build must have a functional png device,
which requires one of the following capabilities:
"png", "aqua" or "cairo". Alternatively, a
Cairo device from package Cairo must be
available with Cairo.capabilities
"raster" or "png".
If either of these requirements is not met, at least one
message is generated and the function reverts to regular
plotting. The bg argument is then handled by drawing a
filled rectangle. Also region is honored, but the other
settings do not apply.
Mikko Korpela
library(graphics) library(stats) ## Picture with various graphical elements x <- 1:100 y0 <- quote(sin(pi * x / 20) + x / 100 + rnorm(100, 0, 0.2)) y <- eval(y0) ylab <- deparse(y0) spl <- smooth.spline(y) plot(x, y, type = "n", axes = FALSE, ylab = ylab) usr <- par("usr") xrange <- usr[2] - usr[1] xsize <- xrange * 0.4 nsteps <- 8 xmar <- xsize / 20 yrange <- usr[4] - usr[3] ysize <- yrange / 20 ymar <- 0.5 * ysize X <- seq(usr[1] + xmar, by = xsize / nsteps, length.out = nsteps + 1) xleft <- X[-(nsteps + 1)] xright <- X[-1] pin <- par("pin") maxrad <- xsize / 3 * min(1, pin[2] / pin[1]) nrad <- 16 minrad <- maxrad / nrad Rad <- seq(maxrad, by = (minrad - maxrad) / (nrad - 1), length.out=nrad) xmar2 <- xmar + maxrad ymar2 <- (xmar2 / xrange) * pin[1] / pin[2] * yrange expr <- quote({ rect(xleft, usr[4] - 1.5 * ysize, xright, usr[4] - ymar, col = rainbow(8), border = NA) symbols(rep(usr[2] - xmar2, nrad), rep(usr[3] + ymar2, nrad), circles = Rad, inches = FALSE, add = TRUE, fg = NA, bg = gray.colors(nrad + 1, 1, 0)[-1]) points(y) lines(spl) }) rasterPlot(expr, res = 50) box() axis(1) axis(2) ## The same picture with higher resolution but no antialiasing plot(y, type = "n", axes = FALSE, ann = FALSE) ## No content in margin, but region = "figure" and bg = "white" ## paints margin white rasterPlot(expr, antialias = "none", interpolate = FALSE, region = "figure", bg = "white") ## Draw box, axes, labels parnew <- par(new = TRUE) plot(x, y, type = "n", ylab = ylab) par(parnew) ## Draw plot(1:5) with adjusted margins and additional axes. Some parts ## are drawn with rasterPlot, others normally. Resize to see stretching. op <- par(no.readonly = TRUE) par(mar = c(5.1, 4.1, 2.1, 2.1)) plot(1:5, type = "n", axes = FALSE, ann = FALSE) expr2 <- quote({ points(c(2, 4), c(2, 4)) axis(2) axis(3) }) rasterPlot(expr2, region = "figure", bg = "white") points(c(1, 3, 5), c(1, 3, 5)) box() axis(1) axis(4) title(xlab = "Index", ylab = "1:5") par(op)library(graphics) library(stats) ## Picture with various graphical elements x <- 1:100 y0 <- quote(sin(pi * x / 20) + x / 100 + rnorm(100, 0, 0.2)) y <- eval(y0) ylab <- deparse(y0) spl <- smooth.spline(y) plot(x, y, type = "n", axes = FALSE, ylab = ylab) usr <- par("usr") xrange <- usr[2] - usr[1] xsize <- xrange * 0.4 nsteps <- 8 xmar <- xsize / 20 yrange <- usr[4] - usr[3] ysize <- yrange / 20 ymar <- 0.5 * ysize X <- seq(usr[1] + xmar, by = xsize / nsteps, length.out = nsteps + 1) xleft <- X[-(nsteps + 1)] xright <- X[-1] pin <- par("pin") maxrad <- xsize / 3 * min(1, pin[2] / pin[1]) nrad <- 16 minrad <- maxrad / nrad Rad <- seq(maxrad, by = (minrad - maxrad) / (nrad - 1), length.out=nrad) xmar2 <- xmar + maxrad ymar2 <- (xmar2 / xrange) * pin[1] / pin[2] * yrange expr <- quote({ rect(xleft, usr[4] - 1.5 * ysize, xright, usr[4] - ymar, col = rainbow(8), border = NA) symbols(rep(usr[2] - xmar2, nrad), rep(usr[3] + ymar2, nrad), circles = Rad, inches = FALSE, add = TRUE, fg = NA, bg = gray.colors(nrad + 1, 1, 0)[-1]) points(y) lines(spl) }) rasterPlot(expr, res = 50) box() axis(1) axis(2) ## The same picture with higher resolution but no antialiasing plot(y, type = "n", axes = FALSE, ann = FALSE) ## No content in margin, but region = "figure" and bg = "white" ## paints margin white rasterPlot(expr, antialias = "none", interpolate = FALSE, region = "figure", bg = "white") ## Draw box, axes, labels parnew <- par(new = TRUE) plot(x, y, type = "n", ylab = ylab) par(parnew) ## Draw plot(1:5) with adjusted margins and additional axes. Some parts ## are drawn with rasterPlot, others normally. Resize to see stretching. op <- par(no.readonly = TRUE) par(mar = c(5.1, 4.1, 2.1, 2.1)) plot(1:5, type = "n", axes = FALSE, ann = FALSE) expr2 <- quote({ points(c(2, 4), c(2, 4)) axis(2) axis(3) }) rasterPlot(expr2, region = "figure", bg = "white") points(c(1, 3, 5), c(1, 3, 5)) box() axis(1) axis(4) title(xlab = "Index", ylab = "1:5") par(op)
Detrend multiple ring-width series simultaneously using a regional curve.
rcs(rwl, po = NULL, nyrs = NULL, f = 0.5, biweight = TRUE, ratios = TRUE, rc.out = FALSE, make.plot = TRUE, method = c("caps", "ads"), min.n = NULL, pos.slope = TRUE, ...)rcs(rwl, po = NULL, nyrs = NULL, f = 0.5, biweight = TRUE, ratios = TRUE, rc.out = FALSE, make.plot = TRUE, method = c("caps", "ads"), min.n = NULL, pos.slope = TRUE, ...)
rwl |
a |
po |
a |
nyrs |
a number giving the rigidity of the smoothing spline.
For |
f |
a number between 0 and 1 giving the frequency response or wavelength cutoff. Defaults to 0.5. |
biweight |
|
ratios |
|
rc.out |
|
make.plot |
|
method |
a |
min.n |
an optional integer giving the minimum sample depth
required at a given cambial age for that age to be included when
fitting the regional curve. Ages where fewer than |
pos.slope |
a |
... |
other arguments passed to
|
This method detrends and standardizes tree-ring series by calculating
an age-related growth curve specific to the rwl. The
detrending is the estimation and removal of the tree’s natural
biological growth trend. The standardization is done by either
dividing each series by the growth trend or subtracting the growth
trend from each series to produce units in the dimensionless
ring-width index (RWI). The option to produce indices by
subtraction is intended to be used on series that have been subject to
variance stabilization (e.g., using powt).
Two smoothers are available for fitting the regional curve. The
default (method = "caps") uses a cubic smoothing spline where
the frequency response is 0.50 at a wavelength of 10 percent of the
maximum cambial age unless specified differently via nyrs
and f (see caps). The alternative
(method = "ads") uses an age-dependent spline whose stiffness
increases with cambial age, which may better preserve low-frequency
variability in the biological trend (see ads).
The min.n argument can be used to truncate the regional
curve where sample depth becomes thin, preventing poorly replicated
tail ages from influencing the fit.
This attempts to remove the low frequency variability that is due to biological or stand effects. See the references below for further details on detrending in general, and Biondi and Qeadan (2008) for an explanation of RCS.
A series with no values at all is dropped, with a message naming it, and the rest are standardized as if it had never been there.
An object of class c("rwi", "data.frame") (see
as.rwi) containing the dimensionless and detrended
ring-width indices with column names, row names and dimensions of
rwl. If rc.out is TRUE then a
list will be returned with a data.frame containing the
detrended ring widths as above and a vector containing the
regional curve.
Code provided by DendroLab based on programming by F. Qeadan and
F. Biondi, University of Nevada Reno, USA and adapted for
dplR by Andy Bunn. Patched and improved by Mikko Korpela. Extended
with method, min.n, and pos.slope arguments by
Andy Bunn.
Biondi, F. and Qeadan, F. (2008) A theory-driven approach to tree-ring standardization: Defining the biological trend from expected basal area increment. Tree-Ring Research, 64(2), 81–96.
Cook, E. R. and Kairiukstis, L. A., editors (1990) Methods of Dendrochronology: Applications in the Environmental Sciences. Springer. ISBN-13: 978-0-7923-0586-6.
Fritts, H. C. (2001) Tree Rings and Climate. Blackburn. ISBN-13: 978-1-930665-39-2.
detrend, chron, cms,
caps, ads
library(utils) data(gp.rwl) data(gp.po) ## Basic use: caps smoother (default), return indices only gp.rwi <- rcs(rwl = gp.rwl, po = gp.po, biweight = TRUE, make.plot = FALSE) str(gp.rwi) ## Return the regional curve alongside the indices gp.out <- rcs(rwl = gp.rwl, po = gp.po, biweight = TRUE, rc.out = TRUE, make.plot = FALSE) str(gp.out) ## Plot the regional curve with a title rcs(rwl = gp.rwl, po = gp.po, biweight = TRUE, rc.out = FALSE, make.plot = TRUE, main = "Regional Curve") ## Use the age-dependent spline smoother instead of caps gp.rwi.ads <- rcs(rwl = gp.rwl, po = gp.po, biweight = TRUE, method = "ads", rc.out = FALSE, make.plot = FALSE) ## Truncate the regional curve where fewer than 5 series contribute. ## Indices for rings beyond the truncated curve are returned as NA. gp.out.trunc <- rcs(rwl = gp.rwl, po = gp.po, biweight = TRUE, method = "ads", min.n = 5, rc.out = TRUE, make.plot = FALSE) ## Compare the two smoothers visually op <- par(no.readonly = TRUE) par(mfrow = c(1, 2)) rcs(rwl = gp.rwl, po = gp.po, biweight = TRUE, method = "caps", make.plot = TRUE, main = "caps") rcs(rwl = gp.rwl, po = gp.po, biweight = TRUE, method = "ads", make.plot = TRUE, main = "ads") par(op) ## Compare caps and ads indices for one series gp.caps <- rcs(rwl = gp.rwl, po = gp.po, biweight = TRUE, method = "caps", rc.out = FALSE, make.plot = FALSE) gp.ads <- rcs(rwl = gp.rwl, po = gp.po, biweight = TRUE, method = "ads", rc.out = FALSE, make.plot = FALSE) cor(gp.caps[[1]], gp.ads[[1]], use = "complete.obs") ## Use subtraction rather than division (e.g. after variance stabilization) gp.rwi.sub <- rcs(rwl = gp.rwl, po = gp.po, biweight = TRUE, ratios = FALSE, make.plot = FALSE)library(utils) data(gp.rwl) data(gp.po) ## Basic use: caps smoother (default), return indices only gp.rwi <- rcs(rwl = gp.rwl, po = gp.po, biweight = TRUE, make.plot = FALSE) str(gp.rwi) ## Return the regional curve alongside the indices gp.out <- rcs(rwl = gp.rwl, po = gp.po, biweight = TRUE, rc.out = TRUE, make.plot = FALSE) str(gp.out) ## Plot the regional curve with a title rcs(rwl = gp.rwl, po = gp.po, biweight = TRUE, rc.out = FALSE, make.plot = TRUE, main = "Regional Curve") ## Use the age-dependent spline smoother instead of caps gp.rwi.ads <- rcs(rwl = gp.rwl, po = gp.po, biweight = TRUE, method = "ads", rc.out = FALSE, make.plot = FALSE) ## Truncate the regional curve where fewer than 5 series contribute. ## Indices for rings beyond the truncated curve are returned as NA. gp.out.trunc <- rcs(rwl = gp.rwl, po = gp.po, biweight = TRUE, method = "ads", min.n = 5, rc.out = TRUE, make.plot = FALSE) ## Compare the two smoothers visually op <- par(no.readonly = TRUE) par(mfrow = c(1, 2)) rcs(rwl = gp.rwl, po = gp.po, biweight = TRUE, method = "caps", make.plot = TRUE, main = "caps") rcs(rwl = gp.rwl, po = gp.po, biweight = TRUE, method = "ads", make.plot = TRUE, main = "ads") par(op) ## Compare caps and ads indices for one series gp.caps <- rcs(rwl = gp.rwl, po = gp.po, biweight = TRUE, method = "caps", rc.out = FALSE, make.plot = FALSE) gp.ads <- rcs(rwl = gp.rwl, po = gp.po, biweight = TRUE, method = "ads", rc.out = FALSE, make.plot = FALSE) cor(gp.caps[[1]], gp.ads[[1]], use = "complete.obs") ## Use subtraction rather than division (e.g. after variance stabilization) gp.rwi.sub <- rcs(rwl = gp.rwl, po = gp.po, biweight = TRUE, ratios = FALSE, make.plot = FALSE)
This function reads in a DPL compact format file of ring widths.
read.compact(fname)read.compact(fname)
fname |
a |
This function should be able to read files written by the Dendrochronology Program Library (DPL) in its compact format.
An object of class c("rwl", "data.frame") with the series in
columns and the years as rows. The series IDs are the
column names and the years are the row names.
Mikko Korpela
read.rwl, read.tucson,
read.tridas, read.fh,
write.compact
## Not run: data(co021) fname <- write.compact(rwl.df = co021, fname = tempfile(fileext=".rwl"), append = FALSE, prec = 0.001) foo <- read.compact(fname) str(foo) str(co021) all.equal(foo,co021) unlink(fname) ## End(Not run)## Not run: data(co021) fname <- write.compact(rwl.df = co021, fname = tempfile(fileext=".rwl"), append = FALSE, prec = 0.001) foo <- read.compact(fname) str(foo) str(co021) all.equal(foo,co021) unlink(fname) ## End(Not run)
This function reads in a Tucson (decadal) format file of tree-ring chronologies (.crn).
read.crn(fname, header = NULL, encoding = getOption("encoding"), long = TRUE)read.crn(fname, header = NULL, encoding = getOption("encoding"), long = TRUE)
fname |
a |
header |
|
encoding |
the name of the encoding to be used when reading the
crn file. Usually the default value will work, but a crn file
written in a non-default encoding may crash the function. In that
case, identifying the encoding and specifying it here should fix the
problem. Examples of popular encodings available on many systems
are |
long |
|
This reads in a standard crn file as defined according to the standards of the ITRDB at https://www.ncei.noaa.gov/pub/data/paleo/treering/treeinfo.txt. Despite the standards at the ITRDB, this occasionally fails due to formatting problems.
A data.frame with each chronology in columns and the years as
rows. The chronology IDs are the column names and the years
are the row names. If the file includes sample depth that is included
as the last column (samp.depth). The output class is
class "crn" and "data.frame"
Andy Bunn. Patched and improved by Mikko Korpela.
This function reads in a Heidelberg (block or column) format file of ring widths (.fh).
read.fh(fname, BC_correction = FALSE, encoding = NULL)read.fh(fname, BC_correction = FALSE, encoding = NULL)
fname |
a |
BC_correction |
a |
encoding |
the encoding of the file, used only if the file is not
valid UTF-8. Any name |
This reads in a fh-file with ring widths in blocks (decadal format) or in columns (e.g., as with comment flags) as used by TSAP program. Chronologies or half-chronos in fh-format are not supported.
An object of class c("rwl", "data.frame") with the series in
columns and the years as rows. The keycodes are the column names and
the years are the row names. Depending on metadata available in the
input file, the following attributes may be present in the
data.frame:
ids |
A |
po |
A |
Christian Zang. New features and patches by Mikko Korpela and Ronald Visser.
Rinn, F. (2003) TSAP-Win User Reference Manual. Rinntech, Heidelberg. https://rinntech.info/products/tsap-win/.
These functions try to read site, tree, and core IDs from a
rwl data.frame.
read.ids(rwl, stc = c(3, 2, 3), ignore.site.case = FALSE, ignore.case = FALSE, fix.typos = FALSE, typo.ratio = 5, use.cor = TRUE) autoread.ids(rwl, ignore.site.case = TRUE, ignore.case = "auto", fix.typos = TRUE, typo.ratio = 5, use.cor = TRUE)read.ids(rwl, stc = c(3, 2, 3), ignore.site.case = FALSE, ignore.case = FALSE, fix.typos = FALSE, typo.ratio = 5, use.cor = TRUE) autoread.ids(rwl, ignore.site.case = TRUE, ignore.case = "auto", fix.typos = TRUE, typo.ratio = 5, use.cor = TRUE)
rwl |
a |
stc |
a vector of three integral values or character string
"auto". The numbers indicate the number of characters to split the
site code ( |
use.cor |
a |
The following parameters affect the handling of suspected typing
errors. Some have different default values in read.ids and
autoread.ids.
ignore.site.case |
a |
ignore.case |
a |
fix.typos |
a |
typo.ratio |
a |
Because dendrochronologists often take more than one core per tree, it is occasionally useful to calculate within vs. between tree variance. The International Tree Ring Data Bank (ITRDB) allows the first eight characters in an rwl file for series IDs but these are often shorter. Typically the creators of rwl files use a logical labeling method that can allow the user to determine the tree and core ID from the label.
Argument stc tells how each series separate into site,
tree, and core IDs. For instance a series code might be
"ABC011" indicating site "ABC", tree 1, core 1. If this
format is consistent then the stc mask would be
c(3, 2, 3) allowing up to three characters for the core
ID (i.e., pad to the right). If it is not possible to
define the scheme (and often it is not possible to machine read
IDs), then the output data.frame can be built
manually. See Value for format.
The function autoread.ids is a wrapper to read.ids with
stc="auto", i.e. automatic detection of the site / tree / core
scheme, and different default values of some parameters. In automatic
mode, the names in the same rwl can even follow different
site / tree / core schemes. As there are numerous possible encoding
schemes for naming measurement series, the function cannot always
produce the correct result.
With stc="auto", the site part can be one of the following.
In names mostly consisting of numbers, the longest common prefix is the site part
Alphanumeric site part ending with alphabet, when followed by numbers and alphabets
Alphabetic site part (quite complicated actual
definition). Setting ignore.case to "auto"
allows the function to try to guess when a case change in the middle
of a sequence of alphabets signifies a boundary between the site
part and the tree part.
The characters before the first sequence of space / punctuation characters in a name that contains at least two such sequences
These descriptions are somewhat general, and the details can be found in regular expressions inside the function. If a name does not match any of the descriptions, it is matched against a previously found site part, starting from the longest.
The following ID schemes are detected and supported in the tree / core part. The detection is done per site.
Numbers in tree part, core part starts with something else
Alphabets in tree part, core part starts with something else
Alphabets, either tree part all lower case and core part all
upper case or vice versa. For this to work,
ignore.case must be set to "auto" or
FALSE.
All digits. In this case, the number of characters belonging to the tree and core parts is detected with one of the following methods.
If numeric tree parts were found before, it is assumed that the core part is missing (one core per tree).
It the series are numbered continuously, one core per tree is assumed.
Otherwise, try to find a core part as the suffix so that the cores are numbered continuously.
If none of the above fits, the tree / core split of the all-digit names will be decided with the methods described further down the list, or finally with the fallback mechanism.
The combined tree / core part is empty or one character. In this case, the core part is assumed to be missing.
Tree and core parts separated by a punctuation or white space character
If the split of a tree / core part cannot be found with any of the
methods described above, the prefix of the string is matched against a
previously found tree part, starting from the longest. The fallback
mechanism for the still undecided tree / core parts is one of the
following. The first one is used if use.cor is
TRUE, number two if it is FALSE.
Pairwise correlation coefficients are computed between all remaining series. Pairs of series with above median correlation are flagged as similar, and the other pairs are flagged as dissimilar. Each possible number of characters (minimum 1) is considered for the share of the tree ID. The corresponding unique would-be tree IDs determine a set of clusterings where one cluster is formed by all the measurement series of a single tree. For each clustering (allocation of characters), an agreement score is computed. The agreement score is defined as the sum of the number of similar pairs with matching cluster number and the number of dissimilar pairs with non-matching cluster number. The number of characters with the maximum agreement is chosen.
If the majority of the names in the site use k
characters for the tree part, that number is chosen. Otherwise, one
core per tree is assumed. Parameter typo.ratio has a
double meaning as it also defines what is meant by majority here: at
least typo.ratio / (typo.ratio + 1) *
n.tot, where n.tot is the number of names in the site.
In both fallback mechanisms, the number of characters allocated for the tree part will be increased until all trees have a non-zero ID or there are no more characters.
Suspected typing errors will be fixed by the function if
fix.typos is TRUE. The parameter
typo.ratio affects the eagerness to fix typos, i.e. the
number of counterexamples required to declare a typo. The following
main typo fixing mechanisms are implemented:
If a rare site string resembles an at
least typo.ratio times more frequent alternative, and
if fixing it would not create any name collisions, make the fix.
The alternative string must be unique, or if there is more than
one alternative, it is enough if only one of them is a look-alike
string. Any kind of substitution in one character place is
allowed if the alternative string has the same length as the
original string. The alternative string can be one character
longer or one character shorter than the original string, but only
if it involves interpreting one digit as the look-alike alphabet
or vice versa. There are requirements to how long a site string
must be in order to be eligible for replacement / typo fixing,
i.e. cannot be shortened to zero length, cannot change the only
character of a site string. The parameters
ignore.case and ignore.site.case have
some effect on this typo fixing mechanism.
If all tree / core parts of a
site have the same length, each character position is inspected
individually. If the characters in the i:th position are
predominantly digits (alphabets), any alphabets (digits) are
changed to the corresponding look-alike digit (alphabet) if there
is one. The look-alike groups are {0, O, o}, {1, I, i}, {5,
S, s} and {6, G}. The parameter typo.ratio
determines the decision threshold of interpreting the type of each
character position as alphabet (digit): the ratio of alphabets
(digits) to the total number of characters must be at least
typo.ratio / (typo.ratio + 1). If a name
differs from the majority type in more than one character
position, it is not fixed. Also, no fixes are performed if any of
them would cause a possible monotonic order of numeric prefixes to
break.
The function attempts to convert the tree and core substrings to
integral values. When this succeeds, the converted values are copied
to the output without modification. When non-integral substrings are
observed, each unique tree is assigned a unique integral value. The
same applies to cores within a tree, but there are some subtleties
with respect to the handling of duplicates. Substrings are sorted
before assigning the numeric IDs.
The order of columns in rwl, in most cases, does not
affect the tree and core IDs assigned to each series.
A data.frame with column one named "tree" giving an
ID for each tree and column two named "core" giving
an ID for each core. The original series IDs are
copied from rwl as rownames. The order of the rows in the output
matches the order of the series in rwl. If more than one
site is detected, an additional third column named "site" will
contain a site ID. All columns have integral valued
numeric values.
Andy Bunn (original version) and Mikko Korpela (patches,
stc="auto", fix.typos, etc.).
library(utils) data(ca533) read.ids(ca533, stc = c(3, 2, 3)) autoread.ids(ca533)library(utils) data(ca533) read.ids(ca533, stc = c(3, 2, 3)) autoread.ids(ca533)
This function reads in a file of ring widths (.rwl) in one of the available formats.
read.rwl(fname, format = c("auto", "tucson", "compact", "tridas", "heidelberg", "sheet", "csv"), ...)read.rwl(fname, format = c("auto", "tucson", "compact", "tridas", "heidelberg", "sheet", "csv"), ...)
fname |
a |
format |
a |
... |
arguments specific to the function implementing the operation for the chosen format. |
This is a simple wrapper to the functions actually implementing the read operation.
With format = "auto" the file's first lines are scanned and the most
specific match wins: a DPL compact column specification or a
HEADER: line, then a <tridas> element, then a
NOAA/NCEI template header, then a comma separated
sheet, and Tucson if nothing else matches. A sheet is recognised by every
line splitting into the same number of comma separated fields, not by the
presence of a comma. Only commas are looked for: a tab separated file may be
a NOAA template, so tab separated sheets need
format = "sheet" with a sep argument.
format = "sheet" is handled by read.sheet, which as of
dplR 1.8.0 replaces the deprecated csv2rwl. Files that
csv2rwl accepted may now be refused; see read.sheet.
"csv" is accepted as a synonym for "sheet" because it has been
a valid value of format since before read.sheet existed. It is
the less accurate of the two: read.sheet also reads tab, semicolon
and pipe separated files, so format = "sheet" with a sep
argument is an ordinary call. Prefer "sheet" in new code.
If a "tucson", "compact", "heidelberg", "sheet" file is
read (even through "auto"), returns an object of class
c("rwl", "data.frame") with the series in columns and the years
as rows. The series IDs are the column names and the years
are the row names.
If a "tridas" file is read (even through "auto"),
returns a list of results. See read.tridas for more
information.
Mikko Korpela
read.tucson,
read.tucson.legacy, read.compact,
read.tridas, read.fh, read.sheet,
write.rwl
Read a file of ring widths saved in “spreadsheet” layout: years down the rows, series across the columns, and the years in the first column.
read.sheet(fname, sep = NULL, dec = ".", layout = c("wide", "long"), transpose = FALSE, comment.char = "#", fill.internal.NA = NULL, fix.dup.char = "X", encoding = NULL, verbose = TRUE, strict = FALSE, ...) csv2rwl(fname, ...)read.sheet(fname, sep = NULL, dec = ".", layout = c("wide", "long"), transpose = FALSE, comment.char = "#", fill.internal.NA = NULL, fix.dup.char = "X", encoding = NULL, verbose = TRUE, strict = FALSE, ...) csv2rwl(fname, ...)
fname |
a |
sep |
the field separator: one of |
dec |
the decimal mark, |
layout |
the shape of the file. |
transpose |
|
comment.char |
lines beginning with this string are treated as a comment header: skipped, and kept in the provenance record. |
fill.internal.NA |
passed to |
fix.dup.char |
|
encoding |
the encoding of the file, used only if the file is not
valid UTF-8. Any name |
verbose |
|
strict |
|
... |
other arguments passed to |
The expected layout is the one a spreadsheet produces: the first column holds the years, the first row holds the series IDs, and each remaining cell holds one ring width.
| Year | Ser1A | Ser1B | Ser2A | Ser2B |
| 1901 | NA | 0.45 | 0.43 | 0.24 |
| 1902 | NA | 0.05 | 0.00 | 0.07 |
| 1903 | 0.17 | 0.46 | 0.03 | 0.21 |
| 1904 | 0.28 | 0.21 | 0.54 | 0.41 |
| etc... |
An empty cell, NA, NaN, "." and "-" are all read
as missing. Any other value that does not parse as a number is an error
rather than a missing value, and the offending cells are named.
Unlike a Tucson file, a spreadsheet has no format to conform to, so this
function checks the contents rather than assuming them. The years must be
whole numbers, ascending, unique and consecutive: a year with no measurements
is a row of NA, not a missing row. Every column after the first must
be numeric. Series IDs are read verbatim, and anything that changes
one – a stripped byte order mark, a resolved duplicate – is reported and
recorded rather than done silently.
Comma, tab, semicolon and pipe separated files are all read. Left at
NULL, sep is detected by looking for the candidate that
gives every line the same number of fields, preferring the one that gives
the most; quoted spans are ignored while counting, so a series
ID may contain the separator. The detected separator is recorded
in the provenance record as SEP_GUESS and printed when
verbose is TRUE, but it is not a warning: detection is the
default, and a defect it is not.
A semicolon separated file is usually a European export and carries decimal
commas. When the separator is detected as a semicolon and a digit-comma-digit
appears in the data, dec is set to "," and recorded as
DEC_COMMA. Thousands separators are not handled: "1.234,5"
and "1,234.5" are the same characters under two conventions and
nothing in the file says which.
sep and dec may not be the same character.
With layout = "long" the file holds one row per observation rather
than a rectangle: a series ID, a year and a value. Columns are taken
by position, which is what write.sheet writes; if the header
names all three of series, year and value, in any
case and any order, the names are used instead.
The year span of the result runs from the earliest to the latest year in
the file. A year with no observation in any series therefore comes back as
a row of NA, and is reported, since years with no data break several
dplR functions. One series may hold only one value per year.
read.sheet refuses a NOAA/NCEI template file. Those
files are a commented metadata block followed by a tab separated data table,
and reading the table alone would discard the coordinates, species,
investigators and DOI above it.
An object of class c("rwl", "data.frame") with the series in columns
and the years as rows. The series IDs are the column names and the
years are the row names.
The object carries an attribute "dplR.provenance", a list in the
same shape as the one attached by read.tucson, recording what
the reader found and what it changed. Its events element is a
data.frame of findings, each with a stable id such as
"ID_RENAMED" or "UNITS_SUSPECT".
csv2rwl is deprecated as of dplR 1.8.0 and now calls
read.sheet. It will be made defunct in a later release.
This is a change of behaviour and not only a change of name. csv2rwl
assigned the class "rwl" directly, which bypassed as.rwl
and its requirement that the row names be consecutive integers. It therefore
accepted files that read.sheet refuses:
non-consecutive or duplicated years, which produced an object whose
time was not a continuous span;
columns holding text, which travelled inside the rwl until
some later function failed on them;
series IDs were passed through
read.table(check.names = TRUE), so "1A" became
"X1A" and "LF-2B" became "LF.2B", silently.
A file that csv2rwl read may therefore now stop with an error. That is
the deprecation doing its job: the object it used to return was invalid.
csv2rwl also stopped when a series ID appeared twice, where
read.sheet renames the duplicate and records the change, as
read.tucson does.
There is no csv2rwl.legacy. read.tucson.legacy exists
because the behaviour of the old Tucson reader differs from the new one in
ways that are occasionally wanted; that is not the case here.
Andy Bunn
write.sheet, read.rwl,
read.tucson, rwl.check, as.rwl
library(utils) data(ca533) # write out a sheet that read.sheet will understand tm <- time(ca533) foo <- data.frame(tm, ca533, check.names = FALSE) names(foo)[1] <- "Year" tmpName <- tempfile(fileext = ".csv") write.csv(foo, file = tmpName, row.names = FALSE) # read it back in bar <- read.sheet(tmpName, verbose = FALSE) # the provenance record travels with the data str(attr(bar, "dplR.provenance")$events) unlink(tmpName)library(utils) data(ca533) # write out a sheet that read.sheet will understand tm <- time(ca533) foo <- data.frame(tm, ca533, check.names = FALSE) names(foo)[1] <- "Year" tmpName <- tempfile(fileext = ".csv") write.csv(foo, file = tmpName, row.names = FALSE) # read it back in bar <- read.sheet(tmpName, verbose = FALSE) # the provenance record travels with the data str(attr(bar, "dplR.provenance")$events) unlink(tmpName)
This function reads in a TRiDaS format XML file. Measurements, derived series and various kinds of metadata are supported.
read.tridas(fname, ids.from.titles = FALSE, ids.from.identifiers = TRUE, combine.series = TRUE, trim.whitespace = TRUE, warn.units = TRUE)read.tridas(fname, ids.from.titles = FALSE, ids.from.identifiers = TRUE, combine.series = TRUE, trim.whitespace = TRUE, warn.units = TRUE)
fname |
|
ids.from.titles |
|
ids.from.identifiers |
|
combine.series |
|
trim.whitespace |
|
warn.units |
|
The Tree Ring Data Standard (TRiDaS) is described in Jansma et. al (2010).
The parameters used for rearranging (ids.from.titles,
ids.from.identifiers) and combining
(combine.series) measurement series only affect the four
lowest levels of document structure: element, sample, radius,
measurementSeries. Series are not reorganized or combined at the
upper structural levels (project, object).
A list with a variable number of components according to the contents of the input file. The possible list components are:
measurements |
A |
ids |
A If |
titles |
A |
wood.completeness |
A |
unit |
A |
project.id |
A |
project.title |
A |
site.id |
A |
site.title |
A |
taxon |
A |
variable |
A |
undated |
A
|
derived |
A
|
type |
A
|
comments |
A
|
identifier |
A
|
remark |
A
|
laboratory |
A
|
research |
A
|
altitude |
A
|
preferred |
A
|
This is an early version of the function. Bugs are likely to exist, and parameters and return values are subject to change. Not all metadata defined in the TRiDaS specification is supported – unsupported elements are quietly ignored.
Mikko Korpela
Jansma, E., Brewer, P. W., and Zandhuis, I. (2010) TRiDaS 1.1: The tree-ring data standard. Dendrochronologia, 28(2), 99–130.
read.rwl, read.tucson,
read.compact, read.fh,
write.tridas
This function reads in a Tucson (decadal) format file of ring widths (.rwl).
read.tucson(fname, header = NULL, long = FALSE, encoding = getOption("encoding"), edge.zeros = TRUE, verbose = TRUE, comment.char = "#", fix.dup.char = "X", fill.internal.NA = NULL, strict = FALSE)read.tucson(fname, header = NULL, long = FALSE, encoding = getOption("encoding"), edge.zeros = TRUE, verbose = TRUE, comment.char = "#", fix.dup.char = "X", fill.internal.NA = NULL, strict = FALSE)
fname |
a |
header |
ignored, and accepted only so that existing calls do not fail. Header lines are now identified per line by their content. See ‘Details’. |
long |
ignored, and accepted only so that existing calls do not
fail. The two possible column layouts are now detected per line, so
8-character series IDs and years before -999 may occur in the
same file. As in |
encoding |
the encoding of the file, used only if the file is not
valid UTF-8. Any name |
edge.zeros |
|
verbose |
|
comment.char |
a |
fix.dup.char |
a |
fill.internal.NA |
what to do with interior gaps, i.e. years inside
a series for which the file records no measurement. The default,
|
strict |
|
This reads in a standard rwl file as defined according to the standards of the ITRDB at https://www.ncei.noaa.gov/pub/data/paleo/treering/treeinfo.txt.
This function was replaced in dplR 1.8.0. The previous implementation is
still available, unchanged, as read.tucson.legacy. The two
differ in at least three important ways.
Interior gaps are no longer filled with zero. This is the change
most likely to alter your numbers. Where a file records no measurement
for a stretch of years inside a series, the old reader silently wrote
zeros. A ring width of zero means a locally absent ring, which is a real
observation about a tree in a year; a gap means the ring was not measured,
which is a statement about the data. These are different claims and the
reader no longer substitutes one for the other. Set
fill.internal.NA = 0 to recover the old values exactly.
Note that several dplR functions, detrend among them, do not
accept NA inside a series and will fail on such data. If you need
to detrend a series containing interior gaps you must decide what those
gaps mean and fill them deliberately, with fill.internal.NA
or with fill.internal.NA = 0 here.
Malformed files are reported rather than guessed at. Where the ten
fixed-width columns and a whitespace split of the same line disagree, the
line does not conform to the format and nothing in it says which reading
was meant, so it is returned as NA with both readings reported.
Repeated series IDs are reported instead of being silently
welded into one series, and are renamed when their records overlap. Tab
characters, which have no defined width in a fixed-width format, are
expanded to 8-column tab stops and reported.
The header and column layout are determined per line. This is why
header and long are no longer used. header could
only skip a fixed three lines and so could not describe the 4- and 6-line
headers that real files contain. long is worse: years before -999
need five columns and so take column 8 away from the series ID,
but that varies line by line, so a file mixing 8-character IDs
with BC dates is read wrongly whichever way a per-file switch is
set. Both are now decided from the content of each line. The arguments
are still accepted, in their original positions, so that existing code and
read.rwl's pass-through of ... do not fail with an
“unused argument” error; passing either one warns.
Editorial: A closing word on the format itself. The Tucson decadal format
dates from the era of the punch card. It is nominally fixed-width,
yet files in the ITRDB arrive with tab characters sitting in the
measurement fields, and a tab has no defined width at all. Column 8
belongs to the series ID unless the year is earlier than -999, in
which case the year claims it, and nothing but a minus sign distinguishes
the two readings. A negative number marks missing data, except when it
marks the end of a record; 999 ends a record in a 0.01 mm file, so a
genuine 9.99 mm ring cannot be told apart from a terminator. A single
ID may carry several records written in any order at all: in
ITRDB ‘ut542.rwl’ a series runs to 1841 and then starts over at
1353 further
down the file. A decade line may resume off its boundary and quietly
swallow the years it skipped, as ‘chil012.rwl’ does at 1242 for series
AGU034. None of
this is the fault of the people who made these data available, and the
tree-ring community deserves credit for sharing its measurements
openly long before most of science thought to do so. But we are still
paying for a format built around eighty columns of cardboard.
read.tucson tries to read
what the file says, to report plainly what it did, and to refuse
rather than guess when a line admits two readings. Even so, and despite
our best efforts, this format can and does fail.
An object of class c("rwl", "data.frame") with the series in
columns and the years as rows. The series IDs are the
column names and the years are the row names. Columns are returned in
the order the series appear in the file.
The returned object carries a "dplR.provenance" attribute recording
what the reader saw: the header lines, the precision each series was measured
at and whether the file mixes them, any series the reader renamed (as
old and new), the interior gaps and what the file held at
each, and one row per recoverable problem found while parsing. Most of this
cannot be recovered from the returned data or by reading the file again, and
rwl.check reports on it. Subsetting an rwl object with
[.rwl carries the record along and cuts it down to the series
and years that are left, but functions that return a new object, such as
detrend, drop it, so it describes the read rather than
travelling with the data indefinitely.
Ring widths are digits, but the header lines and occasionally the series
IDs are not, and archived files carry accented site names and
investigator names in whatever 8-bit encoding the contributor's machine
used. read.tucson resolves this in three steps.
First, the file is tested against UTF-8. This is a decision and not a guess: UTF-8 is self-validating, and plain ASCII passes, so virtually every file takes this path and nothing is reported.
If the file is not valid UTF-8 and encoding was supplied,
that encoding is used and an ENCODING_DECLARED event is recorded.
If the declared encoding does not fit the file, read.tucson stops
rather than transcode into replacement characters.
If the file is not valid UTF-8 and no encoding was supplied, it
is read as "latin1" and an ENCODING_ASSUMED event is
recorded, with a warning naming the line and quoting the text the
assumption produced, so the guess can be judged at a glance. Under
strict = TRUE this becomes an error.
The fallback guesses rather than running a charset detector because
detectors do not work on this kind of file. They are byte-frequency
language models and need a volume of non-ASCII text that a file
of ring widths never has; on a rwl that is ASCII apart from one
accented name, ICU's detector scores the right answer at 0.16
and ranks UTF-16 alongside it. "latin1" is used instead
because it is total (every byte decodes, so it cannot fail) and lossless
(the round trip is byte-identical, so a wrong guess discards nothing and
the file can simply be re-read with encoding set).
Original reader by Hung Nguyen. Reworked and extended by Andy Bunn.
read.tucson.legacy, read.rwl,
read.compact, read.tridas,
read.fh, write.tucson,
fill.internal.NA, [.rwl
## A short file with an interior gap: the 1910s are marked -999, ## i.e. not measured. tf <- tempfile() writeLines(c("TST01A 1900 123 134 145 156 167 178 189 150 141 132", "TST01A 1910 -999 -999 -999 -999 -999 -999 -999 -999 -999 -999", "TST01A 1920 211 222 233 244 255 266 277 288 299 300", "TST01A 1930 311 999"), tf) ## The default reports the gap and returns it as NA. x <- read.tucson(tf) x["1915", ] ## Ask for the old behaviour explicitly. x0 <- read.tucson(tf, fill.internal.NA = 0) x0["1915", ] unlink(tf)## A short file with an interior gap: the 1910s are marked -999, ## i.e. not measured. tf <- tempfile() writeLines(c("TST01A 1900 123 134 145 156 167 178 189 150 141 132", "TST01A 1910 -999 -999 -999 -999 -999 -999 -999 -999 -999 -999", "TST01A 1920 211 222 233 244 255 266 277 288 299 300", "TST01A 1930 311 999"), tf) ## The default reports the gap and returns it as NA. x <- read.tucson(tf) x["1915", ] ## Ask for the old behaviour explicitly. x0 <- read.tucson(tf, fill.internal.NA = 0) x0["1915", ] unlink(tf)
This function reads in a Tucson (decadal) format file of ring widths
(.rwl). It is the reader that dplR used through version 1.7.9, kept
unchanged for backward compatibility. New code should use
read.tucson.
read.tucson.legacy(fname, header = NULL, long = FALSE, encoding = getOption("encoding"), edge.zeros = TRUE, verbose = TRUE)read.tucson.legacy(fname, header = NULL, long = FALSE, encoding = getOption("encoding"), edge.zeros = TRUE, verbose = TRUE)
fname |
a |
header |
|
long |
|
encoding |
the name of the encoding to be used when reading the
rwl file. Usually the default value will work, but an rwl file
written in a non-default encoding may crash the function. In that
case, identifying the encoding and specifying it here should fix the
problem. Examples of popular encodings available on many systems
are |
edge.zeros |
|
verbose |
|
This reads in a standard rwl file as defined according to the standards of the ITRDB at https://www.ncei.noaa.gov/pub/data/paleo/treering/treeinfo.txt. Despite the standards at the ITRDB, this occasionally fails due to formatting problems.
This function was the default Tucson reader in dplR through version
1.7.9. As of 1.8.0 that role belongs to read.tucson, which
reads files this one cannot, reports malformed lines rather than guessing
at them, and by default returns interior gaps as NA instead of
filling them with zero. This function is retained so that existing
workflows continue to produce exactly the numbers they always have, and
because it honours the encoding argument, which
read.tucson does not. Use
read.tucson(fname, fill.internal.NA = 0) to get the new reader's
parsing with the old reader's treatment of gaps.
An object of class c("rwl", "data.frame") with the series in
columns and the years as rows. The series IDs are the
column names and the years are the row names.
Andy Bunn. Patched and greatly improved by Mikko Korpela.
read.tucson, read.rwl,
read.compact, read.tridas,
read.fh, write.tucson
Estimate red-noise spectra from a possibly unevenly spaced time-series.
redfit(x, t, tType = c("time", "age"), nsim = 1000, mctest = TRUE, ofac = 4, hifac = 1, n50 = 3, rhopre = NULL, p = c(0.10, 0.05, 0.02), iwin = 2, txOrdered = FALSE, verbose = FALSE, seed = NULL, maxTime = 10, nLimit = 10000) runcrit(n, p = c(0.10, 0.05, 0.02), maxTime = 10, nLimit = 10000)redfit(x, t, tType = c("time", "age"), nsim = 1000, mctest = TRUE, ofac = 4, hifac = 1, n50 = 3, rhopre = NULL, p = c(0.10, 0.05, 0.02), iwin = 2, txOrdered = FALSE, verbose = FALSE, seed = NULL, maxTime = 10, nLimit = 10000) runcrit(n, p = c(0.10, 0.05, 0.02), maxTime = 10, nLimit = 10000)
x |
a |
t |
a |
tType |
a |
nsim |
a |
mctest |
a |
ofac |
oversampling factor for Lomb-Scargle Fourier transform.
A |
hifac |
maximum frequency to analyze relative to the Nyquist
frequency. A |
n50 |
number of segments. The segments overlap by about 50 percent. |
rhopre |
a |
p |
a |
iwin |
the type of window used for scaling the values of each
segment of data. A |
txOrdered |
a |
verbose |
a |
seed |
a value to be given to |
maxTime |
a |
nLimit |
a |
n |
an integral value giving the length of the sequence in the number of runs test. |
Function redfit computes the spectrum of a possibly unevenly
sampled time-series by using the Lomb-Scargle Fourier transform. The
spectrum is bias-corrected using spectra computed from simulated AR1
series and the theoretical AR1 spectrum.
The function duplicates the functionality of program REDFIT by Schulz and Mudelsee. See the manual of that program for more information. The results of this function should be very close to REDFIT. However, some changes have been made:
More precision is used in some constants and computations.
All the data are used: the last segment always contains the
last pair of (t, x). There may be small differences
between redfit and REDFIT with respect to the number of
points per segment and the overlap of consecutive segments.
The critical values of the runs test (see the description of
runcrit below) differ between redfit and REDFIT. The
approximate equations in REDFIT produce values quite far off from
the exact values when the number of frequencies is large.
The user can select the significance levels of the runs test.
Most of the window functions have been adjusted.
6 dB bandwidths have been computed for discrete-time windows.
Function runcrit computes the limits of the acceptance region
of a number of runs test: assuming a sequence of n i.i.d.
discrete random variables with two possible values a and b
of equal probability (0.5), we are examining the distribution of the
number of runs. A run is an uninterrupted sequence of only a or
only b. The minimum number of runs is 1 (a sequence with only
a or only b) while the maximum number is n
(alternating a and b). See Bradley, p. 253–254,
259–263. The function is also called from redfit;
see rcnt in ‘Value’ for the interpretation. In
this case the arguments p, maxTime and
nLimit are passed from redfit to runcrit,
and n is the number of output frequencies.
The results of runcrit have been essentially precomputed for
some values of p and n. If a precomputed
result is not found and n is not too large
(nLimit, maxTime), the exact results are
computed on-demand. Otherwise, or if package "gmp" is not
installed, the normal distribution is used for approximation.
Function runcrit returns a list containing
rcritlo, rcrithi and rcritexact
(see below). Function redfit returns a list with the
following elements:
varx |
variance of |
rho |
average autocorrelation coefficient, either estimated
from the data or prescribed ( |
tau |
the time scale of an AR1 process corresponding to
|
rcnt |
a |
rcritlo |
a |
rcrithi |
a |
rcritexact |
a |
freq |
the frequencies used. A |
gxx |
estimated spectrum of the data (t, x). A
|
gxxc |
red noise corrected spectrum of the data. A
|
grravg |
average AR1 spectrum over |
gredth |
theoretical AR1 spectrum. A |
corr |
a |
ci80 |
a |
ci90 |
a |
ci95 |
95th percentile red noise spectrum. |
ci99 |
99th percentile red noise spectrum. |
call |
the call to the function. See |
params |
A
|
vers |
version of dplR. See |
seed |
value of the |
t |
if duplicated values of |
x |
if duplicated values of |
Mikko Korpela. Examples by Andy Bunn.
Function redfit is based on the Fortran program
REDFIT
(version 3.8e), which is in the public domain.
Bradley, J. V. (1968) Distribution-Free Statistical Tests. Prentice-Hall.
Schulz, M. and Mudelsee, M. (2002) REDFIT: estimating red-noise spectra directly from unevenly spaced paleoclimatic time series. Computers & Geosciences, 28(3), 421–426.
# Create a simulated tree-ring width series that has a red-noise # background ar1=phi and sd=sigma and an embedded signal with # a period of 10 and an amplitude of have the rednoise sd. library(graphics) library(stats) runif(1) rs <- .Random.seed set.seed(123) nyrs <- 500 yrs <- 1:nyrs # Here is an ar1 time series with a mean of 2mm, # an ar1 of phi, and sd of sigma phi <- 0.7 sigma <- 0.3 sigma0 <- sqrt((1 - phi^2) * sigma^2) x <- arima.sim(list(ar = phi), n = nyrs, sd = sigma0) + 2 # Here is a sine wave at f=0.1 to add in with an amplitude # equal to half the sd of the red noise background per <- 10 amp <- sigma0 / 2 wav <- amp * sin(2 * pi / per * yrs) # Add them together so we have signal and noise x <- x + wav # Here is the redfit spec redf.x <- redfit(x, nsim = 500) # Acceptance region of number of runs test # (not useful with default arguments of redfit()) runcrit(length(redf.x[["freq"]])) op <- par(no.readonly = TRUE) # Save to reset on exit par(tcl = 0.5, mar = rep(2.2, 4), mgp = c(1.1, 0.1, 0)) plot(redf.x[["freq"]], redf.x[["gxxc"]], ylim = range(redf.x[["ci99"]], redf.x[["gxxc"]]), type = "n", ylab = "Spectrum", xlab = "Frequency (1/yr)", axes = FALSE) grid() lines(redf.x[["freq"]], redf.x[["gxxc"]], col = "#1B9E77") lines(redf.x[["freq"]], redf.x[["ci99"]], col = "#D95F02") lines(redf.x[["freq"]], redf.x[["ci95"]], col = "#7570B3") lines(redf.x[["freq"]], redf.x[["ci90"]], col = "#E7298A") freqs <- pretty(redf.x[["freq"]]) pers <- round(1 / freqs, 2) axis(1, at = freqs, labels = TRUE) axis(3, at = freqs, labels = pers) mtext(text = "Period (yr)", side = 3, line = 1.1) axis(2); axis(4) legend("topright", c("x", "CI99", "CI95", "CI90"), lwd = 2, col = c("#1B9E77", "#D95F02", "#7570B3", "#E7298A"), bg = "white") box() ## Not run: # Second example with tree-ring data # Note the long-term low-freq signal in the data. E.g., # crn.plot(cana157) library(utils) data(cana157) yrs <- time(cana157) x <- cana157[, 1] redf.x <- redfit(x, nsim = 1000) plot(redf.x[["freq"]], redf.x[["gxxc"]], ylim = range(redf.x[["ci99"]], redf.x[["gxxc"]]), type = "n", ylab = "Spectrum", xlab = "Frequency (1/yr)", axes = FALSE) grid() lines(redf.x[["freq"]], redf.x[["gxxc"]], col = "#1B9E77") lines(redf.x[["freq"]], redf.x[["ci99"]], col = "#D95F02") lines(redf.x[["freq"]], redf.x[["ci95"]], col = "#7570B3") lines(redf.x[["freq"]], redf.x[["ci90"]], col = "#E7298A") freqs <- pretty(redf.x[["freq"]]) pers <- round(1 / freqs, 2) axis(1, at = freqs, labels = TRUE) axis(3, at = freqs, labels = pers) mtext(text = "Period (yr)", side = 3, line = 1.1) axis(2); axis(4) legend("topright", c("x", "CI99", "CI95", "CI90"), lwd = 2, col = c("#1B9E77", "#D95F02", "#7570B3", "#E7298A"), bg = "white") box() par(op) ## End(Not run) .Random.seed <- rs# Create a simulated tree-ring width series that has a red-noise # background ar1=phi and sd=sigma and an embedded signal with # a period of 10 and an amplitude of have the rednoise sd. library(graphics) library(stats) runif(1) rs <- .Random.seed set.seed(123) nyrs <- 500 yrs <- 1:nyrs # Here is an ar1 time series with a mean of 2mm, # an ar1 of phi, and sd of sigma phi <- 0.7 sigma <- 0.3 sigma0 <- sqrt((1 - phi^2) * sigma^2) x <- arima.sim(list(ar = phi), n = nyrs, sd = sigma0) + 2 # Here is a sine wave at f=0.1 to add in with an amplitude # equal to half the sd of the red noise background per <- 10 amp <- sigma0 / 2 wav <- amp * sin(2 * pi / per * yrs) # Add them together so we have signal and noise x <- x + wav # Here is the redfit spec redf.x <- redfit(x, nsim = 500) # Acceptance region of number of runs test # (not useful with default arguments of redfit()) runcrit(length(redf.x[["freq"]])) op <- par(no.readonly = TRUE) # Save to reset on exit par(tcl = 0.5, mar = rep(2.2, 4), mgp = c(1.1, 0.1, 0)) plot(redf.x[["freq"]], redf.x[["gxxc"]], ylim = range(redf.x[["ci99"]], redf.x[["gxxc"]]), type = "n", ylab = "Spectrum", xlab = "Frequency (1/yr)", axes = FALSE) grid() lines(redf.x[["freq"]], redf.x[["gxxc"]], col = "#1B9E77") lines(redf.x[["freq"]], redf.x[["ci99"]], col = "#D95F02") lines(redf.x[["freq"]], redf.x[["ci95"]], col = "#7570B3") lines(redf.x[["freq"]], redf.x[["ci90"]], col = "#E7298A") freqs <- pretty(redf.x[["freq"]]) pers <- round(1 / freqs, 2) axis(1, at = freqs, labels = TRUE) axis(3, at = freqs, labels = pers) mtext(text = "Period (yr)", side = 3, line = 1.1) axis(2); axis(4) legend("topright", c("x", "CI99", "CI95", "CI90"), lwd = 2, col = c("#1B9E77", "#D95F02", "#7570B3", "#E7298A"), bg = "white") box() ## Not run: # Second example with tree-ring data # Note the long-term low-freq signal in the data. E.g., # crn.plot(cana157) library(utils) data(cana157) yrs <- time(cana157) x <- cana157[, 1] redf.x <- redfit(x, nsim = 1000) plot(redf.x[["freq"]], redf.x[["gxxc"]], ylim = range(redf.x[["ci99"]], redf.x[["gxxc"]]), type = "n", ylab = "Spectrum", xlab = "Frequency (1/yr)", axes = FALSE) grid() lines(redf.x[["freq"]], redf.x[["gxxc"]], col = "#1B9E77") lines(redf.x[["freq"]], redf.x[["ci99"]], col = "#D95F02") lines(redf.x[["freq"]], redf.x[["ci95"]], col = "#7570B3") lines(redf.x[["freq"]], redf.x[["ci90"]], col = "#E7298A") freqs <- pretty(redf.x[["freq"]]) pers <- round(1 / freqs, 2) axis(1, at = freqs, labels = TRUE) axis(3, at = freqs, labels = pers) mtext(text = "Period (yr)", side = 3, line = 1.1) axis(2); axis(4) legend("topright", c("x", "CI99", "CI95", "CI90"), lwd = 2, col = c("#1B9E77", "#D95F02", "#7570B3", "#E7298A"), bg = "white") box() par(op) ## End(Not run) .Random.seed <- rs
These functions calculate descriptive statistics on a
data.frame of (usually) ring-width indices. The statistics are
optionally computed in a running window with adjustable length and
overlap. The data can be filtered so that the comparisons are made to
on just high-frequency data.
rwi.stats.running(rwi, ids = NULL, period = c("max", "common"), method = c("spearman", "pearson","kendall"), prewhiten=FALSE,n=NULL, nyrs = NULL, ar.order.max = NULL, running.window = TRUE, window.length = min(50, nrow(rwi)), window.overlap = floor(window.length / 2), first.start = NULL, min.corr.overlap = min(30, window.length), round.decimals = 3, zero.is.missing = TRUE) rwi.stats(rwi, ids=NULL, period=c("max", "common"), method = c("spearman", "pearson","kendall"), ...) rwi.stats.legacy(rwi, ids=NULL, period=c("max", "common"))rwi.stats.running(rwi, ids = NULL, period = c("max", "common"), method = c("spearman", "pearson","kendall"), prewhiten=FALSE,n=NULL, nyrs = NULL, ar.order.max = NULL, running.window = TRUE, window.length = min(50, nrow(rwi)), window.overlap = floor(window.length / 2), first.start = NULL, min.corr.overlap = min(30, window.length), round.decimals = 3, zero.is.missing = TRUE) rwi.stats(rwi, ids=NULL, period=c("max", "common"), method = c("spearman", "pearson","kendall"), ...) rwi.stats.legacy(rwi, ids=NULL, period=c("max", "common"))
rwi |
a |
ids |
an optional |
period |
a |
method |
Can be either |
n |
|
nyrs |
|
prewhiten |
|
ar.order.max |
|
running.window |
|
window.length |
|
window.overlap |
|
first.start |
an optional |
min.corr.overlap |
|
round.decimals |
non-negative integer |
zero.is.missing |
|
... |
arguments passed on to |
This calculates a variety of descriptive statistics commonly used in dendrochronology.
The function rwi.stats is a wrapper that calls
rwi.stats.running with running.window = FALSE.
The results may differ from those prior to dplR 1.5.3, where the
former rwi.stats (now renamed to rwi.stats.legacy) was
replaced with a call to rwi.stats.running.
For correctly calculating the statistics on within and between series
variability, an appropriate mask (parameter ids) must be
provided that identifies each series with a tree as it is common for
dendrochronologists to take more than one core per tree. The function
read.ids is helpful for creating a mask based on the
series ID.
If ids has duplicate tree/core combinations, the
corresponding series are averaged before any statistics are computed.
The value of the parameter zero.is.missing is relevant in
the averaging: TRUE ensures that zeros don’t
contribute to the average. The default value of
zero.is.missing is TRUE. The default prior to
dplR 1.5.3 was FALSE. If the parameter is set to FALSE,
the user will be warned in case zeros are present. Duplicate
tree/core combinations are not detected by rwi.stats.legacy.
Row names of ids may be used for matching the
IDs with series in rwi. In this case, the
number of rows in ids is allowed to exceed the number of
series. If some names of rwi are missing from the row
names of ids, the rows of ids are assumed to
be in the same order as the columns of rwi, and the
dimensions must match. The latter is also the way that
rwi.stats.legacy handles ids, i.e. names are
ignored and dimensions must match.
Note that period = "common" can produce NaN for many of
the stats if there is no common overlap period among the cores. This
happens especially in chronologies with floating subfossil samples
(e.g., ca533).
Some of the statistics are specific to dendrochronology (e.g., the effective number of cores or the expressed population signal). Users unfamiliar with these should see Cook and Kairiukstis (1990) and Fritts (2001) for further details for computational details on the output. The signal-to-noise ratio is calculated following Cook and Pederson (2011).
Please note that Buras (2017) cautions against the use of expressed
population signal (EPS) for evaluating the climate-reconstruction potential
of a tree-ring sample. Instead, he recommends the use of subsample signal
strength (sss) for evaluating the loss of predictive power
back in time when sample replication drops.
If desired, the rwi can be filtered in the same manner
as the family of cross-dating functions using prewhiten and
n. See the help page for corr.rwl.seg for
more details.
The statistics are correlations, so they do not depend on the level
of each series. rwi may hold values that can be
negative, such as indices from detrend with
difference = TRUE, log widths or isotope values; each
series then has its mean subtracted rather than being divided by it,
which would flip a series with a negative mean. The n and nyrs
filters divide each series by a smooth curve, so they refuse data with
negative values.
A data.frame containing the following columns (each row
corresponds to one position of the window):
start.year |
the first year in the window. Not returned if
|
mid.year |
the middle year in the window, rounded down. Not
returned if |
end.year |
the last year in the window. Not returned if
|
n.cores |
the number of cores |
n.trees |
the number of trees |
n |
the average number of trees (for each year, a tree needs at
least one non- |
n.tot |
total number of correlations calculated as
Equal to |
n.wt |
number of within-tree correlations computed |
n.bt |
number of between-tree correlations computed |
rbar.tot |
the mean of all the correlations between different cores |
rbar.wt |
the mean of the correlations between series from the same tree over all trees |
rbar.bt |
the mean interseries correlation between all series from different trees |
c.eff |
the effective number of cores (takes into account the number of within-tree correlations in each tree) |
rbar.eff |
the effective signal calculated as
|
eps |
the expressed population signal calculated using the average
number of trees as |
snr |
the signal to noise ratio calculated using the average
number of trees as |
This function uses the foreach looping
construct with the %dopar% operator.
For parallel computing and a potential speedup, a parallel backend
must be registered before running the function.
Mikko Korpela, based on rwi.stats.legacy by Andy
Bunn
Buras, A. (2017) A comment on the Expressed Population Signal. Dendrochronologia 44:130-132.
Cook, E. R. and Kairiukstis, L. A., editors (1990) Methods of Dendrochronology: Applications in the Environmental Sciences. Springer. ISBN-13: 978-0-7923-0586-6.
Cook, E. R. and Pederson, N. (2011) Uncertainty, Emergence, and Statistics in Dendrochronology. In Hughes, M. K., Swetnam, T. W., and Diaz, H. F., editors, Dendroclimatology: Progress and Prospects, pages 77–112. Springer. ISBN-13: 978-1-4020-4010-8.
Fritts, H. C. (2001) Tree Rings and Climate. Blackburn. ISBN-13: 978-1-930665-39-2.
detrend, cor,
read.ids, rwi.stats,
corr.rwl.seg
library(utils) data(gp.rwl) data(gp.po) gp.rwi <- cms(rwl = gp.rwl, po = gp.po) gp.ids <- read.ids(gp.rwl, stc = c(0, 2, 1)) # On a running window rwi.stats.running(gp.rwi, gp.ids) ## With no running window (i.e. running.window = FALSE) rwi.stats(gp.rwi, gp.ids) ## Restrict to common overlap (in this case 1899 to 1987) rwi.stats(gp.rwi, gp.ids, period="common") rwi.stats.legacy(gp.rwi, gp.ids) # rwi.stats prior to dplR 1.5.3library(utils) data(gp.rwl) data(gp.po) gp.rwi <- cms(rwl = gp.rwl, po = gp.po) gp.ids <- read.ids(gp.rwl, stc = c(0, 2, 1)) # On a running window rwi.stats.running(gp.rwi, gp.ids) ## With no running window (i.e. running.window = FALSE) rwi.stats(gp.rwi, gp.ids) ## Restrict to common overlap (in this case 1899 to 1987) rwi.stats(gp.rwi, gp.ids, period="common") rwi.stats.legacy(gp.rwi, gp.ids) # rwi.stats prior to dplR 1.5.3
Run a battery of integrity checks against a rwl object or a Tucson
format file and return the result as data: one row per finding, each carrying
a stable check ID and a severity. Intended both for a researcher
looking at one collection and for sweeping a large archive.
rwl.check(x, file = NULL, checks = c("structure", "series", "values", "zeros", "crossdating", "provenance", "file"), control = rwl.check.control(), ...) rwl.check.control(min.depth = 2, depth.run = 10, min.length = 30, run.min = 6, zero.run = 10, lag.max = 5, min.overlap = 50, spline.nyrs = 32, r.dating = 0.35, r.margin = 0.05, outlier.mad = 4, outlier.gap = 0.2, r.cohesion = 0.35, plausible.mean = c(0.05, 10), small.thresh = NA, big.thresh = NA, max.year = as.integer(format(Sys.Date(), "%Y"))) rwl.check.catalogue()rwl.check(x, file = NULL, checks = c("structure", "series", "values", "zeros", "crossdating", "provenance", "file"), control = rwl.check.control(), ...) rwl.check.control(min.depth = 2, depth.run = 10, min.length = 30, run.min = 6, zero.run = 10, lag.max = 5, min.overlap = 50, spline.nyrs = 32, r.dating = 0.35, r.margin = 0.05, outlier.mad = 4, outlier.gap = 0.2, r.cohesion = 0.35, plausible.mean = c(0.05, 10), small.thresh = NA, big.thresh = NA, max.year = as.integer(format(Sys.Date(), "%Y"))) rwl.check.catalogue()
x |
a |
file |
a |
checks |
a |
control |
a |
min.depth |
years measured by fewer than this many series are flagged. |
depth.run |
how many consecutive such years are needed before they are reported. Every collection thins at its edges, so a year or two says nothing. |
min.length |
series with fewer than this many rings are flagged. |
run.min |
a run of this many identical non-zero rings is flagged. |
zero.run |
a run of this many zeros in a series is flagged as
|
lag.max |
largest lag searched when looking for dating errors. |
min.overlap |
rings a series must share with the master to be checked against it. |
spline.nyrs |
stiffness, in years, of the spline used to high pass the
series before the crossdating checks. Crossdating works on year-to-year
variation, so correlating raw ring widths would measure the agreement of
age trends instead. The default is the COFECHA value, which is
also |
r.dating |
correlation a series must reach at its best lag before a non-zero lag is called a dating error. |
r.margin |
how much better than the correlation as dated that best-lag correlation must be. |
outlier.mad |
how many median absolute deviations below its own collection's median correlation a series must fall to be flagged as not fitting the collection. |
outlier.gap |
how far below the collection median, in correlation, that series must also fall. The second condition stops a very tight collection from flagging trivial spread. |
r.cohesion |
median series correlation below which the collection as a whole is reported as sharing little common signal. |
plausible.mean |
range, in mm, within which a collection's mean ring width is taken to be plausible. |
small.thresh, big.thresh
|
thresholds for flagging small and large
rings. |
max.year |
years after this are flagged. |
... |
not used. |
rwl.check complements rwl.report. Where
rwl.report describes a collection for a reader, rwl.check looks
for defects and returns them as rows, so that examining one file and sweeping
ten thousand are the same operation.
Every check runs independently and none of them stops. A check that fails
becomes a finding with the ID RWL_CHECK_ERROR rather than an
error, so a pathological file still yields a report. This matters at scale:
the files that break are the ones worth looking at.
Each finding carries a stable check ID and one of three severities:
"error" for something that cannot be right, "warning" for
something probably wrong, and "note" for something worth knowing.
rwl.check.catalogue returns the full table of IDs, groups,
severities and descriptions. The IDs are a contract: they are what a
sweep filters on and what two runs are compared by, and they do not change
meaning between releases.
The "provenance" checks read the record read.tucson
attaches to what it returns, and report things that cannot be recovered any
other way. Chief among them is RWL_ID_RENAMED: where a file gives two
different cores the same id, the reader renames one, so a series on the
returned object carries a name that appears nowhere in the file. Nothing but
the reader can say that. The group is silent for an object that carries no
such record, including one read by read.tucson.legacy.
The "file" checks need the file itself and are skipped when only an
object is given. They are the only way to see line endings, stray tabs, and
the span declared in the ITRDB header, all of which are gone once
the file has been parsed into a matrix of numbers.
A zero in a rwl object means a locally absent ring, and a few in a
row can be real. A long run cannot: it is filler for a stretch of wood
that was not measured, typed into the file as zeros or put there by
read.tucson.legacy, which fills gaps inside a series with
zeros. RWL_ZERO_RUN reports those, and RWL_REPEATED_VALUE
reports the same thing done with a non-zero constant. Both are warnings
because the values are placeholders that every later calculation will
treat as growth. Neither can say what the investigator meant; they say
where to look.
The crossdating checks ask whether a series fits the collection it is in
rather than whether it clears a fixed correlation, because what counts as a
good correlation is a property of the site: a high-elevation conifer stand
runs 0.7 to 0.8, while some collections, particularly ecological ones sampled
for growth rather than for a climate signal, sit far below that and are
perfectly sound. A collection with little common signal is therefore reported
once, as RWL_WEAK_COLLECTION and as a note rather than a warning: it
is not a fault to be corrected, but it does decide whether the series can be
crossdated against each other or carry a chronology, so it is worth saying.
The defaults in rwl.check.control were calibrated against the
rwl objects shipped with dplR. In particular RWL_DATING_LAG
fires on none of anos1, ca533,
co021, gp.rwl, nm046 or
wa082, and does fire on a series displaced by two years.
The value of an RWL_DATING_LAG finding is the lag at which
the series correlates best with the master, with the sign used by
ccf.series.rwl (with series.x = FALSE) and by
best.lag in corr.rwl.seg: negative means the series
is probably missing rings, positive that it probably has false rings or a
ring counted twice.
An object of class "rwl.check": a list with the file name, the
control values used, a findings data.frame, and a meta
list of summary values.
as.data.frame returns the findings, one row per finding, with columns
file, check, severity, group, series,
year.from, year.to, n, value and message.
summary returns a one-row data.frame holding the collection's
summary values, counts of errors, warnings and notes, and one count column per
check ID. Rows from different files have identical columns and can
be combined with rbind into a triage table.
Andy Bunn
rwl.report, read.tucson,
interseries.cor, corr.rwl.seg
library(utils) data(zof.rwl) res <- rwl.check(zof.rwl, file = "zof.rwl") res ## the findings as data head(as.data.frame(res)) ## one row per file: rbind these over an archive to get a work queue data(ca533) sweep <- rbind(summary(rwl.check(zof.rwl, file = "zof.rwl")), summary(rwl.check(ca533, file = "ca533"))) sweep[, c("file", "n.series", "n.error", "n.warning", "n.note")] ## what is looked for head(rwl.check.catalogue()) ## a fast pass, skipping the crossdating checks rwl.check(ca533, checks = c("structure", "series", "values", "zeros"))library(utils) data(zof.rwl) res <- rwl.check(zof.rwl, file = "zof.rwl") res ## the findings as data head(as.data.frame(res)) ## one row per file: rbind these over an archive to get a work queue data(ca533) sweep <- rbind(summary(rwl.check(zof.rwl, file = "zof.rwl")), summary(rwl.check(ca533, file = "ca533"))) sweep[, c("file", "n.series", "n.error", "n.warning", "n.note")] ## what is looked for head(rwl.check.catalogue()) ## a fast pass, skipping the crossdating checks rwl.check(ca533, checks = c("structure", "series", "values", "zeros"))
This function generates a small report on a rwl object
that gives the user some basic information on the data including the number of
series, the span of the data, the mean interseries correlation, the number of
missing rings (zeros), internal NA values, and rings that are very small,
or very large.
rwl.report(rwl,small.thresh=NA,big.thresh=NA)rwl.report(rwl,small.thresh=NA,big.thresh=NA)
rwl |
an |
small.thresh |
a |
big.thresh |
a |
This generates information about a rwl object including the number of series, the mean length of all the series, the first year, last year, the mean first-order autocorrelation (via summary.rwl), the mean interseries correlation (via interseries.cor), the years where a series has a missing ring (zero), internal NA, very small ring, very large rings, etc.
This output of this function is not typically meant for the user to access but has a print method for the user.
When the object still carries the record read.tucson attaches
to what it returns, the printed report opens with a short header naming the
file, the site and species from the ITRDB header, the precision the
file declares, and the span the header claims, which is worth seeing beside
the span the measurements actually cover. It also notes when the reader
renamed a series, so the ids in the report are not the file's, and when
interior gaps were filled. An object with no such record – one built by
hand, read by read.tucson.legacy, or subsetted by column –
is reported exactly as before. Use rwl.check to have any of
this reported as findings rather than as context.
A list with elements containing descriptive information on the rwl object. Specifically:
small.thresh |
a |
big.thresh |
a |
nSeries |
a |
n |
a |
meanSegLength |
a |
firstYear |
a |
lastYear |
a |
meanAR1 |
a |
sdAR1 |
a |
unconnected |
a |
unconnectedYrs |
a |
nZeros |
a |
zeros |
a |
allZeroYears |
a |
consecutiveZeros |
a |
meanInterSeriesCor |
a |
sdInterSeriesCor |
a |
internalNAs |
a |
provenance |
a |
smallRings |
a |
bigRings |
a |
Andy Bunn. Patched and improved by Mikko Korpela.
read.rwl, summary.rwl,
interseries.cor
data("gp.rwl") rwl.report(rwl = gp.rwl) # list very small (smallest 1pct) of rings as well one.pct <- quantile(gp.rwl[gp.rwl != 0], na.rm=TRUE, probs=0.01) rwl.report(rwl = gp.rwl, small.thresh = one.pct)data("gp.rwl") rwl.report(rwl = gp.rwl) # list very small (smallest 1pct) of rings as well one.pct <- quantile(gp.rwl[gp.rwl != 0], na.rm=TRUE, probs=0.01) rwl.report(rwl = gp.rwl, small.thresh = one.pct)
This function calculates descriptive statistics on a rwl object
of raw or detrended ring-width series.
rwl.stats(rwl) ## S3 method for class 'rwl' summary(object, ...)rwl.stats(rwl) ## S3 method for class 'rwl' summary(object, ...)
rwl, object
|
a |
... |
Additional arguments from the generic function. These are silently ignored. |
This calculates a variety of descriptive statistics commonly used in dendrochronology (see below). Users unfamiliar with these should see Cook and Kairiukstis (1990) and Fritts (2001) for further details.
The summary method for class "rwl" is a wrapper
for rwl.stats.
A data.frame containing descriptive stats on each
"series". These are the first and last year of the series as
well as the length of the series ("first", "last",
"year"). The mean, median, standard deviation are given
("mean", "median", "stdev") as are the skewness,
the excess kurtosis (calculated as Pearson’s kurtosis minus 3), the Gini
coefficient, and first order
autocorrelation ("skew", "kurtosis", "gini.coef",
"ar1").
Note that prior to version 1.6.8, two measures of sensitivity were also included. However mean sensitivity is not a robust statistic that should rarely, if ever, be used (Bunn et al. 2013). Those sensitivity functions ("sens1" and "sens2") are still available for continuity. Users should consider the coef of variation in lieu of mean sensitivity.
Andy Bunn. Slightly improved by Mikko Korpela.
Bunn, A. G., Jansma, E., Korpela, M., Westfall, R. D., and Baldwin,
J. (2013) Using simulations and data to evaluate mean sensitivity
() as a useful statistic in dendrochronology.
Dendrochronologia, 31(3), 250–254.
Cook, E. R. and Kairiukstis, L. A., editors (1990) Methods of Dendrochronology: Applications in the Environmental Sciences. Springer. ISBN-13: 978-0-7923-0586-6.
Fritts, H. C. (2001) Tree Rings and Climate. Blackburn. ISBN-13: 978-1-930665-39-2.
library(utils) data(ca533) rwl.stats(ca533) summary(ca533)library(utils) data(ca533) rwl.stats(ca533) summary(ca533)
This function calculates the significance of the departure from the mean for a given set of key event years and lagged years.
sea(x, key, lag = 5, resample = 1000)sea(x, key, lag = 5, resample = 1000)
x |
a chronology |
key |
a vector specifying the key event years for the superposed epoch |
lag |
an integral value defining the number of lagged years |
resample |
an integral value specifying the number of bootstrap sample for calculation of confidence intervals |
Superposed epoch analysis (SEA) is used to test the significance of a mean
tree growth response to certain events (such as droughts). Departures
from the mean RWI values for the specified years prior to
each event year, the event year, and the specified years immediately
after each event are averaged to a superposed epoch. To determine if
RWI for these years was significantly different from
randomly selected sets of lag+1 other years, bootstrap
resampling is used to randomly select sets of lag+1 years
from the data set and to estimate significances for the departures
from the mean RWI.
SEA computation is based on scaled RWI values, and 95%-confidence intervals are computed for the scaled values for each year in the superposed epoch.
A data.frame with
lag |
the lagged years, |
se |
the superposed epoch, i.e. the scaled mean RWI for the event years, |
se.unscaled |
the unscaled superposed epoch, i.e. the mean RWI for the event years, |
p |
significance of the departure from the chrono’s mean RWI, |
ci.95.lower |
lower 95% confidence band, |
ci.95.upper |
upper 95% confidence band, |
ci.99.lower |
lower 99% confidence band, |
ci.99.upper |
upper 99% confidence band. |
Christian Zang. Patched and improved by Mikko Korpela.
Lough, J. M. and Fritts, H. C. (1987) An assessment of the possible effects of volcanic eruptions on North American climate using tree-ring data, 1602 to 1900 AD. Climatic Change, 10(3), 219–239.
library(graphics) library(utils) data(cana157) event.years <- c(1631, 1742, 1845) cana157.sea <- sea(cana157, event.years) foo <- cana157.sea$se.unscaled names(foo) <- cana157.sea$lag barplot(foo, col = ifelse(cana157.sea$p < 0.05, "grey30", "grey75"), ylab = "RWI", xlab = "Superposed Epoch")library(graphics) library(utils) data(cana157) event.years <- c(1631, 1742, 1845) cana157.sea <- sea(cana157, event.years) foo <- cana157.sea$se.unscaled names(foo) <- cana157.sea$lag barplot(foo, col = ifelse(cana157.sea$p < 0.05, "grey30", "grey75"), ylab = "RWI", xlab = "Superposed Epoch")
Makes a segment plot of tree-ring data.
seg.plot(rwl, ...)seg.plot(rwl, ...)
rwl |
a |
... |
arguments to be passed to plot. |
This makes a simple plot of the length of each series in a tree-ring data set.
None. This function is invoked for its side effect, which is to produce a plot.
Andy Bunn. Patched and improved by Mikko Korpela.
library(utils) data(co021) seg.plot(co021)library(utils) data(co021) seg.plot(co021)
This function calculates mean sensitivity of a detrended ring-width series.
sens1(x)sens1(x)
x |
a |
This calculates mean sensitivity according to Eq. 1 in Biondi and Qeadan (2008). This is the standard measure of sensitivity in dendrochronology and is typically calculated on detrended series. However, note that mean sensitivity is not a robust statistic and should rarely, if ever, be used (Bunn et al. 2013).
the mean sensitivity.
Mikko Korpela, based on original by Andy Bunn
Biondi, F. and Qeadan, F. (2008) Inequality in Paleorecords. Ecology, 89(4), 1056–1067.
Bunn, A. G., Jansma, E., Korpela, M., Westfall, R. D., and Baldwin,
J. (2013) Using simulations and data to evaluate mean sensitivity
() as a useful statistic in dendrochronology.
Dendrochronologia, 31(3), 250–254.
library(utils) data(ca533) ca533.rwi <- detrend(rwl = ca533, method = "ModNegExp") sens1(ca533.rwi[, 1])library(utils) data(ca533) ca533.rwi <- detrend(rwl = ca533, method = "ModNegExp") sens1(ca533.rwi[, 1])
This function calculates mean sensitivity of a raw or detrended ring-width series.
sens2(x)sens2(x)
x |
a |
This calculates mean sensitivity according to Eq. 2 in Biondi and Qeadan (2008). This is a measure of sensitivity in dendrochronology that is typically used in the presence of a trend. However, note that mean sensitivity is not a robust statistic and should rarely, if ever, be used (Bunn et al. 2013).
the mean sensitivity.
Mikko Korpela, based on original by Andy Bunn
Biondi, F. and Qeadan, F. (2008) Inequality in Paleorecords. Ecology, 89(4), 1056–1067.
Bunn, A. G., Jansma, E., Korpela, M., Westfall, R. D., and Baldwin,
J. (2013) Using simulations and data to evaluate mean sensitivity
() as a useful statistic in dendrochronology.
Dendrochronologia, 31(3), 250–254.
library(utils) data(ca533) ca533.rwi <- detrend(rwl = ca533, method = "ModNegExp") sens2(ca533.rwi[, 1])library(utils) data(ca533) ca533.rwi <- detrend(rwl = ca533, method = "ModNegExp") sens2(ca533.rwi[, 1])
Plots a tree-ring series with a master chronology and displays their fit, segments, and detrending options in support of the cross-dating functions.
series.rwl.plot(rwl, series, series.yrs = as.numeric(names(series)), seg.length = 100, bin.floor = 100, n = NULL, nyrs = NULL, prewhiten = TRUE, ar.order.max = NULL, biweight = TRUE, floor.plus1 = FALSE)series.rwl.plot(rwl, series, series.yrs = as.numeric(names(series)), seg.length = 100, bin.floor = 100, n = NULL, nyrs = NULL, prewhiten = TRUE, ar.order.max = NULL, biweight = TRUE, floor.plus1 = FALSE)
rwl |
a |
series |
a |
series.yrs |
a |
seg.length |
an even integral value giving length of segments in years (e.g., 20, 50, 100 years). |
bin.floor |
a non-negative integral value giving the base for locating the first segment (e.g., 1600, 1700, 1800 AD). Typically 0, 10, 50, 100, etc. |
n |
|
nyrs |
|
prewhiten |
|
ar.order.max |
|
biweight |
|
floor.plus1 |
|
The function is typically invoked to produce four plots showing the
effect of the detrending options n and
prewhiten and the binning options seg.length
and bin.floor.
Time series plot of the filtered series and the master
Scatterplot of series vs. master
Segments that would be used in the other cross-dating
functions (e.g., corr.series.seg)
Text giving the detrending options and the time span of the raw and filtered series and master
The series and master are returned as well.
See help pages for corr.rwl.seg,
corr.series.seg, and ccf.series.rwl for
more information on these arguments.
A list containing the filtered vectors series and
master.
Andy Bunn. Patched and improved by Mikko Korpela.
corr.rwl.seg, corr.series.seg,
ccf.series.rwl
library(utils) data(co021) foo <- series.rwl.plot(rwl = co021, series = "646244", seg.length = 100, n = 5) ## note effect of n on first year in the series foo <- series.rwl.plot(rwl = co021, series = "646244", seg.length = 100, n = 13, prewhiten = FALSE) bar <- series.rwl.plot(rwl = co021, series = "646244", seg.length = 100, n = 7, prewhiten = FALSE) head(foo$series) head(bar$series)library(utils) data(co021) foo <- series.rwl.plot(rwl = co021, series = "646244", seg.length = 100, n = 5) ## note effect of n on first year in the series foo <- series.rwl.plot(rwl = co021, series = "646244", seg.length = 100, n = 13, prewhiten = FALSE) bar <- series.rwl.plot(rwl = co021, series = "646244", seg.length = 100, n = 7, prewhiten = FALSE) head(foo$series) head(bar$series)
This function calculates the synchronous growth changes (sgc), semi synchronous growth changes (ssgc) and the length of the compared overlap for a given set of tree-ring records. Optionally the probability of exceedence is calculated.
sgc(rwl, overlap = 50, prob = TRUE)sgc(rwl, overlap = 50, prob = TRUE)
rwl |
an |
overlap |
integer value with minimal length of overlapping growth changes (compared number of tree rings - 1). Comparisons with less overlap are not compared. |
prob |
if |
The sgc is a non parametric test based on sign tests.The synchronous growth changes (sgc) and semi synchronous growth changes (ssgc) are meant to replace the Gleichläufigkeit (glk()), since the Gleichläufigkeit can be (strongly) influenced by years when one of the compared series shows no growth change. The sgc gives a better description of the similarity (Visser, 2020). The ssgc gives the percentage years that one of the compared series shows no growth change. This function implements sgc and ssgc as the vectorized pairwise comparison of all records in data set.
The probability of exceedence (p) for the sgc expresses the chance that the sgc is incorrect. The observed value of the sgc is converted to a z-score and based on the standard normal curve the probability of exceedence is calculated (Visser 2020). The result is a matrix of all p-values.
A list with three or four matrices (p_mat is optional if prob = TRUE):
sgc_mat: matrix with synchronous growth changes (sgc) for all possible combinations of records
ssgc_mat: matrix with semi-synchronous growth changes (ssgc) for all possible combinations of records
overlap: matrix with number of overlapping growth changes.This is the number of overlapping years minus one.
p_mat: matrix of all probabilities of exceedence for all observed sgc values.
The matrices can be extracted from the list by selecting the name or the index number. Comparisons are only compared if the overlap is above the set theshold and if no threshold is set, this defaults to 50 years.If no comparison can be compared, NA is returned.
To calculate the global sgc of the dataset (assuming x.sgc <- sgc(rwl): mean(x.sgc$sgc_mat, na.rm = TRUE)). For the global ssgc use: mean(x.sgc$ssgc_mat, na.rm = TRUE).
Ronald Visser
Visser, R.M. (2020) On the similarity of tree-ring patterns: Assessing the influence of semi-synchronous growth changes on the Gleichläufigkeit for big tree-ring data sets,Archaeometry, 63, 204-215 DOI: https://doi.org/10.1111/arcm.12600
library(dplR) data(ca533) ca533.sgclist <- sgc(ca533) mean(ca533.sgclist$sgc_mat, na.rm = TRUE) mean(ca533.sgclist$ssgc_mat, na.rm = TRUE)library(dplR) data(ca533) ca533.sgclist <- sgc(ca533) mean(ca533.sgclist$sgc_mat, na.rm = TRUE) mean(ca533.sgclist$ssgc_mat, na.rm = TRUE)
Automatically generates a skeleton plot of tree-ring data.
skel.plot(rw.vec, yr.vec = NULL, sname = "", filt.weight = 9, dat.out = FALSE, master = FALSE, plot = TRUE)skel.plot(rw.vec, yr.vec = NULL, sname = "", filt.weight = 9, dat.out = FALSE, master = FALSE, plot = TRUE)
rw.vec |
a |
yr.vec |
optional |
sname |
an optional |
filt.weight |
filter length for the Hanning filter, defaults to 9 |
dat.out |
|
master |
|
plot |
|
This makes a skeleton plot – a plot that gives the relative growth for
year t relative to years t-1 and
t+1. Note that this plot is a standard plot in
dendrochronology and typically made by hand for visually cross-dating
series. This type of plot might be confusing to those not accustomed
to visual cross-dating. See references for more information. The
implementation is based on Meko’s (2002) skeleton plotting approach.
The skeleton plot is made by calculating departures from high
frequency growth for each year by comparing year t to the
surrounding three years
(t-1,t,t+1). Low frequency
variation is removed using a hanning filter. Relative
growth is scaled from one to ten but only values greater than three
are plotted. This function’s primary effect is to create plot with
absolute units that can be printed and compared to other plots. Here,
anomalous growth is plotted on a 2mm grid and up to 120 years are
plotted on a single row with a maximum of 7 rows (840 years). These
plots are designed to be plotted on standard paper using an
appropriate device, e.g., postscript with defaults or to
pdf with plot width and height to accommodate a landscape plot,
e.g., width = 10, height = 7.5,
paper = "USr". These plots are designed to be printable
and cut into strips to align long series. Statistical cross-dating is
possible if the data are output but more easily done using the functions
xskel.plot and xskel.ccf.plot.
This function is invoked primarily for its side effect, which is to
produce a plot. If dat.out is TRUE then a
data.frame is returned with the years and height of the
skeleton plot segments as columns.
Andy Bunn. Patched and improved by Mikko Korpela.
Stokes, M. A. and Smiley, T. L. (1968) An Introduction to Tree-Ring Dating. The University of Arizona Press. ISBN-13: 978-0-8165-1680-3.
Sheppard, P. R. (2002) Crossdating Tree Rings Using Skeleton Plotting. https://www.ltrr.arizona.edu/skeletonplot/introcrossdate.htm.
Meko, D. (2002) Tree-Ring MATLAB Toolbox. https://dmeko.ltrr.arizona.edu/toolbox.html.
Devices, hanning,
xskel.plot, xskel.ccf.plot
library(utils) data(co021) x <- co021[,33] x.yrs <- time(co021) x.name <- colnames(co021)[33] ## On a raw ring width series - undated skel.plot(x) ## On a raw ring width series - dated with names skel.plot(x, yr.vec = x.yrs, sname = x.name, master = TRUE) ## Not run: library(grDevices) ## Try cross-dating y <- co021[, 11] y.yrs <- time(co021) y.name <- colnames(co021)[11] ## send to postscript - 3 pages total fname1 <- tempfile(fileext=".ps") print(fname1) # tempfile used for PS output postscript(fname1) ## "Master series" with correct calendar dates skel.plot(x, yr.vec = x.yrs, sname = x.name, master = TRUE) ## Undated series, try to align with last plot skel.plot(y) ## Here's the answer... skel.plot(y, yr.vec = y.yrs, sname = y.name) dev.off() unlink(fname1) # remove the PS file ## alternatively send to pdf fname2 <- tempfile(fileext=".pdf") print(fname2) # tempfile used for PDF output pdf(fname2, width = 10, height = 7.5, paper = "USr") skel.plot(x, yr.vec = x.yrs, sname = x.name, master = TRUE) skel.plot(y) skel.plot(y, yr.vec = y.yrs, sname = y.name) dev.off() unlink(fname2) # remove the PDF file ## End(Not run)library(utils) data(co021) x <- co021[,33] x.yrs <- time(co021) x.name <- colnames(co021)[33] ## On a raw ring width series - undated skel.plot(x) ## On a raw ring width series - dated with names skel.plot(x, yr.vec = x.yrs, sname = x.name, master = TRUE) ## Not run: library(grDevices) ## Try cross-dating y <- co021[, 11] y.yrs <- time(co021) y.name <- colnames(co021)[11] ## send to postscript - 3 pages total fname1 <- tempfile(fileext=".ps") print(fname1) # tempfile used for PS output postscript(fname1) ## "Master series" with correct calendar dates skel.plot(x, yr.vec = x.yrs, sname = x.name, master = TRUE) ## Undated series, try to align with last plot skel.plot(y) ## Here's the answer... skel.plot(y, yr.vec = y.yrs, sname = y.name) dev.off() unlink(fname1) # remove the PS file ## alternatively send to pdf fname2 <- tempfile(fileext=".pdf") print(fname2) # tempfile used for PDF output pdf(fname2, width = 10, height = 7.5, paper = "USr") skel.plot(x, yr.vec = x.yrs, sname = x.name, master = TRUE) skel.plot(y) skel.plot(y, yr.vec = y.yrs, sname = y.name) dev.off() unlink(fname2) # remove the PDF file ## End(Not run)
Makes a spaghetti plot of tree-ring data.
spag.plot(rwl, zfac = 1, useRaster = FALSE, res = 150, ...)spag.plot(rwl, zfac = 1, useRaster = FALSE, res = 150, ...)
rwl |
a |
zfac |
a multiplier for |
useRaster |
A |
res |
A |
... |
arguments to be passed to |
This makes a simple plot of each series in a tree-ring data set. Each
series is centered first by subtracting the column mean using
scale. The plot can be grossly tuned with
zfac which is a multiplier to rwl before
plotting and centering.
Ring-width indices (class "rwi", see as.rwi) are
centred on 1, or on 0 if they are differences, and not on their
means, so the grey line under each series is the value the indices
should sit at.
None. This function is invoked for its side effect, which is to produce a plot.
Andy Bunn. Patched and improved by Mikko Korpela.
library(utils) data(co021) plot(co021,plot.type = "spag") spag.plot(co021, zfac = 2)library(utils) data(co021) plot(co021,plot.type = "spag") spag.plot(co021, zfac = 2)
A simple implementation of the signal-free chronology
ssf(rwl, method="Spline", nyrs = NULL, difference = FALSE, max.iterations = 25, mad.threshold = 5e-4, recode.zeros = FALSE, return.info = FALSE, verbose = TRUE)ssf(rwl, method="Spline", nyrs = NULL, difference = FALSE, max.iterations = 25, mad.threshold = 5e-4, recode.zeros = FALSE, return.info = FALSE, verbose = TRUE)
rwl |
a |
method |
a |
nyrs |
a number controlling the smoothness of the
fitted curve in methods. See ‘Details’ in |
difference |
a |
max.iterations |
a |
mad.threshold |
a |
recode.zeros |
a |
return.info |
a |
verbose |
a |
This function creates a simple signal-free chronology that loosely follows the procedures laid out on p75 of Melvin and Briffa (2008). This function is a lighter version of that procedure and users who want more control and refinement should look to the CRUST program described in Melvin and Briffa (2014). These steps are described in more detail in Learning to Love dplR.
Detrend each series using the selected method, calculate RWI by division (or subtraction), and create an initial mean-value chronology.
Create signal-free measurements by dividing (or subtracting) each series of measurements by the chronology. If return.info is invoked these are returned in sfRW_Array.
Rescale the signal-free measurements to their original mean. If return.info is invoked these are returned in sfRWRescaled_Array.
If the sample depth is one, replace signal-free measurements with original measurements.
Fit curves to signal free measurements.If return.info is invoked these are returned in sfRWRescaledCurves_Array.
Get new growth indicies by dividing (or subtracting) the original measurements by curves in the last step. If return.info is invoked these are returned in sfRWI_Array.
Create a mean-value chronology using the indicies from the prior step. If return.info is invoked these are returned in sfCrn_Mat.
Repeat steps two through seven up to maxIter or until the madThreshold is reached. The stopping criteria is determined using the absolute difference between filtered chronologies generated in interation k and k-1. This is done with the residuals of a high-pass filter on the chronology using a cubic smoothing spline (caps) with the stiffness set as the median of the segment lengths of series contributing to the chronology. The stopping threshold is calculated as the median absolute difference of the kth and kth-1 chronologies weighted by the normalized sample depth. If return.info is invoked the residual chronologies are returned in hfCrnResids_Mat and the median absolute differences are returns in MAD_Vec.
The input object (rwl) should be of class rwl. If it not, the function will attempt to coerce it using as.rwl and a warning will be issued.
See the references below for further details on detrending. It's a dark art.
An object of of class crn and data.frame with the signal-free chronology and the sample depth. The years are stored as row numbers.
If return.info is TRUE a list containing ouptput by iteration (k):
infoList |
a |
k |
a |
ssfCrn |
the signal-free chronology as above. |
sfRW_Array |
an |
sfRWRescaled_Array |
an |
sfRWRescaledCurves_Array |
an |
sfRWI_Array |
an |
sfCrn_Mat |
a |
hfCrn_Mat |
a |
hfCrnResids_Mat |
a |
MAD_out |
a |
Ed Cook provided Fortran code that was ported to R by Andy Bunn.
Melvin, TM, Briffa, KR (2008) A 'signal-free' approach to dendroclimatic standardisation. Dendrochronologia 26: 71–86 doi: 10.1016/j.dendro.2007.12.001
Melvin T. M. and Briffa K.R. (2014a) CRUST: Software for the implementation of Regional Chronology Standardisation: Part 1. Signal-Free RCS. Dendrochronologia 32, 7-20, doi: 10.1016/j.dendro.2013.06.002
Melvin T. M. and Briffa K.R. (2014b) CRUST: Software for the implementation of Regional Chronology Standardisation: Part 2. Further RCS options and recommendations. Dendrochronologia 32, 343-356, doi: 10.1016/j.dendro.2014.07.008
library(stats) data(wa082) wa082_SSF <- ssf(wa082) plot(wa082_SSF,add.spline=TRUE,nyrs=20) wa082_SSF_Full <- ssf(wa082,method = "AgeDepSpline", difference = TRUE, return.info = TRUE) plot(wa082_SSF_Full$ssfCrn,add.spline=TRUE,nyrs=20)library(stats) data(wa082) wa082_SSF <- ssf(wa082) plot(wa082_SSF,add.spline=TRUE,nyrs=20) wa082_SSF_Full <- ssf(wa082,method = "AgeDepSpline", difference = TRUE, return.info = TRUE) plot(wa082_SSF_Full$ssfCrn,add.spline=TRUE,nyrs=20)
Calculate subsample signal strength on a
data.frame of (usually) ring-width indices.
sss(rwi, ids = NULL)sss(rwi, ids = NULL)
rwi |
a |
ids |
an optional |
This calculates subsample signal strength (sss) following equation 3.50 in
Cook and Kairiukstis (1990) but using notation from Buras (2017) because
writing the prime unicode symbol seems too difficult. The function
calls rwi.stats and passes it the arguments ids
and prewhiten.
To make better use of variation in growth within and between series, an
appropriate mask (parameter ids) should be provided that
identifies each series with a tree as it is common for dendrochronologists
to take more than one core per tree. The function read.ids is
helpful for creating a mask based on the series ID.
Subsample signal strength is calculated as
where n and N are the number of cores or trees in the
subsample and sample respectively and rbar is mean interseries
correlation. If there is only one core per tree n is the sample
depth in a given year (rowSums(!is.na(rwi))), N is the
number of cores (n.cores as given by rwi.stats),
and rbar is the mean interseries correlation between all series
(r.bt as given by rwi.stats). If there are multiple
cores per tree n is the number of trees present in a given year,
N is the number of trees (n.trees as given by
rwi.stats), and rbar is the effective mean interseries
correlation (r.eff as given by rwi.stats).
Readers interested in the differences between subsample signal strength and the more commonly used (running) expressed population signal should look at Buras (2017) on the frequently mis-used citation of Wigley et al. (1984) of the expressed population signal threshold EPS=0.85 as well as Cook and Pederson (2011) for a more general approach to categorizing variability in tree-ring data.
A numeric containing the subsample signal strength that is
the same as number if rows ofrwi.
Andy Bunn. Patched and improved by Mikko Korpela.
Buras, A. (2017) A comment on the Expressed Population Signal. Dendrochronologia 44:130-132.
Cook, E. R. and Kairiukstis, L. A., editors (1990) Methods of Dendrochronology: Applications in the Environmental Sciences. Springer. ISBN-13: 978-0-7923-0586-6.
Cook, E. R. and Pederson, N. (2011) Uncertainty, Emergence, and Statistics in Dendrochronology. In Hughes, M. K., Swetnam, T. W., and Diaz, H. F., editors, Dendroclimatology: Progress and Prospects, pages 77–112. Springer. ISBN-13: 978-1-4020-4010-8.
Wigley, T. M., Briffa, K. R. and Jones, P. D. (1984) On the average value of correlated time series, with applications in dendroclimatology and hydrometeorology. Journal of Applied Meteorology and Climatology 23: 201-213.
data(ca533) ca533.rwi <- detrend(ca533,method="Spline") # assuming 1 core / tree ca533.sss <- sss(ca533.rwi) ca533.ids <- autoread.ids(ca533) # done properly with >=1 core / tree as per the ids ca533.sss2 <- sss(ca533.rwi,ca533.ids) yr <- time(ca533) plot(yr,ca533.sss,type="l",ylim=c(0.4,1), col="darkblue",lwd=2,xlab="Year",ylab="SSS") lines(yr,ca533.sss2,lty="dashed", col="darkgreen",lwd=2) # Plot the chronology showing a potential cutoff year based on SSS # (using sss2 with the correct series IDs to get >=1 core / tree as per the ids) ca533.crn <- chron(ca533.rwi) def.par <- par(no.readonly=TRUE) par(mar = c(2, 2, 2, 2), mgp = c(1.1, 0.1, 0), tcl = 0.25, xaxs='i') plot(yr, ca533.crn[, 1], type = "n", xlab = "Year", ylab = "RWI", axes=FALSE) cutoff <- max(yr[ca533.sss2 < 0.85]) xx <- c(500, 500, cutoff, cutoff) yy <- c(-1, 3, 3, -1) polygon(xx, yy, col = "grey80") abline(h = 1, lwd = 1.5) lines(yr, ca533.crn[, 1], col = "grey50") lines(yr, caps(ca533.crn[, 1], nyrs = 32), col = "red", lwd = 2) axis(1); axis(2); axis(3); par(new = TRUE) ## Add SSS plot(yr, ca533.sss2, type = "l", xlab = "", ylab = "", axes = FALSE, col = "blue") abline(h=0.85,col="blue",lty="dashed") axis(4, at = pretty(ca533.sss2)) mtext("SSS", side = 4, line = 1.1, lwd=1.5) box() par(def.par)data(ca533) ca533.rwi <- detrend(ca533,method="Spline") # assuming 1 core / tree ca533.sss <- sss(ca533.rwi) ca533.ids <- autoread.ids(ca533) # done properly with >=1 core / tree as per the ids ca533.sss2 <- sss(ca533.rwi,ca533.ids) yr <- time(ca533) plot(yr,ca533.sss,type="l",ylim=c(0.4,1), col="darkblue",lwd=2,xlab="Year",ylab="SSS") lines(yr,ca533.sss2,lty="dashed", col="darkgreen",lwd=2) # Plot the chronology showing a potential cutoff year based on SSS # (using sss2 with the correct series IDs to get >=1 core / tree as per the ids) ca533.crn <- chron(ca533.rwi) def.par <- par(no.readonly=TRUE) par(mar = c(2, 2, 2, 2), mgp = c(1.1, 0.1, 0), tcl = 0.25, xaxs='i') plot(yr, ca533.crn[, 1], type = "n", xlab = "Year", ylab = "RWI", axes=FALSE) cutoff <- max(yr[ca533.sss2 < 0.85]) xx <- c(500, 500, cutoff, cutoff) yy <- c(-1, 3, 3, -1) polygon(xx, yy, col = "grey80") abline(h = 1, lwd = 1.5) lines(yr, ca533.crn[, 1], col = "grey50") lines(yr, caps(ca533.crn[, 1], nyrs = 32), col = "red", lwd = 2) axis(1); axis(2); axis(3); par(new = TRUE) ## Add SSS plot(yr, ca533.sss2, type = "l", xlab = "", ylab = "", axes = FALSE, col = "blue") abline(h=0.85,col="blue",lty="dashed") axis(4, at = pretty(ca533.sss2)) mtext("SSS", side = 4, line = 1.1, lwd=1.5) box() par(def.par)
EPS-based chronology stripping after Fowler & Boswijk 2003.
strip.rwl(rwl, ids = NULL, verbose = FALSE, comp.plot = FALSE, legacy.eps = FALSE, nyrs = 20)strip.rwl(rwl, ids = NULL, verbose = FALSE, comp.plot = FALSE, legacy.eps = FALSE, nyrs = 20)
rwl |
the series to strip. Best given as ring-width indices
(class |
ids |
an optional |
verbose |
|
comp.plot |
|
legacy.eps |
|
nyrs |
for raw widths only: a number giving the rigidity of the
smoothing spline they are detrended with before stripping, as in
|
The EPS-based chronology stripping is implemented after
Fowler & Boswijk 2003: First, raw widths are standardized using a
spline with a frequency cutoff of 50% at nyrs years. Indices
are used as they are. Then, EPS is calculated for the
chronology including all (remaining) series. In each iteration, the
algorithm calculates leave-one-out EPS values, and the
series whose removal increases overall EPS the most is
discarded. This is repeated until no further increase in
EPS is gained by discarding a single series. The procedure
is then repeated in the opposite direction, i.e., the reinsertion of
each previously removed series into the data.frame is
considered. In each iteration, the series (if any) whose reinsertion
increases EPS the most is reinserted. As a last step,
EPS is calculated for each year of the stripped and original
chronology including all series. If comp.plot is set to
TRUE, a diagnostic plot is shown for the year-wise comparison.
When verbose output is chosen, the EPS values for all leave-one-out (or back-in) chronologies are reported. If discarding or re-inserting a single series leads to an improvement in EPS, this series is marked with an asterisk.
Which series are left out depends on the standardization. Fowler and Boswijk made two sets of indices, with 20-year and with 200-year splines, and stripped each to see how far the result depended on the choice. It did: at their largest site about half of the series left out were the same in both. They chose 20 years because it gave the highest correlations within a site for the species they worked on (kauri, Agathis australis), and describe 200 years as nearer to what is used for work on climate trends. The default here is their 20 years, which is not a recommendation for other species or purposes. To judge series on the variation that will be kept in the chronology, detrend them as the chronology will be detrended and strip the indices.
Until version 1.8.1 the function applied the 20-year and the 200-year spline one after the other to the same series. That was a misreading of the method, and came to the 20-year spline alone, because that leaves nothing for a 200-year spline to remove. The indices differ from the old ones in the third decimal place or beyond.
When a series is left out, the function prints what that cost and
records it in the attribute "dplR.strip". The EPS
that is maximized is one number for the whole span. It can rise while
the chronology gets worse in the years that few trees reach, because a
series that was left out may be one of the few there. So the trees
present in each year are counted before and after, and for each year
the EPS of that many trees is computed from the
rbar.eff of the whole set,
. This
is subsample signal strength (sss) multiplied by
EPS. It is used in place of subsample signal strength
because that is measured against the full set of trees, which is not
the same set before and after stripping.
The function returns the series it was given, raw tree-ring widths or indices, where series that do not contribute to an overall improvement in EPS are left out.
It carries an attribute "dplR.strip", a list recording
what the stripping did and what it cost:
removed |
the names of the series left out |
nyrs |
the rigidity of the spline the widths were detrended
with, or |
stats |
a |
years |
a |
The attribute describes this result and is dropped when the result is subset.
A higher EPS after stripping is not evidence of a better chronology for reconstructing climate. EPS says how well the mean of these series stands for the population they were sampled from, and depends only on how many trees there are and how well they agree. It says nothing about what they agree on (Buras 2017). Stripping raises it by leaving out the trees that agree least with the others, in the variation the standardization keeps: with the default, faster than about 20 years. Those trees are part of the stand, and a chronology without them looks more certain than the sample was.
The gain is usually small. Fowler and Boswijk (2003) stripped 15
sites and found a mean rise in EPS of 0.007 with 20-year
splines and 0.017 with 200-year splines. For wa082
with trees identified, EPS goes from 0.907 to 0.909.
The last step of their method is not automatic: they judged each result, and in six of their 30 analyses chose not to use it, because EPS over the whole span rose while a period with few trees got worse. This function does not make that judgement. Look at which series were left out and why they differ, and at the years in which replication was lost, before using the result.
Christian Zang. Patched and improved by Mikko Korpela.
Buras, A. (2017) A comment on the Expressed Population Signal. Dendrochronologia, 44, 130–132.
Fowler, A. and Boswijk, G. (2003) Chronology stripping as a tool for enhancing the statistical quality of tree-ring chronologies. Tree-Ring Research, 59(2), 53–62.
library(utils) data(anos1) anos1.ids <- read.ids(anos1, stc = c(4, 3, 1)) srwl <- strip.rwl(anos1, ids = anos1.ids, verbose = TRUE) tail(srwl) ## what was left out, and the statistics before and after attr(srwl, "dplR.strip")$removed attr(srwl, "dplR.strip")$stats ## strip the indices the chronology will be built from data(wa082) wa082.ids <- autoread.ids(wa082) wa082.rwi <- detrend(wa082, method = "Spline") srwi <- strip.rwl(wa082.rwi, ids = wa082.ids) attr(srwi, "dplR.strip")$statslibrary(utils) data(anos1) anos1.ids <- read.ids(anos1, stc = c(4, 3, 1)) srwl <- strip.rwl(anos1, ids = anos1.ids, verbose = TRUE) tail(srwl) ## what was left out, and the statistics before and after attr(srwl, "dplR.strip")$removed attr(srwl, "dplR.strip")$stats ## strip the indices the chronology will be built from data(wa082) wa082.ids <- autoread.ids(wa082) wa082.rwi <- detrend(wa082, method = "Spline") srwi <- strip.rwl(wa082.rwi, ids = wa082.ids) attr(srwi, "dplR.strip")$stats
This calculates a robust average that is unaffected by outliers.
tbrm(x, C = 9)tbrm(x, C = 9)
x |
a |
C |
a constant. |
This is a one step computation that follows the Affy whitepaper below,
see page 22. This function is called by chron to
calculate a robust mean. C determines the point at which
outliers are given a weight of 0 and therefore do not contribute to
the calculation of the mean. C = 9 sets values roughly
+/-6 standard deviations to 0. C = 6 is also used in
tree-ring chronology development. Cook and Kairiukstis (1990) have
further details.
An exact summation algorithm (Shewchuk 1997) is used. When some assumptions about the rounding of floating point numbers and conservative compiler optimizations hold, summation error is completely avoided. Whether the assumptions hold depends on the platform, i.e. compiler and CPU.
A numeric mean.
Mikko Korpela
Statistical Algorithms Description Document, 2002, Affymetrix.
Cook, E. R. and Kairiukstis, L. A., editors (1990) Methods of Dendrochronology: Applications in the Environmental Sciences. Springer. ISBN-13: 978-0-7923-0586-6.
Mosteller, F. and Tukey, J. W. (1977) Data Analysis and Regression: a second course in statistics. Addison-Wesley. ISBN-13: 978-0-201-04854-4.
Shewchuk, J. R. (1997) Adaptive precision floating-point arithmetic and fast robust geometric predicates. Discrete and Computational Geometry, 18(3), 305–363.
library(stats) library(utils) foo <- rnorm(100) tbrm(foo) mean(foo) ## Compare data(co021) co021.rwi <- detrend(co021, method = "ModNegExp") crn1 <- apply(co021.rwi, 1, tbrm) crn2 <- chron(co021.rwi) cor(crn1, crn2[, 1])library(stats) library(utils) foo <- rnorm(100) tbrm(foo) mean(foo) ## Compare data(co021) co021.rwi <- detrend(co021, method = "ModNegExp") crn1 <- apply(co021.rwi, 1, tbrm) crn2 <- chron(co021.rwi) cor(crn1, crn2[, 1])
Retrieve or set the time values for rwl and crn objects.
## S3 method for class 'rwl' time(x, ...) ## S3 method for class 'crn' time(x, ...) time(x) <- value## S3 method for class 'rwl' time(x, ...) ## S3 method for class 'crn' time(x, ...) time(x) <- value
x |
An object of class |
... |
Not used. |
value |
A |
A numeric vector of time (typically in years) for the object. This is done via as.numeric(rownames(x)) but has been asked for by users so many times that it is being included as a function.
Andy Bunn
library(utils) data(co021) # extract years co021.yrs <- time(co021) # set years -- silly example time(co021) <- co021.yrs+100library(utils) data(co021) # extract years co021.yrs <- time(co021) # set years -- silly example time(co021) <- co021.yrs+100
This function calculates the mean value for each tree in a rwl or rwi object.
treeMean(rwl, ids, na.rm=FALSE)treeMean(rwl, ids, na.rm=FALSE)
rwl |
a |
ids |
a |
na.rm |
|
This function averages together multiple cores to give a mean value of growth.
It is very common in dendrochronology to take more than one core per tree. In
those cases it is occasionally desirable to have an average of the cores.
This function merely loops through the rwl object and calculates the
rowMeans for each tree. If na.rm=FALSE trees with >1
sample will be averaged only over the period where the samples overlap.
If TRUE each year is the mean of the samples present, so the number of
samples behind a tree's mean can vary through time. See examples.
An object with the mean annual value for each tree. It has class
c("rwi", "data.frame") if rwl has class
"rwi", with the record of how the indices were made carried
over, and class c("rwl", "data.frame") otherwise.
Andy Bunn. Patched and improved by Mikko Korpela.
data(gp.rwl) gp.ids <- read.ids(gp.rwl, stc = c(0, 2, 1)) gp.treeMean <- treeMean(gp.rwl, gp.ids) gp.treeMean2 <- treeMean(gp.rwl, gp.ids, na.rm=TRUE) # look at an example of a single tree with different averaging periods. # The years are named on every subset so that the cores and the two tree # means stay on one grid: selecting series alone would give each of them # only the years it covers, and the three spans are not the same. yrs <- rownames(gp.rwl) tree40 <- data.frame(gp.rwl[yrs, c("40A","40B")], gp.treeMean[yrs, "40", drop=FALSE], gp.treeMean2[yrs, "40", drop=FALSE]) names(tree40) <- c("coreA", "coreB", "treeMean1", "treeMean2") head(tree40,50) data(ca533) ca533.treeMean <- treeMean(ca533, autoread.ids(ca533)) # plot using S3method for class "rwl" plot(ca533.treeMean,plot.type="spag")data(gp.rwl) gp.ids <- read.ids(gp.rwl, stc = c(0, 2, 1)) gp.treeMean <- treeMean(gp.rwl, gp.ids) gp.treeMean2 <- treeMean(gp.rwl, gp.ids, na.rm=TRUE) # look at an example of a single tree with different averaging periods. # The years are named on every subset so that the cores and the two tree # means stay on one grid: selecting series alone would give each of them # only the years it covers, and the three spans are not the same. yrs <- rownames(gp.rwl) tree40 <- data.frame(gp.rwl[yrs, c("40A","40B")], gp.treeMean[yrs, "40", drop=FALSE], gp.treeMean2[yrs, "40", drop=FALSE]) names(tree40) <- c("coreA", "coreB", "treeMean1", "treeMean2") head(tree40,50) data(ca533) ca533.treeMean <- treeMean(ca533, autoread.ids(ca533)) # plot using S3method for class "rwl" plot(ca533.treeMean,plot.type="spag")
This function can be used to browse the TRiDaS vocabulary by category.
tridas.vocabulary(category = c("dating type", "measuring method", "shape", "location type", "variable", "unit", "remark", "dating suffix", "presence / absence", "complex presence / absence", "certainty"), idx = NA, term = NA, match.exact = FALSE)tridas.vocabulary(category = c("dating type", "measuring method", "shape", "location type", "variable", "unit", "remark", "dating suffix", "presence / absence", "complex presence / absence", "certainty"), idx = NA, term = NA, match.exact = FALSE)
category |
Vocabulary category as a |
idx |
A |
term |
A |
match.exact |
A |
The Tree Ring Data Standard (TRiDaS) is described in Jansma et. al (2010).
The function has four usage modes:
When idx is given, returns item number
idx in the given category. There may be
several numbers in idx, in which case multiple items
are returned.
When term contains one or more items and
match.exact is TRUE, checks whether any of the
terms is an exact match in the given category
When term contains one or more items and
match.exact is FALSE, expands partial matches of
the terms in the vocabulary of the given category
When only category is given, returns the complete
vocabulary in the given category
In mode 1 |
A |
In mode 2 |
A |
In mode 3 |
A |
In mode 4 |
A |
Mikko Korpela
Jansma, E., Brewer, P. W., and Zandhuis, I. (2010) TRiDaS 1.1: The tree-ring data standard. Dendrochronologia, 28(2), 99–130.
## Show all entries in category "measuring method" tridas.vocabulary(category = "measuring") ## Show item number one in category "complex presence / absence" tridas.vocabulary(category = "complex", idx = 1) ## Check whether "half section" exists in category "shape" tridas.vocabulary(category = "shape", term = "half section", match.exact = TRUE) ## Return unabbreviated matches to several queries in category "remark" tridas.vocabulary(category = "remark", term = c("trauma", "fire", "diffuse"))## Show all entries in category "measuring method" tridas.vocabulary(category = "measuring") ## Show item number one in category "complex presence / absence" tridas.vocabulary(category = "complex", idx = 1) ## Check whether "half section" exists in category "shape" tridas.vocabulary(category = "shape", term = "half section", match.exact = TRUE) ## Return unabbreviated matches to several queries in category "remark" tridas.vocabulary(category = "remark", term = c("trauma", "fire", "diffuse"))
Initializes and returns a generator of universally unique identifiers. Use the returned function repeatedly for creating one or more UUIDs, one per function call.
uuid.gen(more.state = "")uuid.gen(more.state = "")
more.state |
A |
This function returns a function (closure) which generates
UUIDs. The state of that anonymous function is set when
uuid.gen is called. The state consists of the following:
System and user information (Sys.info)
R version (R.version)
Platform information (.Platform)
Working directory
Process ID of the R session
Time when uuid.gen was called (precision of seconds or
finer)
The text in parameter more.state
The Pseudo Random Number Generator of R (see
.Random.seed) is used in the generation of
UUIDs. No initialization of the PRNG is done.
Tampering with the state of the R PRNG while using a given
UUID generator causes a risk of non-unique identifiers.
Particularly, setting the state of the PRNG to the same
value before two calls to the UUID generator guarantees two
identical identifiers. If two UUID generators have a
different state, it is not a problem to have the PRNG
going through or starting from the same state with both generators.
The user is responsible for selecting a PRNG with a reasonable number of randomness. Usually, this doesn’t require any action. For example, any PRNG algorithm available in R works fine. However, the uniqueness of UUIDs can be destroyed by using a bad user-supplied PRNG.
The UUIDs produced by uuid.gen generators are Version
4 (random) with 122 random bits and 6 fixed bits. The UUID
is presented as a character string of 32 hexadecimal digits and
4 hyphens:
‘xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx’
where x is any hexadecimal digit and y is one of
"8", "9", "a", or "b". Each x and
y in the example is an independent variables (for all practical
purposes); subscripts are omitted for clarity. The UUID
generator gets 32 hex digits from the MD5 message digest
algorithm by feeding it a string consisting of the constant generator
state and 5 (pseudo) random numbers. After that, the 6 bits are fixed
and the hyphens are added to form the final UUID.
A parameterless function which returns a single UUID
(character string)
Mikko Korpela
Leach, P., Mealling, M., and Salz, R. (2005) A Universally Unique IDentifier (UUID) URN namespace. RFC 4122, RFC Editor. https://www.rfc-editor.org/rfc/rfc4122.txt.
## Normal use ug <- uuid.gen() uuids <- character(100) for(i in 1:100){ uuids[i] <- ug() } length(unique(uuids)) == 100 # TRUE, UUIDs are unique with high probability ## Do NOT do the following unless you want non-unique IDs rs <- .Random.seed set.seed(0L) id1 <- ug() set.seed(0L) id2 <- ug() id1 != id2 # FALSE, The UUIDs are the same .Random.seed <- rs ## Strange usage pattern, but will probably produce unique IDs ug1 <- uuid.gen("1") set.seed(0L) id1 <- ug1() ug2 <- uuid.gen("2") set.seed(0L) id2 <- ug2() id1 != id2 # TRUE, The UUIDs are different with high probability .Random.seed <- rs## Normal use ug <- uuid.gen() uuids <- character(100) for(i in 1:100){ uuids[i] <- ug() } length(unique(uuids)) == 100 # TRUE, UUIDs are unique with high probability ## Do NOT do the following unless you want non-unique IDs rs <- .Random.seed set.seed(0L) id1 <- ug() set.seed(0L) id2 <- ug() id1 != id2 # FALSE, The UUIDs are the same .Random.seed <- rs ## Strange usage pattern, but will probably produce unique IDs ug1 <- uuid.gen("1") set.seed(0L) id1 <- ug1() ug2 <- uuid.gen("2") set.seed(0L) id2 <- ug2() id1 != id2 # TRUE, The UUIDs are different with high probability .Random.seed <- rs
This data set gives the raw ring widths for Pacific silver fir
Abies amabilis at Hurricane Ridge in Washington, USA.
There are 23 series. Data set was created using read.rwl
and saved to an .rda file using save.
The source file records no measurement for series 712011 in the year
1900, holding the value -999 there. This data set was built before
read.tucson distinguished a missing measurement from a ring
width of zero, and that cell holds a zero. It has been left as it is for
continuity with earlier versions of dplR. Reading the source file today
gives NA in that cell; passing fill.internal.NA = 0 to
read.tucson reproduces this data set exactly.
data(wa082)data(wa082)
A data.frame containing 23 tree-ring series in columns and 286
years in rows.
International tree-ring data bank, Accessed on 20-April-2021 at https://www.ncei.noaa.gov/pub/data/paleo/treering/measurements/northamerica/usa/wa082.rwl
Schweingruber, F. (1983) Hurricane Ridge Data Set. IGBP PAGES/World Data Center for Paleoclimatology Data Contribution Series 1983-wa082.RWL. NOAA/NCDC Paleoclimatology Program, Boulder, Colorado, USA.
library(utils) data(wa082) ## Where the data came from. read.tucson() records what it saw and attaches ## it to what it returns; this data set carries that record. prov <- attr(wa082, "dplR.provenance") prov$file prov$header ## The file records no measurement for series 712011 in 1900, holding -999 ## there. This data set was built with fill.internal.NA = 0, so that cell ## holds a zero. See the description above. prov$gaps wa082["1900", "712011"] ## rwl.report() shows the same in its header rwl.report(wa082)library(utils) data(wa082) ## Where the data came from. read.tucson() records what it saw and attaches ## it to what it returns; this data set carries that record. prov <- attr(wa082, "dplR.provenance") prov$file prov$header ## The file records no measurement for series 712011 in 1900, holding -999 ## there. This data set was built with fill.internal.NA = 0, so that cell ## holds a zero. See the description above. prov$gaps wa082["1900", "712011"] ## rwl.report() shows the same in its header rwl.report(wa082)
This function creates a filled.contour plot of a continuous
wavelet transform as output from morlet.
wavelet.plot(wave.list, wavelet.levels = quantile(wave.list$Power, probs = (0:10)/10), add.coi = TRUE, add.sig = TRUE, x.lab = gettext("Time", domain = "R-dplR"), period.lab = gettext("Period", domain = "R-dplR"), crn.lab = gettext("RWI", domain = "R-dplR"), key.cols = rev(rainbow(length(wavelet.levels)-1)), key.lab = parse(text=paste0("\"", gettext("Power", domain="R-dplR"), "\"^2")), add.spline = FALSE, f = 0.5, nyrs = NULL, crn.col = "black", crn.lwd = 1,coi.col='black', crn.ylim = range(wave.list$y) * c(0.95, 1.05), side.by.side = FALSE, useRaster = FALSE, res = 150, reverse.y = FALSE, ...)wavelet.plot(wave.list, wavelet.levels = quantile(wave.list$Power, probs = (0:10)/10), add.coi = TRUE, add.sig = TRUE, x.lab = gettext("Time", domain = "R-dplR"), period.lab = gettext("Period", domain = "R-dplR"), crn.lab = gettext("RWI", domain = "R-dplR"), key.cols = rev(rainbow(length(wavelet.levels)-1)), key.lab = parse(text=paste0("\"", gettext("Power", domain="R-dplR"), "\"^2")), add.spline = FALSE, f = 0.5, nyrs = NULL, crn.col = "black", crn.lwd = 1,coi.col='black', crn.ylim = range(wave.list$y) * c(0.95, 1.05), side.by.side = FALSE, useRaster = FALSE, res = 150, reverse.y = FALSE, ...)
wave.list |
A |
wavelet.levels |
A |
add.coi |
A |
add.sig |
A |
x.lab |
X-axis label. |
period.lab |
Y-axis label for the wavelet plot. |
crn.lab |
Y-axis label for the time-series plot. |
key.cols |
A vector of colors for the wavelets and the key. |
key.lab |
Label for key. |
add.spline |
A |
nyrs |
A number giving the rigidity of the smoothing spline,
defaults to 0.33 of series length if |
f |
A number between 0 and 1 giving the frequency response or wavelength cutoff for the smoothing spline. Defaults to 0.5. |
crn.col |
Line color for the time-series plot. |
crn.lwd |
Line width for the time-series plot. |
coi.col |
Color for the COI if |
crn.ylim |
Axis limits for the time-series plot. |
side.by.side |
A |
useRaster |
A |
res |
A |
reverse.y |
A |
... |
Arguments passed to |
This produces a plot of a continuous wavelet transform and plots the original time series. Contours are added for significance and a cone of influence polygon can be added as well. Anything within the cone of influence should not be interpreted.
The time series can be plotted with a smoothing spline as well.
None. This function is invoked for its side effect, which is to produce a plot.
The function morlet is a port of Torrence’s
IDL code, which can be accessed through the
Internet Archive Wayback Machine.
Andy Bunn. Patched and improved by Mikko Korpela.
Torrence, C. and Compo, G. P. (1998) A practical guide to wavelet analysis. Bulletin of the American Meteorological Society, 79(1), 61–78.
library(stats) library(utils) data(ca533) ca533.rwi <- detrend(rwl = ca533, method = "ModNegExp") ca533.crn <- chron(ca533.rwi, prewhiten = FALSE) Years <- time(ca533.crn) CAMstd <- ca533.crn[, 1] out.wave <- morlet(y1 = CAMstd, x1 = Years, p2 = 9, dj = 0.1, siglvl = 0.99) wavelet.plot(out.wave, useRaster = NA) ## Not run: # Alternative palette with better separation of colors # via: rev(RColorBrewer::brewer.pal(10, "Spectral")) specCols <- c("#5E4FA2", "#3288BD", "#66C2A5", "#ABDDA4", "#E6F598", "#FEE08B", "#FDAE61", "#F46D43", "#D53E4F", "#9E0142") wavelet.plot(out.wave, key.cols=specCols,useRaster = NA) # fewer colors levs <- quantile(out.wave$Power, probs = c(0, 0.5, 0.75, 0.9, 0.99)) wavelet.plot(out.wave, wavelet.levels = levs, add.sig = FALSE, key.cols = c("#FFFFFF", "#ABDDA4", "#FDAE61", "#D7191C"), useRaster = NA) ## End(Not run)library(stats) library(utils) data(ca533) ca533.rwi <- detrend(rwl = ca533, method = "ModNegExp") ca533.crn <- chron(ca533.rwi, prewhiten = FALSE) Years <- time(ca533.crn) CAMstd <- ca533.crn[, 1] out.wave <- morlet(y1 = CAMstd, x1 = Years, p2 = 9, dj = 0.1, siglvl = 0.99) wavelet.plot(out.wave, useRaster = NA) ## Not run: # Alternative palette with better separation of colors # via: rev(RColorBrewer::brewer.pal(10, "Spectral")) specCols <- c("#5E4FA2", "#3288BD", "#66C2A5", "#ABDDA4", "#E6F598", "#FEE08B", "#FDAE61", "#F46D43", "#D53E4F", "#9E0142") wavelet.plot(out.wave, key.cols=specCols,useRaster = NA) # fewer colors levs <- quantile(out.wave$Power, probs = c(0, 0.5, 0.75, 0.9, 0.99)) wavelet.plot(out.wave, wavelet.levels = levs, add.sig = FALSE, key.cols = c("#FFFFFF", "#ABDDA4", "#FDAE61", "#D7191C"), useRaster = NA) ## End(Not run)
This function creates a pith offset data structure based on wood completeness data.
wc.to.po(wc)wc.to.po(wc)
wc |
A |
Computes the sum of the variables n.missing.heartwood and
n.unmeasured.inner in wc.
A data.frame containing two variables. Variable one
(series) gives the series ID as either
characters or factors. These match
rownames(wc). Variable two (pith.offset) is
of integer type and gives the years from the beginning of the
core to the pith (or center) of the tree. The minimum value is 1.
Mikko Korpela
library(utils) data(gp.po) all(wc.to.po(po.to.wc(gp.po)) == gp.po)library(utils) data(gp.po) all(wc.to.po(po.to.wc(gp.po)) == gp.po)
Take the years from start to end of an "rwl",
"rwi", "bai" or "crn" object.
## S3 method for class 'rwl' window(x, start = NULL, end = NULL, ...) ## S3 method for class 'rwi' window(x, start = NULL, end = NULL, ...) ## S3 method for class 'bai' window(x, start = NULL, end = NULL, ...) ## S3 method for class 'crn' window(x, start = NULL, end = NULL, ...)## S3 method for class 'rwl' window(x, start = NULL, end = NULL, ...) ## S3 method for class 'rwi' window(x, start = NULL, end = NULL, ...) ## S3 method for class 'bai' window(x, start = NULL, end = NULL, ...) ## S3 method for class 'crn' window(x, start = NULL, end = NULL, ...)
x |
an object of class |
start, end
|
the first and last years to keep, each a single
number. |
... |
not used. |
The years are those in time(x). The rows are taken with
[, so an "rwl", "rwi" or "bai" object keeps its class
and its provenance record, cut down to the years that remain (see
[.rwl). Series with no values in the window are
dropped from an "rwl", "rwi" or "bai" object, with a message
naming them, since an empty series is not one any dplR function can
use; if no series has values in the window, that is an error. The
years returned are still the ones asked for. subset drops
empty series in the same way. x[i, ] does not: [
returns every series it is asked for, empty or not, so that its
columns stay lined up with anything indexed alongside them (see
[.rwl). Use window to take years for analysis.
A window is usually taken to line the data up with something else, so
a window that runs past either end of x gives a warning that
says which years were returned, and a window that does not overlap
x at all is an error.
An object of the same class as x, holding the years from
start to end and the series with values in them.
Andy Bunn
data(ca533) ca533.1800s <- window(ca533, 1800, 1899) range(time(ca533.1800s)) ca533.crn <- chron(detrend(ca533, method = "Spline")) tail(window(ca533.crn, start = 1950))data(ca533) ca533.1800s <- window(ca533, 1800, 1899) range(time(ca533.1800s)) ca533.crn <- chron(detrend(ca533, method = "Spline")) tail(window(ca533.crn, start = 1950))
This function writes a chronology to a DPL compact format file.
write.compact(rwl.df, fname, append = FALSE, prec = 0.01, mapping.fname = "", mapping.append = FALSE, ...)write.compact(rwl.df, fname, append = FALSE, prec = 0.01, mapping.fname = "", mapping.append = FALSE, ...)
rwl.df |
a |
fname |
a |
append |
|
prec |
|
mapping.fname |
a |
mapping.append |
|
... |
Unknown arguments are accepted but not used. |
The output should be readable by the Dendrochronology Program Library (DPL) as a compact format file.
In series IDs, letters of the English alphabet and numbers are allowed. Other characters will be removed. The length of the IDs is limited to about 50 characters, depending on the length of the other items to be placed on the header lines of the output file. Longer IDs will be truncated. Also any duplicate IDs will be automatically edited so that only unique IDs exist. If series IDs are changed, one or more warnings are shown. In that case, the user may wish to print a list of the renamings (see Arguments).
fname
Mikko Korpela, based on write.tucson by Andy Bunn
write.rwl, write.tucson,
write.tridas, read.compact
library(utils) data(co021) fname <- write.compact(rwl.df = co021, fname = tempfile(fileext=".rwl"), append = FALSE, prec = 0.001) print(fname) # tempfile used for output unlink(fname) # remove the filelibrary(utils) data(co021) fname <- write.compact(rwl.df = co021, fname = tempfile(fileext=".rwl"), append = FALSE, prec = 0.001) print(fname) # tempfile used for output unlink(fname) # remove the file
This function writes a chronology to a Tucson (decadal) format file.
write.crn(crn, fname, header = NULL, append = FALSE)write.crn(crn, fname, header = NULL, append = FALSE)
crn |
a |
fname |
a |
header |
a |
append |
|
This writes a standard crn file as defined according to the standards
of the ITRDB at
https://www.ncei.noaa.gov/pub/data/paleo/treering/treeinfo.txt. This is the
decadal or Tucson format. It is an ASCII file and machine
readable by the standard dendrochronology programs. Header information
for the chronology can be written according to the International Tree
Ring Data Bank (ITRDB) standard. The header standard is not
very reliable however and should be thought of as experimental
here. Do not try to write headers using dplR to submit to the
ITRDB. When submitting to the ITRDB, you can enter
the metadata via their website. If you insist however, the header
information is given as a list and must be formatted with the
following:
| Description | Name | Class | Max Width |
| Site ID | site.id |
character |
6 |
| Site Name | site.name |
character |
52 |
| Species Code | spp.code |
character |
4 |
| State or Country | state.country |
character |
13 |
| Species | spp |
character |
18 |
| Elevation | elev |
character |
5 |
| Latitude | lat |
character or numeric |
5 |
| Longitude | long |
character or numeric |
5 |
| First Year | first.yr |
character or numeric |
4 |
| Last Year | last.yr |
character or numeric |
4 |
| Lead Investigator | lead.invs |
character |
63 |
| Completion Date | comp.date |
character |
8 |
See examples for a correctly formatted header list. If the width of
the fields is less than the max width, then the fields will be padded
to the right length when written. Note that lat and
long are really lat*100 or
long*100 and given as integral values. E.g., 37 degrees
30 minutes would be given as 3750.
This function takes a single chronology with sample depth as
input. This means that it will fail if given output from
chron where prewhiten == TRUE. However,
more than one chronology can be appended to the bottom of an existing
file (e.g., standard and residual) with a second call to
write.crn. However, the ITRDB recommends
saving and publishing only one chronology per file. The examples
section shows how to circumvent this. The output from this function
might be suitable for publication on the ITRDB although the
header writing is clunky (see above) and rwl files are much better
than crn files in terms of usefulness on the ITRDB.
fname
Andy Bunn. Patched and improved by Mikko Korpela.
library(utils) data(ca533) ca533.rwi <- detrend(rwl = ca533, method = "ModNegExp") ca533.crn <- chron(ca533.rwi) fname1 <- write.crn(ca533.crn, tempfile(fileext=".crn")) print(fname1) # tempfile used for output ## Put the standard and residual chronologies in a single file ## with ITRDB header info on top. Not recommended. ca533.crn <- chron(ca533.rwi, prewhiten = TRUE) ca533.hdr <- list(site.id = "CAM", site.name = "Campito Mountain", spp.code = "PILO", state.country = "California", spp = "Bristlecone Pine", elev = "3400M", lat = 3730, long = -11813, first.yr = 626, last.yr = 1983, lead.invs = "Donald A. Graybill, V.C. LaMarche, Jr.", comp.date = "Nov1983") fname2 <- write.crn(ca533.crn[, -2], tempfile(fileext=".crn"), header = ca533.hdr) write.crn(ca533.crn[, -1], fname2, append = TRUE) print(fname2) # tempfile used for output unlink(c(fname1, fname2)) # remove the fileslibrary(utils) data(ca533) ca533.rwi <- detrend(rwl = ca533, method = "ModNegExp") ca533.crn <- chron(ca533.rwi) fname1 <- write.crn(ca533.crn, tempfile(fileext=".crn")) print(fname1) # tempfile used for output ## Put the standard and residual chronologies in a single file ## with ITRDB header info on top. Not recommended. ca533.crn <- chron(ca533.rwi, prewhiten = TRUE) ca533.hdr <- list(site.id = "CAM", site.name = "Campito Mountain", spp.code = "PILO", state.country = "California", spp = "Bristlecone Pine", elev = "3400M", lat = 3730, long = -11813, first.yr = 626, last.yr = 1983, lead.invs = "Donald A. Graybill, V.C. LaMarche, Jr.", comp.date = "Nov1983") fname2 <- write.crn(ca533.crn[, -2], tempfile(fileext=".crn"), header = ca533.hdr) write.crn(ca533.crn[, -1], fname2, append = TRUE) print(fname2) # tempfile used for output unlink(c(fname1, fname2)) # remove the files
This function writes a rwl object to a file in one of the available
formats.
write.rwl(rwl.df, fname, format = c("tucson", "compact", "tridas", "sheet", "csv"), ...)write.rwl(rwl.df, fname, format = c("tucson", "compact", "tridas", "sheet", "csv"), ...)
rwl.df |
a |
fname |
a |
format |
a |
... |
arguments specific to the function implementing the operation for the chosen format. |
This is a simple wrapper to the functions actually implementing the write operation.
fname
Mikko Korpela
write.crn, write.tucson, write.sheet,
write.compact, write.tridas,
read.rwl
library(utils) data(co021) co021.hdr <- list(site.id = "CO021", site.name = "SCHULMAN OLD TREE NO. 1, MESA VERDE", spp.code = "PSME", state.country = "COLORADO", spp = "DOUGLAS FIR", elev = 2103, lat = 3712, long = -10830, first.yr = 1400, last.yr = 1963, lead.invs = "E. SCHULMAN", comp.date = "") fname <- write.rwl(rwl.df = co021, fname = tempfile(fileext=".rwl"), format = "tucson", header = co021.hdr, append = FALSE, prec = 0.001) print(fname) # tempfile used for output unlink(fname) # remove the filelibrary(utils) data(co021) co021.hdr <- list(site.id = "CO021", site.name = "SCHULMAN OLD TREE NO. 1, MESA VERDE", spp.code = "PSME", state.country = "COLORADO", spp = "DOUGLAS FIR", elev = 2103, lat = 3712, long = -10830, first.yr = 1400, last.yr = 1963, lead.invs = "E. SCHULMAN", comp.date = "") fname <- write.rwl(rwl.df = co021, fname = tempfile(fileext=".rwl"), format = "tucson", header = co021.hdr, append = FALSE, prec = 0.001) print(fname) # tempfile used for output unlink(fname) # remove the file
Write a ring width object to a file in “spreadsheet” layout: years down the rows, series across the columns, and the years in the first column.
write.sheet(rwl.df, fname, sep = ",", dec = ".", layout = c("wide", "long"), prec = NULL, na.string = "", year.name = "Year")write.sheet(rwl.df, fname, sep = ",", dec = ".", layout = c("wide", "long"), prec = NULL, na.string = "", year.name = "Year")
rwl.df |
a |
fname |
a |
sep |
the field separator, a single character. |
dec |
the decimal mark, |
layout |
the shape to write. |
prec |
the precision to write, in mm, or |
na.string |
|
year.name |
|
The file is written in the layout that read.sheet reads: a
header row of the year column's name followed by the series IDs,
then one row per year.
prec controls how many decimal places are written. Left at
NULL it is taken from the "dplR.provenance" attribute that
read.sheet and read.tucson attach to the objects
they return, and failing that it is inferred from the data. This is what
keeps a width read at 0.001 mm from being written back as
0.5670000000000001.
A precision that was derived rather than given is checked against the data
before it is used, and if rounding there would discard real digits the file
is written at full precision with a warning instead. A precision passed
explicitly is an instruction and is obeyed, so prec = 0.1 rounds.
Trailing zeros are kept: at prec = 0.001 a width of 0.51 is
written as 0.510.
With layout = "long" the file holds one row per observation — the
series ID, the year and the value — with missing values left
out. Rows are written one series at a time, years ascending within a
series. year.name names the year column here too.
A year in which every series is NA has no rows. An
interior such year still survives a round trip, because
read.sheet rebuilds the span from the earliest and latest
year in the file and the year reappears as a row of NA in its
original place. A leading or trailing one has nothing outside it
to pin the span and is lost; write.sheet warns when it writes a
file in that state. Write with layout = "wide" to keep those years.
A ring width of zero is a locally absent ring and is written as a zero. A
missing value is written as na.string. The two are different statements
about a tree in a year and are never written the same way.
Series IDs are written verbatim. An ID containing the separator, a double quote or a line break is quoted using the usual comma-separated-value escape.
The function returns fname, the name of the file written.
Andy Bunn
read.sheet, write.rwl,
write.tucson
library(utils) data(ca533) tmpName <- tempfile(fileext = ".csv") # write and read back write.sheet(ca533, tmpName) bar <- read.sheet(tmpName, verbose = FALSE) # the data survives the round trip unchanged. Provenance describes the file an # object was read from, so it is dropped from both sides before comparing. no.prov <- function(x) { attr(x, "dplR.provenance") <- NULL; x } identical(no.prov(ca533), no.prov(bar)) unlink(tmpName)library(utils) data(ca533) tmpName <- tempfile(fileext = ".csv") # write and read back write.sheet(ca533, tmpName) bar <- read.sheet(tmpName, verbose = FALSE) # the data survives the round trip unchanged. Provenance describes the file an # object was read from, so it is dropped from both sides before comparing. no.prov <- function(x) { attr(x, "dplR.provenance") <- NULL; x } identical(no.prov(ca533), no.prov(bar)) unlink(tmpName)
This function writes measured or derived (standardized, averaged) series of values to a TRiDaS format file. Some metadata are also supported.
write.tridas(rwl.df = NULL, fname, crn = NULL, prec = NULL, ids = NULL, titles = NULL, crn.types = NULL, crn.titles = NULL, crn.units = NULL, tridas.measuring.method = NA, other.measuring.method = "unknown", sample.type = "core", wood.completeness = NULL, taxon = "", tridas.variable = "ring width", other.variable = NA, project.info = list(type = c("unknown"), description = NULL, title = "", category = "", investigator = "", period = ""), lab.info = data.frame(name = "", acronym = NA, identifier = NA, domain = "", addressLine1 = NA, addressLine2 = NA, cityOrTown = NA, stateProvinceRegion = NA, postalCode = NA, country = NA), research.info = data.frame(identifier = NULL, domain = NULL, description = NULL), site.info = list(type = "unknown", description = NULL, title = ""), random.identifiers = FALSE, identifier.domain = lab.info$name[1], ...)write.tridas(rwl.df = NULL, fname, crn = NULL, prec = NULL, ids = NULL, titles = NULL, crn.types = NULL, crn.titles = NULL, crn.units = NULL, tridas.measuring.method = NA, other.measuring.method = "unknown", sample.type = "core", wood.completeness = NULL, taxon = "", tridas.variable = "ring width", other.variable = NA, project.info = list(type = c("unknown"), description = NULL, title = "", category = "", investigator = "", period = ""), lab.info = data.frame(name = "", acronym = NA, identifier = NA, domain = "", addressLine1 = NA, addressLine2 = NA, cityOrTown = NA, stateProvinceRegion = NA, postalCode = NA, country = NA), research.info = data.frame(identifier = NULL, domain = NULL, description = NULL), site.info = list(type = "unknown", description = NULL, title = ""), random.identifiers = FALSE, identifier.domain = lab.info$name[1], ...)
rwl.df |
|
fname |
|
crn |
|
prec |
optional |
ids |
optional
data.frame(tree=1:n.col, core=rep(1,n.col),
radius=rep(1,n.col), measurement=rep(1,n.col))
where |
titles |
optional |
crn.types |
|
crn.titles |
optional |
crn.units |
optional |
tridas.measuring.method |
|
other.measuring.method |
|
sample.type |
optional |
wood.completeness |
optional
|
taxon |
|
tridas.variable |
|
other.variable |
|
project.info |
|
lab.info |
|
research.info |
optional
|
site.info |
|
random.identifiers |
|
identifier.domain |
|
... |
Unknown arguments are accepted but not used. |
The Tree Ring Data Standard (TRiDaS) is described in Jansma et. al (2010).
fname
This is an early version of the function. Bugs are likely to exist, and parameters are subject to change.
Mikko Korpela
Jansma, E., Brewer, P. W., and Zandhuis, I. (2010) TRiDaS 1.1: The tree-ring data standard. Dendrochronologia, 28(2), 99–130.
write.rwl, write.tucson,
write.compact, write.crn,
read.tridas
library(utils) ## Not run: ## Write raw ring widths data(co021) fname1 <- write.tridas(rwl.df = co021, fname = tempfile(fileext=".xml"), prec = 0.01, site.info = list(title = "Schulman old tree no. 1, Mesa Verde", type = "unknown"), taxon = "Pseudotsuga menziesii var. menziesii (Mirb.) Franco", project.info = list(investigator = "E. Schulman", title = "", category = "", period = "", type = "unknown")) print(fname1) # tempfile used for output ## Write mean value chronology of detrended ring widths data(ca533) ca533.rwi <- detrend(rwl = ca533, method = "ModNegExp") ca533.crn <- chron(ca533.rwi, prewhiten = TRUE) fname2 <- write.tridas(crn = ca533.crn, fname = tempfile(fileext=".xml"), taxon = "Pinus longaeva D.K. Bailey", project.info = list(investigator = "Donald A. Graybill, V.C. LaMarche, Jr.", title = "Campito Mountain", category = "", period = "", type = "unknown")) print(fname2) # tempfile used for output unlink(c(fname1, fname2)) # remove the files ## End(Not run)library(utils) ## Not run: ## Write raw ring widths data(co021) fname1 <- write.tridas(rwl.df = co021, fname = tempfile(fileext=".xml"), prec = 0.01, site.info = list(title = "Schulman old tree no. 1, Mesa Verde", type = "unknown"), taxon = "Pseudotsuga menziesii var. menziesii (Mirb.) Franco", project.info = list(investigator = "E. Schulman", title = "", category = "", period = "", type = "unknown")) print(fname1) # tempfile used for output ## Write mean value chronology of detrended ring widths data(ca533) ca533.rwi <- detrend(rwl = ca533, method = "ModNegExp") ca533.crn <- chron(ca533.rwi, prewhiten = TRUE) fname2 <- write.tridas(crn = ca533.crn, fname = tempfile(fileext=".xml"), taxon = "Pinus longaeva D.K. Bailey", project.info = list(investigator = "Donald A. Graybill, V.C. LaMarche, Jr.", title = "Campito Mountain", category = "", period = "", type = "unknown")) print(fname2) # tempfile used for output unlink(c(fname1, fname2)) # remove the files ## End(Not run)
This function writes a chronology to a Tucson (decadal) format file.
write.tucson(rwl.df, fname, header = NULL, append = FALSE, prec = 0.01, mapping.fname = "", mapping.append = FALSE, long.names = FALSE, fill.internal.NA = NULL, extra.chars = c("-", "_", "."), ...)write.tucson(rwl.df, fname, header = NULL, append = FALSE, prec = 0.01, mapping.fname = "", mapping.append = FALSE, long.names = FALSE, fill.internal.NA = NULL, extra.chars = c("-", "_", "."), ...)
rwl.df |
a |
fname |
a |
header |
a |
append |
|
prec |
|
mapping.fname |
a |
mapping.append |
|
long.names |
|
fill.internal.NA |
what to do with interior |
extra.chars |
a |
... |
Unknown arguments are accepted but not used. |
This writes a standard rwl file as defined according to the standards
of the ITRDB at
https://www.ncei.noaa.gov/pub/data/paleo/treering/treeinfo.txt. This is the
decadal or Tucson format. It is an ASCII file and machine
readable by the standard dendrochronology programs. Header information
for the rwl can be written according to the International Tree Ring
Data Bank (ITRDB) standard. The header standard is not very
reliable however and should be thought of as experimental here. Do not
try to write headers using dplR to submit to the ITRDB. When
submitting to the ITRDB, you can enter the metadata via
their website. If you insist however, the header information is given
as a list and must be formatted with the following:
| Description | Name | Class | Max Width |
| Site ID | site.id |
character |
5 |
| Site Name | site.name |
character |
52 |
| Species Code | spp.code |
character |
4 |
| State or Country | state.country |
character |
13 |
| Species | spp |
character |
18 |
| Elevation | elev |
character |
5 |
| Latitude | lat |
character or numeric |
5 |
| Longitude | long |
character or numeric |
5 |
| First Year | first.yr |
character or numeric |
4 |
| Last Year | last.yr |
character or numeric |
4 |
| Lead Investigator | lead.invs |
character |
63 |
| Completion Date | comp.date |
character |
8 |
See examples for a correctly formatted header list. If the width of
the fields is less than the max width, then the fields will be padded
to the right length when written. Note that lat and
long are really lat * 100 or
long * 100 and given as integral values. E.g., 37 degrees
30 minutes would be given as 3750.
Series can be appended to the bottom of an existing file with a second
call to write.tucson. The output from this file is suitable for
publication on the ITRDB.
The function is capable of altering excessively long and/or duplicate
series IDs to fit the Tucson specification. Additionally,
characters outside a–z, A–Z,
0–9 and extra.chars will be removed. If
series IDs are changed, a single warning is shown giving the
reasons and the first few renamings as old -> new. The user may
also wish to print the full list (see mapping.fname in
Arguments).
Renaming is worth attention because it is not confined to the series
that prompted it. Removing a character shortens a name, and a shortened
name can collide with one that needed no change; the duplicate pass then
renames both. Before dplR 1.8.0, a file holding
"CC1-1" and "CC11" was written out as "CC110" and
"CC111", neither of which is an ID in the input.
The Tucson format does not restrict the character set of a series
ID: the ITRDB description names only the columns
the ID occupies. Hyphens, underscores and periods are common in
real IDs, they do not disturb the fixed-width layout, and
read.tucson reads them back unchanged, so they are
written as they stand rather than removed. There is one position where
a hyphen cannot go: column 8, which is where a minus sign distinguishes
a 5-character year before -999 from an 8-character series
ID. An 8-character ID ending in a hyphen is
therefore shortened by that hyphen, with a warning. This can only
arise when long.names = TRUE; at the default width an
ID stops at column 6.
Interior NA – years between a series' first and last measurement
where rwl.df records nothing – are written as -999,
the negative value the Tucson format uses to mark missing data, at both
precisions. read.tucson reads any negative value that is
not the stop marker back as NA, so a
read.tucson–write.tucson–read.tucson
cycle preserves the gaps. Note that read.tucson.legacy, and
other dendrochronology programs, will read those cells as a ring width of
zero. A message is given whenever gaps are written.
Before dplR 1.8.0 interior NA were written as -999 at
prec = 0.01 but as 0 at prec = 0.001.
A zero ring width is a locally absent ring, which is a real observation
about a tree in a year, and it is not the same statement as "not
measured"; the two are no longer conflated. Use
fill.internal.NA = 0 to get the old prec =
0.001 output. Files with no interior NA are written exactly as
before.
A series that is entirely NA has nothing to write. It is skipped
with a warning naming the series, and the rest of the file is written
normally.
Setting long.names = TRUE allows series IDs to
be 8 characters long, or 7 in case there are year numbers using 5
characters. Note that in the latter case the limit of 7 characters
applies to all IDs, not just the one corresponding to the
series with long year numbers. The default (long.names =
FALSE) is to allow 6 characters. Long IDs may cause
incompatibility with other software.
fname
Andy Bunn. Patched and improved by Mikko Korpela.
write.crn, read.tucson,
read.tucson.legacy, fill.internal.NA,
write.rwl, write.compact,
write.tridas
library(utils) data(co021) co021.hdr <- list(site.id = "CO021", site.name = "SCHULMAN OLD TREE NO. 1, MESA VERDE", spp.code = "PSME", state.country = "COLORADO", spp = "DOUGLAS FIR", elev = "2103M", lat = 3712, long = -10830, first.yr = 1400, last.yr = 1963, lead.invs = "E. SCHULMAN", comp.date = "") fname <- write.tucson(rwl.df = co021, fname = tempfile(fileext=".rwl"), header = co021.hdr, append = FALSE, prec = 0.001) print(fname) # tempfile used for output unlink(fname) # remove the file ## Interior NA survive a write and a read gappy <- data.frame(SER01 = round(seq(0.5, 2, length.out = 40), 3), row.names = 1901:1940) gappy[15:19, 1] <- NA # five years with no measurement fname2 <- write.tucson(gappy, tempfile(fileext=".rwl"), prec = 0.001) back <- read.tucson(fname2, verbose = FALSE) identical(is.na(back$SER01), is.na(gappy$SER01)) # TRUE ## The old behaviour, if you want it: gaps filled with zero fname3 <- write.tucson(gappy, tempfile(fileext=".rwl"), prec = 0.001, fill.internal.NA = 0) read.tucson(fname3, verbose = FALSE)$SER01[15:19] # zeros, not NA unlink(c(fname2, fname3)) ## Hyphens and underscores in series IDs survive a round trip dashed <- data.frame(`CC1-1` = 1:5, CC11 = 6:10, `CC_5` = 11:15, `CC.7` = 16:20, check.names = FALSE, row.names = 1901:1905) fname4 <- write.tucson(dashed, tempfile(fileext=".rwl")) names(read.tucson(fname4, verbose = FALSE)) ## The pre-1.8.0 rule, if you want it: note that stripping the hyphen from ## CC1-1 collides with CC11, so both series are renamed fname5 <- write.tucson(dashed, tempfile(fileext=".rwl"), extra.chars = character(0)) names(read.tucson(fname5, verbose = FALSE)) unlink(c(fname4, fname5))library(utils) data(co021) co021.hdr <- list(site.id = "CO021", site.name = "SCHULMAN OLD TREE NO. 1, MESA VERDE", spp.code = "PSME", state.country = "COLORADO", spp = "DOUGLAS FIR", elev = "2103M", lat = 3712, long = -10830, first.yr = 1400, last.yr = 1963, lead.invs = "E. SCHULMAN", comp.date = "") fname <- write.tucson(rwl.df = co021, fname = tempfile(fileext=".rwl"), header = co021.hdr, append = FALSE, prec = 0.001) print(fname) # tempfile used for output unlink(fname) # remove the file ## Interior NA survive a write and a read gappy <- data.frame(SER01 = round(seq(0.5, 2, length.out = 40), 3), row.names = 1901:1940) gappy[15:19, 1] <- NA # five years with no measurement fname2 <- write.tucson(gappy, tempfile(fileext=".rwl"), prec = 0.001) back <- read.tucson(fname2, verbose = FALSE) identical(is.na(back$SER01), is.na(gappy$SER01)) # TRUE ## The old behaviour, if you want it: gaps filled with zero fname3 <- write.tucson(gappy, tempfile(fileext=".rwl"), prec = 0.001, fill.internal.NA = 0) read.tucson(fname3, verbose = FALSE)$SER01[15:19] # zeros, not NA unlink(c(fname2, fname3)) ## Hyphens and underscores in series IDs survive a round trip dashed <- data.frame(`CC1-1` = 1:5, CC11 = 6:10, `CC_5` = 11:15, `CC.7` = 16:20, check.names = FALSE, row.names = 1901:1905) fname4 <- write.tucson(dashed, tempfile(fileext=".rwl")) names(read.tucson(fname4, verbose = FALSE)) ## The pre-1.8.0 rule, if you want it: note that stripping the hyphen from ## CC1-1 collides with CC11, so both series are renamed fname5 <- write.tucson(dashed, tempfile(fileext=".rwl"), extra.chars = character(0)) names(read.tucson(fname5, verbose = FALSE)) unlink(c(fname4, fname5))
Pulls an undated (or misdated) series through a dated rwl object
in order to establish possible dates for the series.
xdate.floater(rwl, series, series.name = "Unknown", min.overlap = 50, n = NULL, nyrs = NULL, prewhiten = TRUE, ar.order.max = NULL, biweight = TRUE, method = c("spearman", "pearson", "kendall"), make.plot = TRUE, return.rwl = TRUE, verbose = TRUE) ## S3 method for class 'floater' print(x, ...) ## S3 method for class 'floater' plot(x, ...)xdate.floater(rwl, series, series.name = "Unknown", min.overlap = 50, n = NULL, nyrs = NULL, prewhiten = TRUE, ar.order.max = NULL, biweight = TRUE, method = c("spearman", "pearson", "kendall"), make.plot = TRUE, return.rwl = TRUE, verbose = TRUE) ## S3 method for class 'floater' print(x, ...) ## S3 method for class 'floater' plot(x, ...)
rwl |
a |
series |
a numeric vector of ring widths, e.g. a single column
from an |
series.name |
a |
min.overlap |
a positive integer giving the minimum number of
years of overlap required between the series and the master
chronology at each search position. Defaults to |
n |
|
nyrs |
|
prewhiten |
logical flag. If |
ar.order.max |
|
biweight |
logical flag. If |
method |
the correlation coefficient to use. One of
|
make.plot |
logical flag. If |
return.rwl |
logical flag. If |
verbose |
logical flag. If |
x |
a |
... |
additional arguments — currently ignored. |
The undated series is slid along the master chronology built from
rwl (using the leave-one-out principle) and the correlation
between the series and the master is computed at each position with
sufficient overlap. The position with the highest correlation gives
the proposed dates.
The series must be one unbroken run of rings. NA before and
after the measurements is dropped, so a column can be passed straight
from an rwl object. NA inside the series stops the
function: dropping it would close the gap and put the rings on either
side out of step by the length of the gap, and the search would then
date one part of the series or neither. Fill the gap first (see
fill.internal.NA) or date the parts separately.
The proposed dates are those with the highest correlation, whatever
the overlap. A high correlation over a short overlap is easier to get
by chance than a lower one over a long overlap, so compare p
and n in the returned table before accepting a position near
the ends of the master.
Both series and master are optionally prewhitened and/or smoothed
with a Hanning filter before correlation, consistent with the
approach used in corr.series.seg.
The two-panel plot (produced when make.plot = TRUE, or by
calling plot() on the returned object) shows: (1) a segment
plot of the master series with the floater at its best-fit position
highlighted in green; and (2) the correlation at each end-year
searched, overlaid with a dashed significance line and a light-blue
polygon showing the 5th–95th percentile band of the typical
interseries correlation in the master chronology. The dark-blue
horizontal line shows the median interseries correlation. The
best-fit position is marked with green points and a dashed segment.
If return.rwl = TRUE (the default), an object of class
"floater" is returned. This is a named list with the
following elements:
series.name |
the name given to the undated series. |
floaterCorStats |
a |
rwlCombined |
an |
rwlOut |
an |
If return.rwl = FALSE, only the floaterCorStats
data.frame is returned.
This function is experimental and may change in future releases. Users should always verify proposed dates visually and against the physical wood.
The choice of min.overlap affects both which search positions
are evaluated and the reliability of the correlations at those
positions. A short min.overlap allows the series to be placed
near the edges of the master chronology where little overlap exists,
producing correlations based on few observations that may be
spuriously high. A very long min.overlap restricts the search
to positions where the series is well inside the master, which is
statistically conservative but can cause the function to miss the
correct dates entirely if the true position lies near an edge, or to
produce wrong dates if the best correlation within the constrained
search window happens to be a false match. As a rule,
min.overlap should be long enough to produce a stable
correlation (50 years is a common starting point for annual
tree-ring data) but no longer than roughly half the length of the
undated series. The dashed significance line in the plot is
calculated from the overlap length at each position and provides a
useful guide: positions with short overlaps will have high
significance thresholds and should be interpreted with caution.
Andy Bunn. Patched and improved by Mikko Korpela.
corr.series.seg, ccf.series.rwl,
skel.plot, series.rwl.plot
library(utils) data(co021) summary(co021) # Remove a series and try to recover its dates foo <- co021[, "645232"] bar <- co021 bar$"645232" <- NULL out <- xdate.floater(bar, foo, min.overlap = 50, series.name = "645232") print(out) # A longer series. With min.overlap = 100 the correct dates are recovered. # With min.overlap = 200 the search window is so constrained that the true # position is excluded and the function returns the best match within the # remaining positions, which is a false fit. Compare the two results. foo <- co021[, "646118"] bar <- co021 bar$"646118" <- NULL out <- xdate.floater(bar, foo, min.overlap = 100, series.name = "646118") out <- xdate.floater(bar, foo, min.overlap = 200, series.name = "646118")library(utils) data(co021) summary(co021) # Remove a series and try to recover its dates foo <- co021[, "645232"] bar <- co021 bar$"645232" <- NULL out <- xdate.floater(bar, foo, min.overlap = 50, series.name = "645232") print(out) # A longer series. With min.overlap = 100 the correct dates are recovered. # With min.overlap = 200 the search window is so constrained that the true # position is excluded and the function returns the best match within the # remaining positions, which is a false fit. Compare the two results. foo <- co021[, "646118"] bar <- co021 bar$"646118" <- NULL out <- xdate.floater(bar, foo, min.overlap = 100, series.name = "646118") out <- xdate.floater(bar, foo, min.overlap = 200, series.name = "646118")
Builds a crossdating report in the layout of the COFECHA
output carried by the International Tree-Ring Data Bank
(ITRDB) correlation-stats files: a summary header, the
correlation of each series by segment with ‘A’ and ‘B’
flags, descriptive statistics for each series, and the findings of
rwl.check, with a record of how the report was made.
xdate.report(x, seg.length = 50, bin.floor = 100, nyrs = 32, prewhiten = TRUE, ar.order.max = 3, pcrit = 0.01, lag.max = 10, method = c("pearson", "spearman", "kendall"), biweight = TRUE, check = TRUE, meta = list(), title = NULL) ## S3 method for class 'xdate.report' format(x, type = c("text", "markdown", "html"), bins.per.page = 20, ...) ## S3 method for class 'xdate.report' print(x, ...) write.xdate.report(x, fname, type = NULL, ...)xdate.report(x, seg.length = 50, bin.floor = 100, nyrs = 32, prewhiten = TRUE, ar.order.max = 3, pcrit = 0.01, lag.max = 10, method = c("pearson", "spearman", "kendall"), biweight = TRUE, check = TRUE, meta = list(), title = NULL) ## S3 method for class 'xdate.report' format(x, type = c("text", "markdown", "html"), bins.per.page = 20, ...) ## S3 method for class 'xdate.report' print(x, ...) write.xdate.report(x, fname, type = NULL, ...)
x |
an |
seg.length |
an even integral value giving the length of the segments in years. Reduced, with a note in the report, when the record is too short for it. |
bin.floor |
a non-negative integral value giving the base for
locating the first segment, as in |
nyrs |
|
prewhiten |
|
ar.order.max |
|
pcrit |
a number between 0 and 1 giving the critical value for the one-tailed correlation test. The default, 0.01, is COFECHA’s. |
lag.max |
the largest shift, in years, at which each segment is also correlated with the master. Reduced if it is not less than the segment length. |
method |
the correlation coefficient, |
biweight |
|
check |
|
meta |
a |
title |
the title printed on each part. Defaults to the file name without its extension, or the name of the object. |
type |
the layout: |
fname |
the name of the file to write. |
bins.per.page |
the number of segments printed side by side in the correlation table before it continues on a new page, as COFECHA does. |
... |
further arguments to |
The segment correlations and flags come from corr.rwl.seg
with lag.max set: each segment of each series is
correlated with a leave-one-out master, at its dated position and at
every shift up to lag.max years. A segment is flagged
‘B’ when some other position correlates better than the dated
one, and ‘A’ when the dated position is the best tested but its
correlation is under the critical value. With Pearson correlation
the critical value printed in the report is exactly the one the test
uses. Lags follow COFECHA: a negative lag means rings are
probably missing from the series. The report lists each flagged
segment with its lag and the gain in correlation, because a B flag is
a hypothesis to check on the wood, and the size of the gain says how
seriously to take it. A B flag whose best correlation is itself under
the critical value is marked “weak at every lag”: the segment
does not crossdate anywhere in the window, the shift only wins among
weak correlations, and it is better read as a low correlation than as
a dating error. The letter stays B, as COFECHA’s
rule has it. See corr.rwl.seg for how to read
the lags along a series.
The report differs from COFECHA in three ways, and says so in its notes. A segment is tested only where the series and the master cover all of it, at every lag, so series may show fewer segments than in COFECHA, which also tests partial segments at the ends of a series, and no flag can be raised at the ends of the record. The filtered block of the descriptive statistics describes the series that dplR correlated, which is not COFECHA’s filtered series, and is labelled “dplR filtered”. The correlation with the master is computed by dplR and usually differs from COFECHA’s in the second decimal place.
A series whose spline cannot be fitted, because it has internal
NA values or its spline is not all positive, is described but
left out of the crossdating, and the report names it and says why.
With fewer than three series that can be crossdated there is no
master, and the report gives the descriptive statistics alone.
The averages in the summary and in the totals row are weighted by the number of years in each series, as COFECHA’s are.
The report records how it was made: the dplR and R versions, the time,
the MD5 checksum of the measurement file when x is a
path, the filtering, the master, the correlation and the segments, and
every setting that had to be changed to fit the data.
xdate.report returns an object of class "xdate.report", a
list with elements
title, file, meta
|
as given or found. |
stats |
a |
flags |
a |
flagged |
a |
crs |
the result of |
excluded |
a |
check |
the result of |
notes |
the changes made to fit the data. |
settings |
the settings asked for and used. |
provenance |
the dplR and R versions, the time, and the file and its checksum. |
format returns the report as a character vector, one
element per line. print prints it and returns x
invisibly. write.xdate.report writes it to fname and
returns fname invisibly.
Andy Bunn.
Holmes, R. L. (1983) Computer-assisted quality control in tree-ring dating and measurement. Tree-Ring Bulletin, 43, 69–78.
corr.rwl.seg, rwl.check,
ccf.series.rwl, xskel.ccf.plot
library(utils) data(co021) ## The fault planted in the other crossdating examples: the 1500 ring ## deleted from series 641143 dat <- co021 x <- dat$"641143" names(x) <- rownames(dat) dat$"641143" <- delete.ring(x, year = 1500) rpt <- xdate.report(dat, meta = list(site.name = "Schulman Old Tree No. 1", species = "PSME")) rpt ## The flagged segments, as data rpt$flagged ## Save it as fixed-width text, as Markdown, or as HTML fn <- tempfile(fileext = ".txt") write.xdate.report(rpt, fn) fn.md <- tempfile(fileext = ".md") write.xdate.report(rpt, fn.md) head(readLines(fn.md), 12) fn.html <- tempfile(fileext = ".html") write.xdate.report(rpt, fn.html) ## Not run: utils::browseURL(fn.html) ## End(Not run) unlink(c(fn, fn.md, fn.html))library(utils) data(co021) ## The fault planted in the other crossdating examples: the 1500 ring ## deleted from series 641143 dat <- co021 x <- dat$"641143" names(x) <- rownames(dat) dat$"641143" <- delete.ring(x, year = 1500) rpt <- xdate.report(dat, meta = list(site.name = "Schulman Old Tree No. 1", species = "PSME")) rpt ## The flagged segments, as data rpt$flagged ## Save it as fixed-width text, as Markdown, or as HTML fn <- tempfile(fileext = ".txt") write.xdate.report(rpt, fn) fn.md <- tempfile(fileext = ".md") write.xdate.report(rpt, fn.md) head(readLines(fn.md), 12) fn.html <- tempfile(fileext = ".html") write.xdate.report(rpt, fn.html) ## Not run: utils::browseURL(fn.html) ## End(Not run) unlink(c(fn, fn.md, fn.html))
...
xskel.ccf.plot(rwl, series, series.yrs = as.numeric(names(series)), win.start, win.width = 50, n = NULL, nyrs = NULL, prewhiten = TRUE, ar.order.max = NULL, biweight = TRUE, series.x=FALSE)xskel.ccf.plot(rwl, series, series.yrs = as.numeric(names(series)), win.start, win.width = 50, n = NULL, nyrs = NULL, prewhiten = TRUE, ar.order.max = NULL, biweight = TRUE, series.x=FALSE)
rwl |
a |
series |
a |
series.yrs |
a |
win.start |
year to start window |
win.width |
an even integral value |
n |
|
nyrs |
|
prewhiten |
|
ar.order.max |
|
biweight |
|
series.x |
|
This function produces a plot that is a mix of a skeleton plot and a cross-correlation plot. It’s used in crossdating.
The top panel shows the normalized values for the master chronology (bottom half) and the series (top half) in green. The values are the detrended and standardized data (e.g., RWI).
Similarly, the black lines are a skeleton plot for the master and series with the marker years annotated for the master on the bottom axis and series on the top. The text at the top of the figure gives the correlation between the series and master (green bars) as well as the percentage of agreement between the years of skeleton bars for the series and master. I.e., if all the black lines occur in the same years the percentage would be 100%.
The bottom panels show cross correlations for the first half (left)
and second half of the time series using function ccf.
The cross correlations are calculated calling
ccf as ccf(x=master, y=series, lag.max=lag.max, plot=FALSE) if series.x is
FALSE and as ccf(x=series, y=master, lag.max=lag.max, plot=FALSE) if
series.x is TRUE. This argument was introduced in dplR version 1.7.0.
Different users have different expectations about how missing or extra rings are notated. If series.x = FALSE the behavior will be like COFECHA where a missing ring in a series produces a negative lag in the plot rather than a positive lag.
The plot is built using the Grid package which
allows for great flexibility in building complicated plots. However,
these plots look best when they don’t cover too wide a range
of years (unless the plotting device is wider than is typical). For
that reason the user will get a warning if win.width is
greater than 100 years.
Old-school skeleton plots to print on paper are made with skel.plot.
None. Invoked for side effect (plot).
Andy Bunn. Patched and improved by Mikko Korpela.
library(utils) data(co021) dat <- co021 ## Create a missing ring: delete the 1500 ring of series 641143 and ## drop the original from the master. Dated from the bark, every ring ## before 1500 now sits one year late. bad.series <- dat$"641143" names(bad.series) <- rownames(dat) bad.series <- delete.ring(bad.series, year = 1500) dat$"641143" <- NULL ## after 1500 the dating is right xskel.ccf.plot(rwl = dat, series = bad.series, win.start = 1550, win.width = 50) ## this window straddles the missing ring xskel.ccf.plot(rwl = dat, series = bad.series, win.start = 1475, win.width = 50)library(utils) data(co021) dat <- co021 ## Create a missing ring: delete the 1500 ring of series 641143 and ## drop the original from the master. Dated from the bark, every ring ## before 1500 now sits one year late. bad.series <- dat$"641143" names(bad.series) <- rownames(dat) bad.series <- delete.ring(bad.series, year = 1500) dat$"641143" <- NULL ## after 1500 the dating is right xskel.ccf.plot(rwl = dat, series = bad.series, win.start = 1550, win.width = 50) ## this window straddles the missing ring xskel.ccf.plot(rwl = dat, series = bad.series, win.start = 1475, win.width = 50)
...
xskel.plot(rwl, series, series.yrs = as.numeric(names(series)), win.start, win.end = win.start+100, n = NULL, nyrs = NULL, prewhiten = TRUE, ar.order.max = NULL, biweight = TRUE)xskel.plot(rwl, series, series.yrs = as.numeric(names(series)), win.start, win.end = win.start+100, n = NULL, nyrs = NULL, prewhiten = TRUE, ar.order.max = NULL, biweight = TRUE)
rwl |
a |
series |
a |
series.yrs |
a |
win.start |
year to start window |
win.end |
year to end window |
n |
|
nyrs |
|
prewhiten |
|
ar.order.max |
|
biweight |
|
This function produces a plot that is a mix of a skeleton plot and a cross-correlation plot. It’s used in crossdating.
The top panel shows the normalized values for the master chronology (bottom half) and the series (top half) in green. The values are the detrended and standardized data (e.g., RWI).
Similarly, the black lines are a skeleton plot for the master and series with the marker years annotated for the master on the bottom axis and series on the top. The text at the top of the figure gives the correlation between the series and master (green bars) as well as the percentage of agreement between the years of skeleton bars for the series and master. I.e., if all the black lines occur in the same years the percentage would be 100%.
The bottom panels show cross correlations for the first half (left)
and second half of the time series using function ccf as
ccf(x=series,y=master,lag.max=5).
The plot is built using the Grid package which
allows for great flexibility in building complicated plots. However,
these plots look best when they don’t cover too wide a range
of years (unless the plotting device is wider than is typical). For
that reason the user will get a warning if win.width is
greater than 100 years.
Old-school skeleton plots to print on paper are made with skel.plot.
None. Invoked for side effect (plot).
Andy Bunn. Patched and improved by Mikko Korpela.
library(utils) data(co021) dat <- co021 ## Create a missing ring: delete the 1500 ring of series 641143 and ## drop the original from the master. Dated from the bark, every ring ## before 1500 now sits one year late. bad.series <- dat$"641143" names(bad.series) <- rownames(dat) bad.series <- delete.ring(bad.series, year = 1500) dat$"641143" <- NULL ## after 1500 the dating is right xskel.plot(rwl = dat, series = bad.series, win.start = 1550) ## this window straddles the missing ring xskel.plot(rwl = dat, series = bad.series, win.start = 1475)library(utils) data(co021) dat <- co021 ## Create a missing ring: delete the 1500 ring of series 641143 and ## drop the original from the master. Dated from the bark, every ring ## before 1500 now sits one year late. bad.series <- dat$"641143" names(bad.series) <- rownames(dat) bad.series <- delete.ring(bad.series, year = 1500) dat$"641143" <- NULL ## after 1500 the dating is right xskel.plot(rwl = dat, series = bad.series, win.start = 1550) ## this window straddles the missing ring xskel.plot(rwl = dat, series = bad.series, win.start = 1475)
zof.rwl This data set gives the pith offsets, distance to pith, and diameter that match the ring widths for zof.rwl – a data set of European Beech (Fagus sylvatica) increment cores collected at the Zofingen in Switzerland.
data(zof.anc)data(zof.anc)
A data.frame containing four columns. Column one gives the series ID. Column two (PO) gives the number of rings estimated to be missing to the pith. Column three (d2pith) gives the estimated distance to the pith (mm). Column four (diam) gives the diameter at breast height (DBH) in cm.
Contributed by Stefan Klesse
Klesse, S., Babst, F., Lienert, S., Spahni, R., Joos, F., Bouriaud, O., Carrer, M., Filippo, A.D., Poulter, B., Trotsiuk, V., Wilson, R., Frank, D.C. (2018) A combined tree ring and vegetation model assessment of European forest growth sensitivity to interannual climate variability. Global Biogeochemical Cycles 32, 1226 – 1240.
This data set includes ring-width measurements for European Beech (Fagus sylvatica) increment cores collected at the Zofingen in Switzerland. There are 61 series.
data(zof.rwl)data(zof.rwl)
A data.frame containing 61 ring-width series in columns and 156
years in rows.
Contributed by Stefan Klesse
Klesse, S., Babst, F., Lienert, S., Spahni, R., Joos, F., Bouriaud, O., Carrer, M., Filippo, A.D., Poulter, B., Trotsiuk, V., Wilson, R., Frank, D.C. (2018) A combined tree ring and vegetation model assessment of European forest growth sensitivity to interannual climate variability. Global Biogeochemical Cycles 32, 1226 – 1240.