content
stringlengths 0
14.9M
| filename
stringlengths 44
136
|
---|---|
#' @title Change-points detected by WBS or BS
#' @description The function applies user-specified stopping criteria to extract change-points from \code{object}
#' generated by \code{\link{wbs}} or \code{\link{sbs}}. For \code{object} of class 'sbs', the function returns
#' change-points whose corresponding test statistic exceeds threshold given in \code{th}. For \code{object} of class 'wbs',
#' the change-points can be also detected using information criteria with penalties specified in \code{penalty}.
#' @details
#' For the change-point detection based on thresholding (\code{object} of class 'sbs' or 'wbs'), the user can either specify the thresholds in \code{th} directly,
#' determine the maximum number \code{Kmax} of change-points to be detected, or let \code{th} depend on \code{th.const}.
#'
#' When \code{Kmax} is given, the function automatically sets \code{th} to the lowest threshold such that the number of detected change-points is lower or equal than \code{Kmax}.
#' Note that for the BS algorithm it might be not possible to find the threshold such that exactly \code{Kmax} change-points are found.
#'
#' When \code{th} and \code{Kmax} are omitted, the threshold value is set to
#' \deqn{th = sigma \times th.const \sqrt{2\log(n)},}{th=sigma * th.const* sqrt(2 log(n)),}
#' where sigma is the Median Absolute Deviation estimate of the noise level and \eqn{n}{n} is the number of elements in \code{x}.
#'
#' For the change-point detection based on information criteria (\code{object} of class 'wbs' only),
#' the user can specify both the maximum number of change-points (\code{Kmax}) and a type of the penalty used.
#' Parameter \code{penalty} should contain a list of characters with names of the functions of at least two arguments (\code{n} and \code{cpt}).
#' For each penalty given, the following information criterion is minimized over candidate sets of change-points \code{cpt}:
#' \deqn{\frac{n}{2}\log\hat{\sigma}_{k}^{2}+penalty(n,cpt),}{n/2 log(sigma_k)+ penalty(n,cpt),}
#' where \eqn{k}{k} denotes the number of elements in \eqn{cpt}{cpt}, \eqn{\hat{\sigma}_{k}}{sigma_k} is the corresponding maximum
#' likelihood estimator of the residual variance.
#' @param object an object of 'wbs' or 'sbs' class returned by, respectively, \code{\link{wbs}} and \code{\link{sbs}} functions
#' @param th a vector of positive scalars
#' @param th.const a vector of positive scalars
#' @param penalty a character vector with names of penalty functions used
#' @param Kmax a maximum number of change-points to be detected
#' @param ... further arguments that may be passed to the penalty functions
#' @return
#' \item{sigma}{Median Absolute Deviation estimate of the noise level}
#' \item{th}{a vector of thresholds}
#' \item{no.cpt.th}{the number of change-points detected for each value of \code{th}}
#' \item{cpt.th}{a list with the change-points detected for each value of \code{th}}
#' \item{Kmax}{a maximum number of change-points detected}
#' \item{ic.curve}{a list with values of the chosen information criteria}
#' \item{no.cpt.ic}{the number of change-points detected for each information criterion considered}
#' \item{cpt.ic}{a list with the change-points detected for each information criterion considered}
#' @rdname changepoints
#' @export
#' @examples
#' #we generates gaussian noise + Poisson process signal with 10 jumps on average
#' set.seed(10)
#' N <- rpois(1,10)
#' true.cpt <- sample(1000,N)
#' m1 <- matrix(rep(1:1000,N),1000,N,byrow=FALSE)
#' m2 <- matrix(rep(true.cpt,1000),1000,N,byrow=TRUE)
#' x <- rnorm(1000) + apply(m1>=m2,1,sum)
#'
#' # we apply the BS and WBS algorithms with default values for their parameters
#'
#' s <- sbs(x)
#' w <- wbs(x)
#'
#' s.cpt <- changepoints(s)
#' s.cpt
#'
#' w.cpt <- changepoints(w)
#' w.cpt
#'
#' #we can use different stopping criteria, invoking sbs/wbs functions is not necessary
#'
#' s.cpt <- changepoints(s,th.const=c(1,1.3))
#' s.cpt
#' w.cpt <- changepoints(w,th.const=c(1,1.3))
#' w.cpt
changepoints <- function(object,...) UseMethod("changepoints")
#' @method changepoints sbs
#' @export
#' @rdname changepoints
#' @importFrom stats mad var quantile
changepoints.sbs <- function(object,th=NULL,th.const=1.3,Kmax=NULL,...){
th <- as.numeric(th)
th.const <- as.numeric(th.const)
Kmax <- as.integer(Kmax)
w.cpt <- list()
w.cpt$sigma <- mad(diff(object$x)/sqrt(2))
if(length(th)) w.cpt$th <- as.numeric(th)
else if(length(Kmax)){
if(Kmax[1] < 1) stop("Kmax should be at least 1")
Kmax <- as.integer(min(nrow(object$res),Kmax))
if(Kmax < nrow(object$res)){
tmp <- sort(object$res[,5],decreasing=TRUE)
w.cpt$th <- tmp[Kmax]-min(diff(sort(unique(tmp),decreasing=FALSE)))/2
}else w.cpt$th <- 0;
}else{
w.cpt$th <- th.const * w.cpt$sigma *sqrt(2*log(object$n))
}
th.l <- length(w.cpt$th)
if(th.l) w.cpt$th <- sort(w.cpt$th)
else stop("th vector should contain at least one value")
if(NA%in%w.cpt$th) stop("th cannot contain NA's")
if(NA%in%w.cpt$Kmax) stop("Kmax cannot be NA")
if(length(Kmax)>1){
Kmax <- Kmax[1]
warning("Kmax could contain only one number")
}
res.tmp <- matrix(object$res[order(abs(object$res[,4]),decreasing=TRUE),c(3,5)],ncol=2)
w.cpt$no.cpt.th <- as.integer(rep(0,th.l))
w.cpt$cpt.th <- list()
for(i in 1:th.l)
if(nrow(res.tmp)){
res.tmp <- matrix(res.tmp[res.tmp[,2]>w.cpt$th[i],],ncol=2)
if(nrow(res.tmp)){
w.cpt$cpt.th[[i]] <- res.tmp[,1]
w.cpt$no.cpt.th[i] <- length(w.cpt$cpt.th[[i]])
}else w.cpt$cpt.th[[i]] <- NA
}else w.cpt$cpt.th[[i]] <- NA
w.cpt$Kmax <- as.integer(max(w.cpt$no.cpt.th))
return(w.cpt)
}
#' @method changepoints wbs
#' @export
#' @rdname changepoints
changepoints.wbs <- function(object,th=NULL,th.const=1.3, Kmax=50,penalty=c("ssic.penalty","bic.penalty","mbic.penalty"),...){
w.cpt <- changepoints.sbs(object,th,th.const=th.const,Kmax=NULL)
penalty <- as.character(penalty)
#ic part
if(length(penalty))
{
if(Kmax==0 || object$n<=3) {
w.cpt$cpt.ic$ssic <- w.cpt$cpt.ic$bic <- w.cpt$cpt.ic$mbic <- NA
w.cpt$no.cpt.ic[c("ssic","mbic","bic")] <- as.integer(c(0,0,0))
w.cpt$ic.curve <- list()
w.cpt$ic.curve$bic<-w.cpt$ic.curve$ssic<-w.cpt$ic.curve$mbic <- NA
if(Kmax==0){
stop("no change-poinst found, choose larger Kmax")
}else{
stop("sample size is too small")
}
}else{
w.cpt$Kmax <- as.integer(Kmax)
cpt.cand <- changepoints.sbs(object,th,th.const=1.3,Kmax=w.cpt$Kmax)$cpt.th[[1]]
if(NA%in%cpt.cand) stop("no change-poinst found, choose larger Kmax")
if(length(cpt.cand)>min(Kmax,object$n-2)) cpt.cand <- cpt.cand[1:min(Kmax,object$n-2)]
len.cpt<- length(cpt.cand)
w.cpt$ic.curve <- list()
for(j in 1:length(penalty)){
w.cpt$ic.curve[[penalty[j]]] <- rep(0,len.cpt+1)
}
if(len.cpt) for(i in len.cpt:1){
min.log.lik <- object$n/2 * log(sum((object$x - means.between.cpt(object$x,cpt.cand[1:i]))^2)/object$n)
for(j in 1:length(penalty)){
w.cpt$ic.curve[[penalty[j]]][i+1] <- min.log.lik + do.call(penalty[j],list(n=object$n,cpt=cpt.cand[1:i],...))
}
}
for(j in 1:length(penalty)){
w.cpt$ic.curve[[penalty[j]]][1] <- object$n/2 * log(var(object$x))
}
w.cpt$cpt.ic <- list()
for(j in 1:length(penalty)){
tmp <- quantile(which.min(w.cpt$ic.curve[[penalty[j]]]), .5, type=3)
if(tmp ==1){
w.cpt$cpt.ic[[penalty[j]]] <- NA
w.cpt$no.cpt.ic[penalty[j]] <- as.integer(0)
}else{
w.cpt$cpt.ic[[penalty[j]]] <- cpt.cand[1:(tmp-1)]
w.cpt$no.cpt.ic[penalty[j]] <- as.integer(tmp-1);
}
}
}
}
return(w.cpt)
}
|
/scratch/gouwar.j/cran-all/cranData/wbs/R/changepoints.R
|
#' Fixed intervals
#'
#' The function generates approximately \code{M} intervals with endpoints in \code{1},\code{2},...,\code{n}, without random drawing. This routine
#' can be used inside \code{\link{wbs}} function and is typically not called directly by the user.
#'
#' @details Function finds the minimal \code{m} such that \eqn{M\leq \frac{m(m-1)}{2}}{\code{M} <= \code{m(m-1)/2}}.
#' Then it generates \code{m} approximately equally-spaced positive integers lower than \code{n} and returns all possible intervals consisting of any two of these points.
#' @param n a number of endpoints to choose from
#' @param M a number of intervals to generate
#' @return a 2-column matrix with start (first column) and end (second column) points of an interval in each row
#' @examples
#' fixed.intervals(10,100)
#' @export fixed.intervals
#' @seealso \code{\link{random.intervals}} \code{\link{wbs}}
fixed.intervals <-
function(n,M){
n <- as.integer(n)
M <- as.integer(M)
m <- ceiling(0.5*(sqrt(8*M+1)+1))
m <- min(n,m)
M <- m*(m-1)/2
end.points <- round(c(1,seq.int(2,n-1,length.out=(m-2)),n))
intervals <- matrix(0,nrow=M,ncol=2)
k <- 0;
for(i in 1:(m-1)){
tmp <- (m-i);
intervals[(k+1):(k+tmp),1] <- rep(end.points[i],tmp)
intervals[(k+1):(k+tmp),2] <- end.points[(i+1):m]
k <- k+tmp;
}
intervals
}
|
/scratch/gouwar.j/cran-all/cranData/wbs/R/fixed.intervals.R
|
#' Means between change-points
#'
#' The function finds the average of the input vector \code{x} between change-points given in \code{cpt}.
#'
#' @param x a vector
#' @param cpt a vector of integers with localisations of change-points
#' @param ... further arguments passed to \code{mean} method
#' @return a vector of the same length as \code{x}, piecewise constant and equal to the mean between change-points given in \code{cpt}
#' @export means.between.cpt
#' @examples
#' x <- rnorm(100)+c(rep(-1,50),rep(1,50))
#' cpt <- 50
#' means.between.cpt(x,cpt)
#' w <- wbs(x)
#' cpt <- changepoints(w)
#' means.between.cpt(x,cpt=cpt$cpt.ic$sbic)
means.between.cpt <-
function(x, cpt=NULL,...) {
x <- as.numeric(x)
if(NA%in%x) stop("x vector cannot contain NA's")
n <- length(x)
if(!is.null(cpt)) cpt <- as.integer(cpt)
cpt <- cpt[!is.na(cpt)]
len.cpt <- length(cpt)
if (len.cpt) {
if(min(cpt)<1 || max(cpt)>=n) stop("change-points should be between 1 and n-1")
cpt <- sort(cpt)
}
s <- e <- rep(0, len.cpt+1)
s[1] <- 1
e[len.cpt+1] <- n
if (len.cpt) {
s[2:(len.cpt+1)] <- cpt+1
e[1:len.cpt] <- cpt
}
means <- rep(0, len.cpt+1)
for (i in 1:(len.cpt+1)) means[i] <- mean(x[s[i]:e[i]],...)
rep(means, e-s+1)
}
|
/scratch/gouwar.j/cran-all/cranData/wbs/R/means.between.cpt.R
|
#' @rdname ssic.penalty
#' @title Strengthened Schwarz Information Criterion penalty term
#' @description The function evaluates the penalty term for the strengthened Schwarz Information Criterion proposed in P. Fryzlewicz (2014). This routine is typically not called directly by the user; its name can be passed as an argument to \code{\link{changepoints}}.
#' @param n the number of observations
#' @param cpt a vector with localisations of change-points
#' @param alpha a scalar greater than one
#' @param ssic.type a string ("log" or "power")
#' @export ssic.penalty
#' @return the penalty term \eqn{k(\log(n))^{alpha}}{k(log(n))^(alpha)} for \code{ssic.penalty="log"} or \eqn{k n^{alpha}}{k * n^(alpha)} for \code{ssic.penalty="power"}, where \eqn{k}{k} denotes the number of elements in \code{cpt}
#' @references P. Fryzlewicz (2014), Wild Binary Segmentation for multiple change-point detection. Annals of Statistics, to appear. (\url{http://stats.lse.ac.uk/fryzlewicz/wbs/wbs.pdf})
#' @examples
#' x <- rnorm(300) + c(rep(1,50),rep(0,250))
#' w <- wbs(x)
#' w.cpt <- changepoints(w,penalty="ssic.penalty")
#' w.cpt$cpt.ic
ssic.penalty <- function(n,cpt,alpha=1.01,ssic.type=c("log","power")){
alpha <- as.numeric(alpha)
ssic.type <- match.arg(ssic.type)
if (ssic.type == "log") pen <- log(n)^alpha
else if (ssic.type == "power") n^alpha
k <- length(cpt)
return(k*pen)
}
#' @rdname bic.penalty
#' @title Bayesian Information Criterion penalty term
#' @description The function evaluates the penalty term for the standard Bayesian Information Criterion applied to the change-point detection problem. This routine is typically not called directly by the user; its name can be passed as an argument to \code{\link{changepoints}}.
#' @return the penalty term \eqn{k\log(n)}{k * log(n)} where \eqn{k}{k} denotes the number of elements in \code{cpt}
#' @param n the number of observations
#' @param cpt a vector with localisations of change-points
#' @examples
#' x <- rnorm(300) + c(rep(1,50),rep(0,250))
#' w <- wbs(x)
#' w.cpt <- changepoints(w,penalty="bic.penalty")
#' w.cpt$cpt.ic
#' @examples
#' x <- rnorm(300) + c(rep(1,50),rep(0,250))
#' w <- wbs(x)
#' w.cpt <- changepoints(w,penalty="bic.penalty")
#' w.cpt$cpt.ic
bic.penalty <- function(n,cpt){
k <- length(cpt)
return(k*log(n))
}
#' @rdname mbic.penalty
#' @title Modified Bayes Information Criterion penalty term
#' @description The function evaluates the penalty term for the Modified Bayes Information Criterion proposed in N. Zhang and D. Siegmund (2007). This routine is typically not called directly by the user; its name can be passed as an argument to \code{\link{changepoints}}.
#' @references N. Zhang and D. Siegmund (2007), A modified Bayes information criterion with applications to the analysis of comparative genomic hybridization data, Biometrics.
#' @param n the number of observations
#' @param cpt a vector with localisations of change-points
#' @return the penalty term \deqn{\frac{3}{2}k\log(n)+\frac{1}{2}\sum_{i=1}^{k+1}\log\frac{l_{i}}{n},}{3/2 * k * log(n)+1/2 * sum_i^k+1 log(l_i)/n,} where \eqn{k}{k} denotes the number of elements in \code{cpt} and \eqn{l_{i}}{l_i} are the lengths of the intervals between changepoints in \code{cpt}
#' @examples
#' x <- rnorm(300) + c(rep(1,50),rep(0,250))
#' w <- wbs(x)
#' w.cpt <- changepoints(w,penalty="mbic.penalty")
#' w.cpt$cpt.ic
mbic.penalty <- function(n,cpt){
k <- length(cpt)
if(k>0) 3/2 * k * log(n) + 1/2 * sum(log(diff(c(0,sort(cpt),n))/n))
else 1/2 * sum(log(diff(c(0,n))/n))
}
|
/scratch/gouwar.j/cran-all/cranData/wbs/R/penalties.R
|
#' @title Plot for an 'sbs' object
#' @description Plots the input vector used to generate 'sbs' object \code{x} with fitted piecewise constant function, equal to the mean
#' between change-points specified in \code{cpt}.
#' @details When \code{cpt} is omitted, the function automatically finds change-points
#' using \code{changepoints} function with a default value of the threshold.
#' @method plot sbs
#' @importFrom stats ts.plot
#' @importFrom graphics lines title
#' @export
#' @param x an object of class 'sbs', returned by \code{\link{sbs}}
#' @param cpt a vector of integers with localisations of change-points
#' @param ... other parameters which may be passed to \code{plot} and \code{changepoints}
#' @seealso \code{\link{sbs}} \code{\link{changepoints}}
plot.sbs <- function(x,cpt,...){
ts.plot(x$x,ylab="x",...)
if(missing(cpt)){
w.cpt <- changepoints(x,...)
print
means <- means.between.cpt(x$x,w.cpt$cpt.th[[1]])
}else{
means <- means.between.cpt(x$x,cpt)
}
lines(x=means,type="l",col="red")
title("Fitted piecewise constant function")
}
#' @title Plot for a 'wbs' object
#' @description Plots the input vector used to generate 'wbs' object \code{x} with fitted piecewise constant function, equal to the mean
#' between change-points specified in \code{cpt}.
#' @details When \code{cpt} is omitted, the function automatically finds change-points
#' using \code{changepoints} function with strengthened Schwarz Information Criterion as a stopping criterion for the WBS algorithm.
#' @method plot wbs
#' @export
#' @param x an object of class 'wbs', returned by \code{\link{wbs}}
#' @param cpt a vector of integers with localisations of change-points
#' @param ... other parameters which may be passed to \code{plot} and \code{changepoints}
#' @seealso \code{\link{wbs}} \code{\link{changepoints}} \code{\link{ssic.penalty}}
plot.wbs <- function(x,cpt,...){
if(missing(cpt)) plot.sbs(x,cpt=changepoints(x,penalty="ssic.penalty")$cpt.ic[["ssic.penalty"]],...)
else plot.sbs(x,cpt,...)
}
|
/scratch/gouwar.j/cran-all/cranData/wbs/R/plot.R
|
#' Print for a 'wbs' object
#'
#' @param x an object of class 'wbs'
#' @param ... further arguments passed to \code{print} method
#' @return NULL
#' @method print wbs
#' @export
#' @seealso \code{\link{wbs}}
print.wbs <- function(x,...){
cat("Algorithm: ")
if(x$integrated) cat("Wild Binary Segmentation integreated with standard BS\n")
else cat("Wild Binary Segmentation\n")
cat(paste("Number of intervals M =",x$M,"\n"))
cat("Type of intervals: ")
if(x$rand.intervals) cat("random\n")
else cat("fixed\n")
cat("Results: \n")
print(x$res)
}
#' Print for an 'sbs' object
#'
#' @param x an object of class 'sbs'
#' @param ... further arguments passed to \code{print} method
#' @return NULL
#' @method print sbs
#' @export
#' @seealso \code{\link{sbs}}
print.sbs <- function(x,...){
cat("Algorithm: standard Binary Segmentation\n")
cat("Results: \n")
print(x$res)
}
|
/scratch/gouwar.j/cran-all/cranData/wbs/R/print.R
|
#' Random intervals
#'
#' The function generates \code{M} intervals, whose endpoints are
#' are drawn uniformly without replacements from \code{1},\code{2},..., \code{n}. This routine can be
#' used inside \code{\link{wbs}} function and is typically not called directly by the user.
#' @param n a number of endpoints to choose from
#' @param M a number of intervals to generate
#' @return a \code{M} by 2 matrix with start (first column) and end (second column) points of an interval in each row
#' @examples
#' random.intervals(10,100)
#' @importFrom stats runif
#' @export random.intervals
#' @seealso \code{\link{fixed.intervals}} \code{\link{wbs}}
random.intervals <- function(n,M) {
n <- as.integer(n)
M <- as.integer(M)
intervals <- matrix(0,nrow=M,ncol=2)
intervals[,1] <- ceiling(runif(M)*(n-1))
intervals[,2] <- intervals[,1]+ ceiling(runif(M)*(n-intervals[,1]))
intervals
}
|
/scratch/gouwar.j/cran-all/cranData/wbs/R/random.intervals.R
|
#' @title Change-point detection via standard Binary Segmentation
#' @description The function applies the Binary Segmentation algorithm to identify potential locations of the change-points in the mean of the input vector \code{x}.
#' The object returned by this routine can be further passed to the \code{\link{changepoints}} function,
#' which finds the final estimate of the change-points based on thresholding.
#' @param x a numeric vector
#' @param ... not in use
#' @examples
#' x <- rnorm(300) + c(rep(1,50),rep(0,250))
#' s <- sbs(x)
#' s.cpt <- changepoints(s)
#' s.cpt
#' th <- c(s.cpt$th,0.7*s.cpt$th)
#' s.cpt <- changepoints(s,th=th)
#' s.cpt
#' @rdname sbs
#' @export
#' @return an object of class "sbs", which contains the following fields
#' \item{x}{the vector provided}
#' \item{n}{the length of \code{x}}
#' \item{res}{a 6-column matrix with results, where 's' and 'e' denote start-
#' end points of the intervals in which change-points candidates 'cpt' have been found;
#' column 'CUSUM' contains corresponding value of CUSUM statistic; 'min.th' is the smallest
#' threshold value for which given change-point candidate would be not added to the set of estimated
#' change-points; the last column is the scale at which the change-point has been found}
sbs <- function(x, ...) UseMethod("sbs")
#' @method sbs default
#' @export
#' @rdname sbs
sbs.default <- function(x, ...){
results <- list()
results$x <- as.numeric(x)
results$n <- length(results$x)
if(results$n <2) stop("x should contain at least two elements")
if(NA%in%results$x) stop("x vector cannot contain NA's")
if(var(x)==0) stop("x is a constant vector, change-point detection is not needed")
results$res <- matrix(.C("bs_rec_wrapper",
x = as.double(results$x),
n = as.integer(results$n),
res = double(6*(results$n-1)))$res,results$n-1,6)
colnames(results$res) <- c("s","e","cpt","CUSUM","min.th","scale")
class(results) <- "sbs"
return(results)
}
|
/scratch/gouwar.j/cran-all/cranData/wbs/R/sbs.R
|
#' @title Wild Binary Segmentation for multiple change-point detection
#' @description The package implements Wild Binary Segmentation, a technique for
#' consistent estimation of the number and locations of multiple change-points in data.
#' It also provides a fast implementation of the standard Binary Segmentation algorithm.
#' @details The main routines of the package are \code{\link{wbs}}, \code{\link{sbs}} and \code{\link{changepoints}}.
#' @references P. Fryzlewicz (2014), Wild Binary Segmentation for multiple change-point detection. Annals of Statistics, to appear. (\url{http://stats.lse.ac.uk/fryzlewicz/wbs/wbs.pdf})
#' @docType package
#' @useDynLib wbs, .registration = TRUE
#' @name wbs-package
#' @examples
#' #an example in which standard Binary Segmentation fails to detect change points
#' x <- rnorm(300)+ c(rep(0,130),rep(-1,20),rep(1,20),rep(0,130))
#'
#' s <- sbs(x)
#' w <- wbs(x)
#'
#' s.cpt <- changepoints(s)
#' s.cpt
#'
#' w.cpt <- changepoints(w)
#' w.cpt
#' # in this example, both algorithms work well
#' x <- rnorm(300) + c(rep(1,50),rep(0,250))
#'
#' s <- sbs(x)
#' w <- wbs(x)
#'
#' s.cpt <- changepoints(s)
#' s.cpt
#'
#' w.cpt <- changepoints(w)
#' w.cpt
#' @keywords ts models math
NULL
#' @title Change-point detection via Wild Binary Segmentation
#' @description The function applies the Wild Binary Segmentation algorithm to identify potential locations of the change-points in the mean of the input vector \code{x}.
#' The object returned by this routine can be further passed to the \code{\link{changepoints}} function,
#' which finds the final estimate of the change-points based on chosen stopping criteria.
#' @param x a numeric vector
#' @examples
#' x <- rnorm(300) + c(rep(1,50),rep(0,250))
#' w <- wbs(x)
#' plot(w)
#' w.cpt <- changepoints(w)
#' w.cpt
#' th <- c(w.cpt$th,0.7*w.cpt$th)
#' w.cpt <- changepoints(w,th=th)
#' w.cpt$cpt.th
#' @rdname wbs
#' @export
wbs <- function(x, ...) UseMethod("wbs")
#' @method wbs default
#' @export
#' @rdname wbs
#' @param M a number of intervals used in the WBS algorithm
#' @param rand.intervals a logical variable; if \code{rand.intervals=TRUE} intervals used in the procedure are random, thus
#' the output of the algorithm may slightly vary from run to run; for \code{rand.intervals=FALSE} the intervals used depend on \code{M} and the length of \code{x} only,
#' hence the output is always the same for given input parameters
#' @param integrated a logical variable indicating the version of Wild Binary Segmentation algorithm used; when \code{integrated=TRUE},
#' augmented version of WBS is launched, which combines WBS and BS into one
#' @param ... not in use
#' @return an object of class "wbs", which contains the following fields
#' \item{x}{the input vector provided}
#' \item{n}{the length of \code{x}}
#' \item{M}{the number of intervals used}
#' \item{rand.intervals}{a logical variable indicating type of intervals}
#' \item{integrated}{a logical variable indicating type of WBS procedure}
#' \item{res}{a 6-column matrix with results, where 's' and 'e' denote start-
#' end points of the intervals in which change-points candidates 'cpt' have been found;
#' column 'CUSUM' contains corresponding value of CUSUM statistic; 'min.th' is the smallest
#' threshold value for which given change-point candidate would be not added to the set of estimated
#' change-points; the last column is the scale at which the change-point has been found}
wbs.default <- function(x, M=5000, rand.intervals = TRUE,integrated=TRUE,...){
results <- list()
results$x <- as.numeric(x)
results$n <- length(results$x)
results$M <- as.integer(M)
results$integrated <- as.logical(integrated)
results$rand.intervals <- as.logical(rand.intervals)
results$res <- matrix(nrow=0,ncol=6)
if(results$n <2) stop("x should contain at least two elements")
if(NA%in%results$x) stop("x vector cannot contain NA's")
if(var(x)==0) stop("x is a constant vector, change-point detection is not needed")
if(is.na(results$M)) stop("M cannot be NA")
if(length(results$M)> 1) stop("M should be a single integer")
if(results$M<0) stop("M should be an integer > 0")
if(results$rand.intervals) intervals <- matrix(random.intervals(results$n,results$M),ncol=2)
else {
intervals <- matrix(fixed.intervals(results$n,results$M),ncol=2)
results$M <- nrow(intervals)
}
if(results$integrated){
results$res <- matrix(.C("wbs_int_rec_wrapper",
x = as.double(results$x),
n = as.integer(results$n),
res = double(6*(results$n-1)),
intervals = as.integer(intervals),
M = as.integer(results$M))$res,results$n-1,6)
}else{
results$res <- matrix(.C("wbs_rec_wrapper",
x = as.double(results$x),
n = as.integer(results$n),
res = double(6*(results$n-1)),
intervals = as.integer(intervals),
M = as.integer(results$M))$res,results$n-1,6)
results$res <- matrix(results$res[as.integer(results$res[,1])>0,],ncol=6)
}
colnames(results$res) <- c("s","e","cpt","CUSUM","min.th","scale")
class(results) <- "wbs"
results$cpt <- changepoints(results)
return(results)
}
|
/scratch/gouwar.j/cran-all/cranData/wbs/R/wbs.R
|
# Generated by using Rcpp::compileAttributes() -> do not edit by hand
# Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393
rrank <- function(A, tol) {
.Call('_wbsd_rrank', PACKAGE = 'wbsd', A, tol)
}
rkernel <- function(A, tol) {
.Call('_wbsd_rkernel', PACKAGE = 'wbsd', A, tol)
}
ctest <- function(umat, Rbmat, Wvec, Bmat, cores, tol) {
.Call('_wbsd_ctest', PACKAGE = 'wbsd', umat, Rbmat, Wvec, Bmat, cores, tol)
}
|
/scratch/gouwar.j/cran-all/cranData/wbsd/R/RcppExports.R
|
#
# Copyright (C) 2020 David Preinerstorfer
# [email protected]
#
# This file is a part of wbsd.
#
# wbsd is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. A copy may be obtained at
# http://www.r-project.org/Licenses/
###########################################################################
###########################################################################
#
# Wrapper function for test statistic of the form (in case y is vector):
#
# ``(R\hat{\beta}(y) - rboot)' VCESTIMATOR^{-1} (R\hat{\beta}(y) - rboot)''
#
# here \hat{\beta} denotes the OLS estimator
# and VCESTIMATOR is a covariance matrix estimator that might be based
# on restricted or unrestricted residuals (restriction: R\beta = r);
# (the choice of restricted or unrestricted residuals also has an effect
# on the weights in the construction of the HC1 - HC4 estimators)
#
###########################################################################
###########################################################################
F.wrap <- function(
y, #matrix (n rows) of observations
R, #restriction matrix (q times k, rank q)
r, #right-hand side in restriction (q-vector)
rboot, #centralisation used in test statistic (typically equal to r;
#but in case of bootstrap with unrestricted centering required
#to be ``R \hat{\beta} (y)''); (q-vector)
X, #design matrix (n times k, rank k)
n, #sample size
k, #number of columns of X
q, #number of rows of R
qrX, #qr decomposition of X
hcmethod, #-1:4; -1 = classical F-test without df adjustment; 0 = HC0, 1 = HC1, etc.
cores, #number of cores used in computation
restr.cov, #Covariance Matrix estimator computed with restricted residuals (TRUE or FALSE)
Bfac, #R(X'X)^{-1}X' (cf. function Bfactor.matrix below)
Bfac2, #(R(X'X)^(-1)R')^(-1) (cf. function Bfactor.matrix2 below)
qrM0lin, #qr decomposition of M0lin (cf. function M0lin below)
RF, #RF = (X'X)^(-1)R'(R(X'X)^(-1)R')^(-1) used in res.OLSRF (cf. below)
tol #tolerance parameter used in checking invertibility of VCESTIMATOR in test statistic
#nonpositive numbers are reset to tol = machine epsilon (.Machine$double.eps)
#if VCESTIMATOR is not invertible, -1 is returned
#if VCESTIMATOR is invertible, the test statistic is always nonnegative
){
#computation of residuals and weights used in the construction of the covariance matrix estimators
if(restr.cov == TRUE){
umat <- res.OLSRF(y, qrX, R, r, RF)$Res.res
Wmat <- wvec(k-q, n, qrM0lin, hcmethod)
}
if(restr.cov == FALSE){
umat <- qr.resid(qrX, y)
Wmat <- wvec(k, n, qrX, hcmethod)
}
Rbmat <- R %*% qr.coef(qrX, y) - matrix(rboot, byrow = FALSE, nrow = q, ncol = dim(y)[2])
if(hcmethod == -1){
if(tol <= 0){
tol <- .Machine$double.eps
}
df <- n-(k - restr.cov*q)
var.est <- apply(umat^2,2,sum)/df
nonzero <- (var.est > tol)
test.val <- nonzero*1
CBFac <- chol(Bfac2)
Wmat <- CBFac%*%Rbmat
Wmat <- apply(Wmat^2, 2, sum)
test.val[test.val == 1] <- (Wmat[test.val == 1]/var.est[test.val == 1])
test.val[test.val == 0] <- -1
} else {
test.val <- .Call('_wbsd_ctest', PACKAGE = 'wbsd', umat, Rbmat, Wmat, Bfac, cores, tol)
}
return(test.val)
}
###########################################################################
###########################################################################
#
# Bootstrap Sample Generation
#
# Given observation y, generate sample
#
# Xbeta.est(y) + diag(res(y)) xi
#
# Here res(y) can be the restricted or unrestricted OLS residuals,
# depending on whether boot.res.restr is TRUE or FALSE, respectively,
# and beta.est can be a null-restricted or unrestricted OLS estimator
# depending on whether boot.center.restr is TRUE or FALSE, respectively.
#
###########################################################################
###########################################################################
boot.sample <- function(
#INPUT
y, #matrix (n times 1) of observations
xi, #bootstrap xis (matrix n rows, each column is a bootstrap obs)
qrX, #qr decomposition of X (n times k, rank k)
R, #restriction matrix (q times k, rank q)
r, #right-hand side in restriction to be tested (q-vector)
boot.res.restr, #bootstrap variances using restr. residuals (FALSE or TRUE)
boot.center.restr, #bootstrap centers using restr. residuals (FALSE or TRUE)
RF = NULL #RF = (X'X)^(-1)R'(R(X'X)^(-1)R')^(-1) used in res.OLSRF (cf. below)
#RF is only used in case boot.res.restr or boot.center.restr is TRUE
)
{
# compute restricted OLS estimator and residuals if needed
if(boot.res.restr == TRUE | boot.center.restr == TRUE){
rer <- res.OLSRF(y, qrX, R, r, RF)
}
# obtain residuals from original sample (unrestricted or restricted)
if(boot.res.restr == FALSE){
boot.res <- qr.resid(qrX, y)
} else {
boot.res <- rer$Res.res
}
# compute the center of the bootstrap samples (unrestricted or restricted)
if(boot.center.restr == FALSE){
boot.cen <- qr.fitted(qrX, y)
} else {
boot.cen <- qr.X(qrX)%*%rer$Coef.restr
}
boot.cen <- matrix(rep(boot.cen, times = dim(xi)[2]),
nrow = dim(xi)[1], ncol = dim(xi)[2], byrow = FALSE)
# combine and return bootstrap sample
return(boot.cen + diag(c(boot.res))%*%xi)
}
###########################################################################
###########################################################################
#
# Check if a given design matrix X satisfies Assumption 1 or 2
# whether Assumption 1 or 2 is checked depends on the input qr decomposition
#
# if the qr decomposition of X is provided, Assumption 1 is checked
# if the qr decomposition of a basis of M0lin is provided, Assumption 2 is
# checked
#
# Bfac = R(X'X)^{-1} X' (cf. the function Bfactor.matrix below)
#
###########################################################################
###########################################################################
As.check <- function(
qrXM, #qr decomposition X (n times k, rank k), or of a basis of
#M0lin (n times (k-q), rank (k-q), cf. function M0lin below)
#in the function we abbreviate ``k-q'' by l
Bfac, #R(X'X)^{-1}X' (cf. function Bfactor.matrix below)
q, #number of rows of restriction matrix R
as.tol #tolerance parameter used in checking Assumptions 1 or 2, respectively
#nonpositive numbers are reset to as.tol = machine epsilon (.Machine$double.eps)
){
XM <- qr.X(qrXM)
n <- dim(XM)[1]
l <- dim(XM)[2]
#if l == 0, the Assumption to be checked automatically satisfied
if(l == 0){
return(TRUE)
} else {
#if l != 0, do the following:
e0 <- matrix(0, nrow = n, ncol = 1)
ind <- rep(NA, length = n)
#check whether elements of the canonical basis are in the span of XM
for(i in 1:n){
ei <- e0
ei[i,1] <- 1
ind[i] <- ( rrank(cbind(XM, ei), as.tol) > l )
}
#if all entries of ind are TRUE, the Assumption is automatically
#satisfied, because of the rank assumptions on R and X
#if there are entries of ind that are FALSE, the Assumption
#has to be checked via a rank computation
if(sum(ind) == n){
return ( TRUE )
} else {
return( rrank(Bfac[, ind, drop=FALSE], as.tol) == q )
}
}
}
###########################################################################
###########################################################################
#
# Compute the
#
# rank of a matrix based on the Eigen FullPivLU decomposition
#
# in case input is a matrix with one column or with one row, the
# function checks if the maximal absolute entry of the input exceeds tol
#
############################################################################
############################################################################
rrank <- function(
A, #input matrix
tol #tolerance parameter passed to Eigen FullPivLU decomposition;
#if tolerance parameter is nonpositive, tol is reset to machine epsilon
){
if(min(dim(A)) == 1){
if(tol <= 0){
tol <- .Machine$double.eps
}
(max(abs(A)) > tol)*1
} else {
.Call('_wbsd_rrank', PACKAGE = 'wbsd', A, tol)
}
}
###########################################################################
###########################################################################
#
# Compute the
#
# kernel of a matrix based on the Eigen FullPivLU decomposition
#
###########################################################################
###########################################################################
rkernel <- function(
A, #input matrix
tol #tolerance parameter passed to Eigen FullPivLU decomposition;
#if tolerance parameter is nonpositive, tol is reset to machine epsilon
){
.Call('_wbsd_rkernel', PACKAGE = 'wbsd', A, tol)
}
###########################################################################
###########################################################################
#
# Basis of $M_0^{lin} = \{y \in \mathbb{R}^n: y = Xb, Rb = 0\}$
#
#Computation is based on function rkernel with tol = -1
#
# In case q = k, i.e., M_0^{lin} = (0), output vector of dimension n times 0
#
###########################################################################
###########################################################################
M0lin <- function(
X, #input matrix (n times k, rank k)
R #restriction matrix (q times k, rank q)
){
if(dim(R)[1] == dim(X)[2]){
return(X[,-(1:dim(X)[2])])
} else {
X%*%rkernel(R, -1)
}
}
###########################################################################
###########################################################################
#
# Compute the matrix
#
# R(X'X)^(-1)X'
#
###########################################################################
###########################################################################
Bfactor.matrix <- function(
qrX, #qr decomposition of X (n times k, rank k)
n, #number of rows of X
R = FALSE #restriction matrix R (q times k, rank q)
#if R = FALSE, then (X'X)^(-1)X' is returned
){
A <- qr.coef(qrX, diag(n))
if(is.matrix(R) == TRUE){
return(R%*%A)
} else {
return(A)
}
}
###########################################################################
###########################################################################
#
# Compute the matrix
#
# (R(X'X)^(-1)R')^(-1)
#
###########################################################################
###########################################################################
Bfactor.matrix2 <- function(
qrX, #qr decomposition of X (n times k, rank k)
R #restriction matrix R (q times k, rank q)
){
factor.tmp <- qr.R(qrX)
factor.tmp <- R%*% backsolve(qr.R(qrX), diag(dim(factor.tmp)[1]))
Bfactor2 <- solve(tcrossprod(factor.tmp))
return(Bfactor2)
}
###########################################################################
###########################################################################
#
# Generate the
#
# weights d_i (unrestricted case) or \tilde{d}_i (restricted case)
#
# used in the construction of the covariance estimators H0 - H4
#
# Whether d_i or \tilde{d}_i is generated is via qrXM, which determines the
# hat matrix used
#
###########################################################################
###########################################################################
wvec <- function(
l, #see description of qrXM
n, #see description of qrXM
qrXM, #qr decomposition of matrix XM (n times l, rank l)
#weights are based on the diag of hat matrix corresp. to XM
hcmethod #0-4 (HC0, HC1, HC2, HC3, HC4)
){
if(hcmethod == 0 | l == 0){
return(rep(1, length = n))
}
if(hcmethod == 1){
return(rep(n/(n-l), length = n))
}
Q <- qr.Q(qrXM)
H <- diag(tcrossprod(Q,Q))
H[H == 1] <- 0
h <- 1/(1-H)
if(hcmethod == 2){
return(h)
}
if(hcmethod == 3){
return(h^2)
}
if(hcmethod == 4){
delta <- sapply(n*H/l, function(x) {min(4, x)})
return(h^delta)
}
}
###########################################################################
###########################################################################
#
# Function that computes
#
# restricted OLS estimators and restricted residuals
#
###########################################################################
###########################################################################
res.OLSRF <- function(
y, #matrix (n rows) of observations
qrX, #qr decomposition of X (n times k, rank k)
R, #restriction matrix (q times k, rank q)
r, #right-hand side in the restriction (q-vector)
RF #RF = (X'X)^(-1)R'(R(X'X)^(-1)R')^(-1)
){
OLS.coef <- qr.coef(qrX, y)
OLS.coefs.restr <- OLS.coef - RF%*%R%*%OLS.coef
OLS.coefs.restr <- OLS.coefs.restr + matrix(RF%*%r, nrow = dim(R)[2], ncol = dim(y)[2])
OLS.res.restr <- y - qr.X(qrX)%*%OLS.coefs.restr
return(list("Coef.restr" = OLS.coefs.restr,
"Res.res" = OLS.res.restr))
}
###########################################################################
###########################################################################
#
# Generator of support points of bootstrap distribution on {-1,1}^n
# Either Rademacher or Mammen probabilities
# B.sample = number of bootstrap samples
# Returns an n x B.sample matrix
#
###########################################################################
###########################################################################
XI.generator <- function(wilddist, n, B.sample){
check.wilddist(wilddist)
if(wilddist == "rademacher"){
XI <- matrix(sample(c(-1, 1), size = n * B.sample,
replace = TRUE, prob = c(.5,.5)), ncol = B.sample, nrow = n)
}
if(wilddist == "mammen"){
XI <- matrix(sample(c(-(sqrt(5)-1)/2, (sqrt(5)+1)/2), size = n * B.sample,
replace = TRUE, prob = c((sqrt(5)+1)/(2*sqrt(5)),
(sqrt(5)-1)/(2*sqrt(5)))), ncol = B.sample, nrow = n)
}
return(XI)
}
###########################################################################
###########################################################################
#
# Check if a given design matrix X allows a size-controlling critical value
# Bfac = R(X'X)^{-1} X' (cf. the function Bfactor.matrix below)
#
# Returns TRUE if a size-controlling CV exists, FALSE else.
#
###########################################################################
###########################################################################
ExC.check <- function(
X, #X
R, #R
as.tol #tolerance parameter used in checking rank conditions
){
n <- dim(X)[1]
k <- dim(X)[2]
q <- dim(R)[1]
e0 <- matrix(0, nrow = n, ncol = 1)
XM <- M0lin(X, R)
l <- dim(XM)[2]
qrX <- qr(X)
Bfac <- Bfactor.matrix(qrX, n, R)
#check condition for every index such that ei notin span(XM)
v <- c()
for(i in 1:n){
ei <- e0
ei[i,1] <- 1
if( ( rrank(cbind(XM, ei), as.tol) > l ) ){
A <- Bfac %*% diag(c(qr.resid(qrX, ei)))
v <- c(v, rrank(A, as.tol))
}
}
return(!( length(v[v < q])>0 ))
}
###########################################################################
###########################################################################
#
# Input checks to function ``theta''
#
###########################################################################
###########################################################################
check.X.R <- function(X, R){
if( !is.matrix(X) ){
stop("Invalid 'X' value - must be a matrix")
}
if( !is.matrix(R) ) {
stop("Invalid 'R' value - must be a matrix")
}
if( dim(X)[2] >= dim(X)[1] ){
stop("Number of columns of 'X' is not smaller than its number of rows")
}
if( dim(X)[2] == 0 ){
stop("Number of rows of 'X' must be greater than 0")
}
if( dim(X)[2] != dim(R)[2] ) {
stop("Matrices 'X' and 'R' have different numbers of columns")
}
if( rrank(X, -1) < dim(X)[2] ) {
stop("The matrix 'X' is numerically of rank < k")
}
if( rrank(R, -1) < dim(R)[1] ) {
stop("The matrix 'R' is numerically of rank < q")
}
}
check.r <- function(r, R){
if( !is.vector(r) | !is.numeric(r) | (length(r) != dim(R)[1])){
stop("Invalid 'r' value - 'r' must be a real vector
the length of which coincides with the number of rows of R")
}
}
check.hcmethod <- function(hcmethod){
if(length(hcmethod) != 1 | sum(c(-1:4) == hcmethod) != 1) {
stop("Invalid 'hcmethod' value - 'hcmethod' must be -1, 0, 1, 2, 3, or 4")
}
}
check.restr.cov <- function(restr.cov){
if(!is.logical(restr.cov) | length(restr.cov) != 1){
stop("Invalid 'restr.cov' value - 'restr.cov' must be TRUE or FALSE")
}
}
check.wilddist <- function(wilddist){
if(length(wilddist)!= 1 | sum(c("mammen", "rademacher") == wilddist) != 1) {
stop("Invalid 'wilddist' value - 'wilddist' must be 'mammen' or 'rademacher' ")
}
}
check.wildmult <- function(wildmult){
if(length(wildmult) != 1 | sum(c(0:4) == wildmult) != 1) {
stop("Invalid 'wildmult' value - 'wildmult' must be 0, 1, 2, 3, or 4")
}
}
check.wildmult.restr <- function(wildmult.restr){
if(!is.logical(wildmult.restr) | length(wildmult.restr) != 1){
stop("Invalid 'wildmult.restr' value - 'wildmult.restr' must be TRUE or FALSE")
}
}
check.boot.res.restr <- function(boot.res.restr){
if(!is.logical(boot.res.restr) | length(boot.res.restr) != 1) {
stop("Invalid 'boot.res.restr' value - 'boot.res.restr' must be TRUE or FALSE")
}
}
check.boot.center.restr <- function(boot.center.restr){
if(!is.logical(boot.center.restr) | length(boot.center.restr) != 1){
stop("Invalid 'boot.center.restr' value - 'boot.center.restr' must be TRUE or FALSE")
}
}
check.tol <- function(tol){
if(!is.numeric(tol) | length(tol) != 1){
stop("Invalid 'tol' value - 'tol' must be a real number")
}
if(tol > .1){
warning("Tolerance parameter 'tol' should typically be chosen small, e.g., 1e-07;
your choice seems unusually large, and might yield wrong results.")
}
if(tol <= 0){
warning("Your non-positive 'tol' parameter was converted to tol = machine epsilon")
}
}
check.as.tol <- function(as.tol){
if(!is.numeric(as.tol) | length(as.tol) != 1){
stop("Invalid 'as.tol' value - 'as.tol' must be a real number")
}
if(as.tol > .1){
warning("Tolerance parameter 'as.tol' should typically be chosen small, e.g., 1e-07;
your choice seems unusually large, and might yield wrong results.")
}
if(as.tol <= 0){
warning("Your non-positive 'as.tol' parameter was converted to as.tol = machine epsilon")
}
}
check.in.tol <- function(in.tol){
if(!is.numeric(in.tol) | length(in.tol) != 1){
stop("Invalid 'in.tol' value - 'in.tol' must be a real number")
}
if(in.tol > .1){
warning("Tolerance parameter 'in.tol' should typically be chosen small, e.g., 1e-07;
your choice seems unusually large, and might yield wrong results.")
}
if(in.tol <= 0){
warning("Your non-positive 'in.tol' parameter was converted to in.tol = machine epsilon")
}
}
check.comp.meth <- function(comp.meth){
if(length(comp.meth)!= 1 | sum(c("exact", "approximation") == comp.meth) != 1){
stop("Invalid 'comp.meth' value - 'comp.meth' must be 'exact' or 'approximation'")
}
}
check.Boot.supp <- function(Boot.supp, comp.meth, n){
if(comp.meth == "approximation"){
if(!is.matrix(Boot.supp) | !is.numeric(Boot.supp) | dim(Boot.supp)[1] != n | dim(Boot.supp)[2] < 1){
stop("Invalid 'Boot.supp' value - 'Boot.supp' must be a real matrix with n rows")
}
}
}
check.checks <- function(checks){
if(!is.logical(checks) | length(checks) != 1){
stop("Invalid 'checks' value - 'checks' must be TRUE or FALSE")
}
}
check.cores <- function(cores){
if( cores%%1 != 0 | cores <= 0) {
stop("Invalid 'cores' value - 'cores' must be a positive integer")
}
}
#additional check in the boot.pval function
check.y <- function(y, X){
if( !is.matrix(y) ){
stop("Invalid 'y' value - must be a matrix")
}
if( dim(y)[1] != dim(X)[1]){
stop("Invalid 'y' value - must be a matrix with n rows")
}
}
|
/scratch/gouwar.j/cran-all/cranData/wbsd/R/auxiliary.functions.R
|
#
# Copyright (C) 2020 David Preinerstorfer
# [email protected]
#
# This file is a part of wbsd.
#
# wbsd is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. A copy may be obtained at
# http://www.r-project.org/Licenses/
###########################################################################
###########################################################################
#
# Compute a bootstrap p value for each column vector of a matrix y.
#
#
###########################################################################
###########################################################################
boot.pval <- function(
#INPUT
y, #matrix (n rows) of observations (lhs)
X, #design matrix (n times k, rank k)
R, #restriction matrix (q times k, rank q)
r, #right-hand side in restriction (q-vector)
hcmethod, #-1:4; chi2-Test (no df adjustmen), HC0-HC4
restr.cov, #Covariance Matrix estimator based on restriction (TRUE or FALSE)
wilddist, #Rademacher or Mammen errors in bootstrap samples (only used if comp.meth = "exact")
wildmult, #Multiplicator used in bootstrap errors, 0:4 HC0-HC4 weights
wildmult.restr, #bootstrap multipliers based on restricted hat matrix (TRUE or FALSE)
boot.res.restr, #bootstrap sample residuals based on restricted res (TRUE or FALSE)
boot.center.restr, #bootstrap sample centered at restricted res (TRUE or FALSE)
tol = 1e-07, #tolerance parameter used in checking invertibility of the covariance matrix in F stat
comp.meth = "exact", #computation of theta ``exact'' or ``approximation''
Boot.supp = NULL, #Support bootstrap sample (matrix, n rows, columns = number of bootstrap samples)
#only used if comp.meth = ``approximation'';
#Boot.supp is subsequently further multiplied by wildmult weights
#can be generated via auxiliary function: XI.generator
checks = TRUE, #run input checks (TRUE or FALSE)
cores = 1 #maximal number of cores used in the computations
)
{
###########################################################################
# Run checks if checks == TRUE
###########################################################################
if(checks == TRUE){
check.y(y, X)
check.X.R(X, R)
check.r(r, R)
check.hcmethod(hcmethod)
check.restr.cov(restr.cov)
check.wilddist(wilddist)
check.wildmult(wildmult)
check.wildmult.restr(wildmult.restr)
check.boot.res.restr(boot.res.restr)
check.tol(tol)
check.comp.meth(comp.meth)
check.Boot.supp(Boot.supp, comp.meth, dim(X)[1])
check.checks(checks)
check.cores(cores)
}
###########################################################################
# Elementary quantities
###########################################################################
n <- dim(X)[1] #sample size
k <- dim(X)[2] #number of regressors
q <- length(r) #number of restrictions
e0 <- matrix(0, nrow = n, ncol = 1) #vector of zeros of length n
qrX <- qr(X) #qr decomposition of X
qrM0lin <- qr(M0lin(X, R)) #qr decomp of basis of M0lin = M0-mu0
Bfac <- Bfactor.matrix(qrX, n, R) #R(X'X)^{-1}X'
Bfac2 <- Bfactor.matrix2(qrX, R) #(R(X'X)^{-1}R')^{-1}
###########################################################################
# Prepare input RF for function res.OLSRF (restricted OLS est + resid)
# [only if needed]
# RF = (X'X)^(-1)R'(R(X'X)^(-1)R')^(-1) = (X'X)^(-1)R' %*% Bfac2
# in case q = k, RF = R^{-1}
###########################################################################
if(boot.res.restr == TRUE | boot.center.restr == TRUE | restr.cov == TRUE){
if(q < k){
factor.tmp2 <- tcrossprod( backsolve(qr.R(qrX), diag(k)) )
RF <- factor.tmp2%*%t(R)%*%Bfac2
} else {
RF <- solve(R)
}
} else {
RF <- NULL
}
###########################################################################
# Generate an element of M0: mu0
###########################################################################
if(max(abs(r)) > 0){
mu0 <- X%*%qr.solve(R, r) #assign element of M0
} else {
mu0 <- e0 # if r = 0, then zero vector is in M0lin
}
###########################################################################
#Prepare wild bootstrap multiplier weights
###########################################################################
#restricted
if(wildmult.restr == TRUE){
bootmult <- c(sqrt(wvec(k-q, n, qrM0lin, wildmult)))
}
#unrestricted
if(wildmult.restr == FALSE){
bootmult <- c(sqrt(wvec(k, n, qrX, wildmult)))
}
###########################################################################
# Generate the support set of the bootstrap sample distribution in case
# of exact computation; compute the probabilities, under which
# each support point is attained under a Rademacher or Mammen measure.
###########################################################################
if(comp.meth == "exact"){
if(n >= 20){
warning("Sample size n might be too large for choosing comp.meth = exact.")
}
#In case wilddist = Rademacher:
#Collect the set of all (2^n) elemts of \{-1, 1\}^n in an (2^n x n) matrix
#In case wilddist = Mammen:
#Collect the set of all (2^n) elemts of \{-(sqrt(5)-1)/2, (sqrt(5)+1)/2\}^n
#in an (2^n x n) matrix
if( wilddist == "Rademacher" ){
XI <- as.matrix(expand.grid(replicate(n, c(-1,1), simplify = FALSE)))
} else {
XI <- as.matrix(expand.grid(replicate(n, c(-(sqrt(5)-1)/2, (sqrt(5)+1)/2),
simplify = FALSE)))
}
#Multiply the vectors generated with the bootstrap multiplicators bootmult
XI <- XI%*%diag(bootmult)
#Compute the probability of each row in XI under an n-fold product of
#Rademacher or Mammen distributions
#the probabilities of all coordinates in XI under independent
#Rademacher distributions
if(wilddist == "rademacher"){
probs <- expand.grid(replicate(n, c(.5,.5), simplify = FALSE))
}
#the probabilities of all coordinates in XI under independent
#Mammen distributions
if(wilddist == "mammen"){
probs <- expand.grid(replicate(n, c((sqrt(5)+1)/(2*sqrt(5)),
(sqrt(5)-1)/(2*sqrt(5))), simplify = FALSE))
}
#combine to get the probability of each row of XI under Rademacher or
#Mammen distributions
probs <- apply(probs,1,prod)
}
###########################################################################
# Generate the support set of the bootstrap sample distribution in case
# of approximate computation; i.e., transpose input Boot.supp, and multiply by
# diag(bootmult)
###########################################################################
if(comp.meth == "approximation"){
XI <- t(Boot.supp)%*%diag(bootmult)
}
###########################################################################
# Computation of the bootstrap p values
###########################################################################
#create storage space for p-values and compute test statistic on data y
pvals <- rep(NA, length = dim(y)[2])
Tvals.comp <- F.wrap(y, R, r, r, X, n, k, q, qrX,
hcmethod, cores, restr.cov,
Bfac, Bfac2, qrM0lin, RF, tol)
for(i in 1:dim(y)[2]){
#generate the bootstrap sample
Ystar <- boot.sample(y[,i, drop = FALSE], t(XI), qrX,
R, r, boot.res.restr, boot.center.restr, RF)
if(boot.center.restr == FALSE){
rstar <- R%*%qr.coef(qrX, y[,i])
} else {
rstar <- r
}
Tvalsboot <- F.wrap(Ystar, R, r, rstar, X, n, k, q, qrX,
hcmethod, cores, restr.cov,
Bfac, Bfac2, qrM0lin, RF, tol)
select.support <- ( (Tvalsboot >= Tvals.comp[i]) | (Tvalsboot == -1) )
if(comp.meth == "approximation"){
pvals[i] <- mean(select.support)
} else {
pvals[i] <- sum((probs[select.support]))
}
}
return(list("p" = pvals))
}
|
/scratch/gouwar.j/cran-all/cranData/wbsd/R/boot.pval.R
|
#
# Copyright (C) 2020 David Preinerstorfer
# [email protected]
#
# This file is a part of wbsd.
#
# wbsd is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. A copy may be obtained at
# http://www.r-project.org/Licenses/
###########################################################################
###########################################################################
#
# Compute theta.
#
# For all alpha < theta the size of the respective bootstrap-based test
# is one.
#
###########################################################################
###########################################################################
theta <- function(
#INPUT
X, #design matrix (n times k, rank k)
R, #restriction matrix (q times k, rank q)
r, #right-hand side in restriction (q-vector)
hcmethod, #-1:4; chi2-Test (no df adjustmen), HC0-HC4
restr.cov, #Covariance Matrix estimator based on restriction (TRUE or FALSE)
wilddist, #Rademacher or Mammen errors in bootstrap samples (only used if comp.meth = "exact")
wildmult, #Multiplicator used in bootstrap errors, 0:4 HC0-HC4 weights
wildmult.restr, #bootstrap multipliers based on restricted hat matrix (TRUE or FALSE)
boot.res.restr, #bootstrap sample residuals based on restricted res (TRUE or FALSE)
boot.center.restr, #bootstrap sample centered at restricted res (TRUE or FALSE)
tol = 1e-07, #tolerance parameter used in checking invertibility of the covariance matrix in F stat
as.tol = 1e-07, #tolerance parameter used in checking Assumptions 1 or 2, respectively
in.tol = 1e-05, #tolerance parameter used in checking the strict inequality in the thetat computation
comp.meth = "exact", #computation of theta ``exact'' or ``approximation''
Boot.supp = NULL, #Support bootstrap sample (matrix, n rows, columns = number of bootstrap samples)
#only used if comp.meth = ``approximation'';
#Boot.supp is subsequently further multiplied by wildmult weights
#can be generated via auxiliary function: XI.generator
checks = TRUE, #run input checks (TRUE or FALSE)
cores = 1 #maximal number of cores used in the computations
)
{
###########################################################################
# Run checks if checks == TRUE
###########################################################################
if(checks == TRUE){
check.X.R(X, R)
check.r(r, R)
check.hcmethod(hcmethod)
check.restr.cov(restr.cov)
check.wilddist(wilddist)
check.wildmult(wildmult)
check.wildmult.restr(wildmult.restr)
check.boot.res.restr(boot.res.restr)
check.tol(tol)
check.as.tol(as.tol)
check.in.tol(in.tol)
check.comp.meth(comp.meth)
check.Boot.supp(Boot.supp, comp.meth, dim(X)[1])
check.checks(checks)
check.cores(cores)
}
###########################################################################
# Elementary quantities
###########################################################################
n <- dim(X)[1] #sample size
k <- dim(X)[2] #number of regressors
q <- length(r) #number of restrictions
e0 <- matrix(0, nrow = n, ncol = 1) #vector of zeros of length n
qrX <- qr(X) #qr decomposition of X
qrM0lin <- qr(M0lin(X, R)) #qr decomp of basis of M0lin = M0-mu0
Bfac <- Bfactor.matrix(qrX, n, R) #R(X'X)^{-1}X'
Bfac2 <- Bfactor.matrix2(qrX, R) #(R(X'X)^{-1}R')^{-1}
###########################################################################
# In case hcmethod \in {0:4} and restr.cov = FALSE check Assumption 1
# In case hcmethod \in {0:4} and restr.cov = TRUE check Assumption 2
# If notsatisfied (in the specified cases) return theta = 0.
###########################################################################
if(restr.cov == FALSE){
qrXM <- qrX
} else {
qrXM <- qrM0lin
}
if( hcmethod > -1 ){
Aspt.check <- As.check(qrXM, Bfac, q, as.tol)
} else {
Aspt.check <- TRUE
}
if(hcmethod > -1 &
(Aspt.check == FALSE )){
return(list("theta" = NA, "Aspt.sat" = Aspt.check, "Max.ind" = NA))
} else {
# check whether conditions sufficient for theta = 1 are satisfied
# and return theta = 1 if this is the case;
if( (q == k & boot.res.restr & (boot.center.restr|!restr.cov) & comp.meth == "exact") |
(q == k & boot.res.restr & (boot.center.restr|!restr.cov) &
comp.meth == "approximation" & prod(Boot.supp) != 0)
)
{
return( list("theta" = 1, "Aspt.sat" = Aspt.check, "Max.ind" = NA) )
} else {
###########################################################################
# Prepare input RF for function res.OLSRF (restricted OLS est + resid)
# [only if needed]
# RF = (X'X)^(-1)R'(R(X'X)^(-1)R')^(-1) = (X'X)^(-1)R' %*% Bfac2
# in case q = k, RF = R^{-1}
###########################################################################
if(boot.res.restr == TRUE | boot.center.restr == TRUE | restr.cov == TRUE){
if(q < k){
factor.tmp2 <- tcrossprod( backsolve(qr.R(qrX), diag(k)) )
RF <- factor.tmp2%*%t(R)%*%Bfac2
} else {
RF <- solve(R)
}
} else {
RF <- NULL
}
###########################################################################
# Generate an element of M0: mu0
###########################################################################
if(max(abs(r)) > 0){
mu0 <- X%*%qr.solve(R, r) #assign element of M0
} else {
mu0 <- e0 # if r = 0, then zero vector is in M0lin
}
###########################################################################
#Prepare wild bootstrap multiplier weights
###########################################################################
#restricted
if(wildmult.restr == TRUE){
bootmult <- c(sqrt(wvec(k-q, n, qrM0lin, wildmult)))
}
#unrestricted
if(wildmult.restr == FALSE){
bootmult <- c(sqrt(wvec(k, n, qrX, wildmult)))
}
###########################################################################
# Generate the support set of the bootstrap sample distribution in case
# of exact computation; compute the probabilities, under which
# each support point is attained under a Rademacher or Mammen measure.
###########################################################################
if(comp.meth == "exact"){
if(n >= 20){
warning("Sample size n might be too large for choosing comp.meth = exact.")
}
#In case wilddist = Rademacher:
#Collect the set of all (2^n) elemts of \{-1, 1\}^n in an (2^n x n) matrix
#In case wilddist = Mammen:
#Collect the set of all (2^n) elemts of \{-(sqrt(5)-1)/2, (sqrt(5)+1)/2\}^n
#in an (2^n x n) matrix
if( wilddist == "Rademacher" ){
XI <- as.matrix(expand.grid(replicate(n, c(-1,1), simplify = FALSE)))
} else {
XI <- as.matrix(expand.grid(replicate(n, c(-(sqrt(5)-1)/2, (sqrt(5)+1)/2),
simplify = FALSE)))
}
colnames(XI) <- NULL
#Multiply the vectors generated with the bootstrap multiplicators bootmult
XI <- XI%*%diag(bootmult)
#Compute the probability of each row in XI under an n-fold product of
#Rademacher or Mammen distributions
#the probabilities of all coordinates in XI under independent
#Rademacher distributions
if(wilddist == "rademacher"){
probs <- expand.grid(replicate(n, c(.5,.5), simplify = FALSE))
}
#the probabilities of all coordinates in XI under independent
#Mammen distributions
if(wilddist == "mammen"){
probs <- expand.grid(replicate(n, c((sqrt(5)+1)/(2*sqrt(5)),
(sqrt(5)-1)/(2*sqrt(5))), simplify = FALSE))
}
#combine to get the probability of each row of XI under Rademacher or
#Mammen distributions
probs <- apply(probs,1,prod)
}
###########################################################################
# Generate the support set of the bootstrap sample distribution in case
# of approximate computation; i.e., transpose input Boot.supp, and multiply by
# diag(bootmult)
###########################################################################
if(comp.meth == "approximation"){
XI <- t(Boot.supp)%*%diag(bootmult)
}
###########################################################################
# Actual computation of theta
###########################################################################
#initialize theta with 0 (will be updated in the loop below)
theta.val <- 0
m.ind <- NA
for(i in 1:n){
ei <- e0
ei[i,1] <- 1
#generate the bootstrap sample
Ystar <- boot.sample(mu0 + ei, t(XI), qrX,
R, r, boot.res.restr, boot.center.restr, RF)
#compare test statistics through bootstrap sample with
#test statistic at mu0 + ei;
if(boot.center.restr == FALSE){
rstar <- Bfac[,i] + r
Tvalsboot <- F.wrap(Ystar, R, r, rstar, X, n, k, q, qrX,
hcmethod, cores, restr.cov,
Bfac, Bfac2, qrM0lin, RF, tol)
} else {
Tvalsboot <- F.wrap(Ystar, R, r, r, X, n, k, q, qrX,
hcmethod, cores, restr.cov,
Bfac, Bfac2, qrM0lin, RF, tol)
}
Tvals.comp <- F.wrap(mu0+ei, R, r, r, X, n, k, q, qrX,
hcmethod, 1, restr.cov,
Bfac, Bfac2, qrM0lin, RF, tol)
select.support <- ( Tvalsboot >= 0 & (Tvalsboot + in.tol < Tvals.comp) )
if(comp.meth == "approximation"){
if(mean(select.support) > theta.val){
theta.val <- mean(select.support)
m.ind <- i
}
} else {
if(sum((probs[select.support])) > theta.val){
theta.val <- sum((probs[select.support]))
m.ind <- i
}
}
#in case restr.cov == FALSE generate further bound
if(restr.cov == FALSE){
if( (rrank(cbind(X, ei), -1) <= k) &
( max(abs(R%*%qr.coef(qrX, ei))) > tol )){
select.support2 <- ( Tvalsboot >= 0 )
if(comp.meth == "approximation"){
if(mean(select.support2) > theta.val){
theta.val <- mean(select.support2)
m.ind <- i
}
} else {
if(sum((probs[select.support2])) > theta.val){
theta.val <- sum((probs[select.support2]))
m.ind <- i
}
}
}
}
}
if(is.na(m.ind)){
m.ind <- 1
}
return(list("theta" = 1-theta.val, "Aspt.sat" = Aspt.check, "Max.ind" = m.ind))
}
}
}
|
/scratch/gouwar.j/cran-all/cranData/wbsd/R/theta.R
|
#
# Copyright (C) 2020 David Preinerstorfer
# [email protected]
#
# This file is a part of wbsd.
#
# wbsd is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. A copy may be obtained at
# http://www.r-project.org/Licenses/
.onAttach <- function(...) {
packageStartupMessage("
###############################################################################
# Package wbsd - Version 1.0.0 - License: GPL-2
###############################################################################
# wbsd is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. A copy may be obtained at
# http://www.r-project.org/Licenses/
###############################################################################
")
}
|
/scratch/gouwar.j/cran-all/cranData/wbsd/R/zzz.R
|
#' @noRd
build_wb_url <- function(base_url, indicator, path_list, query_list) {
url_path <- unlist(path_list)
url_path <- url_path[!is.na(url_path)]
query_list <- query_list[!is.na(query_list)]
if(missing(indicator)) {
out_url <- httr::modify_url(base_url, path = url_path, query = query_list)
return(out_url)
}
indicator_path <- wb_api_parameters$indicator
indicator_path <- paste0(indicator_path, "/", indicator)
if(is.null(names(indicator))) names(indicator_path) <- indicator
else names(indicator_path) <- names(indicator)
out_url <- sapply(indicator_path, FUN = function(ind) {
url_path <- c(url_path, ind)
httr::modify_url(base_url, path = url_path, query = query_list)
}
)
out_url
}
#' @noRd
build_get_url <- function(end_point, lang) {
base_url <- wb_api_parameters$base_url
path_list <- list(
version = wb_api_parameters$version,
lang = if_missing(lang, options()$wbstats.lang, lang),
path = wb_api_parameters[[end_point]]
)
query_list <- list(
# per_page = wb_api_parameters$per_page,
per_page = ifelse(end_point == "indicator", 500, wb_api_parameters$per_page),
format = wb_api_parameters$format
)
wb_url <- build_wb_url(
base_url = base_url,
path_list = path_list,
query_list = query_list
)
wb_url
}
#' @noRd
fetch_wb_url <- function(url_string, indicator) {
return_json <- fetch_wb_url_content(url_string = url_string, indicator = indicator)
return_list <- jsonlite::fromJSON(return_json, simplifyVector = FALSE)
if ("message" %in% names(return_list[[1]])) {
message_list <- return_list[[1]]$message[[1]]
stop(sprintf("World Bank API request failed for indicator %s The following message was returned from the server\nid: %s\nkey: %s\nvalue: %s\n\nfailed request:\n%s",
indicator,
message_list$id,
message_list$key,
message_list$value,
url_string),
call. = FALSE)
}
n_pages <- return_list[[1]]$pages
if (n_pages == 0) return(NA) # a blank data frame will be returned to the user
return_list <- jsonlite::fromJSON(return_json, flatten = TRUE)
lastUpdated <- return_list[[1]]$lastupdated
if (n_pages > 1) {
page_list <- lapply(1:n_pages, FUN = function(page) {
if (page == 1) {
return_list[[2]]
} else {
page_url <- paste0(url_string, "&page=", page)
page_return_json <- fetch_wb_url_content(url_string = page_url)
page_return_list <- jsonlite::fromJSON(page_return_json, flatten = TRUE)
page_df <- page_return_list[[2]]
}
}
) # end lapply
return_df <- do.call("rbind", page_list)
} else { # only one page
return_df <- return_list[[2]]
}
return_df$lastUpdated <- lastUpdated
return_df
}
#' @noRd
fetch_wb_url_content <- function(url_string, indicator) {
indicator <- if_missing(indicator)
# move this to data-raw eventually
ua <- httr::user_agent("https://github.com/nset-ornl/wbstats")
# add api_token here if/when that is supported
get_return <- httr::GET(url_string, ua, httr::timeout(20))
if (httr::http_error(get_return)) {
error_status<- httr::http_status(get_return)
stop(sprintf("World Bank API request failed for indicator %s\nmessage: %s\ncategory: %s\nreason: %s \nurl: %s",
indicator,
error_status$message,
error_status$category,
error_status$reason,
url_string),
call. = FALSE)
}
if (httr::http_type(get_return) != "application/json") {
stop("API call executed successfully, but did not return expected json format", call. = FALSE)
}
return_json <- httr::content(get_return, as = "text")
return_json
}
|
/scratch/gouwar.j/cran-all/cranData/wbstats/R/build_urls.R
|
#' Cached information from the World Bank API
#'
#' This data is a cached result of the \code{\link{wb_cache}} function.
#' By default functions \code{\link{wb_data}} and \code{\link{wb_search}} use this
#' data for the \code{cache} parameter.
#'
"wb_cachelist"
|
/scratch/gouwar.j/cran-all/cranData/wbstats/R/data.R
|
#' Cached information from the World Bank API
#'
#' This data is a cached result of the \code{\link{wbcache}} function.
#' By default functions \code{\link{wb}} and \code{\link{wbsearch}} use this
#' data for the \code{cache} parameter.
#'
#'
#' @format A list containing 7 data frames:
#' \itemize{
#' \item \code{countries}: A data frame. The result of calling \code{\link{wbcountries}}
#' \item \code{indicators}: A data frame.The result of calling \code{\link{wbindicators}}
#' \item \code{sources}: A data frame.The result of calling \code{\link{wbsources}}
#' \item \code{datacatalog}: A data frame.The result of calling \code{\link{wbdatacatalog}}
#' \item \code{topics}: A data frame.The result of calling \code{\link{wbtopics}}
#' \item \code{income}: A data frame.The result of calling \code{\link{wbincome}}
#' \item \code{lending}: A data frame.The result of calling \code{\link{wblending}}
#' }
"wb_cachelist_dep"
|
/scratch/gouwar.j/cran-all/cranData/wbstats/R/deprecated-data.R
|
#' @noRd
wburls <- function() {
base_url <- "http://api.worldbank.org/v2/"
utils_url <- "per_page=20000&format=json"
url_list <- list(base_url = base_url, utils_url = utils_url)
url_list
}
#' @noRd
wbformatcols <- function(df, col_names, blank2NA = TRUE) {
col_align <- match(names(col_names), names(df))
col_match <- col_names[!is.na(col_align)]
if (length(col_match) != 0) names(df)[match(names(col_match), names(df))] <- col_match
if (blank2NA & (nrow(df) != 0)) df[df == ""] <- NA
df
}
#' @noRd
wbdate2POSIXct <- function(df, date_col) {
if (requireNamespace("lubridate", versionCheck = list(op = ">=", version = "1.5.0"),
quietly = TRUE)) {
if (nrow(df) == 0) {
# hackish way to support the POSIXct parameter with 0 rows returned
df_ct <- as.data.frame(matrix(nrow = 0, ncol = 2), stringsAsFactors = FALSE)
names(df_ct) <- c("date_ct", "granularity")
df <- cbind(df, df_ct)
return(df)
}
# lastUpdated field
df$lastUpdated <- lubridate::as_date(df$lastUpdated)
# add new columns
df$date_ct <- as.Date.POSIXct(NA)
df$granularity <- NA
date_vec <- df[ , date_col]
# annual ----------
annual_obs_index <- grep("[M|Q|D]", date_vec, invert = TRUE)
if (length(annual_obs_index) > 0) {
annual_posix <- as.Date(date_vec[annual_obs_index], "%Y")
annual_posix_values <- lubridate::floor_date(annual_posix, unit = "year")
df$date_ct[annual_obs_index] <- annual_posix_values
df$granularity[annual_obs_index] <- "annual"
}
# monthly ----------
monthly_obs_index <- grep("M", date_vec)
if (length(monthly_obs_index) > 0) {
monthly_posix <- lubridate::ydm(gsub("M", "01", date_vec[monthly_obs_index]))
monthly_posix_values <- lubridate::floor_date(monthly_posix, unit = "month")
df$date_ct[monthly_obs_index] <- monthly_posix_values
df$granularity[monthly_obs_index] <- "monthly"
}
# quarterly ----------
quarterly_obs_index <- grep("Q", date_vec)
if (length(quarterly_obs_index) > 0) {
# takes a little more work
qtr_obs <- strsplit(date_vec[quarterly_obs_index], "Q")
qtr_df <- as.data.frame(matrix(unlist(qtr_obs), ncol = 2, byrow = TRUE), stringsAsFactors = FALSE)
names(qtr_df) <- c("year", "qtr")
qtr_df$month <- as.numeric(qtr_df$qtr) * 3 # to turn into the max month
qtr_format_vec <- paste0(qtr_df$year, "01", qtr_df$month) # 01 acts as a dummy day
quarterly_posix <- lubridate::ydm(qtr_format_vec)
quarterly_posix_values <- lubridate::floor_date(quarterly_posix, unit = "quarter")
df$date_ct[quarterly_obs_index] <- quarterly_posix_values
df$granularity[quarterly_obs_index] <- "quarterly"
}
} else {
warning("Required Namespace 'lubridate (>= 1.5.0)' not available. This option is being ignored")
}
df
}
#' @noRd
call_api <- function(url_string, indicator) {
# move this to data-raw eventually
ua <- httr::user_agent("https://github.com/GIST-ORNL/wbstats")
# add api_token here if/when that is supported
get_return <- httr::GET(url_string, ua)
if (httr::http_error(get_return)) {
error_status<- httr::http_status(get_return)
stop(sprintf("World Bank API request failed for indicator %s\nmessage: %s\ncategory: %s\nreason: %s \nurl: %s",
indicator,
error_status$message,
error_status$category,
error_status$reason,
url_string),
call. = FALSE)
}
if (httr::http_type(get_return) != "application/json") {
stop("API call executed successfully, but did not return expected json format", call. = FALSE)
}
return_json <- httr::content(get_return, as = "text")
return_json
}
#' @noRd
wbget <- function(url_string, indicator) {
return_json <- call_api(url_string = url_string, indicator = indicator)
return_list <- jsonlite::fromJSON(return_json, simplifyVector = FALSE)
if ("message" %in% names(return_list[[1]])) {
message_list <- return_list[[1]]$message[[1]]
stop(sprintf("World Bank API request failed for indicator %s The following message was returned from the server\nid: %s\nkey: %s\nvalue: %s",
indicator,
message_list$id,
message_list$key,
message_list$value),
call. = FALSE)
}
n_pages <- return_list[[1]]$pages
if (n_pages == 0) return(NA) # a blank data frame will be returned to the user
return_list <- jsonlite::fromJSON(return_json, flatten = TRUE)
lastUpdated <- return_list[[1]]$lastupdated
if (n_pages > 1) {
page_list <- lapply(1:n_pages, FUN = function(page) {
if (page == 1) {
return_list[[2]]
} else {
page_url <- paste0(url_string, "&page=", page)
# page_return <- wbget.raw(page_url)
page_return_json <- call_api(url_string = page_url)
page_return_list <- jsonlite::fromJSON(page_return_json, flatten = TRUE)
page_df <- page_return_list[[2]]
}
}
) # end lapply
return_df <- do.call("rbind", page_list)
} else { # only one page
return_df <- return_list[[2]]
}
return_df$lastUpdated <- lastUpdated
return_df
}
#' @noRd
wbget_dc <- function(url_string) {
return_json <- call_api(url_string = url_string, indicator = "Data Catalog")
return_list <- jsonlite::fromJSON(return_json, flatten = TRUE)
n_pages <- return_list$pages
if (n_pages > 1) {
page_list <- lapply(1:n_pages, FUN = function(page) {
if (page == 1) {
return_list$datacatalog$metatype
} else {
page_url <- paste0(url_string, "&page=", page)
page_return_json <- call_api(url_string = page_url)
page_return_list <- jsonlite::fromJSON(page_return_json, flatten = TRUE)
page_metadata_list <- page_return_list$datacatalog$metatype
}
}
) # end lapply
page_list <- unlist(x = page_list, recursive = FALSE)
} else { # only one page
page_list <- return_list$datacatalog$metatype
}
page_list
}
|
/scratch/gouwar.j/cran-all/cranData/wbstats/R/deprecated-utilities.R
|
#' Download Data from the World Bank API
#'
#' This function downloads the requested information using the World Bank API
#'
#' @param country Character vector of country or region codes. Default value is special code of \code{all}.
#' Other permissible values are codes in the following fields from the \code{\link{wb_cachelist}} \code{country}
#' data frame. \code{iso3c}, \code{iso2c}, \code{regionID}, \code{adminID}, and \code{incomeID}.
#' Additional special values include \code{aggregates}, which returns only aggregates, and \code{countries_only},
#' which returns all countries without aggregates.
#' @param indicator Character vector of indicator codes. These codes correspond to the \code{indicatorID} column
#' from the \code{indicator} data frame of \code{\link{wbcache}} or \code{\link{wb_cachelist}}, or
#' the result of \code{\link{wbindicators}}
#' @param startdate Numeric or character. If numeric it must be in \%Y form (i.e. four digit year).
#' For data at the subannual granularity the API supports a format as follows: for monthly data, "2016M01"
#' and for quarterly data, "2016Q1". This also accepts a special value of "YTD", useful for more frequently
#' updated subannual indicators.
#' @param enddate Numeric or character. If numeric it must be in \%Y form (i.e. four digit year).
#' For data at the subannual granularity the API supports a format as follows: for monthly data, "2016M01"
#' and for quarterly data, "2016Q1".
#' @param mrv Numeric. The number of Most Recent Values to return. A replacement of \code{startdate} and \code{enddate},
#' this number represents the number of observations you which to return starting from the most recent date of collection.
#' Useful in conjuction with \code{freq}
#' @param return_wide Logical. If \code{TRUE} data is returned in a wide format instead of long, with a column named for each
#' \code{indicatorID}. To necessitate this transformation, the \code{indicator} column, that provides the human readable description
#' is dropped. This field is available through from the \code{indicator} data frame of \code{\link{wbcache}} or \code{\link{wb_cachelist}},
#' or the result of \code{\link{wbindicators}}. Default is \code{FALSE}
#' @param gapfill Logical. Works with \code{mrv}. If \code{TRUE} fills values, if not available, by back tracking to the
#' next available period (max number of periods back tracked will be limited by \code{mrv} number)
#' @param freq Character String. For fetching quarterly ("Q"), monthly("M") or yearly ("Y") values.
#' Currently works along with \code{mrv}. Useful for querying high frequency data.
#' @param cache List of data frames returned from \code{\link{wbcache}}. If omitted,
#' \code{\link{wb_cachelist}} is used
#' @param lang Language in which to return the results. If \code{lang} is unspecified,
#' english is the default.
#' @param removeNA if \code{TRUE}, remove any blank or \code{NA} observations that are returned.
#' if \code{FALSE}, no blank or \code{NA} values are removed from the return.
#' @param POSIXct if \code{TRUE}, additonal columns \code{date_ct} and \code{granularity} are added.
#' \code{date_ct} converts the default date into a \code{\link[base]{POSIXct}}. \code{granularity}
#' denotes the time resolution that the date represents. Useful for subannual data and mixing subannual
#' with annual data. If \code{FALSE}, these fields are not added.
#' @param include_dec if \code{TRUE}, the column \code{decimal} is not removed from the return. if \code{FALSE},
#' this column is removed
#' @param include_unit if \code{TRUE}, the column \code{unit} is not removed from the return. if \code{FALSE},
#' this column is removed
#' @param include_obsStatus if \code{TRUE}, the column \code{obsStatus} is not removed from the return. if \code{FALSE},
#' this column is removed
#' @param include_lastUpdated if \code{TRUE}, the column \code{lastUpdated} is not removed from the return. if \code{FALSE},
#' this column is removed. If \code{TRUE} and \code{POSIXct = TRUE} then column will be of class \code{\link[base]{Date}}
#' @return Data frame with all available requested data.
#'
#' @note Not all data returns have support for langauges other than english. If the specific return
#' does not support your requested language by default it will return \code{NA}. For an enumeration of
#' supported languages by data source please see \code{\link{wbdatacatalog}}.
#' The options for \code{lang} are:
#' \itemize{
#' \item \code{en}: English
#' \item \code{es}: Spanish
#' \item \code{fr}: French
#' \item \code{ar}: Arabic
#' \item \code{zh}: Mandarin
#' }
#' The \code{POSIXct} parameter requries the use of \code{\link[lubridate]{lubridate}} (>= 1.5.0). All dates
#' are rounded down to the floor. For example a value for the year 2016 would have a \code{POSIXct} date of
#' \code{2016-01-01}. If this package is not available and the \code{POSIXct} parameter is set to \code{TRUE},
#' the parameter is ignored and a \code{warning} is produced.
#'
#' The \code{include_dec}, \code{include_unit}, and \code{include_obsStatus} are defaulted to \code{FALSE}
#' because as of writing, all returns have a value of \code{0}, \code{NA}, and \code{NA}, respectively.
#' These columns might be used in the future by the API, therefore the option to include the column is available.
#'
#' The \code{include_lastUpdated} is defaulted to \code{FALSE} as well to limit the
#'
#' If there is no data available that matches the request parameters, an empty data frame is returned along with a
#' \code{warning}. This design is for easy aggregation of multiple calls.
#'
#' @examples
#' # GDP at market prices (current US$) for all available countries and regions
#' \donttest{wb(indicator = "NY.GDP.MKTP.CD", startdate = 2000, enddate = 2016)}
#'
#' # GDP and Population in long format for the most recent 20 observations
#' \donttest{wb(indicator = c("SP.POP.TOTL","NY.GDP.MKTP.CD"), mrv = 20)}
#'
#' # GDP and Population in wide format for the most recent 20 observations
#' \donttest{wb(indicator = c("SP.POP.TOTL","NY.GDP.MKTP.CD"), mrv = 20, return_wide = TRUE)}
#'
#' # query using regionID or incomeID
#' # High Income Countries and Sub-Saharan Africa (all income levels)
#' wb(country = c("HIC", "SSF"), indicator = "NY.GDP.MKTP.CD", startdate = 1985, enddate = 1985)
#'
#' # if you do not know when the latest time an indicator is avaiable mrv can help
#' wb(country = c("IN"), indicator = 'EG.ELC.ACCS.ZS', mrv = 1)
#'
#' # increase the mrv value to increase the number of maximum number of returns
#' wb(country = c("IN"), indicator = 'EG.ELC.ACCS.ZS', mrv = 35)
#'
#' # GDP at market prices (current US$) for only available countries
#' \donttest{wb(country = "countries_only", indicator = "NY.GDP.MKTP.CD", startdate = 2000, enddate = 2016)}
#'
#' # GDP at market prices (current US$) for only available aggregate regions
#' \donttest{wb(country = "aggregates", indicator = "NY.GDP.MKTP.CD", startdate = 2000, enddate = 2016)}
#'
#' # if you want to "fill-in" the values in between actual observations use gapfill = TRUE
#' # this highlights a very important difference.
#' # all other parameters are the same as above, except gapfill = TRUE
#' # and the results are very different
#' wb(country = c("IN"), indicator = 'EG.ELC.ACCS.ZS', mrv = 35, gapfill = TRUE)
#'
#' # if you want the most recent values within a certain time frame
#' wb(country = c("US"), indicator = 'SI.DST.04TH.20', startdate = 1970, enddate = 2000, mrv = 2)
#'
#' # without the freq parameter the deafult temporal granularity search is yearly
#' # should return the 12 most recent years of data
#' wb(country = c("CHN", "IND"), indicator = "DPANUSSPF", mrv = 12)
#'
#' # if another frequency is available for that indicator it can be accessed using the freq parameter
#' # should return the 12 most recent months of data
#' wb(country = c("CHN", "IND"), indicator = "DPANUSSPF", mrv = 12, freq = "M")
#' @export
wb <- function(country = "all", indicator, startdate, enddate, mrv, return_wide = FALSE, gapfill,
freq, cache, lang = c("en", "es", "fr", "ar", "zh"), removeNA = TRUE, POSIXct = FALSE,
include_dec = FALSE, include_unit = FALSE, include_obsStatus = FALSE, include_lastUpdated = FALSE) {
lifecycle::deprecate_soft("1.0.0", "wbstats::wb()", "wbstats::wb_data()")
lang <- match.arg(lang)
url_list <- wburls()
base_url <- url_list$base_url
utils_url <- url_list$utils_url
if (missing(cache)) cache <- wbstats::wb_cachelist_dep
# check country ----------
if ("all" %in% country) {
country_url <- "all"
} else if ("aggregates" %in% country) {
cache_cn <- cache$countries[cache$countries$region == "Aggregates" , "iso3c" ]
country_url <- paste0(cache_cn, collapse = ";")
} else if ("countries_only" %in% country) {
cache_cn <- cache$countries[cache$countries$region != "Aggregates" , "iso3c" ]
country_url <- paste0(cache_cn, collapse = ";")
} else {
cache_cn <- cache$countries
cn_check <- cache_cn[ , c("iso3c", "iso2c", "regionID", "adminID", "incomeID")]
cn_check <- unique(unlist(cn_check, use.names = FALSE))
cn_check <- cn_check[!is.na(cn_check)]
good_cn_index <- country %in% cn_check
good_cn <- country[good_cn_index]
if (length(good_cn) == 0) stop("country parameter has no valid values. Please check documentation for valid inputs")
bad_cn <- country[!good_cn_index]
if (length(bad_cn) > 0) warning(paste0("The following country values are not valid and are being excluded from the request: ",
paste(bad_cn, collapse = ",")))
country_url <- paste0(good_cn, collapse = ";")
}
# check indicator ----------
cache_ind <- cache$indicators
ind_check <- cache_ind[, "indicatorID"]
ind_check <- ind_check[!is.na(ind_check)] # should never be needed but make sure
good_ind_index <- indicator %in% ind_check
good_ind <- indicator[good_ind_index]
if (length(good_ind) == 0) stop("indicator parameter has no valid values. Please check documentation for valid inputs")
bad_ind <- indicator[!good_ind_index]
if (length(bad_ind) > 0) warning(paste0("The following indicator values are not valid and are being excluded from the request: ",
paste(bad_ind, collapse = ",")))
## check date and other parameters. add to list if not missing ----------
param_url_list <- list()
# check dates ----------
if (missing(startdate) != missing(enddate)) stop("Using either startdate or enddate requries supplying both. Please provide both if a date range is wanted")
if (!(missing(startdate) & missing(enddate))) {
#
# something here to check the inputs but i'll come back to this
#
date_url <- paste0("date=", startdate, ":", enddate)
param_url_list[length(param_url_list) + 1] <- date_url
}
# check mrv ----------
if (!missing(mrv)) {
if (!is.numeric(mrv)) stop("If supplied, mrv must be numeric")
mrv_url <- paste0("MRV=", round(mrv, digits = 0)) # just to make sure its a whole number
param_url_list[length(param_url_list) + 1] <- mrv_url
}
# check gapfill ----------
if (!missing(gapfill)) {
if (!is.logical(gapfill)) stop("If supplied, values for gapfill must be TRUE or FALSE")
if (missing(mrv)) stop("mrv must be supplied for gapfill to be used")
gapfill_url <- paste0("Gapfill=", ifelse(gapfill, "Y", "N"))
param_url_list[length(param_url_list) + 1] <- gapfill_url
}
# check freq ----------
if (!missing(freq)) {
if (!freq %in% c("Y", "Q", "M")) stop("If supplied, values for freq must be one of the following 'Y' (yearly), 'Q' (Quarterly), or 'M' (Monthly)")
freq_url <- paste0("frequency=", freq)
param_url_list[length(param_url_list) + 1] <- freq_url
}
# combine the url parameters ----------
param_url_list[length(param_url_list) + 1] <- utils_url
param_url <- paste0(param_url_list, collapse = "&")
# make API calls ----------
df_list <- lapply(indicator, FUN = function(i) {
full_url <- paste0(base_url, lang, "/countries/", country_url, "/indicators/", i, "?", param_url)
return_df <- try(wbget(full_url, indicator = i), silent = FALSE)
}
)
# remove the errored out indicator returns ----------
df_index <- sapply(df_list, is.data.frame)
out_list <- df_list[df_index]
# "defaultName" = "newName"
out_cols <- c("value" = "value",
"decimal" = "decimal",
"date" = "date",
"indicator.id" = "indicatorID",
"indicator.value" = "indicator",
"country.id" = "iso2c",
"country.value" = "country",
"countryiso3code" = "iso3c",
"obs_status" = "obsStatus",
"unit" = "unit")
if (length(out_list) == 0) {
warning("No data was returned for any requested country and indicator. Returning empty data frame")
out_df <- as.data.frame(matrix(nrow = 0, ncol = length(out_cols)))
names(out_df) <- names(out_cols)
} else {
out_df <- do.call("rbind", out_list)
}
# a little clean up ----------
out_df$value <- as.numeric(out_df$value)
out_df <- wbformatcols(out_df, out_cols)
if (POSIXct) out_df <- wbdate2POSIXct(out_df, "date")
if (!include_dec) out_df$decimal <- NULL
if (!include_unit) out_df$unit <- NULL
if (!include_obsStatus) out_df$obsStatus <- NULL
if (!include_lastUpdated) out_df$lastUpdated <- NULL
if (removeNA) out_df <- out_df[!is.na(out_df$value), ]
# Namibia bug ----------
# if only Namibia is requested it's iso2c code "NA" is automatically converted
# to logical NA by jsonlite::fromJSON and there currently does not seem to be an
# option to handle that within that function so look if thats the case and fix it
namibia_na <- which(is.na(out_df$iso2c) & out_df$country == "Namibia")
if (!length(namibia_na) == 0) out_df[namibia_na, "iso2c"] <- "NA"
# handle iso3c in iso2c bug ----------
iso3c_in_iso2c_cols <- which(out_df$iso2c %in% cache$countries$iso3c)
if (!length(iso3c_in_iso2c_cols) == 0) {
iso3c_in_iso2c <- unique(out_df[iso3c_in_iso2c_cols, "iso2c"])
iso23_df <- cache$countries[cache$countries$iso3c %in% iso3c_in_iso2c, c("iso2c","iso3c")]
for (i in 1:nrow(iso23_df)) {
replace_rows <- which(out_df$iso2c == iso23_df[i, "iso3c"])
out_df[replace_rows, "iso3c"] <- iso23_df[i,"iso3c"]
out_df[replace_rows, "iso2c"] <- iso23_df[i,"iso2c"]
}
}
# handle blank iso3c ----------
na_iso3c <- which(is.na(out_df$iso3c) & !(is.na(out_df$iso2c)))
if (!length(na_iso3c) == 0) {
iso2c <- unique(out_df[na_iso3c, "iso2c"])
iso23_df <- cache$countries[cache$countries$iso2c %in% iso2c, c("iso2c", "iso3c")]
for (i in 1:nrow(iso23_df)) {
replace_rows <- which(out_df$iso2c == iso23_df[i, "iso2c"])
out_df[replace_rows, "iso3c"] <- iso23_df[i, "iso3c"]
}
}
# check for wide return ----------
if (return_wide) {
out_df$indicator <- NULL
out_df <- tidyr::spread_(data = out_df,
key_col = "indicatorID",
value_col = "value")
}
out_df
}
|
/scratch/gouwar.j/cran-all/cranData/wbstats/R/deprecated-wb.R
|
#' Download updated country and region information from World Bank API
#'
#' Download updated information on available countries and regions
#' from the World Bank API
#'
#' @param lang Language in which to return the results. If \code{lang} is unspecified,
#' english is the default.
#'
#' @return A data frame of available countries and regions with related information
#'
#' @note Not all data returns have support for langauges other than english. If the specific return
#' does not support your requested language by default it will return \code{NA}. For an enumeration of
#' supported languages by data source please see \code{\link{wbdatacatalog}}.
#' The options for \code{lang} are:
#' \itemize{
#' \item \code{en}: English
#' \item \code{es}: Spanish
#' \item \code{fr}: French
#' \item \code{ar}: Arabic
#' \item \code{zh}: Mandarin
#' }
#'
#' @export
wbcountries <- function(lang = c("en", "es", "fr", "ar", "zh")) {
lifecycle::deprecate_soft("1.0.0", "wbstats::wbcountries()", "wbstats::wb_countries()")
# if none supplied english is default
lang <- match.arg(lang)
url_list <- wburls()
base_url <- url_list$base_url
utils_url <- url_list$utils_url
countries_url <- paste0(base_url, lang, "/countries?", utils_url)
countries_df <- wbget(countries_url)
# "defaultName" = "newName"
countries_cols <- c("id" = "iso3c",
"iso2Code" = "iso2c",
"name" = "country",
"capitalCity" = "capital",
"longitude" = "long",
"latitude" = "lat",
"region.id" = "regionID",
"region.value" = "region",
"region.iso2code" = "region_iso2c",
"adminregion.id" = "adminID",
"adminregion.value" = "admin",
"adminregion.iso2code" = "admin_iso2c",
"incomeLevel.id" = "incomeID",
"incomeLevel.value" = "income",
"incomeLevel.iso2code" = "income_iso2c",
"lendingType.id" = "lendingID",
"lendingType.value" = "lending",
"lendingType.iso2code" = "lending_iso2c")
countries_df <- wbformatcols(countries_df, countries_cols)
# regionID and incomeID have "NA" for some results
# do not do replace all for the df because Namibia's iso2c code is "NA"
if ("regionID" %in% names(countries_df)) countries_df[countries_df$regionID == "NA", "regionID"] <- NA
if ("incomeID" %in% names(countries_df)) countries_df[countries_df$incomeID == "NA", "incomeID"] <- NA
if ("region_iso2c" %in% names(countries_df)) countries_df[countries_df$region_iso2c == "NA", "region_iso2c"] <- NA
if ("income_iso2c" %in% names(countries_df)) countries_df[countries_df$income_iso2c == "NA", "income_iso2c"] <- NA
countries_df
}
#' Download updated indicator information from World Bank API
#'
#' Download updated information on available indicators
#' from the World Bank API
#'
#' @param lang Language in which to return the results. If \code{lang} is unspecified,
#' english is the default.
#'
#' @return A data frame of available indicators with related information
#'
#' @note Not all data returns have support for langauges other than english. If the specific return
#' does not support your requested language by default it will return \code{NA}. For an enumeration of
#' supported languages by data source please see \code{\link{wbdatacatalog}}.
#' The options for \code{lang} are:
#' \itemize{
#' \item \code{en}: English
#' \item \code{es}: Spanish
#' \item \code{fr}: French
#' \item \code{ar}: Arabic
#' \item \code{zh}: Mandarin
#' }
#'
#' @export
wbindicators <- function(lang = c("en", "es", "fr", "ar", "zh")) {
lifecycle::deprecate_soft("1.0.0", "wbstats::wbindicators()", "wbstats::wb_indicators()")
# if none supplied english is default
lang <- match.arg(lang)
url_list <- wburls()
base_url <- url_list$base_url
utils_url <- url_list$utils_url
indicators_url <- paste0(base_url, lang, "/indicators?", utils_url)
indicators_df <- wbget(indicators_url)
# the topics return is not in the correct format for a df. topics can be
# retrieved with wbtopics()
indicators_df$topics <- NULL
# "defaultName" = "newName"
indicators_cols <- c("id" = "indicatorID",
"name" = "indicator",
"unit" = "unit",
"sourceNote" = "indicatorDesc",
"sourceOrganization" = "sourceOrg",
"source.id" = "sourceID",
"source.value" = "source")
indicators_df <- wbformatcols(indicators_df, indicators_cols)
indicators_df
}
#' Download updated indicator topic information from World Bank API
#'
#' Download updated information on available indicator topics
#' from the World Bank API
#'
#' @param lang Language in which to return the results. If \code{lang} is unspecified,
#' english is the default.
#'
#' @return A data frame of available indicator topics with related information
#'
#' @note Not all data returns have support for langauges other than english. If the specific return
#' does not support your requested language by default it will return \code{NA}. For an enumeration of
#' supported languages by data source please see \code{\link{wbdatacatalog}}.
#' The options for \code{lang} are:
#' \itemize{
#' \item \code{en}: English
#' \item \code{es}: Spanish
#' \item \code{fr}: French
#' \item \code{ar}: Arabic
#' \item \code{zh}: Mandarin
#' }
#'
#' @export
wbtopics <- function(lang = c("en", "es", "fr", "ar", "zh")) {
lifecycle::deprecate_soft("1.0.0", "wbstats::wbtopics()", "wbstats::wb_topics()")
# if none supplied english is default
lang <- match.arg(lang)
url_list <- wburls()
base_url <- url_list$base_url
utils_url <- url_list$utils_url
topics_url <- paste0(base_url, lang, "/topics?", utils_url)
topics_df <- wbget(topics_url)
# "defaultName" = "newName"
topics_cols <- c("id" = "topicID",
"value" = "topic",
"sourceNote" = "topicDesc")
topics_df <- wbformatcols(topics_df, topics_cols)
topics_df
}
#' Download updated lending type information from World Bank API
#'
#' Download updated information on available lending types
#' from the World Bank API
#'
#' @param lang Language in which to return the results. If \code{lang} is unspecified,
#' english is the default.
#'
#' @return A data frame of available lending types with related information
#'
#' @note Not all data returns have support for langauges other than english. If the specific return
#' does notsupport your requested language by default it will return \code{NA}. For an enumeration of
#' supported languages by data source please see \code{\link{wbdatacatalog}}.
#' The options for \code{lang} are:
#' \itemize{
#' \item \code{en}: English
#' \item \code{es}: Spanish
#' \item \code{fr}: French
#' \item \code{ar}: Arabic
#' \item \code{zh}: Mandarin
#' }
#'
#' @export
wblending <- function(lang = c("en", "es", "fr", "ar", "zh")) {
lifecycle::deprecate_soft("1.0.0", "wbstats::wblending()", "wbstats::wb_lending_types()")
# if none supplied english is default
lang <- match.arg(lang)
url_list <- wburls()
base_url <- url_list$base_url
utils_url <- url_list$utils_url
lending_url <- paste0(base_url, lang, "/lendingTypes?", utils_url)
lending_df <- wbget(lending_url)
# "defaultName" = "newName"
lending_cols <- c("id" = "lendingID",
"value" = "lending",
"iso2code" = "iso2c")
lending_df <- wbformatcols(lending_df, lending_cols)
lending_df
}
#' Download updated income type information from World Bank API
#'
#' Download updated information on available income types
#' from the World Bank API
#'
#' @param lang Language in which to return the results. If \code{lang} is unspecified,
#' english is the default.
#'
#' @return A data frame of available income types with related information
#'
#' @note Not all data returns have support for langauges other than english. If the specific return
#' does not support your requested language by default it will return \code{NA}. For an enumeration of
#' supported languages by data source please see \code{\link{wbdatacatalog}}.
#' The options for \code{lang} are:
#' \itemize{
#' \item \code{en}: English
#' \item \code{es}: Spanish
#' \item \code{fr}: French
#' \item \code{ar}: Arabic
#' \item \code{zh}: Mandarin
#' }
#'
#' @export
wbincome <- function(lang = c("en", "es", "fr", "ar", "zh")) {
lifecycle::deprecate_soft("1.0.0", "wbstats::wbincome()", "wbstats::wb_income_levels()")
# if none supplied english is default
lang <- match.arg(lang)
url_list <- wburls()
base_url <- url_list$base_url
utils_url <- url_list$utils_url
income_url <- paste0(base_url, lang, "/incomelevels?", utils_url)
income_df <- wbget(income_url)
# "defaultName" = "newName"
income_cols <- c("id" = "incomeID",
"value" = "income",
"iso2code" = "iso2c")
income_df <- wbformatcols(income_df, income_cols)
income_df
}
#' Download updated data source information from World Bank API
#'
#' Download updated information on available data sources
#' from the World Bank API
#'
#' @param lang Language in which to return the results. If \code{lang} is unspecified,
#' english is the default.
#'
#' @return A data frame of available data scources with related information
#'
#' @note Not all data returns have support for langauges other than english. If the specific return
#' does not support your requested language by default it will return \code{NA}. For an enumeration of
#' supported languages by data source please see \code{\link{wbdatacatalog}}.
#' The options for \code{lang} are:
#' \itemize{
#' \item \code{en}: English
#' \item \code{es}: Spanish
#' \item \code{fr}: French
#' \item \code{ar}: Arabic
#' \item \code{zh}: Mandarin
#' }
#' @export
wbsources <- function(lang = c("en", "es", "fr", "ar", "zh")) {
lifecycle::deprecate_soft("1.0.0", "wbstats::wbsources()", "wbstats::wb_sources()")
# if none supplied english is default
lang <- match.arg(lang)
url_list <- wburls()
base_url <- url_list$base_url
utils_url <- url_list$utils_url
sources_url <- paste0(base_url, lang, "/sources?", utils_url)
sources_df <- wbget(sources_url)
# "defaultName" = "newName"
sources_cols <- c("id" = "sourceID",
"name" = "source",
"description" = "sourceDesc",
"url" = "sourceURL",
"code" = "sourceAbbr",
"lastupdated" = "lastUpdated",
"dataavailability" = "dataAvail",
"metadataavailability" = "metadataAvail")
sources_df <- wbformatcols(sources_df, sources_cols)
sources_df
}
#' Download an updated list of the World Bank data catalog
#'
#' Download an updated list of the World Bank data catalog
#' from the World Bank API
#'
#' @return A data frame of the World Bank data catalog with related information
#'
#' @note This function does not support any languages other than english due to
#' the lack of support from the World Bank API
#' @export
wbdatacatalog <- function() {
lifecycle::deprecate_soft("1.0.0", "wbstats::wbdatacatalog()",
details = paste("This function uses an out of date version of the Data Catalog API.",
"wbstats does not currently have support for the latest API version.\n",
"Please see https://datacatalog.worldbank.org/ for up to date information.")
)
url_list <- wburls()
base_url <- url_list$base_url
catalog_url <- paste0(base_url, "datacatalog?format=json")
catalog_return <- wbget_dc(catalog_url)
# the return is not very nice
# so we have to do some leg work
catalog_list <- lapply(catalog_return, FUN = function(i) {
i_vec <- i$value
names(i_vec) <- i$id
i_vec
})
# dplyr::rbind_list() would be more compact here but no need to add a dependency
catalog_df <- as.data.frame(do.call(rbind,
lapply(lapply(catalog_list, unlist),
"[", unique(unlist(sapply(catalog_list, names)))
)
), stringsAsFactors = FALSE)
names(catalog_df) <- unique(unlist(sapply(catalog_list, names)))
# "defaultName" = "newName"
catalog_cols <- c("name" = "source",
"acronym" = "sourceAbbr",
"description" = "sourceDesc",
"url" = "url",
"type" = "type",
"languagesupported" = "langSupport",
"periodicity" = "periodicity",
"economycoverage" = "econCoverage",
"granularity" = "granularity",
"numberofeconomies" = "numEcons",
"topics" = "topics",
"updatefrequency" = "updateFreq",
"updateschedule" = "updateSched",
"lastrevisiondate" = "lastRevision",
"contactdetails" = "contactInfo",
"accessoption" = "accessOpt",
"bulkdownload" = "bulkDownload",
"cite" = "cite",
"detailpageurl" = "detailURL",
"coverage" = "coverage",
"api" = "api",
"apiaccessurl" = "apiURL",
"apisourceid" = "SourceID",
"mobileapp" = "mobileApp",
"datanotes" = "dataNotes",
"sourceurl" = "sourceURL",
"apilocation" = "apiLocation",
"listofcountriesregionssubnationaladmins" = "geoCoverage")
catalog_df <- wbformatcols(catalog_df, catalog_cols)
catalog_df
}
#' Download an updated list of country, indicator, and source information
#'
#' Download an updated list of information regarding countries, indicators,
#' sources, data catalog, indicator topics, lending types, and income levels
#' from the World Bank API
#'
#' @param lang Language in which to return the results. If \code{lang} is unspecified,
#' english is the default.
#'
#' @return A list containing the following items:
#' \itemize{
#' \item \code{countries}: A data frame. The result of calling \code{\link{wbcountries}}
#' \item \code{indicators}: A data frame.The result of calling \code{\link{wbindicators}}
#' \item \code{sources}: A data frame.The result of calling \code{\link{wbsources}}
#' \item \code{datacatalog}: A data frame.The result of calling \code{\link{wbdatacatalog}}
#' \item \code{topics}: A data frame.The result of calling \code{\link{wbtopics}}
#' \item \code{income}: A data frame.The result of calling \code{\link{wbincome}}
#' \item \code{lending}: A data frame.The result of calling \code{\link{wblending}}
#' }
#'
#' @note Not all data returns have support for langauges other than english. If the specific return
#' does not support your requested language by default it will return \code{NA}. For an enumeration of
#' supported languages by data source please see \code{\link{wbdatacatalog}}.
#' The options for \code{lang} are:
#' \itemize{
#' \item \code{en}: English
#' \item \code{es}: Spanish
#' \item \code{fr}: French
#' \item \code{ar}: Arabic
#' \item \code{zh}: Mandarin
#' }
#' List item \code{datacatalog} will always return in english, as the API does not support any
#' other langauges for that information.
#'
#' Saving this return and using it has the \code{cache} parameter in \code{\link{wb}} and \code{\link{wbsearch}}
#' replaces the default cached version \code{\link{wb_cachelist}} that comes with the package itself
#' @export
wbcache <- function(lang = c("en", "es", "fr", "ar", "zh")) {
lifecycle::deprecate_soft("1.0.0", "wbstats::wbcache()", "wbstats::wb_cache()")
# if none supplied english is default
lang <- match.arg(lang)
cache_list <- list("countries" = wbcountries(lang = lang),
"indicators" = wbindicators(lang = lang),
"sources" = wbsources(lang = lang),
"datacatalog" = wbdatacatalog(), # does not take lang input
"topics" = wbtopics(lang = lang),
"income" = wbincome(lang = lang),
"lending" = wblending(lang = lang))
cache_list
}
|
/scratch/gouwar.j/cran-all/cranData/wbstats/R/deprecated-wbcache.R
|
#' Search indicator information available through the World Bank API
#'
#' This function allows finds indicators that match a search term and returns
#' a data frame of matching results
#'
#' @param pattern Character string or regular expression to be matched
#' @param fields Character vector of column names through which to search
#' @param extra if \code{FALSE}, only the indicator ID and short name are returned,
#' if \code{TRUE}, all columns of the \code{cache} parameter's indicator data frame
#' are returned
#' @param cache List of data frames returned from \code{\link{wbcache}}. If omitted,
#' \code{\link{wb_cachelist_dep}} is used
#' @return Data frame with indicators that match the search pattern.
#' @examples
#' wbsearch(pattern = "education")
#'
#' wbsearch(pattern = "Food and Agriculture Organization", fields = "sourceOrg")
#'
#' # with regular expression operators
#' # 'poverty' OR 'unemployment' OR 'employment'
#' wbsearch(pattern = "poverty|unemployment|employment")
#' @export
wbsearch <- function(pattern = "poverty", fields = c("indicator", "indicatorDesc"), extra = FALSE, cache){
lifecycle::deprecate_soft("1.0.0", "wbstats::wbsearch()", "wbstats::wb_search()")
if (missing(cache)) cache <- wbstats::wb_cachelist_dep
ind_cache <- cache$indicators
match_index <- sort(unique(unlist(sapply(fields, FUN = function(i)
grep(pattern, ind_cache[, i], ignore.case = TRUE), USE.NAMES = FALSE)
)))
if (length(match_index) == 0) warning(paste0("no matches were found for the search term ", pattern,
". Returning an empty data frame."))
if (extra) {
match_df <- ind_cache[match_index, ]
} else {
match_df <- ind_cache[match_index, c("indicatorID", "indicator")]
}
match_df
}
|
/scratch/gouwar.j/cran-all/cranData/wbstats/R/deprecated-wbsearch.R
|
#' @noRd
wb_end_point <- function(end_point, lang) {
get_url <- build_get_url(end_point, lang = lang)
d <- fetch_wb_url(get_url)
d_names <- format_wb_tidy_names(names(d), end_point = end_point)
names(d) <- d_names
format_wb_data(d, end_point = end_point)
}
#' World Bank Information End Points
#'
#' These functions are simple wrappers around the various useful API end points
#' that are helpful for finding avaiable data and filtering the data you are
#' interested in when using [wb_data()]
#'
#' @inheritParams wb_cache
#' @return A `tibble` of information about the end point
#' @name wb_end_point_info
#' @seealso [wb_cache()]
#' @md
NULL
#' Download World Bank country information
#' @rdname wb_end_point_info
#' @export
wb_countries <- function(lang) {
lang <- if_missing(lang, wb_default_lang(), lang)
wb_end_point("country", lang)
}
#' Download World Bank indicator topic information
#' @rdname wb_end_point_info
#' @export
wb_topics <- function(lang) {
lang <- if_missing(lang, wb_default_lang(), lang)
wb_end_point("topic", lang)
}
#' Download World Bank indicator source information
#' @rdname wb_end_point_info
#' @export
wb_sources <- function(lang) {
lang <- if_missing(lang, wb_default_lang(), lang)
wb_end_point("source", lang)
}
#' Download World Bank region information
#' @rdname wb_end_point_info
#' @export
wb_regions <- function(lang) {
lang <- if_missing(lang, wb_default_lang(), lang)
wb_end_point("region", lang)
}
#' Download World Bank income level information
#' @rdname wb_end_point_info
#' @export
wb_income_levels <- function(lang) {
lang <- if_missing(lang, wb_default_lang(), lang)
wb_end_point("income_level", lang)
}
#' Download World Bank lending type information
#' @rdname wb_end_point_info
#' @export
wb_lending_types <- function(lang) {
lang <- if_missing(lang, wb_default_lang(), lang)
wb_end_point("lending_type", lang)
}
#' Download available languages supported by World Bank
#' @rdname wb_end_point_info
#' @export
wb_languages <- function() {
wb_end_point("language", lang = NA)
}
#' Download Avialable Indicators from the World Bank
#'
#' This function returns a [tibble][tibble::tibble-package] of indicator IDs and related information
#' that are available for download from the World Bank API
#'
#' @inheritParams wb_cache
#' @param include_archive `logical`. If `TRUE` indicators that have been archived
#' by the World Bank will be included in the return. Data for these additional
#' indicators are not available through the standard API and querying them
#' using [wb_data()] will not return data. Default is `FALSE`.
#'
#' @examples
#' # can get a new list of available indicators by downloading new cache
#' \donttest{fresh_cache <- wb_cache()}
#' \donttest{fresh_indicators <- fresh_cache$indicators}
#'
#' # or by running the wb_indicators() function directly
#' \donttest{fresh_indicators <- wb_indicators()}
#'
#' # include archived indicators
#' # see include_archive parameter description
#' \donttest{indicators_with_achrive <- wb_indicators(include_archive = TRUE)}
#' @export
#' @md
wb_indicators <- function(lang, include_archive = FALSE) {
# source 57 are archived indicators that WB no longer supports and aren't
# avaialble through the standard API requests. After coorisponding with
# WB API developers, they suggested the best way forward for now was to
# simply exclude those indicators from being returned and available
# Date: 2019-10-31 (Happy Halloween!)
lang <- if_missing(lang, wb_default_lang(), lang)
df <- wb_end_point("indicator", lang)
if (!include_archive) df <- df[df$source_id != 57, ]
# TODO: unlist topics column
df
}
#' Download an updated list of country, indicator, and source information
#'
#' Download an updated list of information regarding countries, indicators,
#' sources, regions, indicator topics, lending types, income levels, and
#' supported languages from the World Bank API
#'
#' @param lang Language in which to return the results. If `lang` is unspecified,
#' english is the default. For supported languages see [wb_languages()].
#' Possible values of `lang` are in the `iso2` column. A note of warning, not
#' all data returns have support for langauges other than english. If the specific
#' return does not support your requested language by default it will return `NA`.
#'
#' @return A list containing the following items:
#' * `countries`: The result of calling [wb_countries()]
#' * `indicators`: The result of calling [wb_indicators()]
#' * `sources`: The result of calling [wb_sources()]
#' * `topics`: The result of calling [wb_topics()]
#' * `regions`: The result of calling [wb_regions()]
#' * `income_levels`: The result of calling [wb_income_levels()]
#' * `lending_types`: The result of calling [wb_lending_types()]
#' * `languages`: The result of calling [wb_languages()]
#'
#' @note Not all data returns have support for langauges other than english. If the specific return
#' does not support your requested language by default it will return `NA`. For an enumeration of
#' supported languages by data source please see [wb_languages()]
#'
#' Saving this return and using it has the `cache` parameter in [wb_data()] and [wb_search()]
#' replaces the default cached version [wb_cachelist] that comes with the package itself
#'
#' @export
#' @md
wb_cache <- function(lang) {
lang <- if_missing(lang, wb_default_lang(), lang)
list(
countries = wb_countries(lang),
indicators = wb_indicators(lang),
sources = wb_sources(lang),
topics = wb_topics(lang),
regions = wb_regions(lang),
income_levels = wb_income_levels(lang),
lending_types = wb_lending_types(lang),
languages = wb_languages()
)
}
|
/scratch/gouwar.j/cran-all/cranData/wbstats/R/end_points.R
|
#' @noRd
format_wb_tidy_names <- function(x, end_point) {
global_patterns <- wb_api_name_patterns$global_patterns
local_patterns <- wb_api_name_patterns[[end_point]]
all_patterns <- c(global_patterns, local_patterns)
# this can all be replaces by janitor::clean_names
x_trim <- stringr::str_trim(x)
x_lower <- stringr::str_to_lower(x_trim)
x_replace <- stringr::str_replace_all(x_lower, all_patterns)
x_tidy <- tibble::tidy_names(x_replace, quiet = TRUE)
x_tidy
}
#' @noRd
format_wb_data <- function(x, end_point) {
x_field_types <- format_wb_get_col_type(x)
col_index <- which(x_field_types %in% "character")
# skip date column b/c it has its own parsing function
col_index <- setdiff(col_index, which(names(x) == "date"))
x <- format_wb_func(x, readr::parse_guess,
col_index = col_index)
# still need to make sure that blanks are turned to NAs
if (end_point == "data") {
x_names <- format_wb_tidy_names(names(x), end_point = end_point)
names(x) <- x_names
if("value" %in% x_names) x$value <- as.numeric(x$value)
if("unit" %in% x_names) x$unit <- as.character(x$unit)
if("obs_status" %in% x_names) x$obs_status <- as.character(x$obs_status)
if("obs_status" %in% x_names) x$footnote <- as.character(x$footnote)
}
if (end_point == "country") x[x$iso3c == "NAM", "iso2c"] <- "NA"
if (end_point == "source") {
log_fields <- c("data_available", "metadata_available")
col_index <- which(names(x) %in% log_fields)
x <- format_wb_func(x, format_wb_func_as_logical,
true_pattern = "Yes|yes|Y|y",
false_pattern = "No|no|N|n",
col_index = col_index)
}
tibble::as_tibble(x)
}
#' @noRd
format_wb_get_col_type <- function(x, ...) {
x_type <- sapply(seq(ncol(x)), FUN = function(i) typeof(x[ ,i]))
names(x_type) <- names(x)
x_type
}
#' @noRd
format_wb_func_replace_value <- function(x, current_value, replacement, ...) {
x[x == current_value] <- replacement
x
}
#' @noRd
format_wb_func_as_logical <- function(x, true_pattern, false_pattern, ...) {
true_index <- grep(true_pattern, x = x, ...)
false_index <- grep(false_pattern, x = x, ...)
index_in_both <- base::intersect(true_index, false_index)
if(length(index_in_both) != 0)
warning("Patterns provided match both `TRUE` and `FALSE`.")
x[true_index] <- TRUE
x[false_index] <- FALSE
as.logical(x, ...)
}
#' @noRd
format_wb_func <- function(df, func, col_index, ...) {
if(missing(col_index)) col_index <- seq_len(ncol(df))
df[, col_index] <- lapply(col_index, FUN = function(i) {
x<- df[, i]
func(x, ...)
})
df
}
#' @noRd
format_wb_country <- function(x, cache) {
x_lower <- tolower(x)
if (missing(cache)) cache <- wbstats::wb_cachelist
cache_cn <- cache$countries
if (any(x_lower %in% c("countries", "countries_only", "countries only")))
# it is actually faster and more reliable to request 'all' and then filter afterwards
cn_params <- "all"
else if (any(x_lower %in% c("regions", "regions_only", "regions only")))
cn_params <- unique_na(cache_cn$region_iso3c)
else if (any(x_lower %in% c("admin_regions", "admin_regions_only", "admin regions only")))
cn_params <- unique_na(cache_cn$admin_region_iso3c)
else if (any(x_lower %in% c("income_levels", "income_levels_only", "income levels only")))
cn_params <- unique_na(cache_cn$income_level_iso3c)
else if (any(x_lower %in% c("lending_types", "lending_types_only", "lending types only")))
cn_params <- unique_na(cache_cn$lending_type_iso3c)
else if (any(x_lower %in% c("aggregates", "aggregates_only", "aggregates only")))
cn_params <- unique_na(cache_cn$iso3c[cache_cn$region == "Aggregates"])
else if (any(x_lower %in% "all"))
cn_params <- "all"
else if (length(x_lower) == 1 && x_lower == "the motherland") {
message("Good choice comrade...")
cn_params <- "rus"
}
else { # any non-special values
# all of the region, lending, and income names are also listed in these 3
# columns so a check here checks for all of them
cn_check <- as.matrix(cache_cn[ , c("iso3c", "iso2c", "country")])
# don't forget everything is lowercase now
cn_check <- tolower(cn_check)
good_cn_index <- x_lower %in% cn_check
good_cn <- x_lower[good_cn_index]
if (length(good_cn) == 0)
stop("No valid values for the country parameter were found.
Please check the country argument description in wbstats::wb_data() for valid input values.")
# use x instead of x_lower to KeEp UsEr DeFiNeD cAsInG
bad_cn <- x[!good_cn_index]
if (length(bad_cn) > 0)
warning(paste0("The following country values are not valid and are being excluded from the request: ",
paste(bad_cn, collapse = ",")))
# the API only accepts IDs and not names, so if a country is listed in x
# find its iso3c code. This lets the user pass values like "World" or "High Income"
good_cn_iso3c_index <- lapply(1:ncol(cn_check), function(i) {
which(cn_check[1:nrow(cn_check), i] %in% x_lower)
})
good_cn_iso3c_index <- unique(unlist(good_cn_iso3c_index))
cn_params <- cn_check[good_cn_iso3c_index, 1]
}
paste0(cn_params, collapse = ";")
}
|
/scratch/gouwar.j/cran-all/cranData/wbstats/R/format-data.R
|
#' Search indicator information available through the World Bank API
#'
#' This function allows finds indicators that match a search term and returns
#' a data frame of matching results
#'
#' @param pattern Character string or regular expression to be matched
#' @param fields Character vector of column names through which to search
#' @param extra if FALSE, only the indicator ID and short name are returned,
#' if `TRUE`, all columns of the `cache` parameter's indicators data frame
#' are returned. Default is `FALSE`
#' @param ignore.case if `FALSE`, the pattern matching is case sensitive and
#' if `TRUE`, case is ignored during matching. Default is `TRUE`
#' @param cache List of data frames returned from [wb_cache()]. If omitted,
#' [wb_cachelist] is used
#' @param ... Any additional [grep()] agruments you which to pass
#' @return a [tibble][tibble::tibble-package] with indicators that match the search pattern.
#' @md
#' @examples
#' \donttest{d <- wb_search(pattern = "education")}
#'
#' \donttest{d <- wb_search(pattern = "Food and Agriculture Organization", fields = "source_org")}
#'
#' # with regular expression operators
#' # 'poverty' OR 'unemployment' OR 'employment'
#' \donttest{d <- wb_search(pattern = "poverty|unemployment|employment")}
#'
#' # pass any other grep argument along as well
#' # everything without 'education'
#' \donttest{d <- wb_search(pattern = "education", invert = TRUE)}
#'
#' # contains "gdp" AND "trade"
#' \donttest{d <- wb_search("^(?=.*gdp)(?=.*trade).*", perl = TRUE)}
#'
#' # contains "gdp" and NOT "trade"
#' \donttest{d <- wb_search("^(?=.*gdp)(?!.*trade).*", perl = TRUE)}
#' @export
wb_search <- function(pattern, fields = c("indicator_id", "indicator", "indicator_desc"),
extra = FALSE, cache, ignore.case = TRUE, ...){
if (missing(cache)) cache <- wbstats::wb_cachelist
ind_cache <- as.data.frame(cache$indicators)
match_index <- sort(unique(unlist(sapply(fields, FUN = function(i)
grep(pattern, ind_cache[, i], ignore.case = ignore.case, ...), USE.NAMES = FALSE)
)))
if (length(match_index) == 0) warning(paste0("no matches were found for the search term ", pattern,
". Returning an empty data frame."))
if (extra) {
match_df <- cache$indicators[match_index, ]
} else {
match_df <- cache$indicators[match_index, c("indicator_id", "indicator", "indicator_desc")]
}
tibble::as_tibble(match_df)
}
|
/scratch/gouwar.j/cran-all/cranData/wbstats/R/search.R
|
#' @noRd
wb_default_lang <- function(lang) {
if (missing(lang)) {
env_lang <- options()$wbstats.lang
if (!is.null(env_lang)) default_lang <- env_lang
else default_lang <- wb_api_parameters$default_lang
}
else {
# here is where you would set the environ var
# do we check against available defaults?
options(wbstats.lang = lang)
message(paste("Setting default wbstats language to", lang,
"\nTo change this run wb_default_lang(lang = value).",
"The default value is 'en' (english)"))
default_lang <- wb_default_lang()
}
default_lang
}
|
/scratch/gouwar.j/cran-all/cranData/wbstats/R/update_cache.R
|
#' Pipe operator
#'
#' See \code{magrittr::\link[magrittr:pipe]{\%>\%}} for details.
#'
#' @name %>%
#' @rdname pipe
#' @keywords internal
#' @export
#' @importFrom magrittr %>%
#' @usage lhs \%>\% rhs
NULL
|
/scratch/gouwar.j/cran-all/cranData/wbstats/R/utils-pipe.R
|
#' Set the Value of a Missing Function Argument
#'
#' A simple wrapper around ifelse with the condition set to missing(x)
#'
#' @param x A function argument
#' @param true What to return if x is missing. Default is `NA`
#' @param false What to return if x is not missing. Default to return itself
#'
#' @noRd
if_missing <- function(x, true = NA, false = x) {
ifelse(missing(x), true, false)
}
#' @noRd
unique_na <- function(x, na.rm = TRUE) {
x_unique <- unique(x)
if(na.rm) x_unique <- x_unique[!is.na(x_unique)]
x_unique
}
#' @noRd
format_wb_dates <- function(df) {
date_vec <- df$date
new_date_vec <- as.Date(rep(NA, length(date_vec)))
obs_resolution <- as.character(rep(NA, length(date_vec)))
# annual ----------
annual_obs_index <- grep("[M|Q]", date_vec, invert = TRUE, ignore.case = TRUE)
if (length(annual_obs_index) > 0) {
annual_date <- as.Date(date_vec[annual_obs_index], "%Y")
annual_date_values <- lubridate::floor_date(annual_date, unit = "year")
new_date_vec[annual_obs_index] <- annual_date_values
obs_resolution[annual_obs_index] <- "annual"
}
# monthly ----------
monthly_obs_index <- grep("M", date_vec, ignore.case = TRUE)
if (length(monthly_obs_index) > 0) {
monthly_date <- lubridate::ydm(gsub("M", "01", date_vec[monthly_obs_index]))
monthly_date_values <- lubridate::floor_date(monthly_date, unit = "month")
new_date_vec[monthly_obs_index] <- monthly_date_values
obs_resolution[monthly_obs_index] <- "monthly"
}
# quarterly ----------
quarterly_obs_index <- grep("Q", date_vec, ignore.case = TRUE)
if (length(quarterly_obs_index) > 0) {
# takes a little more work
qtr_obs <- strsplit(date_vec[quarterly_obs_index], "Q")
qtr_df <- as.data.frame(matrix(unlist(qtr_obs), ncol = 2, byrow = TRUE), stringsAsFactors = FALSE)
names(qtr_df) <- c("year", "qtr")
qtr_df$month <- as.numeric(qtr_df$qtr) * 3 # to turn into the max month
qtr_format_vec <- paste0(qtr_df$year, "01", qtr_df$month) # 01 acts as a dummy day
quarterly_date <- lubridate::ydm(qtr_format_vec)
quarterly_date_values <- lubridate::floor_date(quarterly_date, unit = "quarter")
new_date_vec[quarterly_obs_index] <- quarterly_date_values
obs_resolution[quarterly_obs_index] <- "quarterly"
}
df$date <- new_date_vec
df$obs_resolution <- obs_resolution
df
}
|
/scratch/gouwar.j/cran-all/cranData/wbstats/R/utils.R
|
#' Download Data from the World Bank API
#'
#' This function downloads the requested information using the World Bank API
#'
#' @param indicator Character vector of indicator codes. These codes correspond
#' to the `indicator_id` column from the `indicators` tibble of [wb_cache()], [wb_cachelist], or
#' the result of running [wb_indicators()] directly
#' @param country Character vector of country, region, or special value codes for the
#' locations you want to return data for. Permissible values can be found in the
#' countries tibble in [wb_cachelist] or by running [wb_countries()] directly.
#' Specifically, values listed in the following fields `iso3c`, `iso2c`, `country`,
#' `region`, `admin_region`, `income_level` and all of the `region_*`,
#' `admin_region_*`, `income_level_*`, columns. As well as the following special values
#' * `"countries_only"` (Default)
#' * `"regions_only"`
#' * `"admin_regions_only"`
#' * `"income_levels_only"`
#' * `"aggregates_only"`
#' * `"all"`
#' @param start_date Numeric or character. If numeric it must be in `%Y` form (i.e. four digit year).
#' For data at the subannual granularity the API supports a format as follows: for monthly data, "2016M01"
#' and for quarterly data, "2016Q1". This also accepts a special value of "YTD", useful for more frequently
#' updated subannual indicators.
#' @param end_date Numeric or character. If numeric it must be in `%Y` form (i.e. four digit year).
#' For data at the subannual granularity the API supports a format as follows: for monthly data, "2016M01"
#' and for quarterly data, "2016Q1".
#' @param return_wide Logical. If `TRUE` data is returned in a wide format instead of long,
#' with a column named for each `indicator_id` or if the `indicator` argument is a named vector,
#' the [names()] given to the indicator will be the column names. To necessitate this transformation,
#' the `indicator` column that provides the human readable description is dropped, but provided as a column label.
#' Default is `TRUE`
#' @param mrv Numeric. The number of Most Recent Values to return. A replacement
#' of `start_date` and `end_date`, this number represents the number of observations
#' you which to return starting from the most recent date of collection. This may include missing values.
#' Useful in conjuction with `freq`
#' @param mrnev Numeric. The number of Most Recent Non Empty Values to return. A replacement
#' of `start_date` and `end_date`, similar in behavior as `mrv` but excludes locations with missing values.
#' Useful in conjuction with `freq`
#' @param cache List of tibbles returned from [wb_cache()]. If omitted, [wb_cachelist] is used
#' @param freq Character String. For fetching quarterly ("Q"), monthly("M") or yearly ("Y") values.
#' Useful for querying high frequency data.
#' @param gapfill Logical. If `TRUE` fills in missing values by carrying forward the last
#' available value until the next available period (max number of periods back tracked will be limited by `mrv` number).
#' Default is `FALSE`
#' @param date_as_class_date Logical. If `TRUE` the date field is returned as class [Date], useful when working with
#' non-annual data or data at mixed resolutions. Default is `FALSE`
#' available value until the next available period (max number of periods back tracked will be limited by `mrv` number).
#' Default is `FALSE`
#' @inheritParams wb_cache
#'
#' @return a [tibble][tibble::tibble-package] of all available requested data.
#'
#' @details
#' ## `obs_status` column
#' Indicates the observation status for location, indicator and date combination.
#' For example `"F"` in the response indicates that the observation status for
#' that data point is "forecast".
#'
#' @export
#' @importFrom rlang .data
#' @md
#'
#'
#' @examples
#'
#'
#' # gdp for all countries for all available dates
#' \donttest{df_gdp <- wb_data("NY.GDP.MKTP.CD")}
#'
#' # Brazilian gdp for all available dates
#' \donttest{df_brazil <- wb_data("NY.GDP.MKTP.CD", country = "br")}
#'
#' # Brazilian gdp for 2006
#' \donttest{
#' df_brazil_1 <- wb_data("NY.GDP.MKTP.CD", country = "brazil", start_date = 2006)
#' }
#'
#' # Brazilian gdp for 2006-2010
#' \donttest{
#' df_brazil_2 <- wb_data("NY.GDP.MKTP.CD", country = "BRA",
#' start_date = 2006, end_date = 2010)
#'}
#'
#' # Population, GDP, Unemployment Rate, Birth Rate (per 1000 people)
#' \donttest{
#' my_indicators <- c("SP.POP.TOTL",
#' "NY.GDP.MKTP.CD",
#' "SL.UEM.TOTL.ZS",
#' "SP.DYN.CBRT.IN")
#'}
#'
#' \donttest{df <- wb_data(my_indicators)}
#'
#' # you pass multiple country ids of different types
#' # Albania (iso2c), Georgia (iso3c), and Mongolia
#' \donttest{
#' my_countries <- c("AL", "Geo", "mongolia")
#' df <- wb_data(my_indicators, country = my_countries,
#' start_date = 2005, end_date = 2007)
#'}
#'
#' # same data as above, but in long format
#' \donttest{
#' df_long <- wb_data(my_indicators, country = my_countries,
#' start_date = 2005, end_date = 2007,
#' return_wide = FALSE)
#'}
#'
#' # regional population totals
#' # regions correspond to the region column in wb_cachelist$countries
#' \donttest{
#' df_region <- wb_data("SP.POP.TOTL", country = "regions_only",
#' start_date = 2010, end_date = 2014)
#' }
#'
#' # a specific region
#' \donttest{
#' df_world <- wb_data("SP.POP.TOTL", country = "world",
#' start_date = 2010, end_date = 2014)
#'}
#'
#' # if the indicator is part of a named vector the name will be the column name
#' my_indicators <- c("pop" = "SP.POP.TOTL",
#' "gdp" = "NY.GDP.MKTP.CD",
#' "unemployment_rate" = "SL.UEM.TOTL.ZS",
#' "birth_rate" = "SP.DYN.CBRT.IN")
#'\donttest{
#' df_names <- wb_data(my_indicators, country = "world",
#' start_date = 2010, end_date = 2014)
#'}
#'
#' # custom names are ignored if returning in long format
#' \donttest{
#' df_names_long <- wb_data(my_indicators, country = "world",
#' start_date = 2010, end_date = 2014,
#' return_wide = FALSE)
#'}
#'
#' # same as above but in Bulgarian
#' # note that not all indicators have translations for all languages
#' \donttest{
#' df_names_long_bg <- wb_data(my_indicators, country = "world",
#' start_date = 2010, end_date = 2014,
#' return_wide = FALSE, lang = "bg")
#'}
wb_data <- function(indicator, country = "countries_only", start_date, end_date,
return_wide = TRUE, mrv, mrnev, cache, freq, gapfill = FALSE,
date_as_class_date = FALSE, lang) {
if (missing(cache)) cache <- wbstats::wb_cachelist
base_url <- wb_api_parameters$base_url
# format country ----------------------------------------------------------
country_param <- format_wb_country(country, cache = cache)
country_path <- paste0(wb_api_parameters$country, "/", country_param)
# check dates ----------
date_query <- NULL
if (!missing(start_date) && missing(end_date)) date_query <- paste0(start_date, ":", start_date)
if (missing(start_date) && !missing(end_date)) date_query <- paste0(end_date, ":", end_date)
if (missing(start_date) == FALSE && missing(end_date) == FALSE) date_query <- paste0(start_date, ":", end_date)
# check freq ----------
freq_query <- NULL
if (!missing(freq)) {
if (!freq %in% c("Y", "Q", "M"))
stop("If supplied, values for freq must be one of the following 'Y' (yearly), 'Q' (Quarterly), or 'M' (Monthly)")
freq_query <- freq
}
# check mrv ----------
mrv_query <- NULL
if (!missing(mrv)) {
if (!is.numeric(mrv)) stop("If supplied, mrv must be numeric")
mrv_query <- paste0(round(mrv, digits = 0)) # just to make sure its a whole number
}
# check mrnev ----------
mrnev_query <- NULL
if (!missing(mrnev)) {
if (!is.numeric(mrnev)) stop("If supplied, mrnev must be numeric")
mrnev_query <- paste0(round(mrnev, digits = 0)) # just to make sure its a whole number
}
# check gapfill ----------
gapfill_query <- NULL
if (!missing(gapfill)) {
if (!is.logical(gapfill)) stop("If supplied, values for gapfill must be TRUE or FALSE")
if (missing(mrv)) stop("mrv must be supplied for gapfill to be used")
gapfill_query <- ifelse(gapfill, "Y", "N")
}
# check scale ----------
scale_query <- NULL
# remove support for scale parameter, it causes more problems that in solves
# if (!missing(scale)) {
# if (!is.logical(scale)) stop("Values for scale must be TRUE or FALSE")
#
# scale_query <- ifelse(scale, "Y", "N")
# }
# country should be part of the path list b/c other endpoint don't require it or need more things
path_list <- list(
version = wb_api_parameters$version,
lang = if_missing(lang, wb_default_lang(), lang),
country = country_path
)
# what is NULL just gets dropped in the build url step
query_list <- list(
date = date_query,
scale = scale_query,
frequency = freq_query,
mrv = mrv_query,
mrnev = mrnev_query,
gapfill = gapfill_query,
footnote = "y",
cntrycode = "y",
per_page = wb_api_parameters$per_page,
format = wb_api_parameters$format
)
# be able to return this for debugging
ind_url <- build_wb_url(
base_url = base_url, indicator = indicator,
path_list = path_list, query_list = query_list
)
# d_list <- lapply(ind_url, fetch_wb_url)
d_list <- lapply(seq_along(ind_url),
FUN = function(i){
fetch_wb_url(
url_string = ind_url[i],
indicator = indicator[i]
)
}
)
d_list <- d_list[sapply(d_list, is.data.frame)]
d <- do.call(rbind, d_list)
if(!is.data.frame(d)) {
warning("No data was returned for your query. Returning an empty tibble")
return(tibble::tibble())
}
d <- format_wb_data(d, end_point = "data")
if (any(is.na(d$iso3c))) {
# country names are not replaced with with cached versions b/c
# some country names are subnational values where the iso3c and iso2c would
# be the same value across mutliple subnational units
d <- d %>%
dplyr::mutate(
iso3c = as.character(.data$iso3c),
iso2c = as.character(.data$iso2c),
iso3c = dplyr::if_else(is.na(.data$iso3c), .data$iso2c, .data$iso3c)
) %>%
dplyr::select(-.data$iso2c) %>%
dplyr::left_join(
dplyr::select(cache$countries, .data$iso3c, .data$iso2c),
by = "iso3c"
)
}
# country_only actually requests 'all' from the API, now remove non-countries
if (any(tolower(country) %in% c("countries", "countries_only", "countries only"))) {
country_only_iso3c <- unique_na(cache$countries$iso3c[cache$countries$region != "Aggregates"])
d <- d[d$iso3c %in% country_only_iso3c, ]
}
if(nrow(d) == 0) {
warning("No data was returned for your query. Returning an empty tibble")
return(tibble::tibble())
}
if (return_wide) {
context_cols <- c("iso2c", "iso3c", "country", "date")
extra_cols <- c("unit", "obs_status","footnote", "last_updated")
ind_names <- as.data.frame(unique(d[, c("indicator", "indicator_id")]))
# the decimal column is dropped here b/c support for scale=TRUE was removed
cols_to_keep <- setdiff(names(d), c("indicator", "decimal"))
# when you return a wide data frame with more than one indicator
# the extra_cols are dropped b/c they are specific to each location, indicator, date
# instance and they have to be rowwise so if you transpose with them it messes
# everything up
if (length(unique(ind_names$indicator_id)) > 1) {
cols_to_keep <- setdiff(cols_to_keep, extra_cols)
}
d <- d[ , cols_to_keep]
d <- tidyr::spread(d, key = "indicator_id", value = "value")
# column labels
for (i in 1:nrow(ind_names)) {
d_col_name <- ind_names$indicator_id[i]
d_col_label <- ind_names$indicator[i]
attr(d[[d_col_name]], "label") <- d_col_label
}
# named vector for indicators
if (!is.null(names(indicator))) {
for (i in 1:nrow(ind_names)) {
d_col_old_name <- ind_names$indicator_id[i]
d_col_new_name <- names(indicator[indicator == d_col_old_name])
if(! (d_col_new_name == "" || is.null(d_col_new_name)) )
names(d)[which(names(d) == d_col_old_name)] <- d_col_new_name
}
}
indicator_cols <- setdiff(names(d), c(context_cols, extra_cols))
d <- dplyr::select(d,
context_cols,
indicator_cols,
dplyr::everything()
)
} # end return_wide
else {
# these columns are reordered for readability
col_order <- c("indicator_id", "indicator", "iso2c", "iso3c", "country", "date",
"value", "unit", "obs_status", "footnote", "last_updated")
col_order2 <- col_order[col_order %in% names(d)]
d <- d[ , col_order2]
}
if (date_as_class_date) d <- format_wb_dates(d)
else if (!any(grepl("M|Q", d$date, ignore.case = TRUE))) d$date <- as.numeric(d$date)
d
}
|
/scratch/gouwar.j/cran-all/cranData/wbstats/R/wb_data.R
|
#' wbstats: An R package for searching and downloading data from the World Bank API.
#'
#' The wbstats package provides structured access to data
#' available from the World Bank API including; support for mutliple languages,
#' access to annual, quarterly, and monthly data.
#'
#' @docType package
#' @importFrom tibble tibble
#' @name wbstats
NULL
|
/scratch/gouwar.j/cran-all/cranData/wbstats/R/wbstats-package.R
|
.onLoad <- function(libname, pkgname) {
op.wbstats <- list(
wbstats.lang = "en",
wbstats.cache_dir = NULL,
wbstats.refresh_cache_on_load = FALSE,
wbstats.cache_life = as.difftime(7, units = "days"),
wbstats.cache_timestamp = NULL
)
# if the options are there, set them
op_to_set <- !(names(op.wbstats) %in% names(options()))
if(any(op_to_set)) options(op.wbstats[op_to_set])
# check_refresh_on_load()
}
|
/scratch/gouwar.j/cran-all/cranData/wbstats/R/zzz.R
|
---
title: "wbstats"
output:
md_document:
variant: gfm
vignette: >
%\VignetteIndexEntry{wbstats}
%\VignetteEngine{knitr::knitr}
%\VignetteEncoding{UTF-8}
---
<!-- README.md is generated from README.Rmd. Please edit that file -->
# wbstats: An R package for searching and downloading data from the World Bank API.
You can install:
The latest release version from CRAN with
```r
install.packages("wbstats")
```
or
The latest development version from github with
```r
devtools::install_github("nset-ornl/wbstats")
```
# Introduction
The World Bank^[<https://www.worldbank.org/>] is a tremendous source of global socio-economic data; spanning several decades and dozens of topics, it has the potential to shed light on numerous global issues. To help provide access to this rich source of information, The World Bank themselves, provide a well structured RESTful API. While this API is very useful for integration into web services and other high-level applications, it becomes quickly overwhelming for researchers who have neither the time nor the expertise to develop software to interface with the API. This leaves the researcher to rely on manual bulk downloads of spreadsheets of the data they are interested in. This too is can quickly become overwhelming, as the work is manual, time consuming, and not easily reproducible. The goal of the `wbstats` R-package is to provide a bridge between these alternatives and allow researchers to focus on their research questions and not the question of accessing the data. The `wbstats` R-package allows researchers to quickly search and download the data of their particular interest in a programmatic and reproducible fashion; this facilitates a seamless integration into their workflow and allows analysis to be quickly rerun on different areas of interest and with realtime access to the latest available data.
### Highlighted features of the `wbstats` R-package:
- Uses version 2 of the World Bank API that provides access to more indicators and metadata than the previous API version
- Access to all annual, quarterly, and monthly data available in the API
- Support for searching and downloading data in multiple languages
- Returns data in either wide (default) or long format
- Support for Most Recent Value queries
- Support for `grep` style searching for data descriptions and names
- Ability to download data not only by country, but by aggregates as well, such as High Income or South Asia
# Getting Started
Unless you know the country and indicator codes that you want to download the first step would be searching for the data you are interested in. `wb_search()` provides `grep` style searching of all available indicators from the World Bank API and returns the indicator information that matches your query.
To access what countries or regions are available you can use the `countries` data frame from either `wb_cachelist` or the saved return from `wb_cache()`. This data frame contains relevant information regarding each country or region. More information on how to use this for downloading data is covered later.
## Finding available data with `wb_cachelist`
For performance and ease of use, a cached version of useful information is provided with the `wbstats` R-package. This data is called `wb_cachelist` and provides a snapshot of available countries, indicators, and other relevant information. `wb_cachelist` is by default the the source from which `wb_search()` and `wb_data()` uses to find matching information. The structure of `wb_cachelist` is as follows
```r
library(wbstats)
str(wb_cachelist, max.level = 1)
#> List of 8
#> $ countries : tibble [304 x 18] (S3: tbl_df/tbl/data.frame)
#> $ indicators : tibble [16,649 x 8] (S3: tbl_df/tbl/data.frame)
#> $ sources : tibble [63 x 9] (S3: tbl_df/tbl/data.frame)
#> $ topics : tibble [21 x 3] (S3: tbl_df/tbl/data.frame)
#> $ regions : tibble [48 x 4] (S3: tbl_df/tbl/data.frame)
#> $ income_levels: tibble [7 x 3] (S3: tbl_df/tbl/data.frame)
#> $ lending_types: tibble [4 x 3] (S3: tbl_df/tbl/data.frame)
#> $ languages : tibble [23 x 3] (S3: tbl_df/tbl/data.frame)
```
## Accessing updated available data with `wb_cache()`
For the most recent information on available data from the World Bank API `wb_cache()` downloads an updated version of the information stored in `wb_cachelist`. `wb_cachelist` is simply a saved return of `wb_cache(lang = "en")`. To use this updated information in `wb_search()` or `wb_data()`, set the `cache` parameter to the saved `list` returned from `wb_cache()`. It is always a good idea to use this updated information to insure that you have access to the latest available information, such as newly added indicators or data sources. There are also cases in which indicators that were previously available from the API have been removed or deprecated.
```r
library(wbstats)
# default language is english
new_cache <- wb_cache()
```
## Search available data with `wb_search()`
`wb_search()` searches through the `indicators` data frame to find indicators that match a search pattern. An example of the structure of this data frame is below
```
#> # A tibble: 2 x 8
#> indicator_id indicator unit indicator_desc source_org topics source_id source
#> <chr> <chr> <lgl> <chr> <chr> <list> <dbl> <chr>
#> 1 NY.GDP.MKTP.~ GDP (curre~ NA GDP at purchaser's prices is the sum of gross va~ World Bank national accounts data, and OECD~ <df[,2]~ 2 World Deve~
#> 2 SP.POP.TOTL Population~ NA Total population is based on the de facto defini~ (1) United Nations Population Division. Wor~ <df[,2]~ 2 World Deve~
```
By default the search is done over the `indicator_id`, `indicator`, and `indicator_desc` fields and returns the those 3 columns of the matching rows. The `indicator_id` values are inputs into `wb_data()`, the function for downloading the data. To return all columns for the `indicators` data frame, you can set `extra = TRUE`.
```r
library(wbstats)
unemploy_inds<- wb_search("unemployment")
head(unemploy_inds)
#> # A tibble: 6 x 3
#> indicator_id indicator indicator_desc
#> <chr> <chr> <chr>
#> 1 fin37.t.a Received government transfers in the past year (~ The percentage of respondents who report personally receiving any financial support from the ~
#> 2 fin37.t.a.1 Received government transfers in the past year, ~ The percentage of respondents who report personally receiving any financial support from the ~
#> 3 fin37.t.a.10 Received government transfers in the past year, ~ The percentage of respondents who report personally receiving any financial support from the ~
#> 4 fin37.t.a.11 Received government transfers in the past year, ~ The percentage of respondents who report personally receiving any financial support from the ~
#> 5 fin37.t.a.2 Received government transfers in the past year, ~ The percentage of respondents who report personally receiving any financial support from the ~
#> 6 fin37.t.a.3 Received government transfers in the past year, ~ The percentage of respondents who report personally receiving any financial support from the ~
```
Other fields can be searched by simply changing the `fields` parameter. For example
```r
library(wbstats)
blmbrg_vars <- wb_search("Bloomberg", fields = "source_org")
head(blmbrg_vars)
#> # A tibble: 2 x 3
#> indicator_id indicator indicator_desc
#> <chr> <chr> <chr>
#> 1 GFDD.OM.02 Stock market return (%, year~ Stock market return is the growth rate of annual average stock market index. Annual average stock market index is~
#> 2 GFDD.SM.01 Stock price volatility Stock price volatility is the average of the 360-day volatility of the national stock market index.
```
Regular expressions are also supported
```r
library(wbstats)
# 'poverty' OR 'unemployment' OR 'employment'
povemply_inds <- wb_search(pattern = "poverty|unemployment|employment")
head(povemply_inds)
#> # A tibble: 6 x 3
#> indicator_id indicator indicator_desc
#> <chr> <chr> <chr>
#> 1 1.0.HCount.1.90usd Poverty Headcount ($1.90 a d~ The poverty headcount index measures the proportion of the population with daily per capita income (in 2011~
#> 2 1.0.HCount.2.5usd Poverty Headcount ($2.50 a d~ The poverty headcount index measures the proportion of the population with daily per capita income (in 2005~
#> 3 1.0.HCount.Mid10t~ Middle Class ($10-50 a day) ~ The poverty headcount index measures the proportion of the population with daily per capita income (in 2005~
#> 4 1.0.HCount.Ofcl Official Moderate Poverty Ra~ The poverty headcount index measures the proportion of the population with daily per capita income below th~
#> 5 1.0.HCount.Poor4u~ Poverty Headcount ($4 a day) The poverty headcount index measures the proportion of the population with daily per capita income (in 2005~
#> 6 1.0.HCount.Vul4to~ Vulnerable ($4-10 a day) Hea~ The poverty headcount index measures the proportion of the population with daily per capita income (in 2005~
```
As well as any `grep` function argument
```r
library(wbstats)
# contains "gdp" and NOT "trade"
gdp_no_trade_inds <- wb_search("^(?=.*gdp)(?!.*trade).*", perl = TRUE)
head(gdp_no_trade_inds)
#> # A tibble: 6 x 3
#> indicator_id indicator indicator_desc
#> <chr> <chr> <chr>
#> 1 5.51.01.10.gdp Per capita GDP growth GDP per capita is the sum of gross value added by all resident producers in the economy plus any produ~
#> 2 6.0.GDP_current GDP (current $) GDP is the sum of gross value added by all resident producers in the economy plus any product taxes an~
#> 3 6.0.GDP_growth GDP growth (annual %) Annual percentage growth rate of GDP at market prices based on constant local currency. Aggregates are~
#> 4 6.0.GDP_usd GDP (constant 2005 $) GDP is the sum of gross value added by all resident producers in the economy plus any product taxes an~
#> 5 6.0.GDPpc_const~ GDP per capita, PPP (constant 2011 ~ GDP per capita based on purchasing power parity (PPP). PPP GDP is gross domestic product converted to ~
#> 6 BI.WAG.TOTL.GD.~ Wage bill as a percentage of GDP <NA>
```
The default cached data in `wb_cachelist` is in English. To search indicators in a different language, you can download an updated copy of `wb_cachelist` using `wb_cache()`, with the `lang` parameter set to the language of interest and then set this as the `cache` parameter in `wb_search()`. Other languages are supported in so far as they are supported by the original data sources. Some sources provide full support for other languages, while some have very limited support. If the data source does not have a translation for a certain field or indicator then the result is `NA`, this may result in a varying number matches depending upon the language you select. To see a list of availabe languages call `wb_languages()`
```r
library(wbstats)
wb_langs <- wb_languages()
```
## Downloading data with `wb_data()`
Once you have found the set of indicators that you would like to explore further, the next step is downloading the data with `wb_data()`. The following examples are meant to highlight the different ways in which `wb_data()` can be used and demonstrate the major optional parameters.
The default value for the `country` parameter is a special value of `"countries_only"`, which as you might expect, returns data on the selected `indicator` for only countries. This is in contrast to `country = "all"` or `country = "regions_only"` which would return data for countries and regional aggregates together, or only regional aggregates, respectively
```r
library(wbstats)
# Population, total
pop_data <- wb_data("SP.POP.TOTL", start_date = 2000, end_date = 2002)
head(pop_data)
#> # A tibble: 6 x 9
#> iso2c iso3c country date SP.POP.TOTL unit obs_status footnote last_updated
#> <chr> <chr> <chr> <dbl> <dbl> <chr> <chr> <chr> <date>
#> 1 AW ABW Aruba 2000 90853 <NA> <NA> <NA> 2020-10-15
#> 2 AW ABW Aruba 2001 92898 <NA> <NA> <NA> 2020-10-15
#> 3 AW ABW Aruba 2002 94992 <NA> <NA> <NA> 2020-10-15
#> 4 AF AFG Afghanistan 2000 20779953 <NA> <NA> <NA> 2020-10-15
#> 5 AF AFG Afghanistan 2001 21606988 <NA> <NA> <NA> 2020-10-15
#> 6 AF AFG Afghanistan 2002 22600770 <NA> <NA> <NA> 2020-10-15
```
If you are interested in only some subset of countries or regions you can pass along the specific codes to the `country` parameter. The country and region codes and names that can be passed to the `country` parameter as well, most prominently the coded values from the `iso2c` and `iso3c` from the `countries` data frame in `wb_cachelist` or the return of `wb_cache()`. Any values from the above columns can mixed together and passed to the same call
```r
library(wbstats)
# you can mix different ids and they are case insensitive
# you can even use SpOnGeBoB CaSe if that's the kind of thing you're into
# iso3c, iso2c, country, region_iso3c, admin_region_iso3c, admin_region, income_level
example_geos <- c("ABW","AF", "albania", "SSF", "eca", "South Asia", "HiGh InCoMe")
pop_data <- wb_data("SP.POP.TOTL", country = example_geos,
start_date = 2012, end_date = 2012)
pop_data
#> # A tibble: 7 x 9
#> iso2c iso3c country date SP.POP.TOTL unit obs_status footnote last_updated
#> <chr> <chr> <chr> <dbl> <dbl> <chr> <chr> <chr> <date>
#> 1 AW ABW Aruba 2012 102560 <NA> <NA> <NA> 2020-10-15
#> 2 AF AFG Afghanistan 2012 31161376 <NA> <NA> <NA> 2020-10-15
#> 3 AL ALB Albania 2012 2900401 <NA> <NA> <NA> 2020-10-15
#> 4 7E ECA Europe & Central Asia (excluding high income) 2012 382509766 <NA> <NA> <NA> 2020-10-15
#> 5 8S SAS South Asia 2012 1683747130 <NA> <NA> <NA> 2020-10-15
#> 6 ZG SSF Sub-Saharan Africa 2012 917726973 <NA> <NA> <NA> 2020-10-15
#> 7 <NA> XD High income 2012 1191504227 <NA> <NA> <NA> 2020-10-15
```
As of `wbstats 1.0` queries are now returned in wide format. This was a request made by multiple users and is in line with the principles of [tidy data](https://www.jstatsoft.org/article/view/v059i10). If you would like to return the data in a long format, you can set `return_wide = FALSE`
Now that each indicator is it's own column, we can allow custom names for the indicators
```r
library(wbstats)
my_indicators = c("pop" = "SP.POP.TOTL",
"gdp" = "NY.GDP.MKTP.CD")
pop_gdp <- wb_data(my_indicators, start_date = 2010, end_date = 2012)
head(pop_gdp)
#> # A tibble: 6 x 6
#> iso2c iso3c country date gdp pop
#> <chr> <chr> <chr> <dbl> <dbl> <dbl>
#> 1 AW ABW Aruba 2010 2390502793. 101669
#> 2 AW ABW Aruba 2011 2549720670. 102046
#> 3 AW ABW Aruba 2012 2534636872. 102560
#> 4 AF AFG Afghanistan 2010 15856574731. 29185507
#> 5 AF AFG Afghanistan 2011 17804292964. 30117413
#> 6 AF AFG Afghanistan 2012 20001598506. 31161376
```
You'll notice that when you query only one indicator, as in the first two examples above, it returns the extra fields `unit`, `obs_status`, `footnote`, and `last_updated`, but when we queried multiple indicators at once, as in our last example, they are dropped. This is because those extra fields are tied to a specific observation of a single indicator and when we have multiple indciator values in a single row, they are no longer consistent with the tidy data format. If you would like that information for multiple indicators, you can use `return_wide = FALSE`
```r
library(wbstats)
my_indicators = c("pop" = "SP.POP.TOTL",
"gdp" = "NY.GDP.MKTP.CD")
pop_gdp_long <- wb_data(my_indicators, start_date = 2010, end_date = 2012, return_wide = FALSE)
head(pop_gdp_long)
#> # A tibble: 6 x 11
#> indicator_id indicator iso2c iso3c country date value unit obs_status footnote last_updated
#> <chr> <chr> <chr> <chr> <chr> <dbl> <dbl> <chr> <chr> <chr> <date>
#> 1 SP.POP.TOTL Population, total AF AFG Afghanistan 2012 31161376 <NA> <NA> <NA> 2020-10-15
#> 2 SP.POP.TOTL Population, total AF AFG Afghanistan 2011 30117413 <NA> <NA> <NA> 2020-10-15
#> 3 SP.POP.TOTL Population, total AF AFG Afghanistan 2010 29185507 <NA> <NA> <NA> 2020-10-15
#> 4 SP.POP.TOTL Population, total AL ALB Albania 2012 2900401 <NA> <NA> <NA> 2020-10-15
#> 5 SP.POP.TOTL Population, total AL ALB Albania 2011 2905195 <NA> <NA> <NA> 2020-10-15
#> 6 SP.POP.TOTL Population, total AL ALB Albania 2010 2913021 <NA> <NA> <NA> 2020-10-15
```
### Using `mrv` and `mrnev`
If you do not know the latest date an indicator you are interested in is available for you country you can use the `mrv` instead of `start_date` and `end_date`. `mrv` stands for most recent value and takes a `integer` corresponding to the number of most recent values you wish to return
```r
library(wbstats)
# most recent gdp per captia estimates
gdp_capita <- wb_data("NY.GDP.PCAP.CD", mrv = 1)
head(gdp_capita)
#> # A tibble: 6 x 9
#> iso2c iso3c country date NY.GDP.PCAP.CD unit obs_status footnote last_updated
#> <chr> <chr> <chr> <dbl> <dbl> <chr> <chr> <chr> <date>
#> 1 AW ABW Aruba 2019 NA <NA> <NA> <NA> 2020-10-15
#> 2 AF AFG Afghanistan 2019 502. <NA> <NA> <NA> 2020-10-15
#> 3 AO AGO Angola 2019 2974. <NA> <NA> <NA> 2020-10-15
#> 4 AL ALB Albania 2019 5353. <NA> <NA> <NA> 2020-10-15
#> 5 AD AND Andorra 2019 40886. <NA> <NA> <NA> 2020-10-15
#> 6 AE ARE United Arab Emirates 2019 43103. <NA> <NA> <NA> 2020-10-15
```
Often it is the case that the latest available data is different from country to country. There may be 2020 estimates for one location, while another only has estimates up to 2019. This is especially true for survey data. When you would like to return the latest avialble data for each country regardless of its temporal misalignment, you can use the `mrnev` instead of `mrnev`. `mrnev` stands for most recent non empty value.
```r
library(wbstats)
gdp_capita <- wb_data("NY.GDP.PCAP.CD", mrnev = 1)
head(gdp_capita)
#> # A tibble: 6 x 8
#> iso2c iso3c country date NY.GDP.PCAP.CD obs_status footnote last_updated
#> <chr> <chr> <chr> <dbl> <dbl> <chr> <chr> <date>
#> 1 AW ABW Aruba 2017 29008. <NA> <NA> 2020-10-15
#> 2 AF AFG Afghanistan 2019 502. <NA> <NA> 2020-10-15
#> 3 AO AGO Angola 2019 2974. <NA> <NA> 2020-10-15
#> 4 AL ALB Albania 2019 5353. <NA> <NA> 2020-10-15
#> 5 AD AND Andorra 2019 40886. <NA> <NA> 2020-10-15
#> 6 AE ARE United Arab Emirates 2019 43103. <NA> <NA> 2020-10-15
```
### Dates
Because the majority of data available from the World Bank is at the annual resolution, by default dates in `wbstats` are returned as `numeric`s. This default makes common tasks like filtering easier. If you would like the date field to be of class `Date` you can set `date_as_class_date = TRUE`
# Some Sharp Corners
There are a few behaviors of the World Bank API that being aware of could help explain some potentially unexpected results. These results are known but no special actions are taken to mitigate them as they are the result of the API itself and artifically limiting the inputs or results could potentially causes problems or create unnecessary rescrictions in the future.
## Searching in other languages
Not all data sources support all languages. If an indicator does not have a translation for a particular language, the non-supported fields will return as `NA`. This could potentially result in a differing number of matching indicators from `wb_search()`
```r
library(wbstats)
# english
cache_en <- wb_cache()
sum(is.na(cache_en$indicators$indicator))
#> [1] 0
# spanish
cache_es <- wb_cache(lang = "es")
sum(is.na(cache_es$indicators$indicator))
#> [1] 14791
```
# Legal
The World Bank Group, or any of its member instutions, do not support or endorse this software and are not libable for any findings or conclusions that come from the use of this software.
|
/scratch/gouwar.j/cran-all/cranData/wbstats/inst/doc/wbstats.Rmd
|
library(knitr)
knit("vignettes/wbstats.Rmd.orig", "vignettes/wbstats.Rmd")
|
/scratch/gouwar.j/cran-all/cranData/wbstats/vignettes/precompile.R
|
---
title: "wbstats"
output:
md_document:
variant: gfm
vignette: >
%\VignetteIndexEntry{wbstats}
%\VignetteEngine{knitr::knitr}
%\VignetteEncoding{UTF-8}
---
<!-- README.md is generated from README.Rmd. Please edit that file -->
# wbstats: An R package for searching and downloading data from the World Bank API.
You can install:
The latest release version from CRAN with
```r
install.packages("wbstats")
```
or
The latest development version from github with
```r
devtools::install_github("nset-ornl/wbstats")
```
# Introduction
The World Bank^[<https://www.worldbank.org/>] is a tremendous source of global socio-economic data; spanning several decades and dozens of topics, it has the potential to shed light on numerous global issues. To help provide access to this rich source of information, The World Bank themselves, provide a well structured RESTful API. While this API is very useful for integration into web services and other high-level applications, it becomes quickly overwhelming for researchers who have neither the time nor the expertise to develop software to interface with the API. This leaves the researcher to rely on manual bulk downloads of spreadsheets of the data they are interested in. This too is can quickly become overwhelming, as the work is manual, time consuming, and not easily reproducible. The goal of the `wbstats` R-package is to provide a bridge between these alternatives and allow researchers to focus on their research questions and not the question of accessing the data. The `wbstats` R-package allows researchers to quickly search and download the data of their particular interest in a programmatic and reproducible fashion; this facilitates a seamless integration into their workflow and allows analysis to be quickly rerun on different areas of interest and with realtime access to the latest available data.
### Highlighted features of the `wbstats` R-package:
- Uses version 2 of the World Bank API that provides access to more indicators and metadata than the previous API version
- Access to all annual, quarterly, and monthly data available in the API
- Support for searching and downloading data in multiple languages
- Returns data in either wide (default) or long format
- Support for Most Recent Value queries
- Support for `grep` style searching for data descriptions and names
- Ability to download data not only by country, but by aggregates as well, such as High Income or South Asia
# Getting Started
Unless you know the country and indicator codes that you want to download the first step would be searching for the data you are interested in. `wb_search()` provides `grep` style searching of all available indicators from the World Bank API and returns the indicator information that matches your query.
To access what countries or regions are available you can use the `countries` data frame from either `wb_cachelist` or the saved return from `wb_cache()`. This data frame contains relevant information regarding each country or region. More information on how to use this for downloading data is covered later.
## Finding available data with `wb_cachelist`
For performance and ease of use, a cached version of useful information is provided with the `wbstats` R-package. This data is called `wb_cachelist` and provides a snapshot of available countries, indicators, and other relevant information. `wb_cachelist` is by default the the source from which `wb_search()` and `wb_data()` uses to find matching information. The structure of `wb_cachelist` is as follows
```r
library(wbstats)
str(wb_cachelist, max.level = 1)
#> List of 8
#> $ countries : tibble [304 x 18] (S3: tbl_df/tbl/data.frame)
#> $ indicators : tibble [16,649 x 8] (S3: tbl_df/tbl/data.frame)
#> $ sources : tibble [63 x 9] (S3: tbl_df/tbl/data.frame)
#> $ topics : tibble [21 x 3] (S3: tbl_df/tbl/data.frame)
#> $ regions : tibble [48 x 4] (S3: tbl_df/tbl/data.frame)
#> $ income_levels: tibble [7 x 3] (S3: tbl_df/tbl/data.frame)
#> $ lending_types: tibble [4 x 3] (S3: tbl_df/tbl/data.frame)
#> $ languages : tibble [23 x 3] (S3: tbl_df/tbl/data.frame)
```
## Accessing updated available data with `wb_cache()`
For the most recent information on available data from the World Bank API `wb_cache()` downloads an updated version of the information stored in `wb_cachelist`. `wb_cachelist` is simply a saved return of `wb_cache(lang = "en")`. To use this updated information in `wb_search()` or `wb_data()`, set the `cache` parameter to the saved `list` returned from `wb_cache()`. It is always a good idea to use this updated information to insure that you have access to the latest available information, such as newly added indicators or data sources. There are also cases in which indicators that were previously available from the API have been removed or deprecated.
```r
library(wbstats)
# default language is english
new_cache <- wb_cache()
```
## Search available data with `wb_search()`
`wb_search()` searches through the `indicators` data frame to find indicators that match a search pattern. An example of the structure of this data frame is below
```
#> # A tibble: 2 x 8
#> indicator_id indicator unit indicator_desc source_org topics source_id source
#> <chr> <chr> <lgl> <chr> <chr> <list> <dbl> <chr>
#> 1 NY.GDP.MKTP.~ GDP (curre~ NA GDP at purchaser's prices is the sum of gross va~ World Bank national accounts data, and OECD~ <df[,2]~ 2 World Deve~
#> 2 SP.POP.TOTL Population~ NA Total population is based on the de facto defini~ (1) United Nations Population Division. Wor~ <df[,2]~ 2 World Deve~
```
By default the search is done over the `indicator_id`, `indicator`, and `indicator_desc` fields and returns the those 3 columns of the matching rows. The `indicator_id` values are inputs into `wb_data()`, the function for downloading the data. To return all columns for the `indicators` data frame, you can set `extra = TRUE`.
```r
library(wbstats)
unemploy_inds<- wb_search("unemployment")
head(unemploy_inds)
#> # A tibble: 6 x 3
#> indicator_id indicator indicator_desc
#> <chr> <chr> <chr>
#> 1 fin37.t.a Received government transfers in the past year (~ The percentage of respondents who report personally receiving any financial support from the ~
#> 2 fin37.t.a.1 Received government transfers in the past year, ~ The percentage of respondents who report personally receiving any financial support from the ~
#> 3 fin37.t.a.10 Received government transfers in the past year, ~ The percentage of respondents who report personally receiving any financial support from the ~
#> 4 fin37.t.a.11 Received government transfers in the past year, ~ The percentage of respondents who report personally receiving any financial support from the ~
#> 5 fin37.t.a.2 Received government transfers in the past year, ~ The percentage of respondents who report personally receiving any financial support from the ~
#> 6 fin37.t.a.3 Received government transfers in the past year, ~ The percentage of respondents who report personally receiving any financial support from the ~
```
Other fields can be searched by simply changing the `fields` parameter. For example
```r
library(wbstats)
blmbrg_vars <- wb_search("Bloomberg", fields = "source_org")
head(blmbrg_vars)
#> # A tibble: 2 x 3
#> indicator_id indicator indicator_desc
#> <chr> <chr> <chr>
#> 1 GFDD.OM.02 Stock market return (%, year~ Stock market return is the growth rate of annual average stock market index. Annual average stock market index is~
#> 2 GFDD.SM.01 Stock price volatility Stock price volatility is the average of the 360-day volatility of the national stock market index.
```
Regular expressions are also supported
```r
library(wbstats)
# 'poverty' OR 'unemployment' OR 'employment'
povemply_inds <- wb_search(pattern = "poverty|unemployment|employment")
head(povemply_inds)
#> # A tibble: 6 x 3
#> indicator_id indicator indicator_desc
#> <chr> <chr> <chr>
#> 1 1.0.HCount.1.90usd Poverty Headcount ($1.90 a d~ The poverty headcount index measures the proportion of the population with daily per capita income (in 2011~
#> 2 1.0.HCount.2.5usd Poverty Headcount ($2.50 a d~ The poverty headcount index measures the proportion of the population with daily per capita income (in 2005~
#> 3 1.0.HCount.Mid10t~ Middle Class ($10-50 a day) ~ The poverty headcount index measures the proportion of the population with daily per capita income (in 2005~
#> 4 1.0.HCount.Ofcl Official Moderate Poverty Ra~ The poverty headcount index measures the proportion of the population with daily per capita income below th~
#> 5 1.0.HCount.Poor4u~ Poverty Headcount ($4 a day) The poverty headcount index measures the proportion of the population with daily per capita income (in 2005~
#> 6 1.0.HCount.Vul4to~ Vulnerable ($4-10 a day) Hea~ The poverty headcount index measures the proportion of the population with daily per capita income (in 2005~
```
As well as any `grep` function argument
```r
library(wbstats)
# contains "gdp" and NOT "trade"
gdp_no_trade_inds <- wb_search("^(?=.*gdp)(?!.*trade).*", perl = TRUE)
head(gdp_no_trade_inds)
#> # A tibble: 6 x 3
#> indicator_id indicator indicator_desc
#> <chr> <chr> <chr>
#> 1 5.51.01.10.gdp Per capita GDP growth GDP per capita is the sum of gross value added by all resident producers in the economy plus any produ~
#> 2 6.0.GDP_current GDP (current $) GDP is the sum of gross value added by all resident producers in the economy plus any product taxes an~
#> 3 6.0.GDP_growth GDP growth (annual %) Annual percentage growth rate of GDP at market prices based on constant local currency. Aggregates are~
#> 4 6.0.GDP_usd GDP (constant 2005 $) GDP is the sum of gross value added by all resident producers in the economy plus any product taxes an~
#> 5 6.0.GDPpc_const~ GDP per capita, PPP (constant 2011 ~ GDP per capita based on purchasing power parity (PPP). PPP GDP is gross domestic product converted to ~
#> 6 BI.WAG.TOTL.GD.~ Wage bill as a percentage of GDP <NA>
```
The default cached data in `wb_cachelist` is in English. To search indicators in a different language, you can download an updated copy of `wb_cachelist` using `wb_cache()`, with the `lang` parameter set to the language of interest and then set this as the `cache` parameter in `wb_search()`. Other languages are supported in so far as they are supported by the original data sources. Some sources provide full support for other languages, while some have very limited support. If the data source does not have a translation for a certain field or indicator then the result is `NA`, this may result in a varying number matches depending upon the language you select. To see a list of availabe languages call `wb_languages()`
```r
library(wbstats)
wb_langs <- wb_languages()
```
## Downloading data with `wb_data()`
Once you have found the set of indicators that you would like to explore further, the next step is downloading the data with `wb_data()`. The following examples are meant to highlight the different ways in which `wb_data()` can be used and demonstrate the major optional parameters.
The default value for the `country` parameter is a special value of `"countries_only"`, which as you might expect, returns data on the selected `indicator` for only countries. This is in contrast to `country = "all"` or `country = "regions_only"` which would return data for countries and regional aggregates together, or only regional aggregates, respectively
```r
library(wbstats)
# Population, total
pop_data <- wb_data("SP.POP.TOTL", start_date = 2000, end_date = 2002)
head(pop_data)
#> # A tibble: 6 x 9
#> iso2c iso3c country date SP.POP.TOTL unit obs_status footnote last_updated
#> <chr> <chr> <chr> <dbl> <dbl> <chr> <chr> <chr> <date>
#> 1 AW ABW Aruba 2000 90853 <NA> <NA> <NA> 2020-10-15
#> 2 AW ABW Aruba 2001 92898 <NA> <NA> <NA> 2020-10-15
#> 3 AW ABW Aruba 2002 94992 <NA> <NA> <NA> 2020-10-15
#> 4 AF AFG Afghanistan 2000 20779953 <NA> <NA> <NA> 2020-10-15
#> 5 AF AFG Afghanistan 2001 21606988 <NA> <NA> <NA> 2020-10-15
#> 6 AF AFG Afghanistan 2002 22600770 <NA> <NA> <NA> 2020-10-15
```
If you are interested in only some subset of countries or regions you can pass along the specific codes to the `country` parameter. The country and region codes and names that can be passed to the `country` parameter as well, most prominently the coded values from the `iso2c` and `iso3c` from the `countries` data frame in `wb_cachelist` or the return of `wb_cache()`. Any values from the above columns can mixed together and passed to the same call
```r
library(wbstats)
# you can mix different ids and they are case insensitive
# you can even use SpOnGeBoB CaSe if that's the kind of thing you're into
# iso3c, iso2c, country, region_iso3c, admin_region_iso3c, admin_region, income_level
example_geos <- c("ABW","AF", "albania", "SSF", "eca", "South Asia", "HiGh InCoMe")
pop_data <- wb_data("SP.POP.TOTL", country = example_geos,
start_date = 2012, end_date = 2012)
pop_data
#> # A tibble: 7 x 9
#> iso2c iso3c country date SP.POP.TOTL unit obs_status footnote last_updated
#> <chr> <chr> <chr> <dbl> <dbl> <chr> <chr> <chr> <date>
#> 1 AW ABW Aruba 2012 102560 <NA> <NA> <NA> 2020-10-15
#> 2 AF AFG Afghanistan 2012 31161376 <NA> <NA> <NA> 2020-10-15
#> 3 AL ALB Albania 2012 2900401 <NA> <NA> <NA> 2020-10-15
#> 4 7E ECA Europe & Central Asia (excluding high income) 2012 382509766 <NA> <NA> <NA> 2020-10-15
#> 5 8S SAS South Asia 2012 1683747130 <NA> <NA> <NA> 2020-10-15
#> 6 ZG SSF Sub-Saharan Africa 2012 917726973 <NA> <NA> <NA> 2020-10-15
#> 7 <NA> XD High income 2012 1191504227 <NA> <NA> <NA> 2020-10-15
```
As of `wbstats 1.0` queries are now returned in wide format. This was a request made by multiple users and is in line with the principles of [tidy data](https://www.jstatsoft.org/article/view/v059i10). If you would like to return the data in a long format, you can set `return_wide = FALSE`
Now that each indicator is it's own column, we can allow custom names for the indicators
```r
library(wbstats)
my_indicators = c("pop" = "SP.POP.TOTL",
"gdp" = "NY.GDP.MKTP.CD")
pop_gdp <- wb_data(my_indicators, start_date = 2010, end_date = 2012)
head(pop_gdp)
#> # A tibble: 6 x 6
#> iso2c iso3c country date gdp pop
#> <chr> <chr> <chr> <dbl> <dbl> <dbl>
#> 1 AW ABW Aruba 2010 2390502793. 101669
#> 2 AW ABW Aruba 2011 2549720670. 102046
#> 3 AW ABW Aruba 2012 2534636872. 102560
#> 4 AF AFG Afghanistan 2010 15856574731. 29185507
#> 5 AF AFG Afghanistan 2011 17804292964. 30117413
#> 6 AF AFG Afghanistan 2012 20001598506. 31161376
```
You'll notice that when you query only one indicator, as in the first two examples above, it returns the extra fields `unit`, `obs_status`, `footnote`, and `last_updated`, but when we queried multiple indicators at once, as in our last example, they are dropped. This is because those extra fields are tied to a specific observation of a single indicator and when we have multiple indciator values in a single row, they are no longer consistent with the tidy data format. If you would like that information for multiple indicators, you can use `return_wide = FALSE`
```r
library(wbstats)
my_indicators = c("pop" = "SP.POP.TOTL",
"gdp" = "NY.GDP.MKTP.CD")
pop_gdp_long <- wb_data(my_indicators, start_date = 2010, end_date = 2012, return_wide = FALSE)
head(pop_gdp_long)
#> # A tibble: 6 x 11
#> indicator_id indicator iso2c iso3c country date value unit obs_status footnote last_updated
#> <chr> <chr> <chr> <chr> <chr> <dbl> <dbl> <chr> <chr> <chr> <date>
#> 1 SP.POP.TOTL Population, total AF AFG Afghanistan 2012 31161376 <NA> <NA> <NA> 2020-10-15
#> 2 SP.POP.TOTL Population, total AF AFG Afghanistan 2011 30117413 <NA> <NA> <NA> 2020-10-15
#> 3 SP.POP.TOTL Population, total AF AFG Afghanistan 2010 29185507 <NA> <NA> <NA> 2020-10-15
#> 4 SP.POP.TOTL Population, total AL ALB Albania 2012 2900401 <NA> <NA> <NA> 2020-10-15
#> 5 SP.POP.TOTL Population, total AL ALB Albania 2011 2905195 <NA> <NA> <NA> 2020-10-15
#> 6 SP.POP.TOTL Population, total AL ALB Albania 2010 2913021 <NA> <NA> <NA> 2020-10-15
```
### Using `mrv` and `mrnev`
If you do not know the latest date an indicator you are interested in is available for you country you can use the `mrv` instead of `start_date` and `end_date`. `mrv` stands for most recent value and takes a `integer` corresponding to the number of most recent values you wish to return
```r
library(wbstats)
# most recent gdp per captia estimates
gdp_capita <- wb_data("NY.GDP.PCAP.CD", mrv = 1)
head(gdp_capita)
#> # A tibble: 6 x 9
#> iso2c iso3c country date NY.GDP.PCAP.CD unit obs_status footnote last_updated
#> <chr> <chr> <chr> <dbl> <dbl> <chr> <chr> <chr> <date>
#> 1 AW ABW Aruba 2019 NA <NA> <NA> <NA> 2020-10-15
#> 2 AF AFG Afghanistan 2019 502. <NA> <NA> <NA> 2020-10-15
#> 3 AO AGO Angola 2019 2974. <NA> <NA> <NA> 2020-10-15
#> 4 AL ALB Albania 2019 5353. <NA> <NA> <NA> 2020-10-15
#> 5 AD AND Andorra 2019 40886. <NA> <NA> <NA> 2020-10-15
#> 6 AE ARE United Arab Emirates 2019 43103. <NA> <NA> <NA> 2020-10-15
```
Often it is the case that the latest available data is different from country to country. There may be 2020 estimates for one location, while another only has estimates up to 2019. This is especially true for survey data. When you would like to return the latest avialble data for each country regardless of its temporal misalignment, you can use the `mrnev` instead of `mrnev`. `mrnev` stands for most recent non empty value.
```r
library(wbstats)
gdp_capita <- wb_data("NY.GDP.PCAP.CD", mrnev = 1)
head(gdp_capita)
#> # A tibble: 6 x 8
#> iso2c iso3c country date NY.GDP.PCAP.CD obs_status footnote last_updated
#> <chr> <chr> <chr> <dbl> <dbl> <chr> <chr> <date>
#> 1 AW ABW Aruba 2017 29008. <NA> <NA> 2020-10-15
#> 2 AF AFG Afghanistan 2019 502. <NA> <NA> 2020-10-15
#> 3 AO AGO Angola 2019 2974. <NA> <NA> 2020-10-15
#> 4 AL ALB Albania 2019 5353. <NA> <NA> 2020-10-15
#> 5 AD AND Andorra 2019 40886. <NA> <NA> 2020-10-15
#> 6 AE ARE United Arab Emirates 2019 43103. <NA> <NA> 2020-10-15
```
### Dates
Because the majority of data available from the World Bank is at the annual resolution, by default dates in `wbstats` are returned as `numeric`s. This default makes common tasks like filtering easier. If you would like the date field to be of class `Date` you can set `date_as_class_date = TRUE`
# Some Sharp Corners
There are a few behaviors of the World Bank API that being aware of could help explain some potentially unexpected results. These results are known but no special actions are taken to mitigate them as they are the result of the API itself and artifically limiting the inputs or results could potentially causes problems or create unnecessary rescrictions in the future.
## Searching in other languages
Not all data sources support all languages. If an indicator does not have a translation for a particular language, the non-supported fields will return as `NA`. This could potentially result in a differing number of matching indicators from `wb_search()`
```r
library(wbstats)
# english
cache_en <- wb_cache()
sum(is.na(cache_en$indicators$indicator))
#> [1] 0
# spanish
cache_es <- wb_cache(lang = "es")
sum(is.na(cache_es$indicators$indicator))
#> [1] 14791
```
# Legal
The World Bank Group, or any of its member instutions, do not support or endorse this software and are not libable for any findings or conclusions that come from the use of this software.
|
/scratch/gouwar.j/cran-all/cranData/wbstats/vignettes/wbstats.Rmd
|
# Generated by using Rcpp::compileAttributes() -> do not edit by hand
# Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393
cusum <- function(x) {
.Call(`_wbsts_cusum`, x)
}
finner_prod_maxp <- function(x, p) {
.Call(`_wbsts_finner_prod_maxp`, x, p)
}
across_fip <- function(X, tau, p, epp, p1, Ts) {
.Call(`_wbsts_across_fip`, X, tau, p, epp, p1, Ts)
}
multi_across_fip <- function(X, M, min_draw, tau, p, epp, Ts) {
.Call(`_wbsts_multi_across_fip`, X, M, min_draw, tau, p, epp, Ts)
}
|
/scratch/gouwar.j/cran-all/cranData/wbsts/R/RcppExports.R
|
cr.rand.max.inner.prod <-
function(XX,Ts,C_i,epp,M = 0,Plot = FALSE,cstar=0.95) {
#mult.fip <- function (x.in,n,d,epp,C_i,Ts,min.draw,M,cstar) {
# out=multi_across_fip(X=x.in, M=M, min_draw=min.draw, tau=C_i,p=cstar, epp=epp,Ts = Ts)
# return(out)
#}
# med <- function(x){
# y<-stats:: quantile(x, 0.5, type = 3)[[1]]
# return(y[[1]])
# }
Output = list(NULL)
if (M == 0) M = floor(dim(XX)[1]*1)
l=dim(XX)[2]
n=dim(XX)[1]
i=0
min.draw=floor(log(Ts)^2/3)
cstar=c(0.95,cstar)
loc=multi_across_fip(X=XX, M=M, min_draw=min.draw, tau=tau.fun(XX[,1]), p=cstar,epp=epp,Ts= log(Ts))
output=matrix(c(loc[[1]],loc[[2]],loc[[3]],loc[[4]]),M,4)
max.b = output[which(abs(output[,2]) == max(abs(output[,2])))]
max.inner = quantile(max.b, 0.5, type = 3)[[1]]#med(max.b)
value.max.inner = sign(output[,2][abs(output[,2])==max(abs(output[,2]))])* max(abs(output[,2]))
which.max = which(output[,2]==value.max.inner[1])
if (Plot == TRUE) plot(x=output[,1],y=abs(output[,2]),xlab="index",ylab="inner products")
aux.mat=aggregate(abs(output[,2]),by=list(output[,1]),max)
max.in.prod.series=matrix(0,dim(XX)[1],2)
max.in.prod.series[,1] = 1:dim(XX)[1]
for (i in 1:dim(XX)[1]) {
if (sum(max.in.prod.series[i,1]==aux.mat[,1])==0) {
max.in.prod.series[i,2]=0
} else {
max.in.prod.series[i,2]=aux.mat[which(aux.mat[,1]==i),2]
}
}
Output[[1]] = max.inner
Output[[2]] = unique(value.max.inner)
Output[[3]] = quantile(output[which.max,3], 0.5, type = 3)[[1]] #med(output[which.max,3])
Output[[4]] = quantile(output[which.max,4], 0.5, type = 3)[[1]] #med(output[which.max,4])
Output[[5]] = max.in.prod.series[,2]
return(Output)
}
|
/scratch/gouwar.j/cran-all/cranData/wbsts/R/cr.rand.max.inner.prod.R
|
ews.trans <-
function(x,scales=NULL){
N=length(x)
if (length(scales)==0) {
J=floor(log(N,2))
} else {
J=length(scales)
}
res = modwt(x,filter="haar")
out = matrix(0,N,J)
for (j in 1:J){
out[,j]=res@W[[j]]
}
for (i in 1:(J)) out[,i]=c(out[(2^i):N,i],out[1:(2^i-1),i])
return(out^2)
}
|
/scratch/gouwar.j/cran-all/cranData/wbsts/R/ews.trans.R
|
get.thres <-
function(n, q=.95, r=100, scales=NULL){
J<-round(log(n, 2))
if(is.null(scales)) scales<-J-1:floor(J/2)
max.scale<-length(scales)
M<-NULL
for(i in 1:r){
x<-rnorm(n)
ews<-ews.trans(x,scales=scales)
m<-NULL
for(l in 1:max.scale){
z<-ews[,l]
dis<-c(round((n-n/2^(scales[l])+1)):n)
z<-z[-dis]; nz<-length(z)
m<-c(m, max(abs(cusum(z)))/1/log(n))
}
M<-rbind(M, m)
}
Sigma<-matrix(0, n, n)
for(i in 1:n){ for(j in 1:n){
Sigma[i,j]<-.3^abs(i-j)
}}
X<-mvtnorm:: rmvnorm(r, sigma=Sigma,method="chol")
for(i in 1:r){
x<-X[i,]
ews<-ews.trans(x,scales=scales)
m<-NULL
for(l in 1:max.scale){
z<-ews[,l]
dis<-c(round((n-n/2^(scales[l])+1)):n)
z<-z[-dis]; nz<-length(z)
m<-c(m, max(abs(cusum(z)))/1/log(n))
}
M<-rbind(M, m)
}
for(i in 1:n){ for(j in 1:n){
Sigma[i,j]<-.6^abs(i-j)
}}
X<-mvtnorm:: rmvnorm(r, sigma=Sigma,method="chol")
for(i in 1:r){
x<-X[i,]
ews<-ews.trans(x,scales=scales)
m<-NULL
for(l in 1:max.scale){
z<-ews[,l]
dis<-c(round((n-n/2^(scales[l])+1)):n)
z<-z[-dis]; nz<-length(z)
m<-c(m, max(abs(cusum(z)))/1/log(n))
}
M<-rbind(M, m)
}
for(i in 1:n){ for(j in 1:n){
Sigma[i,j]<-.9^abs(i-j)
}}
X<-mvtnorm:: rmvnorm(r, sigma=Sigma,method="chol")
for(i in 1:r){
x<-X[i,]
ews<-ews.trans(x,scales=scales)
m<-NULL
for(l in 1:max.scale){
z<-ews[,l]
dis<-c(round((n-n/2^(scales[l])+1)):n)
z<-z[-dis]; nz<-length(z)
m<-c(m, max(abs(cusum(z)))/1/log(n))
}
M<-rbind(M, m)
}
return(apply(M, 2, function(x){quantile(x, q)}))
}
|
/scratch/gouwar.j/cran-all/cranData/wbsts/R/get.thres.R
|
get.thres.ar <-
function(y, q=.95, r=100, scales=NULL){
n=length(y)
J<-round(log(n, 2))
if(is.null(scales)) scales<-J-1:floor(J/2)
max.scale<-length(scales)
M<-NULL
ar.est=ar(y)$ar
X=matrix(0,r,n)
for (i in 1:r) X[i,] = arima.sim(n = n, list(ar = c(ar.est),sd = 1))
for(i in 1:r){
x<-X[i,]
ews<-ews.trans(x,scales=scales)
m<-NULL
for(l in 1:max.scale){
z<-ews[,l]
dis<-c((n-n/2^l+1):n)
z<-z[-dis]; nz<-length(z)
m<-c(m, max(abs(cusum(z)))/1/(log(n)))
}
M<-rbind(M, m)
}
return(apply(M, 2, function(x){quantile(x, q)}))
}
|
/scratch/gouwar.j/cran-all/cranData/wbsts/R/get.thres.ar.R
|
# Hello, world!
#
# This is an example function named 'hello'
# which prints 'Hello, world!'.
#
# You can learn more about package authoring with RStudio at:
#
# http://r-pkgs.had.co.nz/
#
# Some useful keyboard shortcuts for package authoring:
#
# Install Package: 'Ctrl + Shift + B'
# Check Package: 'Ctrl + Shift + E'
# Test Package: 'Ctrl + Shift + T'
hello <- function() {
print("Hello, world!")
}
|
/scratch/gouwar.j/cran-all/cranData/wbsts/R/hello.R
|
post.processing <-
function(z,br,del=-1,epp=-1,C_i=NULL,scales=NULL){
n = nz = dim(z)[1]
if (is.null(br)) {
return(NA)
stop
}
if(del<0){ del<-floor(n)^(2/3)
}
br=sort(br, decreasing=F)
if((br[1]) < del) br=br[-1]
if (is.null(br)) {
return(NA)
stop
}
if (sum(epp)<0) {
epp<-c()
for (j in 1:length(scales)) {
ep = round(max(2*n/2^scales[j], ceiling(sqrt(n)/2)))
epp = c(epp,ep)
}
epp=round(epp/2)
}
TT=1
sbr<-fbr<-br
B<-L<-length(br)
pp<-NULL
l=dim(z)[2]
pp<-matrix(fbr, B, 1)
criterion<- log(n)
Cbr<-c(0, fbr, nz)
temp<-rep(1, B)
while(TT>0){
cbr<-c(0, fbr, nz)
for(i in 1:B) {
b<-cbr[i+1]
if (cbr[i]==0) {
s=1
} else {
ind=i
while (temp[ind-1]==0) {
ind=ind-1
if (ind==1) break
}
s<-cbr[ind]+1
}
if (cbr[i+2]==nz) {
e=nz
} else {
ind=i
while(temp[ind+1]==0) {
ind=ind+1
if (ind==B) break
}
e<-cbr[ind+2]
}
cr.ip=0
for (j in 1:l) {
dis<-c(round((n-n/2^(scales[j])+1)):n)
e.epp=e-epp[j]
s.epp=s+epp[j]
if (s.epp>b | b>e.epp) break
v = abs(sqrt((e.epp-b)/(e.epp-s.epp+1)/(b-s.epp+1))*sum(z[s.epp:b,j])-sqrt((b-s.epp+1)/(e.epp-s.epp+1)/(e.epp-b))*sum(z[(b+1):e.epp,j]))
v<-v/mean(z[s.epp:e.epp,j])
cstar=max((b-s.epp)/(e.epp-s.epp),(e.epp-b)/(e.epp-s.epp))
cr.ip=abs(cr.ip)+ifelse(v>criterion*C_i[j],v,0)
}
temp[sbr==b]<-cr.ip
}
pp<-cbind(pp, temp)
TT=TT-1
}
list(pp=pp)
cn = ncol(pp)
if(sum(pp[,cn])==0) {
return(NA)
} else return((pp[,1])[pp[,cn]>0])
}
|
/scratch/gouwar.j/cran-all/cranData/wbsts/R/post.processing.R
|
sim.pw.ar <-
function(N,sd_u ,b.slope,br.loc) {
num.breaks = length(br.loc)
phi = c()
y = rep(0,N)
for (i in 1:length(b.slope)) {
if (i == 1) {
phi=c(phi,rep(b.slope[1],br.loc[1]))
next
}
if (i == length(b.slope)) {
phi=c(phi,rep(tail(b.slope,1),N - br.loc[length(b.slope)-1]))
break
}
else {
phi=c(phi,rep(b.slope[i],br.loc[i] - br.loc[i-1]))
}
}
y[1] = rnorm(1,0,sd_u)
for (i in 2:N) {
y[i] = phi[i] * y[i-1] + rnorm(1,0,sd_u)
}
output = list(NULL)
output[[1]] = phi
output[[2]] = y
output[[3]] = br.loc
return(output)
}
|
/scratch/gouwar.j/cran-all/cranData/wbsts/R/sim.pw.ar.R
|
sim.pw.ar2 <-
function(N,sd_u,b.slope,b.slope2,br.loc) {
num.breaks = length(br.loc)
phi = c()
phi2 = c()
y = rep(0,N)
for (i in 1:length(b.slope)) {
if (i == 1) {
phi=c(phi,rep(b.slope[1],br.loc[1]))
phi2=c(phi2,rep(b.slope2[1],br.loc[1]))
next
}
if (i == length(b.slope)) {
phi=c(phi,rep(tail(b.slope,1),N - br.loc[length(b.slope)-1]))
phi2=c(phi2,rep(tail(b.slope2,1),N - br.loc[length(b.slope2)-1]))
break
}
else {
phi=c(phi,rep(b.slope[i],br.loc[i] - br.loc[i-1]))
phi2=c(phi2,rep(b.slope2[i],br.loc[i] - br.loc[i-1]))
}
}
y[1] = rnorm(1,0,sd_u)
y[2] = rnorm(1,0,sd_u)
for (i in 3:N) {
y[i] = phi[i] * y[i-1] + phi2[i] * y[i-2] + rnorm(1,0,sd_u)
}
output = list(NULL)
output[[1]] = phi
output[[3]] = phi2
output[[2]] = y
output[[4]] = br.loc
return(output)
}
|
/scratch/gouwar.j/cran-all/cranData/wbsts/R/sim.pw.ar2.R
|
sim.pw.arma <-
function(N,sd_u,b.slope,b.slope2, mac,br.loc) {
num.breaks = length(br.loc)
num.coeff = length(b.slope)
if (length(sd_u)==1) sd_u=rep(sd_u,num.coeff)
phi = c()
phi2 = c()
ma = c()
p.sd = c()
y = rep(0,N)
for (i in 1:num.coeff) {
if (i == 1) {
phi=c(phi,rep(b.slope[1],br.loc[1]))
phi2=c(phi2,rep(b.slope2[1],br.loc[1]))
ma=c(ma,rep(mac[1],br.loc[1]))
p.sd = c(p.sd,rep(sd_u[1],br.loc[1]))
next
}
if (i == length(b.slope)) {
phi=c(phi,rep(tail(b.slope,1),N - br.loc[length(b.slope)-1]))
phi2=c(phi2,rep(tail(b.slope2,1),N - br.loc[length(b.slope2)-1]))
ma=c(ma,rep(tail(mac,1),N - br.loc[length(mac)-1]))
p.sd=c(p.sd,rep(tail(sd_u,1),N - br.loc[length(sd_u)-1]))
break
} else {
phi=c(phi,rep(b.slope[i],br.loc[i] - br.loc[i-1]))
phi2=c(phi2,rep(b.slope2[i],br.loc[i] - br.loc[i-1]))
ma=c(ma,rep(mac[i],br.loc[i] - br.loc[i-1]))
p.sd=c(p.sd,rep(sd_u[i],br.loc[i] - br.loc[i-1]))
}
}
y[1] = rnorm(1,0,sd_u[1])
y[2] = rnorm(1,0,sd_u[1])
error_lag.t = rnorm(1,0,sd_u[1])
for (i in 3:N) {
error_t = rnorm(1,0,p.sd[i])
y[i] = phi[i] * y[i-1] + phi2[i] * y[i-2] + ma[i]*error_lag.t + error_t
error_lag.t=error_t
}
output = list(NULL)
output[[1]] = phi
output[[3]] = phi2
output[[2]] = y
output[[4]] = br.loc
output[[5]] = ma
return(output)
}
|
/scratch/gouwar.j/cran-all/cranData/wbsts/R/sim.pw.arma.R
|
tau.fun <-
function(y){
n=ifelse(length(y)<6000,length(y),6000);J=floor(log(n,2))
scales<-J-1:floor(3*0.75*log(log(n)))
sc=min(length(scales),6)
coef=c(9.795793e-01, -1.084024e-04, 3.112115e+01, 1.131661e-08 )
j1=sum(coef*c(1,n,1/n,n^2))
coef=c(1.132108e+00, -1.110789e-04, 3.286444e+01, 1.093054e-08 )
j2=sum(coef*c(1,n,1/n,n^2))
coef=c(1.518703e+00, -1.585613e-04, 2.118412e+01, 1.773870e-08 )
j3=sum(coef*c(1,n,1/n,n^2))
coef=c(2.059255e+00, -1.798321e-04, 7.827924e+00, 1.632834e-08 )
j4=sum(coef*c(1,n,1/n,n^2))
coef=c(1.867909e+00 , 1.633426e-04, 4.867038e+02, -2.425376e-08 )
j5=sum(coef*c(1,n,1/n,n^2))
coef=c(5.782118e+00, -3.728447e-04, -5.025129e+03, 4.673449e-10 )
j6=2.5
return(c(j1,j2,j3,j4,j5,j6))
}
|
/scratch/gouwar.j/cran-all/cranData/wbsts/R/tau.fun.R
|
uh.wbs <-
function(z,C_i, del=-1, epp, scale,M=0,cstar=0.75){
l <- dim(z)[2]
n<-nz<-dim(z)[1]
estimates<-br.list<-NULL
if(epp[1]==-1){
epp<-c()
for (j in 1:l) {
ep = round(max(2*n/2^scale[j], ceiling(sqrt(n)/2)))
epp = c(epp,ep)
}
epp=round(epp/2) ###Be careful here!!!!!!!
}
if(del<0){
del<-round(max(2*epp[1]+2, ceiling(log(n)*sqrt(n)/4)))
}
ep=epp[1]
if(nz<del) stop("Input vector too short")
criterion <- C_i[1] * log(n)
breakpoints<-NULL
f<-NULL
tree<-list(matrix(0, 6, 1))
tree[[1]][1,1]<-1
s<-tree[[1]][4,1]<-1
e<-tree[[1]][6,1]<-nz
# b=-1
# while(b < 0 | b > e) {
temp.r = cr.rand.max.inner.prod(XX=z[s:e,],Ts=n,C_i=C_i,epp=epp,M=M,cstar=cstar,Plot=0)
b <- temp.r[[1]]
#}
tree[[1]][5,1] <- b
d<-temp.r[[2]]
if(!is.numeric(d)) stop("WBS function returns NaN. Check again")
if(abs(d)>criterion){
tree[[1]][2,1]<-d
breakpoints <- c(breakpoints, b)
f<-c(f, d)
j<-1
while(length(tree)==j){
if(sum(tree[[j]][6, ]-tree[[j]][4, ]-rep(2*del, dim(tree[[j]])[2]))>0){
no.parent.coeffs<-dim(tree[[j]])[2]
no.child.coeffs<-0
for(i in 1:no.parent.coeffs){
if(tree[[j]][5, i]-tree[[j]][4, i]>max(ep, del)+1){
s<-tree[[j]][4, i]
e<-tree[[j]][5, i]
#ind.max=-1
#while(ind.max < 0 | ind.max > e) {
temp.RIP = cr.rand.max.inner.prod(XX=z[s:e,],Ts=n,C_i=C_i,epp=epp,M=M,cstar=cstar)
ind.max = temp.RIP[[1]]
#}
b<-s+ind.max-1
d<-temp.RIP[[2]]
d=ifelse(is.numeric(d),d,0)
d=ifelse(abs(d)>10^(-3),d,0)
if(abs(d)>criterion){
if(length(tree)==j) tree<-c(tree, list(matrix(0, 6, 0)))
no.child.coeffs<-no.child.coeffs+1
tree[[j+1]]<-matrix(c(tree[[j+1]], matrix(0, 6, 1)), 6, no.child.coeffs)
tree[[j+1]][1, no.child.coeffs]<-2*tree[[j]][1, i]-1
tree[[j+1]][2, no.child.coeffs]<-d
tree[[j+1]][4, no.child.coeffs]<-s
tree[[j+1]][6, no.child.coeffs]<-e
tree[[j+1]][5, no.child.coeffs]<-b
if (sum(abs(breakpoints-b)>del)==length(breakpoints)) breakpoints<-c(breakpoints,b);
f<-c(f, d)
}
}
if(tree[[j]][6, i]-tree[[j]][5, i]>max(ep, del)+1){
s<-tree[[j]][5, i]+1
e<-tree[[j]][6, i]
#ind.max=-1
#while(ind.max < 0 | ind.max > e) {
temp.RIP = cr.rand.max.inner.prod(XX=z[s:e,],Ts=n,C_i=C_i,epp=epp,M=M,cstar=cstar)
ind.max = temp.RIP[[1]]
#}
b<-s+ind.max-1
d<-temp.RIP[[2]]
d=ifelse(is.numeric(d),d,0)
d=ifelse(abs(d)>10^(-3),d,0)
if(abs(d)>criterion){
if(length(tree)==j) tree<-c(tree, list(matrix(0, 6, 0)))
no.child.coeffs<-no.child.coeffs+1
tree[[j+1]]<-matrix(c(tree[[j+1]], matrix(0, 6, 1)), 6, no.child.coeffs)
tree[[j+1]][1, no.child.coeffs]<-2*tree[[j]][1, i]
tree[[j+1]][2, no.child.coeffs]<-d
tree[[j+1]][4, no.child.coeffs]<-s
tree[[j+1]][6, no.child.coeffs]<-e
tree[[j+1]][5, no.child.coeffs]<-b
if (sum(abs(breakpoints-b)>del)==length(breakpoints)) breakpoints<-c(breakpoints,b)
f<-c(f, d)
}
}
}
}
j<-j+1
}
}
list(tree=tree, breakpoints=breakpoints, f=f)
}
|
/scratch/gouwar.j/cran-all/cranData/wbsts/R/uh.wbs.R
|
wbs.lsw <-
function(y,C_i=tau.fun(y),scales=NULL,M=0,cstar=0.75,lambda=.75) {
n=length(y)
J=floor(log(n,2))
if(is.null(scales)){
scales<-J-1:floor(3*lambda*log(log(n)))
max.scale<-min(scales, J-floor(J/2)+1)
} else{
scales<-sort(scales, decreasing=T)
max.scale<-min(scales)
}
if(length(scales)==1) stop(".........Choose at least two scales.........")
epp<-c()
for (j in 1:length(scales)) {
ep = round(max(2*n/2^scales[j], ceiling(sqrt(n)/2)))
epp = c(epp,ep)
}
epp=round(epp/2)
z=ews.trans(y,scales=scales)
dis<-c((n-n/2^(min(scales))+1):n)
z=z[-dis,]
u<-uh.wbs(z, scale=scales,epp=epp,del=floor(log(length(y))^2/3),C_i=C_i,M=M,cstar=cstar)
cp.out=u$breakpoints
OUT=post.processing(z,del=floor(log(length(y))^2/3),br=cp.out,C_i=C_i,epp=epp,scales=scales)
suppressWarnings(if (is.na(OUT)) OUT=NULL)
list(cp.bef=cp.out,cp.aft=OUT)
}
|
/scratch/gouwar.j/cran-all/cranData/wbsts/R/wbs.lsw.R
|
#' Education group sums
#'
#' @description Cleans `epop` data, downloaded using the `wcde()` function, for summations of population by 4, 6 or 8 education groups.
#'
#' @param d Data frame downloaded from the
#' @param n Number of education groups (from 4, 6 or 8)
#' @param strip_totals Remove total sums in `epop` column. Will not strip education totals if `year < year_edu_start` and `n = 8` as past data on population size by 8 education groups is unavailable.
#' @param factor_convert Convert columns that are character strings to factors, with levels based on order of appearance.
#' @param year_edu_start Year in which education splits are available for given groupings - in some versions past data is not available for some education groupings. Set to 2020 by default.
#'
#' @details Strips the `epop` data set to relevant rows for the `n` education groups.
#' @md
#' @return A tibble with the data selected.
#' @export
#'
#' @examples
#' library(tidyverse)
#' past_epop %>%
#' filter(year == 2020) %>%
#' edu_group_sum()
edu_group_sum <- function(d = NULL, n = 4, strip_totals = TRUE,
factor_convert = TRUE, year_edu_start = 2020){
if(!n %in% c(4, 6, 8))
stop("number of education groups must be 4, 6 or 8")
if(!"epop" %in% names(d))
stop("d must be a population data set, with epop column name")
d0 <- d %>%
{if(strip_totals) dplyr::filter(., age != "All", sex != "Both") else . } %>%
{if(strip_totals & n != 8) dplyr::filter(., education != "Total") else . } %>%
{if("scenario" %in% names(d)) . else dplyr::mutate(., scenario = "")}
if(n == 4){
d1 <- d0 %>%
dplyr::filter(!education %in% names(wcde::wic_col8)[7:9]) %>%
dplyr::mutate(education = stringr::str_remove(string = education, pattern = "Incomplete |Lower |Upper ")) %>%
{if(factor_convert) dplyr::mutate_if(., is.character, forcats::fct_inorder) else . } %>%
dplyr::group_by(scenario, name, country_code, year, age, sex, education) %>%
dplyr::summarise(epop = sum(epop), .groups = "drop_last") %>%
dplyr::ungroup()
}
if(n == 6){
d1 <- d0 %>%
dplyr::filter(!education %in% names(wcde::wic_col8)[7:9]) %>%
{if(factor_convert) dplyr::mutate_if(., is.character, forcats::fct_inorder) else . } %>%
dplyr::group_by(scenario, name, country_code, year, age, sex, education) %>%
dplyr::summarise(epop = sum(epop)) %>%
dplyr::ungroup()
}
if(n == 8){
d1 <- d0 %>%
dplyr::filter(!education == "Post Secondary") %>%
{if(factor_convert) dplyr::mutate_if(., is.character, forcats::fct_inorder) else . } %>%
dplyr::group_by(scenario, name, country_code, year, age, sex, education) %>%
dplyr::summarise(epop = sum(epop)) %>%
dplyr::ungroup() %>%
# all education splits to zero if less than 2015
dplyr::mutate(epop = ifelse(year < year_edu_start & education != "Total", 0, epop)) %>%
# fill in missing rows for masters etc pre 2015
tidyr::complete(scenario, name, country_code, year, age, sex, education, fill = list(epop = 0)) %>%
{if(strip_totals & year >= year_edu_start) dplyr::filter(., education != "Total") else . }
}
d1 <- d1 %>%
{if("scenario" %in% names(d)) . else dplyr::select(., -scenario)}
return(d1)
}
|
/scratch/gouwar.j/cran-all/cranData/wcde/R/edu_group_sum.R
|
#' Select every other (nth) element from a vector
#'
#' @param x Vector to select (remove) elements from
#' @param n Numeric value for the number of elements to skip. Default is 2, i.e. skips every second element
#' @param start Numeric value to indicate which element of the vector to commence from.
#' @param fill Character string to be used in place of skipped element. By default is `NULL` and hence skipped elements are removed rather than replaced.
#'
#' @return Vector with elements removed
#' @export
#'
#' @examples
#' every_other(x = letters)
#' every_other(LETTERS, n = 3, start = 6)
#' every_other(x = letters, fill = "")
every_other <- function(x, n = 2, start = 1, fill = NULL){
nn <- length(x)
x0 <- x[seq(from = start, to = nn, by = n)]
if(!is.null(fill)){
x1 <- x
x1[!x1 %in% x0] <- fill
x0 <- x1
}
return(x0)
}
|
/scratch/gouwar.j/cran-all/cranData/wcde/R/every_other.R
|
#' Find available indicator code names in the Wittgenstein Centre Human Capital Data Explorer
#'
#' @param x Character string on key word or name related to indicator of potential interest.
#'
#' @return A subset of the `wic_indicators` data frame with one or more of the `indicator`, `description` or `definition` columns matching the keyword given to `x`. Use the result in the `indicator` column to input to the `get_wcde` function for downloading data.
#' @export
#'
#' @examples
#' find_indicator("education")
#' find_indicator("migr")
#' find_indicator("fert")
find_indicator <- function(x){
wcde::wic_indicators %>%
dplyr::select_if(is.character) %>%
# across and filter any row not directly possible
dplyr::filter_all(dplyr::any_vars(
stringr::str_detect(string = .,
pattern = stringr::regex(x, ignore_case = TRUE))
))
}
|
/scratch/gouwar.j/cran-all/cranData/wcde/R/find_indicator.R
|
#' Download data from the Wittgenstein Centre Human Capital Data Explorer
#'
#' @description Downloads data from the Wittgenstein Centre Human Capital Data Explorer. Requires a working internet connection.
#'
#' @param indicator One character string based on the `indicator` column in the `wic_indicators` data frame, representing the variable to be downloaded.
#' @param scenario Vector of length one or more with numbers corresponding the scenarios. See details for more information. Defaults to 2 for the SSP2 Medium scenario.
#' @param country_code Vector of length one or more of country numeric codes based on ISO 3 digit numeric values.
#' @param country_name Vector of length one or more of country names. The corresponding country code will be guessed using the countrycodes package.
#' @param pop_age Character string for population age groups if `indicator` is set to `pop`. Defaults to no age groups `total`, but can be set to `all`.
#' @param pop_sex Character string for population sexes if `indicator`is set to `pop`. Defaults to no sex `total`, but can be set to `both` or `all`.
#' @param pop_edu Character string for population educational attainment if `indicator` is set to `pop`. Defaults to `total`, but can be set to `four`, `six` or `eight`.
#' @param include_scenario_names Logical vector of length one to indicate if to include additional columns for scenario names and short names. `FALSE` by default.
#' @param server Character string for server to download from. Defaults to `iiasa`, but can use `github` or `1&1` if IIASA server is down. Can check availability by setting to `search-available`.
#' @param version Character string for version of projections to obtain. Defaults to `wcde-v3`, but can use `wcde-v2` or `wcde-v1`. Scenario and indicator availability vary between versions.
#'
#' @details If no `country_name` or `country_code` is provided data for all countries and regions are downloaded. A full list of available countries and regions can be found in the `wic_locations` data frame.
#'
#' `indicator` must be set to a value in the first column in the table below of available demographic indicators:
#'
#' | `indicator` | Indicator Description |
#' |-----------|----------------------------------------------------------------------------|
#' | `pop` | Population Size (000's) |
#' | `bpop` | Population Size by Broad Age (000's) |
#' | `epop` | Population Size by Education (000's) |
#' | `prop` | Educational Attainment Distribution |
#' | `bprop` | Educational Attainment Distribution by Broad Age |
#' | `growth` | Average Annual Growth Rate |
#' | `nirate` | Average Annual Rate of Natural Increase |
#' | `sexratio` | Sex Ratio |
#' | `mage` | Population Median Age |
#' | `tdr` | Total Dependency Ratio |
#' | `ydr` | Youth Dependency Ratio |
#' | `odr` | Old-age Dependency Ratio |
#' | `ryl15` | Age When Remaining Life Expectancy is Below 15 years |
#' | `pryl15` | Proportion of Population with a Remaining Life Expectancy below 15 Years |
#' | `mys` | Mean Years of Schooling by Age |
#' | `bmys` | Mean Years of Schooling by Broad Age |
#' | `ggapmys15` | Gender Gap in Mean Years Schooling (15+) |
#' | `ggapmys25` | Gender Gap in Mean Years Schooling (25+) |
#' | `ggapedu15` | Gender Gap in Educational Attainment (15+) |
#' | `ggapedu25` | Gender Gap in Educational Attainment (25+) |
#' | `tfr` | Total Fertility Rate |
#' | `etfr` | Total Fertility Rate by Education |
#' | `asfr` | Age-Specific Fertility Rate |
#' | `easfr` | Age-Specific Fertility Rate by Education |
#' | `cbr` | Crude Birth Rate |
#' | `macb` | Mean Age at Childbearing |
#' | `emacb` | Mean Age at Childbearing by Education |
#' | `e0` | Life Expectancy at Birth |
#' | `cdr` | Crude Death Rate |
#' | `assr` | Age-Specific Survival Ratio |
#' | `eassr` | Age-Specific Survival Ratio by Education |
#' | `net` | Net Migration
#' | `netedu` | Net Migration Flows by Education
#' | `emi` | Emigration Flows
#' | `imm` | Immigration Flows
#'
#' See `wic_indicators` data frame for more details.
#'
#' `scenario` must be set to one or values in the first column table below of the available future scenarios:
#'
#' | `scenario` | description | version |
#' |----------|---------------------------------------|--------|
#' | `1` | Rapid Development (SSP1) | V1, V2, V3 |
#' | `2` | Medium (SSP2) | V1, V2, V3 |
#' | `3` | Stalled Development (SSP3) | V1, V2, V3 |
#' | `4` | Inequality (SSP4) | V1, V3 |
#' | `5` | Conventional Development (SSP5) |V1, V3 |
#' | `20` | Medium - Constant Enrollment Rate (SSP2-CER) | V1 |
#' | `21` | Medium - Fast Track Education (SSP2-FT) | V1 |
#' | `22` | Medium - Zero Migration (SSP2-ZM) | V2, V3 |
#' | `23` | Medium - Double Migration (SSP2-DM) | V2, V3 |
#'
#' See `wic_scenarios` data frame for more details.
#'
#'
#' @md
#' @return A [tibble][tibble::tibble-package] with the data selected.
#' @export
#'
#' @examples
#' \donttest{
#' # SSP2 tfr for Austria and Bulgaria
#' get_wcde(indicator = "tfr", country_code = c(40, 100))
#'
#' # SSP1 and SSP2 life expectancy for Vietnam and United Kingdom (guessing the country codes)
#' get_wcde(scenario = c(1, 2), indicator = "e0", country_name = c("Vietnam", "UK"))
#'
#' # SSP1 and SSP3 population by education for all countries
#' get_wcde(scenario = c(1, 3), indicator = "tfr")
#'
#' # population totals (aggregated over age, sex and education)
#' get_wcde(indicator = "pop", country_name = "Austria")
#'
#' # population totals by education group
#' get_wcde(indicator = "pop", country_name = "Austria", pop_edu = "four")
#'
#' # population totals by age-sex group
#' get_wcde(indicator = "pop", country_name = "Austria", pop_age = "all", pop_sex = "both")
#' }
get_wcde <- function(
indicator = "pop", scenario = 2,
country_code = NULL, country_name = NULL,
pop_age = c("total", "all"),
pop_sex = c("total", "both", "all"),
pop_edu = c("total", "four", "six", "eight"),
include_scenario_names = FALSE,
server = c("iiasa", "github", "1&1", "search-available", "iiasa-local"),
version = c("wcde-v3", "wcde-v2", "wcde-v1")
){
# scenario = 2; indicator = "tfr"; country_code = c(410, 288); country_name = NULL; include_scenario_names = FALSE; server = "iiasa"; version = "wcde-v3"
# indicator = "etfr"; country_name = c("Brazil", "Albania"); country_code = NULL; server = "github"
# guess country codes from name
guessed_code <- NULL
if(!is.null(country_name)){
guessed_country <- countrycode::countryname(country_name)
guessed_code <- countrycode::countrycode(
sourcevar = guessed_country, origin = "country.name", destination = "iso3n"
)
}
country_code <- c(country_code, guessed_code)
version <- match.arg(version)
if(indicator == "pop"){
pop_age <- match.arg(pop_age)
pop_sex <- match.arg(pop_sex)
pop_edu <- match.arg(pop_edu)
if(pop_age == "total" & pop_sex == "total" & pop_edu == "total")
indicator <- "pop-total"
if(pop_age == "total" & pop_sex == "both" & pop_edu == "total")
indicator <- "pop-sex"
if(pop_age == "total" & pop_sex == "total" & pop_edu %in% c("four", "six", "eight"))
indicator <- "pop-edattain"
if(pop_age == "all" & pop_sex == "total" & pop_edu == "total")
indicator <- "pop-age"
if(pop_age == "all" & pop_sex == "both" & pop_edu == "total")
indicator <- "pop-age-sex"
if(pop_age == "all" & pop_sex == "total" & pop_edu %in% c("four", "six", "eight"))
indicator <- "pop-age-edattain"
# if(pop_age == "all" & pop_sex == "all" & pop_edu == "total")
# indicator <- "pop"
if(pop_age == "total" & pop_sex == "both" & pop_edu %in% c("four", "six", "eight"))
indicator <- "pop-sex-edattain"
if(pop_age == "all" & pop_sex == "both" & pop_edu %in% c("four", "six", "eight"))
indicator <- "pop-age-sex-edattain"
if(pop_age == "all" & pop_sex == "all" & pop_edu %in% c("four", "six", "eight"))
indicator <- "epop"
if(pop_edu == "eight" & version != "wcde-v2")
stop("Eight education categories only avialable in wcde-v2")
}
d1 <- wcde::wic_indicators %>%
tidyr::pivot_longer(dplyr::contains("wcde"), names_to = "v", values_to = "avail") %>%
dplyr::filter(v == version,
!is.na(avail)) %>%
dplyr::filter(indicator == {{indicator}})
if(nrow(d1) < 1 & !stringr::str_detect(string = indicator, pattern = "pop-")){
stop(paste(indicator, "not an indicator code in wic_indicators for given version, please select an indicator code in the name column of widc_indicators"))
}
if(nrow(d1) == 0){
d1 <- tibble::tibble(
age = stringr::str_detect(string = indicator, pattern = "age"),
sex = stringr::str_detect(string = indicator, pattern = "sex"),
edu = stringr::str_detect(string = indicator, pattern = "edattain"),
bage = FALSE,
sage = FALSE,
period = FALSE
)
}
server <- match.arg(server)
if(server == "search-available" | is.null(server)){
server <- dplyr::case_when(
RCurl::url.exists("https://wicshiny2023.iiasa.ac.at/wcde-data/") ~ "iiasa",
# RCurl::url.exists("https://wicshiny.iiasa.ac.at/wcde-data/") ~ "iiasa",
RCurl::url.exists("https://github.com/guyabel/wcde-data/") ~ "github",
RCurl::url.exists("https://shiny.wittgensteincentre.info/wcde-data/") ~ "1&1",
TRUE ~ "none-available"
)
if(server == "none-available")
stop("No server available. Please contact package maintainer")
}
server_url <- dplyr::case_when(
server == "iiasa" ~ "https://wicshiny2023.iiasa.ac.at/wcde-data/",
server == "iiasa-local" ~ "../wcde-data/",
server == "github" ~ "https://github.com/guyabel/wcde-data/raw/master/",
server == "1&1" ~ "https://shiny.wittgensteincentre.info/wcde-data/",
TRUE ~ server)
vv <- paste0(version, ifelse(is.null(country_code), "-batch", "-single"))
wic_scenarios_v <- wcde::wic_scenarios %>%
tidyr::pivot_longer(dplyr::contains("wcde"), names_to = "v", values_to = "avail") %>%
dplyr::filter(v == version,
avail) %>%
dplyr::select(1:3)
if(is.null(country_code)){
d2 <- tibble::tibble(scenario = scenario) %>%
dplyr::mutate(u = paste0(server_url, vv, "/", scenario, "/",
indicator, ".rds")) %>%
dplyr::mutate(
d = purrr::map(
.x = u,
.f = ~readRDS(url(.x))
)
) %>%
dplyr::select(-u) %>%
tidyr::unnest(d) %>%
{if(include_scenario_names) dplyr::left_join(. , wic_scenarios_v, by = "scenario") else .}
}
if(!is.null(country_code)){
wic_locations_v <- wcde::wic_locations %>%
tidyr::pivot_longer(dplyr::contains("wcde"), names_to = "v", values_to = "avail") %>%
dplyr::filter(v == version,
avail) %>%
dplyr::select(isono, name)
d2 <- get_wcde_single(indicator = indicator, scenario = scenario, country_code = country_code, version = version, server = server) %>%
dplyr::mutate(isono = as.numeric(isono)) %>%
dplyr::left_join(wic_locations_v, by = "isono") %>%
{if(include_scenario_names) dplyr::left_join(. , wic_scenarios_v, by = "scenario") else .}
d2 <- d2 %>%
# {if(d1$period) dplyr::select(., -period) else dplyr::select(., -year)} %>%
# {if(sum(d1$age, d1$bage, d1$sage) == 0) dplyr::select(., -age) else .} %>%
# {if(d1$sex) dplyr::select(., -sex) else .} %>%
# {if(d1$edu) dplyr::select(., -edu) else dplyr::rename(., education=edu)} %>%
{if(d1$edu) dplyr::rename(., education=edu) else .} %>%
tidyr::drop_na(.) %>%
dplyr::relocate(dplyr::contains("scenario"), name, isono) %>%
dplyr::rename(country_code = isono) %>%
{if(stringr::str_detect(string = indicator, pattern = "-")) dplyr::rename(. , pop = dplyr::all_of(indicator)) else .}
}
if(stringr::str_detect(string = indicator, pattern = "pop-")){
# ^ avoids epop
if(pop_edu != "total"){
n_edu <- switch(pop_edu,
"four" = 4,
"six" = 6,
"eight" = 8
)
d2 <- d2 %>%
{if(pop_age == "total") dplyr::mutate(., age = "All") else .} %>%
{if(pop_sex == "total") dplyr::mutate(., sex = "All") else .} %>%
dplyr::rename(epop = pop) %>%
edu_group_sum(n = n_edu, strip_totals = FALSE,
year_edu_start = ifelse(version == "wcde-v3", 2020, 2015)) %>%
{if(pop_age == "total") dplyr::select(., -age) else .} %>%
{if(pop_sex == "total") dplyr::select(., -sex) else .} %>%
dplyr::rename(pop = epop)
}
}
return(d2)
}
|
/scratch/gouwar.j/cran-all/cranData/wcde/R/get_wcde.R
|
#' Pull multiple vectors for a given indicator, scenarios and .Rdata file names
#'
#' @description Requires a working internet connection. Intended for internal use.
#' @param indicator One character string based on the `name` column in the `wic_indicators` data frame, representing the variable to be interested.
#' @param scenario Vector with a numbers corresponding the scenarios. See details in `wcde` for more information.
#' @param country_code Vector of length one or more of country numeric codes based on ISO 3 digit numeric values.
#' @param server Character string for server to download from. Defaults to `iiasa`, but can use `github` if IIASA server is down.
#' @param version Character string for version of projections to obtain. Defaults to `wcde-v3`, but can use `wcde-v2` and `wcde-v1`. Scenario and indicator availability vary between versions.
#'
#' @return A tibble with multiple columns.
#' @keywords internal
#' @export
get_wcde_single <- function(indicator = NULL, scenario = 2, country_code = NULL,
server = NULL, version = NULL){
# scenario = c(1, 3); indicator = "etfr"; country_code = c(40, 100)
# scenario = 2; indicator = "e0"; country_code = "900"
# server = "github"; version = "wcde-v1"
if(length(indicator) > 1){
message("can only get data on one indicator at a time, taking first indicator given")
indicator <- indicator[1]
}
if(!wcde_location(country_code = country_code, version = version)){
stop("data for one of the country codes not available")
}
# if(length(scenario) > 1){
# message("can only get data on one scenario at a time, taking first scenario given")
# scenario <- scenario[1]
# }
wic_scenarios_v <- wcde::wic_scenarios %>%
tidyr::pivot_longer(dplyr::contains("wcde"), names_to = "v", values_to = "avail") %>%
dplyr::filter(v == version,
avail) %>%
dplyr::select(1:3)
if(!all(scenario %in% wic_scenarios_v$scenario)){
stop("scenario must be an integer in wic_scenarios, and available for version specified (default will be wcde-v3)")
}
v0 <- wcde::wic_indicators %>%
dplyr::filter(indicator == {{indicator}}) %>%
dplyr::select_if(is.logical) %>%
tidyr::pivot_longer(cols = dplyr::everything(), names_to = "v", values_to = "avail") %>%
dplyr::filter(avail == 1) %>%
dplyr::pull(v)
if(length(v0) == 0 & stringr::str_detect(string = indicator, pattern = "pop-")){
v0 <- stringr::str_split(string = indicator, pattern = "-")[[1]]
v0 <- v0[-1]
v0 <- stringr::str_replace(string = v0, pattern = "edattain", replacement = "edu")
v0 <- stringr::str_replace(string = v0, pattern = "total", replacement = "")
v0 <- v0[!nchar(v0)==0]
}
if(!any(v0 == "period"))
v0 <- c(v0, "year")
if(any(stringr::str_detect(string = v0, pattern = "bage")))
v0 <- stringr::str_replace(string = v0, pattern = "bage", "age")
if(any(stringr::str_detect(string = v0, pattern = "sage")))
v0 <- stringr::str_replace(string = v0, pattern = "sage", "age")
v1 <- c(v0, country_code)
d0 <- tidyr::expand_grid(scenario, indicator, v1) %>%
dplyr::rename(country_code = 3)
read_with_progress <- function(f){
pb$tick()
# message(f)
f %>%
url() %>%
readRDS()
# readr::read_csv(f, col_types = readr::cols(), guess_max = 1e5, progress = FALSE)
}
# server <- match.arg(server)
# version <- match.arg(version)
if(server == "search-available" | is.null(server)){
server <- dplyr::case_when(
RCurl::url.exists("https://wicshiny2023.iiasa.ac.at/wcde-data/") ~ "iiasa",
# RCurl::url.exists("https://wicshiny.iiasa.ac.at/wcde-data/") ~ "iiasa",
RCurl::url.exists("https://github.com/guyabel/wcde-data/") ~ "github",
RCurl::url.exists("https://shiny.wittgensteincentre.info/wcde-data/") ~ "1&1",
TRUE ~ "none-available"
)
}
server_url <- dplyr::case_when(
server == "iiasa" ~ "https://wicshiny2023.iiasa.ac.at/wcde-data/",
server == "iiasa-local" ~ "../wcde-data/",
server == "github" ~ "https://github.com/guyabel/wcde-data/raw/master/",
server == "1&1" ~ "https://shiny.wittgensteincentre.info/wcde-data/",
TRUE ~ server)
pb <- progress::progress_bar$new(total = nrow(d0))
pb$tick(0)
d0 <- d0 %>%
dplyr::mutate(u = paste0(server_url, version, "-single/", scenario, "/",
indicator, "/", country_code, ".rds")) %>%
dplyr::mutate(d = purrr::map(.x = u, .f = ~read_with_progress(f = .x))) %>%
dplyr::group_by(scenario) %>%
dplyr::reframe(dplyr::bind_cols(d)) %>%
dplyr::ungroup()
pb$terminate()
cc <- which(names(d0) %in% country_code)
d1 <- tidyr::pivot_longer(data = d0, cols = dplyr::all_of(cc),
names_to = "isono", values_to = {{indicator}})
return(d1)
}
|
/scratch/gouwar.j/cran-all/cranData/wcde/R/get_wcde_single.R
|
#' Past population sizes for all countries by education
#'
#' A data set containing population sizes for all countries by education between 1950 and 2020
#'
#' @format A data frame with 840,126 rows and 7 variables, including:
#' \describe{
#' \item{name}{Area name}
#' \item{country_code}{ISO 3 digit country code}
#' \item{year}{Year of observation from 1950 to 2020 in five-year steps}
#' \item{age}{Five-year age groups}
#' \item{education}{Education group}
#' \item{sex}{Sex}
#' \item{epop}{Population size in thousands for each age, sex and education group}
#' }
#' @source \url{http://dataexplorer.wittgensteincentre.org/}
"past_epop"
|
/scratch/gouwar.j/cran-all/cranData/wcde/R/past_epop.R
|
utils::globalVariables(c(".", "age", "edu", "isono", "name", "indicator", "pb", "period", "past", "sex", "year", "u", "education", "d", "v", "avail", "scenario", "country_code", "epop", "pop", "vv"))
|
/scratch/gouwar.j/cran-all/cranData/wcde/R/utils-global.R
|
#' Pipe operator
#'
#' See \code{magrittr::\link[magrittr:pipe]{\%>\%}} for details.
#'
#' @name %>%
#' @rdname pipe
#' @keywords internal
#' @export
#' @importFrom magrittr %>%
#' @usage lhs \%>\% rhs
NULL
|
/scratch/gouwar.j/cran-all/cranData/wcde/R/utils-pipe.R
|
#' Test if country code or codes are in wic_locations
#'
#' @description Intended for internal use.
#'
#' @param country_code `vector` of integers representing country codes
#'
#' @return `TRUE` if all codes given to `country_code` are in wic_locations, `FALSE` if one or more are not.
#' @export
#' @importFrom magrittr %>%
#' @keywords internal
#'
#' @examples
#' wcde_location(country_code = c(-11, 44))
#' wcde_location(country_code = c(100, 44))
#' wcde_location(country_code = 3)
wcde_location <- function(country_code,
version = c("wcde-v3", "wcde-v2", "wcde-v1")){
version <- match.arg(version)
v <- wcde::wic_locations %>%
tidyr::pivot_longer(dplyr::contains("wcde"), names_to = "vv", values_to = "avail") %>%
dplyr::filter(vv == version,
avail) %>%
tidyr::drop_na(isono) %>%
dplyr::pull(isono)
x <- sum(!country_code %in% v) == 0
if(!x){
ok <- which(country_code %in% v)
message(paste0("country code ", country_code[-ok], " not in Wittgenstein Human Capital Data Explorer for version provided"))
}
return(x)
}
|
/scratch/gouwar.j/cran-all/cranData/wcde/R/wcde_location.R
|
#' Colours used in Wittgenstein Centre for Demography and Human Capital Data Explorer
#'
#' Three sets of colours used for filling education based plots based on the different availability of detailed education categories (four, six or eight groups)
#'
#' @format A named vector
"wic_col4"
|
/scratch/gouwar.j/cran-all/cranData/wcde/R/wic_col4.R
|
#' Colours used in Wittgenstein Centre for Demography and Human Capital Data Explorer
#'
#' Three sets of colours used for filling education based plots based on the different availability of detailed education categories (four, six or eight groups)
#'
#' @format A named vector
"wic_col6"
|
/scratch/gouwar.j/cran-all/cranData/wcde/R/wic_col6.R
|
#' Colours used in Wittgenstein Centre for Demography and Human Capital Data Explorer
#'
#' Three sets of colours used for filling education based plots based on the different availability of detailed education categories (four, six or eight groups)
#'
#' @format A named vector
"wic_col8"
|
/scratch/gouwar.j/cran-all/cranData/wcde/R/wic_col8.R
|
#' Indicators used in the Wittgenstein Centre Human Capital Data Explorer
#'
#' A data set containing the indicator codes, names and further details used in the Wittgenstein Centre Human Capital Data Explorer
#'
#' @format A data frame with 37 rows and 11 variables, including:
#' \describe{
#' \item{indicator}{Short name of indicator to be used in the `indicator` argument of the `get_wcde()` function}
#' \item{description}{Brief description of indicator}
#' \item{wcde-v3}{Availability in wcde-v3 of `projection-only` or `past-available` (in addition to projections) of indicator. If value is `NA` then indicator not available in version.}
#' \item{wcde-v2}{Availability in wcde-v2 of `projection-only` or `past-available` (in addition to projections) of indicator. If value is `NA` then indicator not available in version.}
#' \item{wcde-v1}{Availability in wcde-v1 of `projection-only` or `past-available` (in addition to projections) of indicator. If value is `NA` then indicator not available in version.}
#' \item{age}{Availability of indicator by five-year age groups}
#' \item{bage}{Availability of indicator by broad age groups}
#' \item{sage}{Availability of indicator with a new born age group}
#' \item{sex}{Availability of indicator by sex}
#' \item{edu}{Availability of indicator by education}
#' \item{period}{Indicator is a period (flow)}
#' \item{definition_latest}{Full definition for indicator based on latest available version}
#' }
#' @source \url{http://dataexplorer.wittgensteincentre.org/}
"wic_indicators"
|
/scratch/gouwar.j/cran-all/cranData/wcde/R/wic_indicators.R
|
#' Locations used in the Wittgenstein Centre Human Capital Data Explorer
#'
#' A dataset containing the location codes, names and further details used in the Wittgenstein Centre Human Capital Data Explorer
#'
#' @format A data frame with 232 rows and 8 variables, including:
#' \describe{
#' \item{name}{Area name}
#' \item{isono}{ISO 3 digit country code}
#' \item{continent}{Continent of country}
#' \item{region}{UN region of country}
#' \item{dim}{Category or country/region/area}
#' \item{wcde-v3}{Availability of area in Version 3}
#' \item{wcde-v2}{Availability of area in Version 2}
#' \item{wcde-v1}{Availability of area in Version 1}
#' }
#' @source \url{http://dataexplorer.wittgensteincentre.org/}
"wic_locations"
|
/scratch/gouwar.j/cran-all/cranData/wcde/R/wic_locations.R
|
#' Scenarios used in the Wittgenstein Centre Human Capital Data Explorer
#'
#' A data set containing the scenario codes, names short names used in the Wittgenstein Centre Human Capital Data Explorer
#'
#' @format A data frame with 9 rows and 6 variables, including:
#' \describe{
#' \item{scenario_name}{Full scenario name}
#' \item{scenario}{Code to match help file of \code{get_wcde} function}
#' \item{scenario_abb}{Short scenario name}
#' \item{wcde-v3}{Availability of area in Version 3}
#' \item{wcde-v2}{Availability of area in Version 2}
#' \item{wcde-v1}{Availability of area in Version 1}
#' }
#' @source \url{http://dataexplorer.wittgensteincentre.org/}
"wic_scenarios"
|
/scratch/gouwar.j/cran-all/cranData/wcde/R/wic_scenarios.R
|
.onAttach <- function(libname, pkgname) {
packageStartupMessage("Suggested citation for data:\nWittgenstein Centre for Demography and Global Human Capital (WIC) Wittgenstein Centre Data Explorer. Version 3.0 (Beta), 2023")
}
|
/scratch/gouwar.j/cran-all/cranData/wcde/R/zzz.R
|
## ---- include = FALSE---------------------------------------------------------
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
## ----eval=FALSE---------------------------------------------------------------
# install.packages("wcde")
## ----eval=FALSE---------------------------------------------------------------
# library(devtools)
# install_github("guyabel/wcde", ref = "main")
## ---- messages = FALSE, message=FALSE-----------------------------------------
library(wcde)
# download education specific tfr data
get_wcde(indicator = "etfr",
country_name = c("Brazil", "Albania"))
# download education specific survivorship rates
get_wcde(indicator = "eassr",
country_name = c("Niger", "Korea"))
## -----------------------------------------------------------------------------
find_indicator(x = "tfr")
## ---- message=FALSE, warning=FALSE--------------------------------------------
library(tidyverse)
get_wcde(indicator = "e0",
country_name = c("Japan", "Australia")) %>%
filter(period == "2015-2020")
get_wcde(indicator = "sexratio",
country_name = c("China", "South Korea")) %>%
filter(year == 2020)
## -----------------------------------------------------------------------------
wic_indicators %>%
filter(`wcde-v2` == "past-available") %>%
select(1:2)
## ---- messages = FALSE, message=FALSE-----------------------------------------
get_wcde(indicator = "sexratio",
country_name = c("China", "South Korea")) %>%
filter(year == 2020,
age == "All")
## ---- messages = FALSE, message=FALSE-----------------------------------------
get_wcde(indicator = "tfr",
country_name = c("U.A.E", "Espania", "Österreich"))
## ---- messages = FALSE, message=FALSE-----------------------------------------
get_wcde(indicator = "etfr", country_code = c(44, 100))
## -----------------------------------------------------------------------------
wic_locations
## ---- messages = FALSE, message=FALSE-----------------------------------------
get_wcde(indicator = "growth",
country_name = c("India", "China"),
scenario = c(1:3, 22, 23)) %>%
filter(period == "2095-2100")
## ---- messages = FALSE, message=FALSE-----------------------------------------
get_wcde(indicator = "tfr",
country_name = c("Kenya", "Nigeria", "Algeria"),
scenario = 1:3,
include_scenario_names = TRUE) %>%
filter(period == "2045-2050")
## -----------------------------------------------------------------------------
wic_scenarios
## ---- messages = FALSE, message=FALSE-----------------------------------------
get_wcde(indicator = "mage")
## ---- messages = FALSE, message=FALSE-----------------------------------------
mi <- tibble(ind = c("odr", "nirate", "ggapedu25")) %>%
mutate(d = map(.x = ind, .f = ~get_wcde(indicator = .x)))
mi
mi %>%
filter(ind == "odr") %>%
select(-ind) %>%
unnest(cols = d)
mi %>%
filter(ind == "nirate") %>%
select(-ind) %>%
unnest(cols = d)
mi %>%
filter(ind == "ggapedu25") %>%
select(-ind) %>%
unnest(cols = d)
## -----------------------------------------------------------------------------
get_wcde(indicator = "etfr",
country_name = c("Brazil", "Albania"),
version = "wcde-v2")
## -----------------------------------------------------------------------------
get_wcde(indicator = "etfr",
country_name = c("Brazil", "Albania"),
version = "wcde-v2", server = "github")
## -----------------------------------------------------------------------------
get_wcde(indicator = "pop", country_name = "India")
## -----------------------------------------------------------------------------
get_wcde(indicator = "pop", country_code = 900, pop_edu = "four")
## -----------------------------------------------------------------------------
get_wcde(indicator = "pop", country_code = 900, pop_edu = "six", pop_sex = "both")
## -----------------------------------------------------------------------------
w <- get_wcde(indicator = "pop", country_code = 900,
pop_age = "all", pop_sex = "both", pop_edu = "four",
version = "wcde-v2")
w
w <- w %>%
mutate(pop_pm = ifelse(test = sex == "Male", yes = -pop, no = pop),
pop_pm = pop_pm/1e3)
w
## ---- message=FALSE, warning=FALSE--------------------------------------------
library(lemon)
w %>%
filter(year == 2020) %>%
ggplot(mapping = aes(x = pop_pm, y = age, fill = fct_rev(education))) +
geom_col() +
geom_vline(xintercept = 0, colour = "black") +
scale_x_symmetric(labels = abs) +
scale_fill_manual(values = wic_col4, name = "Education") +
labs(x = "Population (millions)", y = "Age") +
theme_bw()
## -----------------------------------------------------------------------------
w <- w %>%
mutate(pop_max = ifelse(sex == "Male", -max(pop/1e3), max(pop/1e3)))
w %>%
filter(year == 2020) %>%
ggplot(mapping = aes(x = pop_pm, y = age, fill = fct_rev(education))) +
geom_col() +
geom_vline(xintercept = 0, colour = "black") +
scale_x_continuous(labels = abs, expand = c(0, 0)) +
scale_fill_manual(values = wic_col4, name = "Education") +
labs(x = "Population (millions)", y = "Age") +
facet_wrap(facets = "sex", scales = "free_x", strip.position = "bottom") +
geom_blank(mapping = aes(x = pop_max * 1.1)) +
theme(panel.spacing.x = unit(0, "pt"),
strip.placement = "outside",
strip.background = element_rect(fill = "transparent"),
strip.text.x = element_text(margin = margin( b = 0, t = 0)))
## ---- echo=FALSE, eval=FALSE--------------------------------------------------
# library(gganimate)
#
# g <- ggplot(data = w,
# mapping = aes(x = pop_pm, y = age, fill = fct_rev(education))) +
# geom_col() +
# geom_vline(xintercept = 0, colour = "black") +
# scale_x_continuous(labels = abs, expand = c(0, 0)) +
# scale_fill_manual(values = wic_col4, name = "Education") +
# facet_wrap(facets = "sex", scales = "free_x", strip.position = "bottom") +
# geom_blank(mapping = aes(x = pop_max * 1.1)) +
# theme(panel.spacing.x = unit(0, "pt"),
# strip.placement = "outside",
# strip.background = element_rect(fill = "transparent"),
# strip.text.x = element_text(margin = margin(b = 0, t = 0))) +
# transition_time(time = year) +
# labs(x = "Population (millions)", y = "Age",
# title = 'SSP2 World Population {round(frame_time)}')
#
# animate(g, width = 672, height = 520, units = "px", res = 100,
# renderer = gifski_renderer())
#
# anim_save(filename = "../man/figures/world4_ssp2.gif")
## ---- eval =FALSE-------------------------------------------------------------
# library(gganimate)
#
# ggplot(data = w,
# mapping = aes(x = pop_pm, y = age, fill = fct_rev(education))) +
# geom_col() +
# geom_vline(xintercept = 0, colour = "black") +
# scale_x_continuous(labels = abs, expand = c(0, 0)) +
# scale_fill_manual(values = wic_col4, name = "Education") +
# facet_wrap(facets = "sex", scales = "free_x", strip.position = "bottom") +
# geom_blank(mapping = aes(x = pop_max * 1.1)) +
# theme(panel.spacing.x = unit(0, "pt"),
# strip.placement = "outside",
# strip.background = element_rect(fill = "transparent"),
# strip.text.x = element_text(margin = margin(b = 0, t = 0))) +
# transition_time(time = year) +
# labs(x = "Population (millions)", y = "Age",
# title = 'SSP2 World Population {round(frame_time)}')
|
/scratch/gouwar.j/cran-all/cranData/wcde/inst/doc/wcde.R
|
---
title: "Overview of the wcde package"
author: Guy J. Abel, Samir K.C., Michaela Potancokova, Claudia Reiter, Andrea Tamburini and Dilek Yildiz
output:
html_document:
fig_caption: false
toc: true
toc_float:
collapsed: false
smooth_scroll: true
toc_depth: 2
vignette: >
%\VignetteIndexEntry{Overview of wcde}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
```
<!-- <img src='https://raw.githubusercontent.com/guyabel/wcde/main/hex/logo_transp.png' align="right" height="200" style="float:right; height:200px;"/> -->
The `wcde` package allows for R users to easily download data from the [Wittgenstein Centre for Demography and Human Capital Data Explorer](http://dataexplorer.wittgensteincentre.org/) as well as containing a number of helpful functions for working with education specific demographic data.
# Installation
You can install the released version of `wcde` from [CRAN](https://CRAN.R-project.org) with:
```{r eval=FALSE}
install.packages("wcde")
```
Install the developmental version with:
```{r eval=FALSE}
library(devtools)
install_github("guyabel/wcde", ref = "main")
```
# Getting data into R
The `get_wcde()` function can be used to download data from the Wittgenstein Centre Human Capital Data Explorer. It requires three user inputs
- `indicator`: a short code for the indicator of interest
- `scenario`: a number referring to a SSP narrative, by default 2 is used (for SSP2)
- `country_code` (or `country_name`): corresponding to the country of interest
```{r, messages = FALSE, message=FALSE}
library(wcde)
# download education specific tfr data
get_wcde(indicator = "etfr",
country_name = c("Brazil", "Albania"))
# download education specific survivorship rates
get_wcde(indicator = "eassr",
country_name = c("Niger", "Korea"))
```
## Indicator codes
The indicator input must match the short code from the indicator table. The `find_indicator()` function can be used to look up short codes (given in the first column) from the `wic_indicators` data frame:
```{r}
find_indicator(x = "tfr")
```
## Temporal coverage
By default, `get_wdce()` returns data for all years or available periods or years. The `filter()` function in [dplyr](https://cran.r-project.org/package=dplyr/index.html) can be used to filter data for specific years or periods, for example:
```{r, message=FALSE, warning=FALSE}
library(tidyverse)
get_wcde(indicator = "e0",
country_name = c("Japan", "Australia")) %>%
filter(period == "2015-2020")
get_wcde(indicator = "sexratio",
country_name = c("China", "South Korea")) %>%
filter(year == 2020)
```
Past data is only available for selected indicators. These can be viewed using the version column:
```{r}
wic_indicators %>%
filter(`wcde-v2` == "past-available") %>%
select(1:2)
```
The `filter()` function can also be used to filter specific indicators to specific age, sex or education groups
```{r, messages = FALSE, message=FALSE}
get_wcde(indicator = "sexratio",
country_name = c("China", "South Korea")) %>%
filter(year == 2020,
age == "All")
```
## Country names and codes
Country names are guessed using the [countrycode](https://cran.r-project.org/package=countrycode/index.html) package.
```{r, messages = FALSE, message=FALSE}
get_wcde(indicator = "tfr",
country_name = c("U.A.E", "Espania", "Österreich"))
```
The `get_wcde()` functions accepts ISO alpha numeric codes for countries via the `country_code` argument:
```{r, messages = FALSE, message=FALSE}
get_wcde(indicator = "etfr", country_code = c(44, 100))
```
A full list of available countries and region aggregates, and their codes, can be found in the `wic_locations` data frame.
```{r}
wic_locations
```
## Scenarios
By default `get_wcde()` returns data for Medium (SSP2) scenario. Results for different SSP scenarios can be returned by passing a different (or multiple) scenario values to the `scenario` argument in `get_data()`.
```{r, messages = FALSE, message=FALSE}
get_wcde(indicator = "growth",
country_name = c("India", "China"),
scenario = c(1:3, 22, 23)) %>%
filter(period == "2095-2100")
```
Set `include_scenario_names = TRUE` to include a columns with the full names of the scenarios
```{r, messages = FALSE, message=FALSE}
get_wcde(indicator = "tfr",
country_name = c("Kenya", "Nigeria", "Algeria"),
scenario = 1:3,
include_scenario_names = TRUE) %>%
filter(period == "2045-2050")
```
Additional details of the pathways for each scenario numeric code can be found in the `wic_scenarios` object. Further background and links to the corresponding literature are provided in the [Data Explorer](http://dataexplorer.wittgensteincentre.org/)
```{r}
wic_scenarios
```
## All countries data
Data for all countries can be obtained by not setting `country_name` or `country_code`
```{r, messages = FALSE, message=FALSE}
get_wcde(indicator = "mage")
```
## Multiple indicators
The `get_wdce()` function needs to be called multiple times to download multiple indicators. This can be done using the `map()` function in [`purrr`](https://cran.r-project.org/package=purrr/index.html)
```{r, messages = FALSE, message=FALSE}
mi <- tibble(ind = c("odr", "nirate", "ggapedu25")) %>%
mutate(d = map(.x = ind, .f = ~get_wcde(indicator = .x)))
mi
mi %>%
filter(ind == "odr") %>%
select(-ind) %>%
unnest(cols = d)
mi %>%
filter(ind == "nirate") %>%
select(-ind) %>%
unnest(cols = d)
mi %>%
filter(ind == "ggapedu25") %>%
select(-ind) %>%
unnest(cols = d)
```
## Previous versions
Previous versions of projections from the Wittgenstein Centre for Demography are available using the `version` argument in `get_wdce()` to [`"wcde-v1"`](https://dataexplorer.wittgensteincentre.org/wcde-v1/) or [`"wcde-v2"`](https://dataexplorer.wittgensteincentre.org/wcde-v2/), where `"wcde-v3"` is used as the default since 2024.
```{r}
get_wcde(indicator = "etfr",
country_name = c("Brazil", "Albania"),
version = "wcde-v2")
```
Note, not all indicators and scenarios are available in all versions - see the the `wic_indicators` and `wic_scenarios` objects for further details (above).
## Server
If you have trouble with connecting to the IIASA server you can try back versions using the `server` option in `get_wcde()`, which can be set to `github`, `1&1`.
```{r}
get_wcde(indicator = "etfr",
country_name = c("Brazil", "Albania"),
version = "wcde-v2", server = "github")
```
You may also set `server = search-available` to search through the three possible data location to download the data whereever it is available.
# Working with population data
Population data for a range of age-sex-educational attainment combinations can be obtained by setting `indicator = "pop"` in `get_wcde()` and specifying a `pop_age`, `pop_sex` and `pop_edu` arguments. By default each of the three population breakdown arguments are set to "total"
```{r}
get_wcde(indicator = "pop", country_name = "India")
```
The `pop_age` argument can be set to `all` to get population data broken down in five-year age groups. The `pop_sex` argument can be set to `both` to get population data broken down into female and male groups. The `pop_edu` argument can be set to `four`, `six` or `eight` to get population data broken down into education categorizations with different levels of detail.
```{r}
get_wcde(indicator = "pop", country_code = 900, pop_edu = "four")
```
The population breakdown arguments can be used in combination to provide further breakdowns, for example sex and education specific population totals
```{r}
get_wcde(indicator = "pop", country_code = 900, pop_edu = "six", pop_sex = "both")
```
The full age-sex-education specific data can also be obtained by setting `indicator = "epop"` in `get_wcde()`.
<!-- The education population data in the data explorer, obtained by setting `indicator = "epop"` in `get_wcde()`, provide results by up to three different education categorizations (4, 6 and 8 education groups). -->
<!-- ```{r, messages = FALSE, message=FALSE} -->
<!-- d <- get_wcde(indicator = "epop", country_code = 900) -->
<!-- d -->
<!-- ``` -->
<!-- As the data frame contains multiple groupings, the `edu_group_sum()` function can be used to provide education specific population data. Users can specify the education groupings by setting the `n` argument to 4, 6 or 8. -->
<!-- ```{r, warning=FALSE, message=FALSE} -->
<!-- d %>% -->
<!-- edu_group_sum(n = 4) %>% -->
<!-- filter(year == 2020) -->
<!-- d %>% -->
<!-- edu_group_sum(n = 6) %>% -->
<!-- filter(year == 2020, -->
<!-- age == "30--34") -->
<!-- ``` -->
# Population pyramids
Create population pyramids by setting male population values to negative equivalent to allow for divergent columns from the y axis.
```{r}
w <- get_wcde(indicator = "pop", country_code = 900,
pop_age = "all", pop_sex = "both", pop_edu = "four",
version = "wcde-v2")
w
w <- w %>%
mutate(pop_pm = ifelse(test = sex == "Male", yes = -pop, no = pop),
pop_pm = pop_pm/1e3)
w
```
## Standard plot
Use standard ggplot code to create population pyramid with
- `scale_x_symmetric()` from the [`lemon`](https://cran.r-project.org/package=lemon/index.html) package to allow for equal male and female x-axis
- fill colours set to the `wic_col4` object in the wcde package which contains the names of the colours used in the Wittgenstein Centre Human Capital Data Explorer Data Explorer.
Note `wic_col6` and `wic_col8` objects also exist for equivalent plots of population data objects with corresponding numbers of categories of education.
```{r, message=FALSE, warning=FALSE}
library(lemon)
w %>%
filter(year == 2020) %>%
ggplot(mapping = aes(x = pop_pm, y = age, fill = fct_rev(education))) +
geom_col() +
geom_vline(xintercept = 0, colour = "black") +
scale_x_symmetric(labels = abs) +
scale_fill_manual(values = wic_col4, name = "Education") +
labs(x = "Population (millions)", y = "Age") +
theme_bw()
```
## Sex label position
Add male and female labels on the x-axis by
- Creating a facet plot with the strips on the bottom with transparent backgrounds and no space between.
- Set the x axis to have zero expansion beyond the values in the data allowing the two sides of the pyramids to meet.
- Add a `geom_blank()` to allow for equal x-axis and additional space at the end of largest columns.
```{r}
w <- w %>%
mutate(pop_max = ifelse(sex == "Male", -max(pop/1e3), max(pop/1e3)))
w %>%
filter(year == 2020) %>%
ggplot(mapping = aes(x = pop_pm, y = age, fill = fct_rev(education))) +
geom_col() +
geom_vline(xintercept = 0, colour = "black") +
scale_x_continuous(labels = abs, expand = c(0, 0)) +
scale_fill_manual(values = wic_col4, name = "Education") +
labs(x = "Population (millions)", y = "Age") +
facet_wrap(facets = "sex", scales = "free_x", strip.position = "bottom") +
geom_blank(mapping = aes(x = pop_max * 1.1)) +
theme(panel.spacing.x = unit(0, "pt"),
strip.placement = "outside",
strip.background = element_rect(fill = "transparent"),
strip.text.x = element_text(margin = margin( b = 0, t = 0)))
```
## Animate
Animate the pyramid through the past data and projection periods using the `transition_time()` function in the
[`gganimate`](https://cran.r-project.org/package=gganimate/index.html) package
```{r, echo=FALSE, eval=FALSE}
library(gganimate)
g <- ggplot(data = w,
mapping = aes(x = pop_pm, y = age, fill = fct_rev(education))) +
geom_col() +
geom_vline(xintercept = 0, colour = "black") +
scale_x_continuous(labels = abs, expand = c(0, 0)) +
scale_fill_manual(values = wic_col4, name = "Education") +
facet_wrap(facets = "sex", scales = "free_x", strip.position = "bottom") +
geom_blank(mapping = aes(x = pop_max * 1.1)) +
theme(panel.spacing.x = unit(0, "pt"),
strip.placement = "outside",
strip.background = element_rect(fill = "transparent"),
strip.text.x = element_text(margin = margin(b = 0, t = 0))) +
transition_time(time = year) +
labs(x = "Population (millions)", y = "Age",
title = 'SSP2 World Population {round(frame_time)}')
animate(g, width = 672, height = 520, units = "px", res = 100,
renderer = gifski_renderer())
anim_save(filename = "../man/figures/world4_ssp2.gif")
```
```{r, eval =FALSE}
library(gganimate)
ggplot(data = w,
mapping = aes(x = pop_pm, y = age, fill = fct_rev(education))) +
geom_col() +
geom_vline(xintercept = 0, colour = "black") +
scale_x_continuous(labels = abs, expand = c(0, 0)) +
scale_fill_manual(values = wic_col4, name = "Education") +
facet_wrap(facets = "sex", scales = "free_x", strip.position = "bottom") +
geom_blank(mapping = aes(x = pop_max * 1.1)) +
theme(panel.spacing.x = unit(0, "pt"),
strip.placement = "outside",
strip.background = element_rect(fill = "transparent"),
strip.text.x = element_text(margin = margin(b = 0, t = 0))) +
transition_time(time = year) +
labs(x = "Population (millions)", y = "Age",
title = 'SSP2 World Population {round(frame_time)}')
```
<img src='../man/figures/world4_ssp2.gif'/>
|
/scratch/gouwar.j/cran-all/cranData/wcde/inst/doc/wcde.Rmd
|
---
title: "Overview of the wcde package"
author: Guy J. Abel, Samir K.C., Michaela Potancokova, Claudia Reiter, Andrea Tamburini and Dilek Yildiz
output:
html_document:
fig_caption: false
toc: true
toc_float:
collapsed: false
smooth_scroll: true
toc_depth: 2
vignette: >
%\VignetteIndexEntry{Overview of wcde}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
```
<!-- <img src='https://raw.githubusercontent.com/guyabel/wcde/main/hex/logo_transp.png' align="right" height="200" style="float:right; height:200px;"/> -->
The `wcde` package allows for R users to easily download data from the [Wittgenstein Centre for Demography and Human Capital Data Explorer](http://dataexplorer.wittgensteincentre.org/) as well as containing a number of helpful functions for working with education specific demographic data.
# Installation
You can install the released version of `wcde` from [CRAN](https://CRAN.R-project.org) with:
```{r eval=FALSE}
install.packages("wcde")
```
Install the developmental version with:
```{r eval=FALSE}
library(devtools)
install_github("guyabel/wcde", ref = "main")
```
# Getting data into R
The `get_wcde()` function can be used to download data from the Wittgenstein Centre Human Capital Data Explorer. It requires three user inputs
- `indicator`: a short code for the indicator of interest
- `scenario`: a number referring to a SSP narrative, by default 2 is used (for SSP2)
- `country_code` (or `country_name`): corresponding to the country of interest
```{r, messages = FALSE, message=FALSE}
library(wcde)
# download education specific tfr data
get_wcde(indicator = "etfr",
country_name = c("Brazil", "Albania"))
# download education specific survivorship rates
get_wcde(indicator = "eassr",
country_name = c("Niger", "Korea"))
```
## Indicator codes
The indicator input must match the short code from the indicator table. The `find_indicator()` function can be used to look up short codes (given in the first column) from the `wic_indicators` data frame:
```{r}
find_indicator(x = "tfr")
```
## Temporal coverage
By default, `get_wdce()` returns data for all years or available periods or years. The `filter()` function in [dplyr](https://cran.r-project.org/package=dplyr/index.html) can be used to filter data for specific years or periods, for example:
```{r, message=FALSE, warning=FALSE}
library(tidyverse)
get_wcde(indicator = "e0",
country_name = c("Japan", "Australia")) %>%
filter(period == "2015-2020")
get_wcde(indicator = "sexratio",
country_name = c("China", "South Korea")) %>%
filter(year == 2020)
```
Past data is only available for selected indicators. These can be viewed using the version column:
```{r}
wic_indicators %>%
filter(`wcde-v2` == "past-available") %>%
select(1:2)
```
The `filter()` function can also be used to filter specific indicators to specific age, sex or education groups
```{r, messages = FALSE, message=FALSE}
get_wcde(indicator = "sexratio",
country_name = c("China", "South Korea")) %>%
filter(year == 2020,
age == "All")
```
## Country names and codes
Country names are guessed using the [countrycode](https://cran.r-project.org/package=countrycode/index.html) package.
```{r, messages = FALSE, message=FALSE}
get_wcde(indicator = "tfr",
country_name = c("U.A.E", "Espania", "Österreich"))
```
The `get_wcde()` functions accepts ISO alpha numeric codes for countries via the `country_code` argument:
```{r, messages = FALSE, message=FALSE}
get_wcde(indicator = "etfr", country_code = c(44, 100))
```
A full list of available countries and region aggregates, and their codes, can be found in the `wic_locations` data frame.
```{r}
wic_locations
```
## Scenarios
By default `get_wcde()` returns data for Medium (SSP2) scenario. Results for different SSP scenarios can be returned by passing a different (or multiple) scenario values to the `scenario` argument in `get_data()`.
```{r, messages = FALSE, message=FALSE}
get_wcde(indicator = "growth",
country_name = c("India", "China"),
scenario = c(1:3, 22, 23)) %>%
filter(period == "2095-2100")
```
Set `include_scenario_names = TRUE` to include a columns with the full names of the scenarios
```{r, messages = FALSE, message=FALSE}
get_wcde(indicator = "tfr",
country_name = c("Kenya", "Nigeria", "Algeria"),
scenario = 1:3,
include_scenario_names = TRUE) %>%
filter(period == "2045-2050")
```
Additional details of the pathways for each scenario numeric code can be found in the `wic_scenarios` object. Further background and links to the corresponding literature are provided in the [Data Explorer](http://dataexplorer.wittgensteincentre.org/)
```{r}
wic_scenarios
```
## All countries data
Data for all countries can be obtained by not setting `country_name` or `country_code`
```{r, messages = FALSE, message=FALSE}
get_wcde(indicator = "mage")
```
## Multiple indicators
The `get_wdce()` function needs to be called multiple times to download multiple indicators. This can be done using the `map()` function in [`purrr`](https://cran.r-project.org/package=purrr/index.html)
```{r, messages = FALSE, message=FALSE}
mi <- tibble(ind = c("odr", "nirate", "ggapedu25")) %>%
mutate(d = map(.x = ind, .f = ~get_wcde(indicator = .x)))
mi
mi %>%
filter(ind == "odr") %>%
select(-ind) %>%
unnest(cols = d)
mi %>%
filter(ind == "nirate") %>%
select(-ind) %>%
unnest(cols = d)
mi %>%
filter(ind == "ggapedu25") %>%
select(-ind) %>%
unnest(cols = d)
```
## Previous versions
Previous versions of projections from the Wittgenstein Centre for Demography are available using the `version` argument in `get_wdce()` to [`"wcde-v1"`](https://dataexplorer.wittgensteincentre.org/wcde-v1/) or [`"wcde-v2"`](https://dataexplorer.wittgensteincentre.org/wcde-v2/), where `"wcde-v3"` is used as the default since 2024.
```{r}
get_wcde(indicator = "etfr",
country_name = c("Brazil", "Albania"),
version = "wcde-v2")
```
Note, not all indicators and scenarios are available in all versions - see the the `wic_indicators` and `wic_scenarios` objects for further details (above).
## Server
If you have trouble with connecting to the IIASA server you can try back versions using the `server` option in `get_wcde()`, which can be set to `github`, `1&1`.
```{r}
get_wcde(indicator = "etfr",
country_name = c("Brazil", "Albania"),
version = "wcde-v2", server = "github")
```
You may also set `server = search-available` to search through the three possible data location to download the data whereever it is available.
# Working with population data
Population data for a range of age-sex-educational attainment combinations can be obtained by setting `indicator = "pop"` in `get_wcde()` and specifying a `pop_age`, `pop_sex` and `pop_edu` arguments. By default each of the three population breakdown arguments are set to "total"
```{r}
get_wcde(indicator = "pop", country_name = "India")
```
The `pop_age` argument can be set to `all` to get population data broken down in five-year age groups. The `pop_sex` argument can be set to `both` to get population data broken down into female and male groups. The `pop_edu` argument can be set to `four`, `six` or `eight` to get population data broken down into education categorizations with different levels of detail.
```{r}
get_wcde(indicator = "pop", country_code = 900, pop_edu = "four")
```
The population breakdown arguments can be used in combination to provide further breakdowns, for example sex and education specific population totals
```{r}
get_wcde(indicator = "pop", country_code = 900, pop_edu = "six", pop_sex = "both")
```
The full age-sex-education specific data can also be obtained by setting `indicator = "epop"` in `get_wcde()`.
<!-- The education population data in the data explorer, obtained by setting `indicator = "epop"` in `get_wcde()`, provide results by up to three different education categorizations (4, 6 and 8 education groups). -->
<!-- ```{r, messages = FALSE, message=FALSE} -->
<!-- d <- get_wcde(indicator = "epop", country_code = 900) -->
<!-- d -->
<!-- ``` -->
<!-- As the data frame contains multiple groupings, the `edu_group_sum()` function can be used to provide education specific population data. Users can specify the education groupings by setting the `n` argument to 4, 6 or 8. -->
<!-- ```{r, warning=FALSE, message=FALSE} -->
<!-- d %>% -->
<!-- edu_group_sum(n = 4) %>% -->
<!-- filter(year == 2020) -->
<!-- d %>% -->
<!-- edu_group_sum(n = 6) %>% -->
<!-- filter(year == 2020, -->
<!-- age == "30--34") -->
<!-- ``` -->
# Population pyramids
Create population pyramids by setting male population values to negative equivalent to allow for divergent columns from the y axis.
```{r}
w <- get_wcde(indicator = "pop", country_code = 900,
pop_age = "all", pop_sex = "both", pop_edu = "four",
version = "wcde-v2")
w
w <- w %>%
mutate(pop_pm = ifelse(test = sex == "Male", yes = -pop, no = pop),
pop_pm = pop_pm/1e3)
w
```
## Standard plot
Use standard ggplot code to create population pyramid with
- `scale_x_symmetric()` from the [`lemon`](https://cran.r-project.org/package=lemon/index.html) package to allow for equal male and female x-axis
- fill colours set to the `wic_col4` object in the wcde package which contains the names of the colours used in the Wittgenstein Centre Human Capital Data Explorer Data Explorer.
Note `wic_col6` and `wic_col8` objects also exist for equivalent plots of population data objects with corresponding numbers of categories of education.
```{r, message=FALSE, warning=FALSE}
library(lemon)
w %>%
filter(year == 2020) %>%
ggplot(mapping = aes(x = pop_pm, y = age, fill = fct_rev(education))) +
geom_col() +
geom_vline(xintercept = 0, colour = "black") +
scale_x_symmetric(labels = abs) +
scale_fill_manual(values = wic_col4, name = "Education") +
labs(x = "Population (millions)", y = "Age") +
theme_bw()
```
## Sex label position
Add male and female labels on the x-axis by
- Creating a facet plot with the strips on the bottom with transparent backgrounds and no space between.
- Set the x axis to have zero expansion beyond the values in the data allowing the two sides of the pyramids to meet.
- Add a `geom_blank()` to allow for equal x-axis and additional space at the end of largest columns.
```{r}
w <- w %>%
mutate(pop_max = ifelse(sex == "Male", -max(pop/1e3), max(pop/1e3)))
w %>%
filter(year == 2020) %>%
ggplot(mapping = aes(x = pop_pm, y = age, fill = fct_rev(education))) +
geom_col() +
geom_vline(xintercept = 0, colour = "black") +
scale_x_continuous(labels = abs, expand = c(0, 0)) +
scale_fill_manual(values = wic_col4, name = "Education") +
labs(x = "Population (millions)", y = "Age") +
facet_wrap(facets = "sex", scales = "free_x", strip.position = "bottom") +
geom_blank(mapping = aes(x = pop_max * 1.1)) +
theme(panel.spacing.x = unit(0, "pt"),
strip.placement = "outside",
strip.background = element_rect(fill = "transparent"),
strip.text.x = element_text(margin = margin( b = 0, t = 0)))
```
## Animate
Animate the pyramid through the past data and projection periods using the `transition_time()` function in the
[`gganimate`](https://cran.r-project.org/package=gganimate/index.html) package
```{r, echo=FALSE, eval=FALSE}
library(gganimate)
g <- ggplot(data = w,
mapping = aes(x = pop_pm, y = age, fill = fct_rev(education))) +
geom_col() +
geom_vline(xintercept = 0, colour = "black") +
scale_x_continuous(labels = abs, expand = c(0, 0)) +
scale_fill_manual(values = wic_col4, name = "Education") +
facet_wrap(facets = "sex", scales = "free_x", strip.position = "bottom") +
geom_blank(mapping = aes(x = pop_max * 1.1)) +
theme(panel.spacing.x = unit(0, "pt"),
strip.placement = "outside",
strip.background = element_rect(fill = "transparent"),
strip.text.x = element_text(margin = margin(b = 0, t = 0))) +
transition_time(time = year) +
labs(x = "Population (millions)", y = "Age",
title = 'SSP2 World Population {round(frame_time)}')
animate(g, width = 672, height = 520, units = "px", res = 100,
renderer = gifski_renderer())
anim_save(filename = "../man/figures/world4_ssp2.gif")
```
```{r, eval =FALSE}
library(gganimate)
ggplot(data = w,
mapping = aes(x = pop_pm, y = age, fill = fct_rev(education))) +
geom_col() +
geom_vline(xintercept = 0, colour = "black") +
scale_x_continuous(labels = abs, expand = c(0, 0)) +
scale_fill_manual(values = wic_col4, name = "Education") +
facet_wrap(facets = "sex", scales = "free_x", strip.position = "bottom") +
geom_blank(mapping = aes(x = pop_max * 1.1)) +
theme(panel.spacing.x = unit(0, "pt"),
strip.placement = "outside",
strip.background = element_rect(fill = "transparent"),
strip.text.x = element_text(margin = margin(b = 0, t = 0))) +
transition_time(time = year) +
labs(x = "Population (millions)", y = "Age",
title = 'SSP2 World Population {round(frame_time)}')
```
<img src='../man/figures/world4_ssp2.gif'/>
|
/scratch/gouwar.j/cran-all/cranData/wcde/vignettes/wcde.Rmd
|
#' Toy example
#'
#' A data set containing patient IDs, event types, event times, and
#' gender of 100 patients.
#'
#' @format {A data frame with 104 rows and 4 columns
#' \describe{
#' \item{PTID}{ID number of patients}
#' \item{EvTp}{Event Types: SHK as Shock, CHF as Congestive Heart
#' Failure, REMI as Recurrent Myocardial Infarction, DTH as
#' Death; and N as No event}
#' \item{EvTm}{Event Time (day)}
#' \item{sex}{Gender of patients, M as Male, F as Female}
#' }
#'}
#'
#'@source {It is a generated example based on ASSENT-3:
#' \url{https://pubmed.ncbi.nlm.nih.gov/21570513}}
#'
#'@section References:
#' Armstrong P. W., Westerhout C. M., Van de Werf F., Califf R. M., Welsh R. C.,
#' Wilcox R. G., Bakal J. A. (2011) Refining clinical trial composite outcomes:
#' an application to the Assessment of the Safety and Efficacy of a New
#' Thrombolytic-3 (ASSENT-3) trial. \var{American Heart Journal}. \bold{161}(5)
#' 848-854.
#'
"toyexample"
|
/scratch/gouwar.j/cran-all/cranData/wcep/R/data.R
|
# Take the events of a patient and return a numirated version
# of events. If a patient has two SHKs function "evt" returns
# SHK1 and SHK2.This provides a vector with unique events for
# each patient's event to use in spread() within library(tidyr).
nam <- function(X) {
rps <- NULL
out <- NULL
a <- length(which(table(X)[which(table(X)>0)] > 1))
if (a==0) {
out <- paste(X, 1, sep = "")
} else {
for (i in 1:length(X)) {
if ((X[i] %in% rps) == FALSE) {
rps <- c(rps, as.character(X[i]))
out <- c(out, paste(X[i], 1, sep=''))
} else {
rps <- c(rps, as.character(X[i]))
b <- length(which(rps == X[i]))
out <- c(out, paste(X[i], b, sep=''))
}
}
}
out
}
|
/scratch/gouwar.j/cran-all/cranData/wcep/R/nam.R
|
#' wcep plot
#'
#' Create a plot of Kaplan-Meier curve with its specified confidence interval
#' @param x is an object of class "wcep"
#' @param main title of plot
#' @param type type of plot
#' @param lty line type
#' @param lwd line width
#' @param xlab first axis label
#' @param ylab second axis label
#' @param xlim first axis limits
#' @param ylim second axis limits
#' @param cex legend font size
#' @param ... other parameters of generic "plot" have no use here
#' setOldClass("wcep")
#' @export
plot.wcep <- function(x, main = " ", type = "n", lty = NULL, lwd = NULL,
xlab = " ", ylab = "Survival Probability", xlim = NULL,
ylim = NULL, cex=NULL, ...){
if(length(x) == 5) {
timelab <- 0:dim(x$life_table)[2]
ymin <- round(max(min (x$lower)-0.0499,0)-0.05, 1)
yl <- if (is.null(ylim)) c(ymin, 1) else ylim
xmax <- length(x$survival_probabilities)
xl <- if (is.null(xlim)) c(0, xmax) else xlim
typ <- if (type == "n") "l" else type
lt <- if (is.null(lty)) 1 else lty
lw <- if (is.null(lwd)) 2 else lwd
plot(timelab, c(1,x$survival_probabilities), type = typ, lwd = lw, col = "hotpink2",
main = main, xlab = xlab, ylab = ylab, xlim = xl, ylim = yl, ...)
b <- c(c(1, x$upper), rev(c(1, x$lower)))
c <- c(timelab,rev(timelab))
polygon(c, b, col = "lavenderblush1", border = NA)
points(timelab, c(1,x$survival_probabilities), type = typ, lty = lt, lwd = lw,
col = "hotpink2")
} else {
timelab <- 0:dim(x[[1]]$life_table)[2]
ymin <- round(max(min (c(x[[1]]$lower, x[[2]]$lower))-0.0499,0)-0.05, 1)
yl <- if (is.null(ylim)) c(ymin,1) else ylim
xl <- if (is.null(xlim)) c(0, length(x[[1]]$survival_probabilities)) else xlim
typ <- if (type == "n") "l" else type
lt <- if (is.null(lty)) 1 else lty
lw <- if (is.null(lwd)) 2 else lwd
plot(timelab, c(1,x[[1]]$survival_probabilities), type = typ, lwd = lw, col = "violetred4",
main = main, xlab = xlab, ylab = ylab, xlim = xl, ylim = yl, lty = lt, ...)
b1 <- c(c(1, x[[1]]$upper), rev(c(1, x[[1]]$lower)))
c1 <- c(timelab,rev(timelab))
polygon(c1, b1, col = rgb(0.92, 0.43, 0.63, 0.43), border = NA)
b2 <- c(c(1, x[[2]]$upper), rev(c(1, x[[2]]$lower)))
c2 <- c(timelab,rev(timelab))
polygon(c2, b2, col = rgb(1,0.58,0.55,0.62), border = NA)
points(timelab, c(1,x[[2]]$survival_probabilities), type = typ, lty = lt,
lwd = lw, col = "orangered1")
cx <- if (is.null(cex)) 0.8 else cex
legend("bottomleft", legend = names(x)[1:2], lty = rep(lt, 2), lwd = rep(lw, 2),
col = c("violetred4", "orangered1"), cex=rep(cx,2))
}
}
|
/scratch/gouwar.j/cran-all/cranData/wcep/R/plot.R
|
#' @aliases wcep-package
#' @keywords internal
"_PACKAGE"
## usethis namespace: start
## usethis namespace: end
NULL
|
/scratch/gouwar.j/cran-all/cranData/wcep/R/wcep-package.R
|
#' @include nam.R wcep_core.R
NULL
#' Analysis of weighted composite endpoints
#'
#' Analyze given data frame and return Kaplan-Meier survival probabilities together with the specified confidence interval.
#' \code{wcep} modifies Kaplan-Meier curve by taking into account severity weights of different event. Alternative methods are Anderson Gill model and win ratio of composite outcomes.The function takes event dataset and user-specified severity weights to generate a modified Kaplan-Meier curve and comparison statistics based on the weighted composite endpoint method. The user supplies the event data set, the weights, and the factor to split on . The package will generate the weighted survival curve, confidence interval and test the differences between the two groups.
#'
#' @param x This data frame usually has 3 columns. The first column specifies patient ID,
#' which is a character or numeric vector, the second column is a factor with character values
#' of event types. The third column is a numeric vector of event times. If split = TRUE,
#' then the forth column is a character vector of split groups of at most two groups,
#' like gender.
#'
#' @param EW This data frame has two columns. The first column
#' specifies a character vector of event types. The second column specify weights.
#' The naming of event types in x and EW should be exactly similar.
#'
#' @param alpha A numeric value between 0-1 which specifies the confidence level,
#' if it is not specified, by default is 0.05.
#'
#' @param split A logical value of T or F which allows to compare two groups.
#'
#' @section References:
#' Bakal J., Westerhout C. M., Armstrong P. W. (2015) Impact of weighted composite
#' compared to traditional composite endpoints for the design of randomized
#' controlled trails. \var{Statistical Methods in Medicine Research}. \bold{24}(6) 980-988.
#'
#' Nabipoor M., Westerhout C. M., Rathwell S., Bakal J. (2023) The empirical
#' estimate of the survival and variance using a weighted composite endpoint,
#' \var{BMC Medical Research Methodology}. \bold{23}(35).
#'
#' @examples
#' data(toyexample)
#' #event weights
#' EW <- data.frame(event = c('CHF','DTH','SHK','REMI'), weight = c(0.3,1,0.5,0.2))
#' res1 <- wcep(toyexample, EW)
#' str(res1)
#' res1$survival_probabilities
#' plot(res1)
#' #comparing two genders
#' res2 <- wcep(toyexample, EW, split=TRUE)
#' plot(res2)
#' #wilcox and t test
#' res2$Wilcoxontest
#' res2$t_test
#' @author
#' Majid Nabipoor: nabipoor@@ualberta.ca,
#' Cynthia Westerhout: cindy.westerhout@@ualberta.ca,
#' Jeffrey Bakal: jbakal@@ualberta.ca
#' @seealso \code{\link{coxph}} for Anderson Gill model
#' @importFrom stats qnorm t.test
#' @importFrom graphics plot points polygon legend
#' @importFrom grDevices rgb
#' @import coin dplyr progress tidyr
#' @export
wcep <- function(x, EW, alpha = 0.05 , split = FALSE){
if (dim(x)[2] < 3 | dim(x)[2] > 4) {
return(noquote("Error: Data frame x should have 3 columns for one group or 4 columns for two groups comparison"))
}
if (alpha >= 1 | alpha <= 0) {
return(noquote("Error: value of alpha should be between 0 and 1"))
}
if ( split == TRUE && dim(x)[2] != 4 ) {
return(noquote("Error: Data frame x should have 4 columns" ))
}
if ( split == TRUE && length(unique(x[,4])) > 2 ) {
return(noquote("Error: The last column should have two levels" ))
}
if ( is.factor(x[,2]) == FALSE ) {
return(noquote("Error: The second column should be factor" ))
}
res <- structure(list(), class = "wcep")
if(split == FALSE) {
pb <- progress_bar$new(
format = " work progress [:bar] :percent",
total = NA, clear = FALSE, width= 80)
res <- wcep_core(x[, 1:3], EW, alpha)
} else {
groups <- unique(x[, 4])
for(i in 1:2) {
pb <- progress_bar$new(
format = " Progress [:bar] :percent",
total = NA, clear = FALSE, width= 80)
res[[paste0(" ", groups[i], sep="")]] <- wcep_core(x[which(x[, 4] == groups[i]), 1:3], EW, alpha)
}
res$Wilcoxontest <- wilcoxsign_test((res[[paste0(" ", groups[1], sep="")]])$survival_probabilities ~
(res[[paste0(" ", groups[2], sep="")]])$survival_probabilities, zero.method = c("Pratt"))
res$t_test <- (t.test((res[[paste0(" ", groups[1], sep="")]])$survival_probabilities,
(res[[paste0(" ", groups[2], sep="")]])$survival_probabilities))
}
res
}
|
/scratch/gouwar.j/cran-all/cranData/wcep/R/wcep.R
|
#' @include nam.R
#'
# Function: wcep_core
#
# Analyze Weighted Composite EndPoints for one data set and produce life table, survival
# probabilities, variances, and 95% C.I. by given alpha or by default alpha = 0.05.
#
# Authors: Majid Nabipoor, Jeff Bakal
# revised: Sep. 2019, Jan. 2020, Oct. 2020
wcep_core <- function(x, ew, alpha) {
# list of output
out <- list()
class(out) <- "wcep"
# add a numerical patient ID column
pt_h <- as.factor(x[, 1])
ptid_h <- 1:length(unique(pt_h))
dd <- data.frame(pt_h = unique(pt_h), ptid_h)
names(dd) <- c(names(x)[1], "c4")
x1 <- merge(x, dd, by = names(x)[1])
# Numerate similar events for a patient; SHK SHK -> SHK1 SHK2
evtp_h <- as.character(x1[, 2])
evtm_h <- as.numeric(x1[, 3])
invisible(sapply(ptid_h, function(i) {ind <- which(x1[, 4] == i);
evtp_h[ind] <<- nam(evtp_h[ind])}))
x2 <- data.frame(c1 = x1[, 4], evtp_h, evtm_h = x1[, 3])
# time matrix for each unique event of patients
xx <- x2 %>% spread(evtp_h, evtm_h)
maxtime <- max(x2[, 3])
xx[is.na(xx)] <- maxtime+1
# life table and survival probabilities
names(ew)<-c("event","weight")
ew1 <- data.frame(event = ew[, 1], weight=ew[, 2])
ew_h <- data.frame(cbind(colnames(xx[, -1]), substr(colnames(xx[, -1]), 1,
nchar(colnames(xx[, -1])) - 1)))
colnames(ew_h) <- c("c1", "event")
ne_h <- setdiff(ew_h[, 2], ew[, 1])
ew_h0<- droplevels(ew_h[-which(ew_h$event==ne_h),],exclude=ne_h)
ew_h1 <- left_join(ew_h0, ew1, by="event")[, c(1, 3)]
xx <- xx[,-which(colnames(xx) %in% setdiff(colnames(xx), ew_h1[,1]))]
n <- length(ptid_h)
lifemat <- matrix(1, nrow = n, ncol = maxtime+1)
tot <- n + maxtime
pb <- progress_bar$new(
format = " downloading :Progress [:bar] :percent",
clear = FALSE, total = tot, width = 80)
s_table <- sapply(1:n, function(i){
pb$tick()
sapply(2:(maxtime + 1), function(j){
lifemat[i,j] <<- prod(apply(cbind(t(xx[i, ]), ew_h1)[, -2], 1, function(v){
ifelse(v[1] <= j-1, 1-as.numeric(v[2]), 1)}))
})})
# lt <- dim(s_table)[1]
# s_table <- s_table[-lt, ]
out$life_table <- t(s_table)
out$survival_probabilities <- apply(s_table, 1, mean)
# variance
s_table1 <- data.frame(1, t(s_table))
Key <- data.frame(key = 1 - ew$weight, ev = ew$event)
s <- cumsum(sapply(2:dim(s_table1)[2], function(j){
pb$tick()
drev <- data.frame( key = s_table1[, j] / s_table1[, j - 1])
f<-table(dplyr::left_join(drev, Key, by = "key")[, 2])
u=attr(f,"dimnames")[[1]]
p<-data.frame(key=Key[,2],0)
p[,2]<-sapply(1:dim(p)[1],function(i){ifelse(length(which(u==p[i,1]))!=0, f[which(u==p[i,1])], 0)})
pj<-matrix(p[,2] / sum(s_table1[, j - 1]), ncol=1)
uj<- matrix(t(ew[, 2]), nrow=1)%*%pj
(1 - uj)^(-2)*(t(ew[,2])%*%(diag(as.vector(pj))- pj%*%t(pj))%*%ew[,2])
}))*apply(t(s_table)^2, 2, sum) / (dim(s_table)[2])^2
out$variance <- s
upper <- out$survival_probabilities + qnorm(1-alpha / 2) * sqrt(s)
lower <- out$survival_probabilities - qnorm(1-alpha / 2) * sqrt(s)
out$upper <- sapply(1:length(upper), function(i) {
ifelse(upper[i] > 1, upper[i] <- 1, upper[i])
ifelse(upper[i] < 0, upper[i] <- 0, upper[i])
})
out$lower <- sapply(1:length(lower), function(i) {
ifelse(lower[i] > 1, lower[i] <- 1, lower[i])
ifelse(lower[i] < 0, lower[i] <- 0, lower[i])
})
out
}
|
/scratch/gouwar.j/cran-all/cranData/wcep/R/wcep_core.R
|
#' @keywords internal
#' @details
#' weightmatrix - configures and visualizes a weight matrix
#'
#' wconfusionmatrix - calculates the weighted confusion matrix from a caret
#' ConfusionMatrix object or a simple matrix, according to one of several
#' weighting schemas and optionally prints the weighted accuracy score.
#'
#' @examples
#' # Generate sample data
#' m = matrix(c(70,0,0,10,10,0,5,3,2), ncol = 3, nrow=3)
#' # Experiment with several weighting schemes to find optimal solution
#' weightmatrix(n=4, weight.type="arithmetic", plot.weights = TRUE)
#' weightmatrix(n=4, weight.type="geometric", geometric.multiplier = 0.6)
#' weightmatrix(n=4, weight.type="geometric", geometric.multiplier = 2)
#' # Compute the weighted confusion matrix
#' wconfusionmatrix(m, weight.type = "arithmetic", print.weighted.accuracy = TRUE)
#'
#' @author Alexandru Monahov
#' @references Kuhn, M. (2008). Building Perspective Models in R Using the caret
#' Package. Journal of Statistical Software, 28(5), 1-26.
#'
#' Monahov, A. (2021). Model Evaluation with Weighted Threshold Optimization
#' (and the "mewto" R package), Machine Learning eJournal, SSRN.
#'
#' Van de Velden, M. et al. (2023). A general framework for implementing
#' distances for categorical variables. arXiv.
#'
#' @source Copyright Alexandru Monahov, 2023. You may use, modify and redistribute
#' this code, provided that you give credit to the author and make any derivative
#' work available to the public for free.
#'
#' @importFrom graphics abline
#' @importFrom graphics axis
#' @importFrom stats dnorm
#'
"_PACKAGE"
|
/scratch/gouwar.j/cran-all/cranData/wconf/R/wconf-package.R
|
#' Weighted confusion matrix
#'
#' This function calculates the weighted confusion matrix from a caret
#' ConfusionMatrix object or a simple matrix, according to one of several
#' weighting schemas and optionally prints the weighted accuracy score.
#'
#' @param m the caret confusion matrix object or simple matrix.
#'
#' @param weight.type the weighting schema to be used. Can be one of:
#' "arithmetic" - a decreasing arithmetic progression weighting scheme,
#' "geometric" - a decreasing geometric progression weighting scheme,
#' "normal" - weights drawn from the right tail of a normal distribution,
#' "interval" - weights contained on a user-defined interval,
#' "custom" - custom weight vector defined by the user.
#'
#' @param weight.penalty determines whether the weights associated with
#' non-diagonal elements generated by the "normal", "arithmetic" and "geometric"
#' weight types are positive or negative values. By default, the value is set to
#' FALSE, which means that generated weights will be positive values.
#'
#' @param standard.deviation standard deviation of the normal distribution, if
#' the normal distribution weighting schema is used.
#'
#' @param geometric.multiplier the multiplier used to construct the geometric
#' progression series, if the geometric progression weighting scheme is used.
#'
#' @param interval.high the upper bound of the weight interval, if the interval
#' weighting scheme is used.
#'
#' @param interval.low the lower bound of the weight interval, if the interval
#' weighting scheme is used.
#'
#' @param custom.weights the vector of custom weight sto be applied, is the
#' custom weighting scheme wasd selected. The vector should be equal to "n", but
#' can be larger, with excess values being ignored.
#'
#' @param print.weighted.accuracy print the weighted accuracy metric, which
#' represents the sum of all weighted confusion matrix cells divided by the
#' total number of observations.
#'
#' @return an nxn weighted confusion matrix
#'
#' @details The number of categories "n" should be greater or equal to 2.
#'
#' @usage wconfusionmatrix(m, weight.type = "arithmetic",
#' weight.penalty = FALSE,
#' standard.deviation = 2,
#' geometric.multiplier = 2,
#' interval.high=1, interval.low = -1,
#' custom.weights = NA,
#' print.weighted.accuracy = FALSE)
#'
#' @keywords weighted confusion matrix accuracy score
#'
#' @seealso [weightmatrix()]
#'
#' @author Alexandru Monahov, <https://www.alexandrumonahov.eu.org/>
#'
#' @examples
#' m = matrix(c(70,0,0,10,10,0,5,3,2), ncol = 3, nrow=3)
#' wconfusionmatrix(m, weight.type="arithmetic", print.weighted.accuracy = TRUE)
#' wconfusionmatrix(m, weight.type="geometric", print.weighted.accuracy = TRUE)
#' wconfusionmatrix(m, weight.type="interval", print.weighted.accuracy = TRUE)
#' wconfusionmatrix(m, weight.type="normal", print.weighted.accuracy = TRUE)
#' wconfusionmatrix(m, weight.type= "custom", custom.weights = c(1,0.1,0),
#' print.weighted.accuracy = TRUE)
#'
#' @export
wconfusionmatrix <- function(m, weight.type = "arithmetic", weight.penalty = FALSE, standard.deviation = 2, geometric.multiplier = 2, interval.high=1, interval.low = -1, custom.weights = NA, print.weighted.accuracy = FALSE) {
if (is.matrix(m) == FALSE) {m = as.matrix(m)}
n = length(m[,1])
if (weight.type == "normal") {
# Normal distribution
a <- seq(from = 1, to = n, by = 1)
fmean <- seq(from = 1, to = n, by = 1)
mat <- t(mapply(function(mean,sd) dnorm(a,mean,sd)/max(dnorm(a,mean,sd)), mean=fmean, sd=standard.deviation))
if (weight.penalty == TRUE) {
mat = -(1-mat)
diag(mat) = 1
}
if (print.weighted.accuracy == TRUE) {
waccuracy = sum(m*mat)/sum(m)
cat("Weighted accuracy = ", sum(m*mat)/sum(m), "\n", "\n")
}
return(m*mat)
}
else if (weight.type == "arithmetic") {
# Arithmetic progression
mat = ((n-1)-abs(outer(seq(0, (n-1), 1), seq(0, (n-1), 1), `-`)))/(n-1)
if (weight.penalty == TRUE) {
mat = -(1-mat)
diag(mat) = 1
}
if (print.weighted.accuracy == TRUE) {
waccuracy = sum(m*mat)/sum(m)
cat("Weighted accuracy = ", sum(m*mat)/sum(m), "\n", "\n")
}
return(m*mat)
}
else if (weight.type == "geometric") {
# Geometric progression
mult = geometric.multiplier
mat = (abs(outer(seq(0, (n-1), 1), seq(0, (n-1), 1), `-`)))+1
x=mult^seq(0,(n-1),by=1)
x_n = (x-min(x))/(max(x)-min(x))
if (mult > 1){
x_dict = 1-x_n
} else if (mult > 0 && mult < 1) {
x_dict = x_n
} else if (mult == 1) {
x_dict = 1-seq(0, (n-1), 1)/(n-1)
} else if (mult <= 0) {
stop("Please enter a multiplier value greater than zero.")
}
for (i in 1:n) {
mat[mat==i] = x_dict[i]
}
if (weight.penalty == TRUE) {
mat = -(1-mat)
diag(mat) = 1
}
if (print.weighted.accuracy == TRUE) {
waccuracy = sum(m*mat)/sum(m)
cat("Weighted accuracy = ", sum(m*mat)/sum(m), "\n", "\n")
}
return(m*mat)
}
else if (weight.type == "interval") {
# Interval weight
hi = interval.high
lo = interval.low
mat = (abs(outer(seq(0, (n-1), 1), seq(0, (n-1), 1), `-`)))+1
x=seq(hi, lo, length.out = n)
for (i in 1:n) {
mat[mat==i] = x[i]
}
if (print.weighted.accuracy == TRUE) {
waccuracy = sum(m*mat)/sum(m)
cat("Weighted accuracy = ", sum(m*mat)/sum(m), "\n", "\n")
}
return(m*mat)
}
else if (weight.type == "custom") {
# Custom weights
wt = custom.weights
mat = (abs(outer(seq(0, (n-1), 1), seq(0, (n-1), 1), `-`)))+1
for (i in 1:n) {
mat[mat==i] = wt[i]
}
if (print.weighted.accuracy == TRUE) {
waccuracy = sum(m*mat)/sum(m)
cat("Weighted accuracy = ", sum(m*mat)/sum(m), "\n", "\n")
}
return(m*mat)
}
}
|
/scratch/gouwar.j/cran-all/cranData/wconf/R/wconfusionmatrix.R
|
#' Weight matrix
#'
#' This function compiles a weight matrix according to one of several weighting
#' schemas and allows users to visualize the impact of the weight matrix on each
#' element of the confusion matrix.
#'
#' @param n the number of classes contained in the confusion matrix.
#'
#' @param weight.type the weighting schema to be used. Can be one of:
#' "arithmetic" - a decreasing arithmetic progression weighting scheme,
#' "geometric" - a decreasing geometric progression weighting scheme,
#' "normal" - weights drawn from the right tail of a normal distribution,
#' "interval" - weights contained on a user-defined interval,
#' "custom" - custom weight vector defined by the user.
#'
#' @param weight.penalty determines whether the weights associated with
#' non-diagonal elements generated by the "normal", "arithmetic" and "geometric"
#' weight types are positive or negative values. By default, the value is set to
#' FALSE, which means that generated weights will be positive values.
#'
#' @param standard.deviation standard deviation of the normal distribution, if
#' the normal distribution weighting schema is used.
#'
#' @param geometric.multiplier the multiplier used to construct the geometric
#' progression series, if the geometric progression weighting scheme is used.
#'
#' @param interval.high the upper bound of the weight interval, if the interval
#' weighting scheme is used.
#'
#' @param interval.low the lower bound of the weight interval, if the interval
#' weighting scheme is used.
#'
#' @param custom.weights the vector of custom weights to be applied, is the
#' custom weighting scheme was selected. The vector should be equal to "n", but
#' can be larger, with excess values being ignored.
#'
#' @param plot.weights optional setting to enable plotting of weight vector,
#' corresponding to the first column of the weight matrix
#'
#' @return an nxn matrix, containing the weights to be multiplied with the
#' confusion matrix.
#'
#' @details The number of categories "n" should be greater or equal to 2.
#'
#' @usage weightmatrix(n, weight.type = "arithmetic", weight.penalty = FALSE,
#' standard.deviation = 2,
#' geometric.multiplier = 2,
#' interval.high=1, interval.low = -1,
#' custom.weights = NA,
#' plot.weights = FALSE)
#'
#' @keywords weight matrix normal arithmetic geometric progression interval
#'
#' @seealso [wconfusionmatrix()]
#'
#' @author Alexandru Monahov, <https://www.alexandrumonahov.eu.org/>
#'
#' @examples
#' weightmatrix(n=4, weight.type="arithmetic", plot.weights = TRUE)
#' weightmatrix(n=4, weight.type="normal", standard.deviation = 1,
#' plot.weights = TRUE)
#' weightmatrix(n=4, weight.type="interval", interval.high = 1,
#' interval.low = -0.5, plot.weights = TRUE)
#' weightmatrix(n=4, weight.type="geometric", geometric.multiplier = 0.6)
#' weightmatrix(n=4, weight.type="custom", custom.weights = c(1,0.2,0.1,0),
#' plot.weights = TRUE)
#'
#' @export
weightmatrix <- function(n, weight.type = "arithmetic", weight.penalty = FALSE, standard.deviation = 2, geometric.multiplier = 2, interval.high=1, interval.low = -1, custom.weights = NA, plot.weights = FALSE) {
if (weight.type == "normal") {
# Normal distribution
a <- seq(from = 1, to = n, by = 1)
fmean <- seq(from = 1, to = n, by = 1)
mat <- t(mapply(function(mean,sd) dnorm(a,mean,sd)/max(dnorm(a,mean,sd)), mean=fmean, sd=standard.deviation))
if (weight.penalty == TRUE) {
mat = -(1-mat)
diag(mat) = 1
}
if (plot.weights == TRUE) {
plot(mat[,1], type = "l", xaxt = "n", xlab = "Category", ylab = "Weight")
axis(1, at = 1:length(mat[,1]))
if (min(mat)<0) {abline(h=0, lty = "dotted")}
}
return(mat)
}
else if (weight.type == "arithmetic") {
# Arithmetic progression
mat = ((n-1)-abs(outer(seq(0, (n-1), 1), seq(0, (n-1), 1), `-`)))/(n-1)
if (weight.penalty == TRUE) {
mat = -(1-mat)
diag(mat) = 1
}
if (plot.weights == TRUE) {
plot(mat[,1], type = "l", xaxt = "n", xlab = "Category", ylab = "Weight")
axis(1, at = 1:length(mat[,1]))
if (min(mat)<0) {abline(h=0, lty = "dotted")}
}
return(mat)
}
else if (weight.type == "geometric") {
# Geometric progression
mult = geometric.multiplier
mat = (abs(outer(seq(0, (n-1), 1), seq(0, (n-1), 1), `-`)))+1
x=mult^seq(0,(n-1),by=1)
x_n = (x-min(x))/(max(x)-min(x))
if (mult > 1){
x_dict = 1-x_n
} else if (mult > 0 && mult < 1) {
x_dict = x_n
} else if (mult == 1) {
x_dict = 1-seq(0, (n-1), 1)/(n-1)
} else if (mult <= 0) {
stop("Please enter a multiplier value greater than zero.")
}
for (i in 1:n) {
mat[mat==i] = x_dict[i]
}
if (weight.penalty == TRUE) {
mat = -(1-mat)
diag(mat) = 1
}
if (plot.weights == TRUE) {
plot(mat[,1], type = "l", xaxt = "n", xlab = "Category", ylab = "Weight")
axis(1, at = 1:length(mat[,1]))
if (min(mat)<0) {abline(h=0, lty = "dotted")}
}
return(mat)
}
else if (weight.type == "interval") {
# Interval weight
hi = interval.high
lo = interval.low
mat = (abs(outer(seq(0, (n-1), 1), seq(0, (n-1), 1), `-`)))+1
x=seq(hi, lo, length.out = n)
for (i in 1:n) {
mat[mat==i] = x[i]
}
if (plot.weights == TRUE) {
plot(mat[,1], type = "l", xaxt = "n", xlab = "Category", ylab = "Weight")
axis(1, at = 1:length(mat[,1]))
if (min(mat)<0) {abline(h=0, lty = "dotted")}
}
return(mat)
}
else if (weight.type == "custom") {
# Custom weights
wt = custom.weights
mat = (abs(outer(seq(0, (n-1), 1), seq(0, (n-1), 1), `-`)))+1
for (i in 1:n) {
mat[mat==i] = wt[i]
}
if (plot.weights == TRUE) {
plot(mat[,1], type = "l", xaxt = "n", xlab = "Category", ylab = "Weight")
axis(1, at = 1:length(mat[,1]))
if (min(mat)<0) {abline(h=0, lty = "dotted")}
}
return(mat)
}
}
|
/scratch/gouwar.j/cran-all/cranData/wconf/R/weightmatrix.R
|
## ----setup, include = FALSE, echo=FALSE---------------------------------------
knitr::opts_chunk$set(
collapse = TRUE,
error = TRUE,
comment = "#>"
)
## -----------------------------------------------------------------------------
# View the weight matrix and plot for a 3-category classification problem, using the arithmetic sequence option.
weightmatrix(3, weight.type = "arithmetic", plot.weights = TRUE)
## -----------------------------------------------------------------------------
# Load libraries and perform transformations
library(caret)
data(iris)
iris$Petal.Length.Cat = cut(iris$Petal.Length, breaks=c(1, 3, 5, 7), right = FALSE)
# Train multinomial logistic regression model using caret
set.seed(1)
control <- trainControl(method="repeatedcv", number=10, repeats=3)
model <- train(Petal.Length.Cat ~ Sepal.Width, data=iris, method="multinom", trace = FALSE, trControl=control)
# Extract original data, predicted values and place them in a table
y = iris$Petal.Length.Cat
yhat = predict(model)
preds = table(data=yhat, reference=y)
# Construct the confusion matrix
confmat = confusionMatrix(preds)
# Compute the weighted confusion matrix and display the weighted accuracy score
wconfusionmatrix(confmat, weight.type = "arithmetic", print.weighted.accuracy = TRUE)
|
/scratch/gouwar.j/cran-all/cranData/wconf/inst/doc/wconf_guide.R
|
---
title: "wconf: Weighted Confusion Matrix"
author: "Alexandru Monahov"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
%\VignetteEncoding{UTF-8}
%\VignetteIndexEntry{wconf: Weighted Confusion Matrix}
%\VignetteEngine{knitr::rmarkdown}
editor_options:
markdown:
wrap: 72
---
```{r setup, include = FALSE, echo=FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
error = TRUE,
comment = "#>"
)
```
## The wconf package
**wconf is a package that allows users to create weighted confusion
matrices and accuracy scores**
Used to improve the model selection process, the package includes
several weighting schemes which can be parameterized, as well as the
option for custom weight configurations. Furthermore, users can decide
whether they wish to positively or negatively affect the accuracy score
as a result of applying weights to the confusion matrix. "wconf"
integrates with the "caret" package, but it can also work standalone
when provided data in matrix form.
#### **About confusion matrices**
Confusion matrices are used to visualize the performance of
classification models in tabular format. A confusion matrix takes the
form of an "n x n" matrix depicting:
a) the reference category, in columns;
b) the predicted category, in rows;
c) the number of observation corresponding to each combination of
"reference - predicted" category couples, as cells of the matrix.
Visually, the simplest binary classification confusion matrix takes on
the form:
$$
A = \begin{bmatrix}TP & FP \\FN & TN\\ \end{bmatrix}
$$ where:
$TP$ - True Positives - the number of observations that were "positive"
and were correctly predicted as being "positive"
$TN$ - True Negatives - the number of originally "negative" observations
that were correctly predicted by the model as being "negative".
$FP$ - False Positives - also called "Type 1 Error" - represents
observations that are in fact "negative", but were incorrectly
classified by the model as being "positive".
$FN$ - False Negatives - also called "Type 2 Error" - represents
observations that are in fact "positive", but were incorrectly
classified by the model as being "negative".
The traditional accuracy metric is compiled by adding the true positives
and true negatives, and dividing them by the total number of
observations.
$$
A = \frac{TP + TN} {N}
$$
A weighted confusion matrix consists in attributing weights to all
classification categories based on their distance from the correctly
predicted category. This is important for multi-category classification
problems (where there are three or more categories), where distance from
the correctly predicted category matters.
The weighted confusion matrix, for the simple binary classification,
takes the form:
$$
A = \begin{bmatrix}w1*TP & w2*FP \\w2*FN & w1*TN\\ \end{bmatrix}
$$
In the case of the weighted confusion matrix, a weighted accuracy score
can be calculated by summing up all of the elements of the matrix and
dividing the resulting amount by the number of observations.
$$
A = \frac{w1*TP + w2*FP + w2*FN + w1*TN} {N}
$$
#### **References**
For more details on the method, see the paper:
Monahov, A. (2023). wconf: The weighted confusion matrix and accuracy
scores package for R
## Functions
#### **weightmatrix - configure and visualize a weight matrix**
This function compiles a weight matrix according to one of several
weighting schemas and allows users to visualize the impact of the weight
matrix on each element of the confusion matrix.
In R, simply call the function:
``` r
weightmatrix(n, weight.type = "arithmetic", weight.penalty = FALSE, standard.deviation = 2, geometric.multiplier = 2, interval.high=1, interval.low = -1, custom.weights = NA, plot.weights = FALSE) {
```
The function takes as input:
*n* -- the number of classes contained in the confusion matrix.
*weight.type* -- the weighting schema to be used. Can be one of:
"arithmetic" - a decreasing arithmetic progression weighting scheme,
"geometric" - a decreasing geometric progression weighting scheme,
"normal" - weights drawn from the right tail of a normal distribution,
"interval" - weights contained on a user-defined interval, "custom" -
custom weight vector defined by the user.
*weight.penalty* -- determines whether the weights associated with
non-diagonal elements generated by the "normal", "arithmetic" and
"geometric" weight types are positive or negative values. By default,
the value is set to FALSE, which means that generated weights will be
positive values.
*standard.deviation* -- standard deviation of the normal distribution,
if the normal distribution weighting schema is used.
*geometric.multiplier* -- the multiplier used to construct the geometric
progression series, if the geometric progression weighting scheme is
used.
*interval.high* -- the upper bound of the weight interval, if the
interval weighting scheme is used.
*interval.low* -- the lower bound of the weight interval, if the
interval weighting scheme is used.
*custom.weights* -- the vector of custom weights to be applied, is the
custom weighting scheme was selected. The vector should be equal to "n",
but can be larger, with excess values being ignored.
*plot.weights* -- optional setting to enable plotting of weight vector,
corresponding to the first column of the weight matrix
The function outputs a matrix:
| | |
|-----|------------------------|
| w | the nxn weight matrix. |
#### **wconfusionmatrix - compute a weighted confusion matrix**
This function calculates the weighted confusion matrix by multiplying,
element-by-element, a weight matrix with a supplied confusion matrix
object.
In R, simply call the function:
``` r
wconfusionmatrix(m, weight.type = "arithmetic", weight.penalty = FALSE, standard.deviation = 2, geometric.multiplier = 2, interval.high=1, interval.low = -1, custom.weights = NA, print.weighted.accuracy = FALSE) {
```
The function takes as input:
*m* -- the caret confusion matrix object or simple matrix.
*weight.type* -- the weighting schema to be used. Can be one of:
"arithmetic" - a decreasing arithmetic progression weighting scheme,
"geometric" - a decreasing geometric progression weighting scheme,
"normal" - weights drawn from the right tail of a normal distribution,
"interval" - weights contained on a user-defined interval, "custom" -
custom weight vector defined by the user.
*weight.penalty* -- determines whether the weights associated with
non-diagonal elements generated by the "normal", "arithmetic" and
"geometric" weight types are positive or negative values. By default,
the value is set to FALSE, which means that generated weights will be
positive values.
*standard.deviation* -- standard deviation of the normal distribution,
if the normal distribution weighting schema is used.
*geometric.multiplier* -- the multiplier used to construct the geometric
progression series, if the geometric progression weighting scheme is
used.
*interval.high* -- the upper bound of the weight interval, if the
interval weighting scheme is used.
*interval.low* -- the lower bound of the weight interval, if the
interval weighting scheme is used.
*custom.weights* -- the vector of custom weights to be applied, is the
custom weighting scheme was selected. The vector should be equal to "n",
but can be larger, with excess values being ignored.
*print.weighted.accuracy* -- optional setting to print the weighted
accuracy metric, which represents the sum of all weighted confusion
matrix cells divided by the total number of observations.
The function outputs a matrix:
| | |
|-----|------------------------------------|
| w_m | the nxn weighted confusion matrix. |
## Examples
#### **Producing a weighted confusion matrix in conjunction with the caret package**
This example provides a real-world usage example of the wconf package on
the Iris dataset included in R.
We will attempt the more difficult task of predicting petal length from
sepal width. In addition, for this task, we are only given categorical
information about the length of the petals, specifically that they are:
- "Short (length between: 1-3)"
- "Medium (length between: 3-5 cm)"
- "Long (length between: 5-7 cm)".
Numeric data is available for the sepal width.
Using caret, we train a multinomial logistic regression model to fit the
numeric sepal width onto our categorical petal length data. We run
10-fold cross-validation, repeated 3 times to avoid overfitting and find
optimal regression coefficient values for various data configurations.
Finally, we extract the confusion matrix. We wish to weigh the confusion
matrix to represent preference for observations fitted closer to the
correct value. We would like to assign some degree of positive value to
observations that are incorrectly classified, but are close to the
correct category. Since our categories are equally spaced, we can use an
arithmetic weighing scheme.
Let's first visualize what this weighting schema would look like:
```{r}
# View the weight matrix and plot for a 3-category classification problem, using the arithmetic sequence option.
weightmatrix(3, weight.type = "arithmetic", plot.weights = TRUE)
```
To obtain the weighted confusion matrix, we run the "wconfusionmatrix"
command and provide it the confusion matrix object generated by caret, a
weighting scheme and, optionally, parameterize it to suit our objectives.
Using the "wconfusionmatrix" function will automatically determine the
dimensions of the weighing matrix and the user need only specify the
parameters associated with their weighting scheme of choice.
The following block of code produces the weighted confusion matrix, to
out specifications.
```{r}
# Load libraries and perform transformations
library(caret)
data(iris)
iris$Petal.Length.Cat = cut(iris$Petal.Length, breaks=c(1, 3, 5, 7), right = FALSE)
# Train multinomial logistic regression model using caret
set.seed(1)
control <- trainControl(method="repeatedcv", number=10, repeats=3)
model <- train(Petal.Length.Cat ~ Sepal.Width, data=iris, method="multinom", trace = FALSE, trControl=control)
# Extract original data, predicted values and place them in a table
y = iris$Petal.Length.Cat
yhat = predict(model)
preds = table(data=yhat, reference=y)
# Construct the confusion matrix
confmat = confusionMatrix(preds)
# Compute the weighted confusion matrix and display the weighted accuracy score
wconfusionmatrix(confmat, weight.type = "arithmetic", print.weighted.accuracy = TRUE)
```
## About the author
The wconf: Weighted Confusion Matrix package was programmed by Dr.
Alexandru Monahov.
Alexandru Monahov holds a PhD in Economics from the University Cote
d'Azur (Nice, France) and a Professional Certificate in Advanced Risk
Management from the New York Institute of Finance (New York, United
States). His Master's Degree in International Economics and Finance and
his Bachelor's Degree in Economics and Business Administration were
completed at the University of Nice (Nice, France).
His professional activity includes working for the Bank of England as a
Research Economist and as Expert Consultant at the National Bank of
Moldova, within the Financial Stability Division. Alexandru also
provides training for professionals in finance from Central Banks and
Ministries of Finance at the Center of Excellence in Finance (Ljubljana,
Slovenia) and the Centre for Central Banking Studies (London, UK).
Previously, he worked as assistant and, subsequently, associate
professor at the University of Nice and IAE in France, where he taught
Finance, Economics, Econometrics and Business Administration. He
developed training and professional education curricula for the Chambers
of Commerce and Industry and directed several continuing education
programs.
Dr. Monahov was awarded funding for continuing professional education by
the World Bank through the Reserve Advisory & Management Partnership
Program, a PhD scholarship by the Doctoral School of Nice and a
scholarship of the French Government.
⠀
Copyright Alexandru Monahov, 2023.
You may use, modify and redistribute this code, provided that you give credit to the author and make any derivative work available to the public for free.
|
/scratch/gouwar.j/cran-all/cranData/wconf/inst/doc/wconf_guide.Rmd
|
---
title: "wconf: Weighted Confusion Matrix"
author: "Alexandru Monahov"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
%\VignetteEncoding{UTF-8}
%\VignetteIndexEntry{wconf: Weighted Confusion Matrix}
%\VignetteEngine{knitr::rmarkdown}
editor_options:
markdown:
wrap: 72
---
```{r setup, include = FALSE, echo=FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
error = TRUE,
comment = "#>"
)
```
## The wconf package
**wconf is a package that allows users to create weighted confusion
matrices and accuracy scores**
Used to improve the model selection process, the package includes
several weighting schemes which can be parameterized, as well as the
option for custom weight configurations. Furthermore, users can decide
whether they wish to positively or negatively affect the accuracy score
as a result of applying weights to the confusion matrix. "wconf"
integrates with the "caret" package, but it can also work standalone
when provided data in matrix form.
#### **About confusion matrices**
Confusion matrices are used to visualize the performance of
classification models in tabular format. A confusion matrix takes the
form of an "n x n" matrix depicting:
a) the reference category, in columns;
b) the predicted category, in rows;
c) the number of observation corresponding to each combination of
"reference - predicted" category couples, as cells of the matrix.
Visually, the simplest binary classification confusion matrix takes on
the form:
$$
A = \begin{bmatrix}TP & FP \\FN & TN\\ \end{bmatrix}
$$ where:
$TP$ - True Positives - the number of observations that were "positive"
and were correctly predicted as being "positive"
$TN$ - True Negatives - the number of originally "negative" observations
that were correctly predicted by the model as being "negative".
$FP$ - False Positives - also called "Type 1 Error" - represents
observations that are in fact "negative", but were incorrectly
classified by the model as being "positive".
$FN$ - False Negatives - also called "Type 2 Error" - represents
observations that are in fact "positive", but were incorrectly
classified by the model as being "negative".
The traditional accuracy metric is compiled by adding the true positives
and true negatives, and dividing them by the total number of
observations.
$$
A = \frac{TP + TN} {N}
$$
A weighted confusion matrix consists in attributing weights to all
classification categories based on their distance from the correctly
predicted category. This is important for multi-category classification
problems (where there are three or more categories), where distance from
the correctly predicted category matters.
The weighted confusion matrix, for the simple binary classification,
takes the form:
$$
A = \begin{bmatrix}w1*TP & w2*FP \\w2*FN & w1*TN\\ \end{bmatrix}
$$
In the case of the weighted confusion matrix, a weighted accuracy score
can be calculated by summing up all of the elements of the matrix and
dividing the resulting amount by the number of observations.
$$
A = \frac{w1*TP + w2*FP + w2*FN + w1*TN} {N}
$$
#### **References**
For more details on the method, see the paper:
Monahov, A. (2023). wconf: The weighted confusion matrix and accuracy
scores package for R
## Functions
#### **weightmatrix - configure and visualize a weight matrix**
This function compiles a weight matrix according to one of several
weighting schemas and allows users to visualize the impact of the weight
matrix on each element of the confusion matrix.
In R, simply call the function:
``` r
weightmatrix(n, weight.type = "arithmetic", weight.penalty = FALSE, standard.deviation = 2, geometric.multiplier = 2, interval.high=1, interval.low = -1, custom.weights = NA, plot.weights = FALSE) {
```
The function takes as input:
*n* -- the number of classes contained in the confusion matrix.
*weight.type* -- the weighting schema to be used. Can be one of:
"arithmetic" - a decreasing arithmetic progression weighting scheme,
"geometric" - a decreasing geometric progression weighting scheme,
"normal" - weights drawn from the right tail of a normal distribution,
"interval" - weights contained on a user-defined interval, "custom" -
custom weight vector defined by the user.
*weight.penalty* -- determines whether the weights associated with
non-diagonal elements generated by the "normal", "arithmetic" and
"geometric" weight types are positive or negative values. By default,
the value is set to FALSE, which means that generated weights will be
positive values.
*standard.deviation* -- standard deviation of the normal distribution,
if the normal distribution weighting schema is used.
*geometric.multiplier* -- the multiplier used to construct the geometric
progression series, if the geometric progression weighting scheme is
used.
*interval.high* -- the upper bound of the weight interval, if the
interval weighting scheme is used.
*interval.low* -- the lower bound of the weight interval, if the
interval weighting scheme is used.
*custom.weights* -- the vector of custom weights to be applied, is the
custom weighting scheme was selected. The vector should be equal to "n",
but can be larger, with excess values being ignored.
*plot.weights* -- optional setting to enable plotting of weight vector,
corresponding to the first column of the weight matrix
The function outputs a matrix:
| | |
|-----|------------------------|
| w | the nxn weight matrix. |
#### **wconfusionmatrix - compute a weighted confusion matrix**
This function calculates the weighted confusion matrix by multiplying,
element-by-element, a weight matrix with a supplied confusion matrix
object.
In R, simply call the function:
``` r
wconfusionmatrix(m, weight.type = "arithmetic", weight.penalty = FALSE, standard.deviation = 2, geometric.multiplier = 2, interval.high=1, interval.low = -1, custom.weights = NA, print.weighted.accuracy = FALSE) {
```
The function takes as input:
*m* -- the caret confusion matrix object or simple matrix.
*weight.type* -- the weighting schema to be used. Can be one of:
"arithmetic" - a decreasing arithmetic progression weighting scheme,
"geometric" - a decreasing geometric progression weighting scheme,
"normal" - weights drawn from the right tail of a normal distribution,
"interval" - weights contained on a user-defined interval, "custom" -
custom weight vector defined by the user.
*weight.penalty* -- determines whether the weights associated with
non-diagonal elements generated by the "normal", "arithmetic" and
"geometric" weight types are positive or negative values. By default,
the value is set to FALSE, which means that generated weights will be
positive values.
*standard.deviation* -- standard deviation of the normal distribution,
if the normal distribution weighting schema is used.
*geometric.multiplier* -- the multiplier used to construct the geometric
progression series, if the geometric progression weighting scheme is
used.
*interval.high* -- the upper bound of the weight interval, if the
interval weighting scheme is used.
*interval.low* -- the lower bound of the weight interval, if the
interval weighting scheme is used.
*custom.weights* -- the vector of custom weights to be applied, is the
custom weighting scheme was selected. The vector should be equal to "n",
but can be larger, with excess values being ignored.
*print.weighted.accuracy* -- optional setting to print the weighted
accuracy metric, which represents the sum of all weighted confusion
matrix cells divided by the total number of observations.
The function outputs a matrix:
| | |
|-----|------------------------------------|
| w_m | the nxn weighted confusion matrix. |
## Examples
#### **Producing a weighted confusion matrix in conjunction with the caret package**
This example provides a real-world usage example of the wconf package on
the Iris dataset included in R.
We will attempt the more difficult task of predicting petal length from
sepal width. In addition, for this task, we are only given categorical
information about the length of the petals, specifically that they are:
- "Short (length between: 1-3)"
- "Medium (length between: 3-5 cm)"
- "Long (length between: 5-7 cm)".
Numeric data is available for the sepal width.
Using caret, we train a multinomial logistic regression model to fit the
numeric sepal width onto our categorical petal length data. We run
10-fold cross-validation, repeated 3 times to avoid overfitting and find
optimal regression coefficient values for various data configurations.
Finally, we extract the confusion matrix. We wish to weigh the confusion
matrix to represent preference for observations fitted closer to the
correct value. We would like to assign some degree of positive value to
observations that are incorrectly classified, but are close to the
correct category. Since our categories are equally spaced, we can use an
arithmetic weighing scheme.
Let's first visualize what this weighting schema would look like:
```{r}
# View the weight matrix and plot for a 3-category classification problem, using the arithmetic sequence option.
weightmatrix(3, weight.type = "arithmetic", plot.weights = TRUE)
```
To obtain the weighted confusion matrix, we run the "wconfusionmatrix"
command and provide it the confusion matrix object generated by caret, a
weighting scheme and, optionally, parameterize it to suit our objectives.
Using the "wconfusionmatrix" function will automatically determine the
dimensions of the weighing matrix and the user need only specify the
parameters associated with their weighting scheme of choice.
The following block of code produces the weighted confusion matrix, to
out specifications.
```{r}
# Load libraries and perform transformations
library(caret)
data(iris)
iris$Petal.Length.Cat = cut(iris$Petal.Length, breaks=c(1, 3, 5, 7), right = FALSE)
# Train multinomial logistic regression model using caret
set.seed(1)
control <- trainControl(method="repeatedcv", number=10, repeats=3)
model <- train(Petal.Length.Cat ~ Sepal.Width, data=iris, method="multinom", trace = FALSE, trControl=control)
# Extract original data, predicted values and place them in a table
y = iris$Petal.Length.Cat
yhat = predict(model)
preds = table(data=yhat, reference=y)
# Construct the confusion matrix
confmat = confusionMatrix(preds)
# Compute the weighted confusion matrix and display the weighted accuracy score
wconfusionmatrix(confmat, weight.type = "arithmetic", print.weighted.accuracy = TRUE)
```
## About the author
The wconf: Weighted Confusion Matrix package was programmed by Dr.
Alexandru Monahov.
Alexandru Monahov holds a PhD in Economics from the University Cote
d'Azur (Nice, France) and a Professional Certificate in Advanced Risk
Management from the New York Institute of Finance (New York, United
States). His Master's Degree in International Economics and Finance and
his Bachelor's Degree in Economics and Business Administration were
completed at the University of Nice (Nice, France).
His professional activity includes working for the Bank of England as a
Research Economist and as Expert Consultant at the National Bank of
Moldova, within the Financial Stability Division. Alexandru also
provides training for professionals in finance from Central Banks and
Ministries of Finance at the Center of Excellence in Finance (Ljubljana,
Slovenia) and the Centre for Central Banking Studies (London, UK).
Previously, he worked as assistant and, subsequently, associate
professor at the University of Nice and IAE in France, where he taught
Finance, Economics, Econometrics and Business Administration. He
developed training and professional education curricula for the Chambers
of Commerce and Industry and directed several continuing education
programs.
Dr. Monahov was awarded funding for continuing professional education by
the World Bank through the Reserve Advisory & Management Partnership
Program, a PhD scholarship by the Doctoral School of Nice and a
scholarship of the French Government.
⠀
Copyright Alexandru Monahov, 2023.
You may use, modify and redistribute this code, provided that you give credit to the author and make any derivative work available to the public for free.
|
/scratch/gouwar.j/cran-all/cranData/wconf/vignettes/wconf_guide.Rmd
|
#' Calculate inverse probability of selection weights.
#'
#' @description
#' This function calculates weights to correct for ascertainment bias in
#' time-to-event data where clusters are outcome-dependently sampled,
#' for example high-risk families in genetic epidemiological studies in
#' cancer research.
#'
#' @details
#' Weights are based on a comparison between the survival between sample and
#' population. Therefore, besides the sample data, the population incidence rate
#' (per 100 000) is needed as input, as well as the cut-offs of the
#' (age/time-to-event) groups for which this is available. The function provides
#' two options for the latter: cut-offs can be provided manually or using the
#' standard 5- or 10-years (age) categories (0-4, 5-9, ... or 0-9, 10-14, ...).
#' Note that resulting intervals are of the form [xx, xx).
#'
#' @export
#' @importFrom stats aggregate end start
#' @importFrom dplyr mutate
#' @importFrom tidyr %>% spread
Calculate_weights <- function(dat){
### Input:
#' @param dat Data.frame with one row per individual with columns *d*
#' non-censoring indicator; **k** interval of (age) group; **S_k**
#' population interval-based proportion of individuals experiencing the
#' event in intervals later than k; **S_k.** sample
#' proportion of individuals experiencing the event in intervals later
#' than k.
### Output:
#' @return Vector with weights.
# --------------- Extract variables from input data.frame.
# Group/interval.
k <- dat$k
# Population proportion of individuals experiencing the event in intervals
# later than k.
S_k <- dat$S_k
# Sample proportion of individuals experiencing the event in intervals
# later than k.
S_k. <- dat$S_k.
# --------------- Create empty containers.
v <- w <- rep(NA, nrow(dat))
# --------------- Calculate the weights.
for (n in 1:nrow(dat)){
# Weights for unaffected.
v[n] = 1
# Weights for cases.
w[n] = ( (1 - S_k[n]) / S_k[n] ) * (S_k.[n] / ( 1 - S_k.[n]))
}
merged <- cbind(dat, w, v)
merged$weight <- NA
# --------------- Assign w for uncensored, v for censored (interval-wise).
merged$weight[which(merged$d == 1)] <- merged$w[which(merged$d == 1)]
merged$weight[which(merged$d == 0)] <- merged$v[which(merged$d == 0)]
merged$w <- merged$v <- NULL # Remove old variable.
# --------------- Collect output.
vec_weights <- merged$weight
# If weight is 0, add very small value (coxph does not accept weights of 0).
vec_weights[which(vec_weights==0)] <- 0.0000001
# --------------- Print warning if weights are invalid.
ifelse((sum(vec_weights<0)>0), warning("Invalid (negative) weights!"),
message("No negative weights"))
# --------------- Return output.
vec_weights
}
|
/scratch/gouwar.j/cran-all/cranData/wcox/R/Calculate_weights.R
|
#' Prepare data to calculate weights.
#'
#' @description
#' This function prepares time-to-event data for weight calculation using
#' external information.
#'
#' @details
#' External information is the population incidence.
#'
#' @export
#' @importFrom stats aggregate end start
#' @importFrom dplyr mutate
#' @importFrom tidyr %>% spread
Prepare_data <- function(dat, population_incidence, breaks){
### Input:
#' @param dat Data.frame with one row per individual which at least includes
#' a column **d** with event indicator (1 for event, 0 for censored), a column
#' **y** with event/censoring time.
#' @param population_incidence A vector (in combination with breaks) or
#' a data.frame (columns 1) 'start age group', 2) 'end age group', 3)'S_pop')
#' with population incidence per 100,000 per interval k.
#' @param breaks Cut-points for the (age/time) groups. Only needed when
#' population_incidence is a vector.
### Output:
#' @return Data.frame one row per individual and a.o. columns *id* unique ID;
#' *d* non-censoring indicator; **k** interval of (age) group; **S_k**
#' population interval-based proportion of individuals experiencing the
#' event in intervals later than k; **S_k.** sample
#' proportion of individuals experiencing the event in intervals later
#' than k.
# --------------- Load packages.
# require(survival)
# require(dplyr)
# require(tidyr)
# --------------- Organize external information (population incidence rate).
# N.B.: there are different options regarding the breaks (1-4).
if(is.vector(population_incidence)){
if(is.numeric(breaks)){ # Option 1: two vectors population_incidence and breaks.
if(length(breaks)!=(length(population_incidence)+1) ) warning("Number of
breaks should
equal the
number of
groups plus
one.")
n_agegroups <- length(population_incidence)
from <- breaks[-(n_agegroups + 1)] # Remove last
to <- breaks[-1] # Remove first
dat_inc <- data.frame(start = from, end = to, incidence_rate =
population_incidence/100000)
} else if(breaks == "5 years"){ # Option 2: 5 years age groups.
n_agegroups <- length(population_incidence)
breaks <- seq(0, 5*(n_agegroups), by = 5)
from <- breaks[-(n_agegroups + 1)] # Remove last
to <- breaks[-1] # Remove first
dat_inc <- data.frame(start = from, end = to, incidence_rate =
population_incidence/100000)
} else if(breaks == "10 years"){ # Option 3: 10 years age groups.
n_agegroups <- length(population_incidence)
breaks <- seq(0, 10*(n_agegroups), by = 10)
from <- breaks[-(n_agegroups + 1)] # Remove last
to <- breaks[-1] # Remove first
dat_inc <- data.frame(start = from, end = to, incidence_rate =
population_incidence/100000)
}
} else { # Option 4: if population incidence is given as a data.frame.
dat_inc <- data.frame(start = population_incidence[,1],
end = population_incidence[,2],
incidence_rate = population_incidence[,3]/100000)
breaks <- population_incidence[,1]
}
dat_inc <- dat_inc %>% mutate( k = paste("(", start, ",", end, "]", sep=""),
t = end - start)
# t is the width of the age interval, in years.
# Note that in the paper, this is referred to
# as (alpha_k - alpha_({k-1}).
# --------------- Calculate S_k population from population incidence.
dat_inc$S_k <- c(exp(-(dat_inc$t * dat_inc$incidence_rate)))
# --------------- Calculate S_k. based on sample data.
dat$y_cat <- cut(dat$y, breaks = breaks)
index <- which(is.na(dat$y_cat)==T)
if(length(index)>0){
dat<- dat[-index,]} # Include only those that fall within an age category.
# Store number of cases and unaffected individuals per age group.
agegroups.info <- aggregate(id ~ y_cat + d, data = dat, length)
agegroups.info <- agegroups.info %>% spread(d, -y_cat)
colnames(agegroups.info) <- c("k","s_k","r_k")
# Transform NA to 0 (its real meaning).
agegroups.info$s_k <- ifelse(!is.na(agegroups.info$s_k), agegroups.info$s_k, 0)
agegroups.info$r_k <- ifelse(!is.na(agegroups.info$r_k), agegroups.info$r_k, 0)
# Calculate person years per outcome and age group.
personyears <- aggregate(y ~ y_cat + d, data =
dat[,c("d","y_cat", "y"),], sum) %>%
spread(d, -y_cat)
colnames(personyears) <- c("k","q_k","p_k")
agegroups.info <- merge(agegroups.info, personyears, by = "k") # Merge.
agegroups.info$q_k <- ifelse(!is.na(agegroups.info$q_k),
agegroups.info$q_k, 0)
agegroups.info$p_k <- ifelse(!is.na(agegroups.info$p_k),
agegroups.info$p_k, 0)
agegroups.info$years.before <- breaks[which(breaks != max(breaks))]
# Person years among censored individuals.
q <- agegroups.info$q_k - (agegroups.info$years.before * agegroups.info$s_k)
# Person years among cases.
p <- agegroups.info$p_k - (agegroups.info$years.before * agegroups.info$r_k)
# Years per age group.
# N.B. in the paper referred to as (alpha_k - alpha_{k-1}).
t <- agegroups.info$t <- dat_inc$t
# Number of censored.
s <- agegroups.info$s_k
# Number of cases.
r <- agegroups.info$r_k
# Age group label.
k <- agegroups.info$k
# Obtain incidence rate (mu) based on sample data.
n_agegroups <- nrow(agegroups.info)
for (k in 1:n_agegroups){
if(k!=n_agegroups){calcsum <- sum(agegroups.info$r_k[(k+1):n_agegroups],
agegroups.info$s_k[(k+1):n_agegroups])
} else {calcsum <- 0}
agegroups.info$mu_k[k] = agegroups.info$r_k[k]/
(agegroups.info$p_k[k]+agegroups.info$q_k[k]+agegroups.info$t[k]*calcsum)
}
# Recalculate S_k. (in the sample!) based on the intervals.
S_k. <- c()
S_k. <- c(exp(-(agegroups.info$mu_k*t)))
agegroups.info$S_k. <- S_k.
agegroups.info$S_k <- dat_inc$S_k
# --------------- Add S_k. to the sample data.
dat_out <- merge(dat, agegroups.info, by.x = "y_cat", by.y = "k") %>%
mutate(k = y_cat) %>%
mutate(population_incidence = mu_k)
dat_out$years.before <- NULL; dat_out$t <- NULL;
dat_out$y_cat <- NULL; dat_out$mu_k <- NULL;
dat_out$s_k <- dat_out$r_k <- dat_out$p_k <- dat_out$q_k <- NULL
# --------------- Output the data.frame.
dat_out
}
|
/scratch/gouwar.j/cran-all/cranData/wcox/R/Prepare_data.R
|
#' Simulated time-to-event data.
#'
#' This toy data set is simulated for educational purposes explaining the
#' package. It concerns of families in which at least two individuals
#' experienced the event of interest during following up. The covariate of
#' interest is risk modifier 'x'. This data set is inspired by data that
#' is often seen in genetic epidemiological studies in cancer research.
#'
#' @docType data
#'
#' @usage data(fam_dat)
#'
#' @format Data.frame.
#'
#' @keywords datasets
#'
#' @references A new inverse probability of selection weighted Cox model to deal with outcome-dependent sampling in survival analysis
#' Vera H. Arntzen, Marta Fiocco, Inge M.M. Lakeman, Maartje Nielsen, Mar Rodríguez-Girondo
#' doi: https://doi.org/10.1101/2023.02.07.527426 (preprint).
#'
"fam_dat"
|
/scratch/gouwar.j/cran-all/cranData/wcox/R/fam_dat.R
|
utils::globalVariables(c("d", "mu_k", "y_cat"))
#stats::globalVariables(c("aggregate", "end", "start"))
#tidyr::globalVariables(c("spread", "mutate", "%>%"))
|
/scratch/gouwar.j/cran-all/cranData/wcox/R/globals.R
|
## ---- include = FALSE---------------------------------------------------------
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
Prepare_data <- function(dat, population_incidence, breaks){
### Input:
#' @param dat Data.frame with one row per individual which at least includes
#' a column **d** with event indicator (1 for event, 0 for censored), a column
#' **y** with event/censoring time.
#' @param population_incidence A vector (in combination with breaks) or
#' a data.frame (columns 1) 'start age group', 2) 'end age group', 3)'S_pop')
#' with population incidence per 100,000 per interval k.
#' @param breaks Cut-points for the (age/time) groups. Only needed when
#' population_incidence is a vector.
### Output:
#' @return Data.frame one row per individual and a.o. columns *id* unique ID;
#' *d* non-censoring indicator; **k** interval of (age) group; **S_k**
#' population interval-based proportion of individuals experiencing the
#' event in intervals later than k; **S_k.** sample
#' proportion of individuals experiencing the event in intervals later
#' than k.
# --------------- Load packages.
# require(survival)
# require(dplyr)
# require(tidyr)
# --------------- Organize external information (population incidence rate).
# N.B.: there are different options regarding the breaks (1-4).
if(is.vector(population_incidence)){
if(is.numeric(breaks)){ # Option 1: two vectors population_incidence and breaks.
if(length(breaks)!=(length(population_incidence)+1) ) warning("Number of
breaks should
equal the
number of
groups plus
one.")
n_agegroups <- length(population_incidence)
from <- breaks[-(n_agegroups + 1)] # Remove last
to <- breaks[-1] # Remove first
dat_inc <- data.frame(start = from, end = to, incidence_rate =
population_incidence/100000)
} else if(breaks == "5 years"){ # Option 2: 5 years age groups.
n_agegroups <- length(population_incidence)
breaks <- seq(0, 5*(n_agegroups), by = 5)
from <- breaks[-(n_agegroups + 1)] # Remove last
to <- breaks[-1] # Remove first
dat_inc <- data.frame(start = from, end = to, incidence_rate =
population_incidence/100000)
} else if(breaks == "10 years"){ # Option 3: 10 years age groups.
n_agegroups <- length(population_incidence)
breaks <- seq(0, 10*(n_agegroups), by = 10)
from <- breaks[-(n_agegroups + 1)] # Remove last
to <- breaks[-1] # Remove first
dat_inc <- data.frame(start = from, end = to, incidence_rate =
population_incidence/100000)
}
} else { # Option 4: if population incidence is given as a data.frame.
dat_inc <- data.frame(start = population_incidence[,1],
end = population_incidence[,2],
incidence_rate = population_incidence[,3]/100000)
breaks <- population_incidence[,1]
}
dat_inc <- dat_inc %>% mutate( k = paste("(", start, ",", end, "]", sep=""),
t = end - start)
# t is the width of the age interval, in years.
# Note that in the paper, this is referred to
# as (alpha_k - alpha_({k-1}).
# --------------- Calculate S_k population from population incidence.
dat_inc$S_k <- c(exp(-(dat_inc$t * dat_inc$incidence_rate)))
# --------------- Calculate S_k. based on sample data.
dat$y_cat <- cut(dat$y, breaks = breaks)
index <- which(is.na(dat$y_cat)==T)
if(length(index)>0){
dat<- dat[-index,]} # Include only those that fall within an age category.
# Store number of cases and unaffected individuals per age group.
agegroups.info <- aggregate(id ~ y_cat + d, data = dat, length)
agegroups.info <- agegroups.info %>% tidyr::spread(d, -y_cat)
colnames(agegroups.info) <- c("k","s_k","r_k")
# Transform NA to 0 (its real meaning).
agegroups.info$s_k <- ifelse(!is.na(agegroups.info$s_k), agegroups.info$s_k, 0)
agegroups.info$r_k <- ifelse(!is.na(agegroups.info$r_k), agegroups.info$r_k, 0)
# Calculate person years per outcome and age group.
personyears <- aggregate(y ~ y_cat + d, data =
dat[,c("d","y_cat", "y"),], sum) %>%
tidyr::spread(d, -y_cat)
colnames(personyears) <- c("k","q_k","p_k")
agegroups.info <- merge(agegroups.info, personyears, by = "k") # Merge.
agegroups.info$q_k <- ifelse(!is.na(agegroups.info$q_k),
agegroups.info$q_k, 0)
agegroups.info$p_k <- ifelse(!is.na(agegroups.info$p_k),
agegroups.info$p_k, 0)
agegroups.info$years.before <- breaks[which(breaks != max(breaks))]
# Person years among censored individuals.
q <- agegroups.info$q_k - (agegroups.info$years.before * agegroups.info$s_k)
# Person years among cases.
p <- agegroups.info$p_k - (agegroups.info$years.before * agegroups.info$r_k)
# Years per age group.
# N.B. in the paper referred to as (alpha_k - alpha_{k-1}).
t <- agegroups.info$t <- dat_inc$t
# Number of censored.
s <- agegroups.info$s_k
# Number of cases.
r <- agegroups.info$r_k
# Age group label.
k <- agegroups.info$k
# Obtain incidence rate (mu) based on sample data.
n_agegroups <- nrow(agegroups.info)
for (k in 1:n_agegroups){
if(k!=n_agegroups){calcsum <- sum(agegroups.info$r_k[(k+1):n_agegroups],
agegroups.info$s_k[(k+1):n_agegroups])
} else {calcsum <- 0}
agegroups.info$mu_k[k] = agegroups.info$r_k[k]/
(agegroups.info$p_k[k]+agegroups.info$q_k[k]+agegroups.info$t[k]*calcsum)
}
# Recalculate S_k. (in the sample!) based on the intervals.
S_k. <- c()
S_k. <- c(exp(-(agegroups.info$mu_k*t)))
agegroups.info$S_k. <- S_k.
agegroups.info$S_k <- dat_inc$S_k
# --------------- Add S_k. to the sample data.
dat_out <- merge(dat, agegroups.info, by.x = "y_cat", by.y = "k") %>%
mutate(k = y_cat) %>%
mutate(population_incidence = mu_k)
dat_out$years.before <- NULL; dat_out$t <- NULL;
dat_out$y_cat <- NULL; dat_out$mu_k <- NULL;
dat_out$s_k <- dat_out$r_k <- dat_out$p_k <- dat_out$q_k <- NULL
# --------------- Output the data.frame.
dat_out
}
#' Calculate inverse probability of selection weights.
#'
#' @description
#' This function calculates weights to correct for ascertainment bias in
#' time-to-event data where clusters are outcome-dependently sampled,
#' for example high-risk families in genetic epidemiological studies in
#' cancer research.
#'
#' @details
#' Weights are based on a comparison between the survival between sample and
#' population. Therefore, besides the sample data, the population incidence rate
#' (per 100 000) is needed as input, as well as the cut-offs of the
#' (age/time-to-event) groups for which this is available. The function provides
#' two options for the latter: cut-offs can be provided manually or using the
#' standard 5- or 10-years (age) categories (0-4, 5-9, ... or 0-9, 10-14, ...).
#' Note that resulting intervals are of the form [xx, xx).
#'
#' @export
Calculate_weights <- function(dat){
### Input:
#' @param dat Data.frame with one row per individual with columns *d*
#' non-censoring indicator; **k** interval of (age) group; **S_k**
#' population interval-based proportion of individuals experiencing the
#' event in intervals later than k; **S_k.** sample
#' proportion of individuals experiencing the event in intervals later
#' than k.
### Output:
#' @return Vector with weights.
# --------------- Extract variables from input data.frame.
# Group/interval.
k <- dat$k
# Population proportion of individuals experiencing the event in intervals
# later than k.
S_k <- dat$S_k
# Sample proportion of individuals experiencing the event in intervals
# later than k.
S_k. <- dat$S_k.
# --------------- Create empty containers.
v <- w <- rep(NA, nrow(dat))
# --------------- Calculate the weights.
for (n in 1:nrow(dat)){
# Weights for unaffected.
v[n] = 1
# Weights for cases.
w[n] = ( (1 - S_k[n]) / S_k[n] ) * (S_k.[n] / ( 1 - S_k.[n]))
}
merged <- cbind(dat, w, v)
merged$weight <- NA
# --------------- Assign w for uncensored, v for censored (interval-wise).
merged$weight[which(merged$d == 1)] <- merged$w[which(merged$d == 1)]
merged$weight[which(merged$d == 0)] <- merged$v[which(merged$d == 0)]
merged$w <- merged$v <- NULL # Remove old variable.
# --------------- Collect output.
vec_weights <- merged$weight
# If weight is 0, add very small value (coxph does not accept weights of 0).
vec_weights[which(vec_weights==0)] <- 0.0000001
# --------------- Print warning if weights are invalid.
ifelse((sum(vec_weights<0)>0), print("Invalid (negative) weights!"),
print("No negative weights"))
# --------------- Return output.
vec_weights
}
## ----Loading, message = F-----------------------------------------------------
library(wcox)
require(dplyr)
require(tidyr)
require(survival)
## ----Load data set, message = F-----------------------------------------------
# Load toy data.
data("fam_dat")
## ----Show first lines data----------------------------------------------------
# Show the first few lines of the toy data.
head(fam_dat)
## ----Distribution of family size----------------------------------------------
# Show the number of families and top rows.
cat( "There are", unique(fam_dat$family_id) %>% length() , "families in data set. ")
# Examine family sizes.
fam_sizes <- fam_dat %>% group_by(family_id) %>% count()
cat( "Family size is on average ",
fam_sizes$n %>% mean() %>% round(1),
" and ranges from ",
fam_sizes$n %>% min(), " to ",
fam_sizes$n %>% max(), ".", sep = "")
## ----External information-----------------------------------------------------
# Enter the incidence by age group per 100 000, starting with the youngest age group.
incidence_rate <- c(2882, 1766, 1367, 1155, 987, 845, 775, 798, 636, 650)
# Define the age group cutoffs.
breaks_manually <- c(0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100)
breaks_10yrs <- "10 years"
## ----Rename variables---------------------------------------------------------
# Rename variables.
my_dat <- rename(fam_dat, id = individual_id, d = event_indicator, y = age)
## ----Prepare data, message = F------------------------------------------------
# Using option 1 (manual cut-offs):
my_dat_out <- Prepare_data(dat = my_dat, population_incidence = incidence_rate,
breaks = breaks_manually)
# Unhash to use option 2 (pre-set cut-offs):
# my_dat_out <- Prepare_data(dat = my_dat, population_incidence = incidence_rate,
# breaks = "10 years")
## ----Look at prepared data----------------------------------------------------
# Select the newly add columns.
my_dat_out %>% select(id, k, d, S_k, S_k.) %>% arrange(id) %>% head(8)
## ----Calculate weights--------------------------------------------------------
# Calculate weights using the object that is output from the Prepare_data() function.
w <- Calculate_weights(dat = my_dat_out)
## ----Show weights-------------------------------------------------------------
# Show the weights.
my_dat_out %>% mutate(weight = w) %>%
select(id, d, weight) %>%
arrange(id) %>%
filter(id %in% c(1,3))
## ----Fit model using weights, message = F-------------------------------------
# Fit the model.
fit <- coxph(Surv(y, d==1) ~ x + cluster(family_id), weights = w, data = my_dat_out)
fit
## ----Examine estimates of fitted model----------------------------------------
# Extract estimates.
fit.summary <- summary(fit)
# Summarize findings.
cat("Covariate effect (95% CI): ",
exp(fit.summary$coefficients[1]), " (",
exp(fit.summary$coefficients[1] - 1.96*fit.summary$coefficients[4]), ", ",
exp(fit.summary$coefficients[1] + 1.96*fit.summary$coefficients[4]), ").", sep = "")
|
/scratch/gouwar.j/cran-all/cranData/wcox/inst/doc/Tutorial_toy_data.R
|
---
title: "Tutorial Inverse probability weights to correct for ascertainment bias using R package 'wcox'"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{Tutorial_toy_data}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
Prepare_data <- function(dat, population_incidence, breaks){
### Input:
#' @param dat Data.frame with one row per individual which at least includes
#' a column **d** with event indicator (1 for event, 0 for censored), a column
#' **y** with event/censoring time.
#' @param population_incidence A vector (in combination with breaks) or
#' a data.frame (columns 1) 'start age group', 2) 'end age group', 3)'S_pop')
#' with population incidence per 100,000 per interval k.
#' @param breaks Cut-points for the (age/time) groups. Only needed when
#' population_incidence is a vector.
### Output:
#' @return Data.frame one row per individual and a.o. columns *id* unique ID;
#' *d* non-censoring indicator; **k** interval of (age) group; **S_k**
#' population interval-based proportion of individuals experiencing the
#' event in intervals later than k; **S_k.** sample
#' proportion of individuals experiencing the event in intervals later
#' than k.
# --------------- Load packages.
# require(survival)
# require(dplyr)
# require(tidyr)
# --------------- Organize external information (population incidence rate).
# N.B.: there are different options regarding the breaks (1-4).
if(is.vector(population_incidence)){
if(is.numeric(breaks)){ # Option 1: two vectors population_incidence and breaks.
if(length(breaks)!=(length(population_incidence)+1) ) warning("Number of
breaks should
equal the
number of
groups plus
one.")
n_agegroups <- length(population_incidence)
from <- breaks[-(n_agegroups + 1)] # Remove last
to <- breaks[-1] # Remove first
dat_inc <- data.frame(start = from, end = to, incidence_rate =
population_incidence/100000)
} else if(breaks == "5 years"){ # Option 2: 5 years age groups.
n_agegroups <- length(population_incidence)
breaks <- seq(0, 5*(n_agegroups), by = 5)
from <- breaks[-(n_agegroups + 1)] # Remove last
to <- breaks[-1] # Remove first
dat_inc <- data.frame(start = from, end = to, incidence_rate =
population_incidence/100000)
} else if(breaks == "10 years"){ # Option 3: 10 years age groups.
n_agegroups <- length(population_incidence)
breaks <- seq(0, 10*(n_agegroups), by = 10)
from <- breaks[-(n_agegroups + 1)] # Remove last
to <- breaks[-1] # Remove first
dat_inc <- data.frame(start = from, end = to, incidence_rate =
population_incidence/100000)
}
} else { # Option 4: if population incidence is given as a data.frame.
dat_inc <- data.frame(start = population_incidence[,1],
end = population_incidence[,2],
incidence_rate = population_incidence[,3]/100000)
breaks <- population_incidence[,1]
}
dat_inc <- dat_inc %>% mutate( k = paste("(", start, ",", end, "]", sep=""),
t = end - start)
# t is the width of the age interval, in years.
# Note that in the paper, this is referred to
# as (alpha_k - alpha_({k-1}).
# --------------- Calculate S_k population from population incidence.
dat_inc$S_k <- c(exp(-(dat_inc$t * dat_inc$incidence_rate)))
# --------------- Calculate S_k. based on sample data.
dat$y_cat <- cut(dat$y, breaks = breaks)
index <- which(is.na(dat$y_cat)==T)
if(length(index)>0){
dat<- dat[-index,]} # Include only those that fall within an age category.
# Store number of cases and unaffected individuals per age group.
agegroups.info <- aggregate(id ~ y_cat + d, data = dat, length)
agegroups.info <- agegroups.info %>% tidyr::spread(d, -y_cat)
colnames(agegroups.info) <- c("k","s_k","r_k")
# Transform NA to 0 (its real meaning).
agegroups.info$s_k <- ifelse(!is.na(agegroups.info$s_k), agegroups.info$s_k, 0)
agegroups.info$r_k <- ifelse(!is.na(agegroups.info$r_k), agegroups.info$r_k, 0)
# Calculate person years per outcome and age group.
personyears <- aggregate(y ~ y_cat + d, data =
dat[,c("d","y_cat", "y"),], sum) %>%
tidyr::spread(d, -y_cat)
colnames(personyears) <- c("k","q_k","p_k")
agegroups.info <- merge(agegroups.info, personyears, by = "k") # Merge.
agegroups.info$q_k <- ifelse(!is.na(agegroups.info$q_k),
agegroups.info$q_k, 0)
agegroups.info$p_k <- ifelse(!is.na(agegroups.info$p_k),
agegroups.info$p_k, 0)
agegroups.info$years.before <- breaks[which(breaks != max(breaks))]
# Person years among censored individuals.
q <- agegroups.info$q_k - (agegroups.info$years.before * agegroups.info$s_k)
# Person years among cases.
p <- agegroups.info$p_k - (agegroups.info$years.before * agegroups.info$r_k)
# Years per age group.
# N.B. in the paper referred to as (alpha_k - alpha_{k-1}).
t <- agegroups.info$t <- dat_inc$t
# Number of censored.
s <- agegroups.info$s_k
# Number of cases.
r <- agegroups.info$r_k
# Age group label.
k <- agegroups.info$k
# Obtain incidence rate (mu) based on sample data.
n_agegroups <- nrow(agegroups.info)
for (k in 1:n_agegroups){
if(k!=n_agegroups){calcsum <- sum(agegroups.info$r_k[(k+1):n_agegroups],
agegroups.info$s_k[(k+1):n_agegroups])
} else {calcsum <- 0}
agegroups.info$mu_k[k] = agegroups.info$r_k[k]/
(agegroups.info$p_k[k]+agegroups.info$q_k[k]+agegroups.info$t[k]*calcsum)
}
# Recalculate S_k. (in the sample!) based on the intervals.
S_k. <- c()
S_k. <- c(exp(-(agegroups.info$mu_k*t)))
agegroups.info$S_k. <- S_k.
agegroups.info$S_k <- dat_inc$S_k
# --------------- Add S_k. to the sample data.
dat_out <- merge(dat, agegroups.info, by.x = "y_cat", by.y = "k") %>%
mutate(k = y_cat) %>%
mutate(population_incidence = mu_k)
dat_out$years.before <- NULL; dat_out$t <- NULL;
dat_out$y_cat <- NULL; dat_out$mu_k <- NULL;
dat_out$s_k <- dat_out$r_k <- dat_out$p_k <- dat_out$q_k <- NULL
# --------------- Output the data.frame.
dat_out
}
#' Calculate inverse probability of selection weights.
#'
#' @description
#' This function calculates weights to correct for ascertainment bias in
#' time-to-event data where clusters are outcome-dependently sampled,
#' for example high-risk families in genetic epidemiological studies in
#' cancer research.
#'
#' @details
#' Weights are based on a comparison between the survival between sample and
#' population. Therefore, besides the sample data, the population incidence rate
#' (per 100 000) is needed as input, as well as the cut-offs of the
#' (age/time-to-event) groups for which this is available. The function provides
#' two options for the latter: cut-offs can be provided manually or using the
#' standard 5- or 10-years (age) categories (0-4, 5-9, ... or 0-9, 10-14, ...).
#' Note that resulting intervals are of the form [xx, xx).
#'
#' @export
Calculate_weights <- function(dat){
### Input:
#' @param dat Data.frame with one row per individual with columns *d*
#' non-censoring indicator; **k** interval of (age) group; **S_k**
#' population interval-based proportion of individuals experiencing the
#' event in intervals later than k; **S_k.** sample
#' proportion of individuals experiencing the event in intervals later
#' than k.
### Output:
#' @return Vector with weights.
# --------------- Extract variables from input data.frame.
# Group/interval.
k <- dat$k
# Population proportion of individuals experiencing the event in intervals
# later than k.
S_k <- dat$S_k
# Sample proportion of individuals experiencing the event in intervals
# later than k.
S_k. <- dat$S_k.
# --------------- Create empty containers.
v <- w <- rep(NA, nrow(dat))
# --------------- Calculate the weights.
for (n in 1:nrow(dat)){
# Weights for unaffected.
v[n] = 1
# Weights for cases.
w[n] = ( (1 - S_k[n]) / S_k[n] ) * (S_k.[n] / ( 1 - S_k.[n]))
}
merged <- cbind(dat, w, v)
merged$weight <- NA
# --------------- Assign w for uncensored, v for censored (interval-wise).
merged$weight[which(merged$d == 1)] <- merged$w[which(merged$d == 1)]
merged$weight[which(merged$d == 0)] <- merged$v[which(merged$d == 0)]
merged$w <- merged$v <- NULL # Remove old variable.
# --------------- Collect output.
vec_weights <- merged$weight
# If weight is 0, add very small value (coxph does not accept weights of 0).
vec_weights[which(vec_weights==0)] <- 0.0000001
# --------------- Print warning if weights are invalid.
ifelse((sum(vec_weights<0)>0), print("Invalid (negative) weights!"),
print("No negative weights"))
# --------------- Return output.
vec_weights
}
```
This tutorial shows a step-by-step analysis of toy data:
* [Step 1: Load of R package 'wcox' and toy data.](#anchor1)
* [Step 2: Acquire population incidence rate in the correct format.](#anchor2)
* [Step 3: Prepare the sample data using Prepare_data().](#anchor3)
* [Step 4: Calculate weights using Calculate_weights().](#anchor4)
* [Step 5: Fit a weighted Cox model using R package 'survival'.](#anchor5)
Let's start!
## Step 1: Load R package *'wcox'* and toy data.
Load the package.
```{r Loading, message = F}
library(wcox)
require(dplyr)
require(tidyr)
require(survival)
```
Load the toy data set.
```{r Load data set, message = F}
# Load toy data.
data("fam_dat")
```
Note that this concerns a simulated data set and no real observations. However, it is similar in structure to what one might come across in for example familial cancer studies.
```{r Show first lines data}
# Show the first few lines of the toy data.
head(fam_dat)
```
Families share the same 'family_id'; 'individual_id' is unique per individual. Risk modifier 'x' is a continuous variable. The event indicator ('event_indicator') takes value 1 if the individual experienced the event during follow-up and 0 otherwise. We consider the follow-up time since birth, i.e. age. For individuals experiencing the event, 'age' is the time-to-event. For others, this is the time-to-censoring.
```{r Distribution of family size}
# Show the number of families and top rows.
cat( "There are", unique(fam_dat$family_id) %>% length() , "families in data set. ")
# Examine family sizes.
fam_sizes <- fam_dat %>% group_by(family_id) %>% count()
cat( "Family size is on average ",
fam_sizes$n %>% mean() %>% round(1),
" and ranges from ",
fam_sizes$n %>% min(), " to ",
fam_sizes$n %>% max(), ".", sep = "")
```
It is good practice to report the distribution of family size together with the analysis results.
Besides sample data, we need some information about the population in order to calculate weights that correct for ascertainment bias.
## Step 2: Acquire population incidence rate in the correct format. {#anchor2}
In the weight calculation *'wcox'* uses the difference between the incidence rate of the event of interest in the sample versus the population. Therefore, the incidence rate in the population at risk is needed.
>**Incidence rate** is the number of events in a certain time window divided by the population.
Think of sentences like *"Breast cancer occurs in <incidence rate> out of 100 000 women between age xx and xx."* For many (medical) events, such data is available in national registries, for example the Dutch cancer registry (https://iknl.nl/nkr/cijfers-op-maat, select crude rate for incidence to get per 100 000). For high-risk populations of carriers of certain pathogenic genetic variants, incidence rates are often available in scientific publications or can be inferred based on published hazard ratios multiplied by underlying general population-based incidence rates.
Two aspects are important here. We need the incidence rate per 100 000 individuals, as that is what the package expects. And we need to make a choice of age groups. *'wcox'* allows to select the standard 5-years or 10-years age groups or define age groups manually.
The population incidence needs to be a so called vector, a sequence of incidence rates per age group. For entering the age group cut-offs: *1)* We can specify them manually where the vector 'breaks' needs to be one item longer than the incidence rate vector because the end of the last age group is also included. Intervals are of the form [begin, end), which means that in our example below, we will only include those with a follow-up time smaller than 100. *2)* We can choose 5-years categories (0-4, 5-9, 10-4 et cetera) or 10-years categories (0-9, 10-19, 20-29 et cetera). Then, 'wcox' will define the cut-offs automatically.
```{r External information}
# Enter the incidence by age group per 100 000, starting with the youngest age group.
incidence_rate <- c(2882, 1766, 1367, 1155, 987, 845, 775, 798, 636, 650)
# Define the age group cutoffs.
breaks_manually <- c(0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100)
breaks_10yrs <- "10 years"
```
We are almost ready to calculate.
## Step 3: Prepare the sample data using *Prepare_data()*. {#anchor3}
The function *Prepare_data()* expects a data.frame() in which each row concerns one individual (wide format). Moreover, it looks for the individual identifier, event indicator and time-to-event/censoring (age) by searching for variables 'id', 'd', 'y', respectively. In our case the latter two variables are named differently and we have to rename them.
```{r Rename variables}
# Rename variables.
my_dat <- rename(fam_dat, id = individual_id, d = event_indicator, y = age)
```
Now, it's time to combine the three pieces (sample data, external data, choice of age categories) to prepare the data for weight calculation. Remember that the calculation is based on the comparison between the sample data and the population and therefore we need to have the population incidence.
The function *Prepare_data()* takes three arguments: dat inputs the sample data.frame with 'id', 'd', 'y' and a family identifier, population_incidence inputs the vector (i.e. sequence of form c(xxx, xxx, xxx, ...) ) with incidence rates per 100 000, breaks inputs either a vector with breaks or one of the pre-set options ("5 years" or "10 years"). The code below uses the manual breaks. To try-out the pre-set option for 10 years age groups, remove the "#" in front of the last lines.
```{r Prepare data, message = F}
# Using option 1 (manual cut-offs):
my_dat_out <- Prepare_data(dat = my_dat, population_incidence = incidence_rate,
breaks = breaks_manually)
# Unhash to use option 2 (pre-set cut-offs):
# my_dat_out <- Prepare_data(dat = my_dat, population_incidence = incidence_rate,
# breaks = "10 years")
```
Let's see what the prepared data looks like.
```{r Look at prepared data}
# Select the newly add columns.
my_dat_out %>% select(id, k, d, S_k, S_k.) %>% arrange(id) %>% head(8)
```
The weights will be calculated based on the newly add columns S_k and S_k. .
In the paper, sample based quantities have a hyperscript '0' which is replaced by a dot (.) here. S_k is based on the external information (incidence rate).
With the prepared data set, we are ready to calculate the weights!
## Step 4: Calculate weights using *Calculate_weights()*. {#anchor4}
Function *Calculate_weights()* requires the data set prepared in the previous step, which we will refer to as **prepared** data. N.B.: Using the original data set directly will fail as the external information is not integrated there.
```{r Calculate weights}
# Calculate weights using the object that is output from the Prepare_data() function.
w <- Calculate_weights(dat = my_dat_out)
```
The function indicates that there are no negative weights. This means that our weights are valid. We will have a look at them now.
```{r Show weights}
# Show the weights.
my_dat_out %>% mutate(weight = w) %>%
select(id, d, weight) %>%
arrange(id) %>%
filter(id %in% c(1,3))
```
Individual 1 (id = 1) experiences the event between age 30 and 39 (d = 1). The weight for the interval in which the event took place is 1, while other intervals get weighted by less than 1. Individual 3 never experiences the event during follow-up and is censored within interval 90-99 years.
## Step 5: Fit a weighted Cox model using R package *'survival'*. {#anchor5}
Now, we show how to fit a Cox proportional hazards model with our calculated weights to correct for ascertainment bias, using R package 'survival'. Weights can be included using the argument 'weights'. Note that because we inputted the exact same data.frame in the function *Calculate_weights()* in the previous step, i.e. the **prepared** data, the resulting weight vector can be directly used: the order of individuals is the same. The covariate of interest is risk modifier 'x'. In order to obtain robust standard errors, the cluster term needs to be included.
```{r Fit model using weights, message = F}
# Fit the model.
fit <- coxph(Surv(y, d==1) ~ x + cluster(family_id), weights = w, data = my_dat_out)
fit
```
What does this say about the effect of the risk modifier?
```{r Examine estimates of fitted model}
# Extract estimates.
fit.summary <- summary(fit)
# Summarize findings.
cat("Covariate effect (95% CI): ",
exp(fit.summary$coefficients[1]), " (",
exp(fit.summary$coefficients[1] - 1.96*fit.summary$coefficients[4]), ", ",
exp(fit.summary$coefficients[1] + 1.96*fit.summary$coefficients[4]), ").", sep = "")
```
The risk of experiencing the event in the next instant of time is estimated to be 3.6 times higher for a unit increase in the risk modifier. The corresponding 95% confidence interval does not include 1, so this positive association is significant (using alpha = 0.05).
## References
Citation paper.
|
/scratch/gouwar.j/cran-all/cranData/wcox/inst/doc/Tutorial_toy_data.Rmd
|
---
title: "Tutorial Inverse probability weights to correct for ascertainment bias using R package 'wcox'"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{Tutorial_toy_data}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
Prepare_data <- function(dat, population_incidence, breaks){
### Input:
#' @param dat Data.frame with one row per individual which at least includes
#' a column **d** with event indicator (1 for event, 0 for censored), a column
#' **y** with event/censoring time.
#' @param population_incidence A vector (in combination with breaks) or
#' a data.frame (columns 1) 'start age group', 2) 'end age group', 3)'S_pop')
#' with population incidence per 100,000 per interval k.
#' @param breaks Cut-points for the (age/time) groups. Only needed when
#' population_incidence is a vector.
### Output:
#' @return Data.frame one row per individual and a.o. columns *id* unique ID;
#' *d* non-censoring indicator; **k** interval of (age) group; **S_k**
#' population interval-based proportion of individuals experiencing the
#' event in intervals later than k; **S_k.** sample
#' proportion of individuals experiencing the event in intervals later
#' than k.
# --------------- Load packages.
# require(survival)
# require(dplyr)
# require(tidyr)
# --------------- Organize external information (population incidence rate).
# N.B.: there are different options regarding the breaks (1-4).
if(is.vector(population_incidence)){
if(is.numeric(breaks)){ # Option 1: two vectors population_incidence and breaks.
if(length(breaks)!=(length(population_incidence)+1) ) warning("Number of
breaks should
equal the
number of
groups plus
one.")
n_agegroups <- length(population_incidence)
from <- breaks[-(n_agegroups + 1)] # Remove last
to <- breaks[-1] # Remove first
dat_inc <- data.frame(start = from, end = to, incidence_rate =
population_incidence/100000)
} else if(breaks == "5 years"){ # Option 2: 5 years age groups.
n_agegroups <- length(population_incidence)
breaks <- seq(0, 5*(n_agegroups), by = 5)
from <- breaks[-(n_agegroups + 1)] # Remove last
to <- breaks[-1] # Remove first
dat_inc <- data.frame(start = from, end = to, incidence_rate =
population_incidence/100000)
} else if(breaks == "10 years"){ # Option 3: 10 years age groups.
n_agegroups <- length(population_incidence)
breaks <- seq(0, 10*(n_agegroups), by = 10)
from <- breaks[-(n_agegroups + 1)] # Remove last
to <- breaks[-1] # Remove first
dat_inc <- data.frame(start = from, end = to, incidence_rate =
population_incidence/100000)
}
} else { # Option 4: if population incidence is given as a data.frame.
dat_inc <- data.frame(start = population_incidence[,1],
end = population_incidence[,2],
incidence_rate = population_incidence[,3]/100000)
breaks <- population_incidence[,1]
}
dat_inc <- dat_inc %>% mutate( k = paste("(", start, ",", end, "]", sep=""),
t = end - start)
# t is the width of the age interval, in years.
# Note that in the paper, this is referred to
# as (alpha_k - alpha_({k-1}).
# --------------- Calculate S_k population from population incidence.
dat_inc$S_k <- c(exp(-(dat_inc$t * dat_inc$incidence_rate)))
# --------------- Calculate S_k. based on sample data.
dat$y_cat <- cut(dat$y, breaks = breaks)
index <- which(is.na(dat$y_cat)==T)
if(length(index)>0){
dat<- dat[-index,]} # Include only those that fall within an age category.
# Store number of cases and unaffected individuals per age group.
agegroups.info <- aggregate(id ~ y_cat + d, data = dat, length)
agegroups.info <- agegroups.info %>% tidyr::spread(d, -y_cat)
colnames(agegroups.info) <- c("k","s_k","r_k")
# Transform NA to 0 (its real meaning).
agegroups.info$s_k <- ifelse(!is.na(agegroups.info$s_k), agegroups.info$s_k, 0)
agegroups.info$r_k <- ifelse(!is.na(agegroups.info$r_k), agegroups.info$r_k, 0)
# Calculate person years per outcome and age group.
personyears <- aggregate(y ~ y_cat + d, data =
dat[,c("d","y_cat", "y"),], sum) %>%
tidyr::spread(d, -y_cat)
colnames(personyears) <- c("k","q_k","p_k")
agegroups.info <- merge(agegroups.info, personyears, by = "k") # Merge.
agegroups.info$q_k <- ifelse(!is.na(agegroups.info$q_k),
agegroups.info$q_k, 0)
agegroups.info$p_k <- ifelse(!is.na(agegroups.info$p_k),
agegroups.info$p_k, 0)
agegroups.info$years.before <- breaks[which(breaks != max(breaks))]
# Person years among censored individuals.
q <- agegroups.info$q_k - (agegroups.info$years.before * agegroups.info$s_k)
# Person years among cases.
p <- agegroups.info$p_k - (agegroups.info$years.before * agegroups.info$r_k)
# Years per age group.
# N.B. in the paper referred to as (alpha_k - alpha_{k-1}).
t <- agegroups.info$t <- dat_inc$t
# Number of censored.
s <- agegroups.info$s_k
# Number of cases.
r <- agegroups.info$r_k
# Age group label.
k <- agegroups.info$k
# Obtain incidence rate (mu) based on sample data.
n_agegroups <- nrow(agegroups.info)
for (k in 1:n_agegroups){
if(k!=n_agegroups){calcsum <- sum(agegroups.info$r_k[(k+1):n_agegroups],
agegroups.info$s_k[(k+1):n_agegroups])
} else {calcsum <- 0}
agegroups.info$mu_k[k] = agegroups.info$r_k[k]/
(agegroups.info$p_k[k]+agegroups.info$q_k[k]+agegroups.info$t[k]*calcsum)
}
# Recalculate S_k. (in the sample!) based on the intervals.
S_k. <- c()
S_k. <- c(exp(-(agegroups.info$mu_k*t)))
agegroups.info$S_k. <- S_k.
agegroups.info$S_k <- dat_inc$S_k
# --------------- Add S_k. to the sample data.
dat_out <- merge(dat, agegroups.info, by.x = "y_cat", by.y = "k") %>%
mutate(k = y_cat) %>%
mutate(population_incidence = mu_k)
dat_out$years.before <- NULL; dat_out$t <- NULL;
dat_out$y_cat <- NULL; dat_out$mu_k <- NULL;
dat_out$s_k <- dat_out$r_k <- dat_out$p_k <- dat_out$q_k <- NULL
# --------------- Output the data.frame.
dat_out
}
#' Calculate inverse probability of selection weights.
#'
#' @description
#' This function calculates weights to correct for ascertainment bias in
#' time-to-event data where clusters are outcome-dependently sampled,
#' for example high-risk families in genetic epidemiological studies in
#' cancer research.
#'
#' @details
#' Weights are based on a comparison between the survival between sample and
#' population. Therefore, besides the sample data, the population incidence rate
#' (per 100 000) is needed as input, as well as the cut-offs of the
#' (age/time-to-event) groups for which this is available. The function provides
#' two options for the latter: cut-offs can be provided manually or using the
#' standard 5- or 10-years (age) categories (0-4, 5-9, ... or 0-9, 10-14, ...).
#' Note that resulting intervals are of the form [xx, xx).
#'
#' @export
Calculate_weights <- function(dat){
### Input:
#' @param dat Data.frame with one row per individual with columns *d*
#' non-censoring indicator; **k** interval of (age) group; **S_k**
#' population interval-based proportion of individuals experiencing the
#' event in intervals later than k; **S_k.** sample
#' proportion of individuals experiencing the event in intervals later
#' than k.
### Output:
#' @return Vector with weights.
# --------------- Extract variables from input data.frame.
# Group/interval.
k <- dat$k
# Population proportion of individuals experiencing the event in intervals
# later than k.
S_k <- dat$S_k
# Sample proportion of individuals experiencing the event in intervals
# later than k.
S_k. <- dat$S_k.
# --------------- Create empty containers.
v <- w <- rep(NA, nrow(dat))
# --------------- Calculate the weights.
for (n in 1:nrow(dat)){
# Weights for unaffected.
v[n] = 1
# Weights for cases.
w[n] = ( (1 - S_k[n]) / S_k[n] ) * (S_k.[n] / ( 1 - S_k.[n]))
}
merged <- cbind(dat, w, v)
merged$weight <- NA
# --------------- Assign w for uncensored, v for censored (interval-wise).
merged$weight[which(merged$d == 1)] <- merged$w[which(merged$d == 1)]
merged$weight[which(merged$d == 0)] <- merged$v[which(merged$d == 0)]
merged$w <- merged$v <- NULL # Remove old variable.
# --------------- Collect output.
vec_weights <- merged$weight
# If weight is 0, add very small value (coxph does not accept weights of 0).
vec_weights[which(vec_weights==0)] <- 0.0000001
# --------------- Print warning if weights are invalid.
ifelse((sum(vec_weights<0)>0), print("Invalid (negative) weights!"),
print("No negative weights"))
# --------------- Return output.
vec_weights
}
```
This tutorial shows a step-by-step analysis of toy data:
* [Step 1: Load of R package 'wcox' and toy data.](#anchor1)
* [Step 2: Acquire population incidence rate in the correct format.](#anchor2)
* [Step 3: Prepare the sample data using Prepare_data().](#anchor3)
* [Step 4: Calculate weights using Calculate_weights().](#anchor4)
* [Step 5: Fit a weighted Cox model using R package 'survival'.](#anchor5)
Let's start!
## Step 1: Load R package *'wcox'* and toy data.
Load the package.
```{r Loading, message = F}
library(wcox)
require(dplyr)
require(tidyr)
require(survival)
```
Load the toy data set.
```{r Load data set, message = F}
# Load toy data.
data("fam_dat")
```
Note that this concerns a simulated data set and no real observations. However, it is similar in structure to what one might come across in for example familial cancer studies.
```{r Show first lines data}
# Show the first few lines of the toy data.
head(fam_dat)
```
Families share the same 'family_id'; 'individual_id' is unique per individual. Risk modifier 'x' is a continuous variable. The event indicator ('event_indicator') takes value 1 if the individual experienced the event during follow-up and 0 otherwise. We consider the follow-up time since birth, i.e. age. For individuals experiencing the event, 'age' is the time-to-event. For others, this is the time-to-censoring.
```{r Distribution of family size}
# Show the number of families and top rows.
cat( "There are", unique(fam_dat$family_id) %>% length() , "families in data set. ")
# Examine family sizes.
fam_sizes <- fam_dat %>% group_by(family_id) %>% count()
cat( "Family size is on average ",
fam_sizes$n %>% mean() %>% round(1),
" and ranges from ",
fam_sizes$n %>% min(), " to ",
fam_sizes$n %>% max(), ".", sep = "")
```
It is good practice to report the distribution of family size together with the analysis results.
Besides sample data, we need some information about the population in order to calculate weights that correct for ascertainment bias.
## Step 2: Acquire population incidence rate in the correct format. {#anchor2}
In the weight calculation *'wcox'* uses the difference between the incidence rate of the event of interest in the sample versus the population. Therefore, the incidence rate in the population at risk is needed.
>**Incidence rate** is the number of events in a certain time window divided by the population.
Think of sentences like *"Breast cancer occurs in <incidence rate> out of 100 000 women between age xx and xx."* For many (medical) events, such data is available in national registries, for example the Dutch cancer registry (https://iknl.nl/nkr/cijfers-op-maat, select crude rate for incidence to get per 100 000). For high-risk populations of carriers of certain pathogenic genetic variants, incidence rates are often available in scientific publications or can be inferred based on published hazard ratios multiplied by underlying general population-based incidence rates.
Two aspects are important here. We need the incidence rate per 100 000 individuals, as that is what the package expects. And we need to make a choice of age groups. *'wcox'* allows to select the standard 5-years or 10-years age groups or define age groups manually.
The population incidence needs to be a so called vector, a sequence of incidence rates per age group. For entering the age group cut-offs: *1)* We can specify them manually where the vector 'breaks' needs to be one item longer than the incidence rate vector because the end of the last age group is also included. Intervals are of the form [begin, end), which means that in our example below, we will only include those with a follow-up time smaller than 100. *2)* We can choose 5-years categories (0-4, 5-9, 10-4 et cetera) or 10-years categories (0-9, 10-19, 20-29 et cetera). Then, 'wcox' will define the cut-offs automatically.
```{r External information}
# Enter the incidence by age group per 100 000, starting with the youngest age group.
incidence_rate <- c(2882, 1766, 1367, 1155, 987, 845, 775, 798, 636, 650)
# Define the age group cutoffs.
breaks_manually <- c(0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100)
breaks_10yrs <- "10 years"
```
We are almost ready to calculate.
## Step 3: Prepare the sample data using *Prepare_data()*. {#anchor3}
The function *Prepare_data()* expects a data.frame() in which each row concerns one individual (wide format). Moreover, it looks for the individual identifier, event indicator and time-to-event/censoring (age) by searching for variables 'id', 'd', 'y', respectively. In our case the latter two variables are named differently and we have to rename them.
```{r Rename variables}
# Rename variables.
my_dat <- rename(fam_dat, id = individual_id, d = event_indicator, y = age)
```
Now, it's time to combine the three pieces (sample data, external data, choice of age categories) to prepare the data for weight calculation. Remember that the calculation is based on the comparison between the sample data and the population and therefore we need to have the population incidence.
The function *Prepare_data()* takes three arguments: dat inputs the sample data.frame with 'id', 'd', 'y' and a family identifier, population_incidence inputs the vector (i.e. sequence of form c(xxx, xxx, xxx, ...) ) with incidence rates per 100 000, breaks inputs either a vector with breaks or one of the pre-set options ("5 years" or "10 years"). The code below uses the manual breaks. To try-out the pre-set option for 10 years age groups, remove the "#" in front of the last lines.
```{r Prepare data, message = F}
# Using option 1 (manual cut-offs):
my_dat_out <- Prepare_data(dat = my_dat, population_incidence = incidence_rate,
breaks = breaks_manually)
# Unhash to use option 2 (pre-set cut-offs):
# my_dat_out <- Prepare_data(dat = my_dat, population_incidence = incidence_rate,
# breaks = "10 years")
```
Let's see what the prepared data looks like.
```{r Look at prepared data}
# Select the newly add columns.
my_dat_out %>% select(id, k, d, S_k, S_k.) %>% arrange(id) %>% head(8)
```
The weights will be calculated based on the newly add columns S_k and S_k. .
In the paper, sample based quantities have a hyperscript '0' which is replaced by a dot (.) here. S_k is based on the external information (incidence rate).
With the prepared data set, we are ready to calculate the weights!
## Step 4: Calculate weights using *Calculate_weights()*. {#anchor4}
Function *Calculate_weights()* requires the data set prepared in the previous step, which we will refer to as **prepared** data. N.B.: Using the original data set directly will fail as the external information is not integrated there.
```{r Calculate weights}
# Calculate weights using the object that is output from the Prepare_data() function.
w <- Calculate_weights(dat = my_dat_out)
```
The function indicates that there are no negative weights. This means that our weights are valid. We will have a look at them now.
```{r Show weights}
# Show the weights.
my_dat_out %>% mutate(weight = w) %>%
select(id, d, weight) %>%
arrange(id) %>%
filter(id %in% c(1,3))
```
Individual 1 (id = 1) experiences the event between age 30 and 39 (d = 1). The weight for the interval in which the event took place is 1, while other intervals get weighted by less than 1. Individual 3 never experiences the event during follow-up and is censored within interval 90-99 years.
## Step 5: Fit a weighted Cox model using R package *'survival'*. {#anchor5}
Now, we show how to fit a Cox proportional hazards model with our calculated weights to correct for ascertainment bias, using R package 'survival'. Weights can be included using the argument 'weights'. Note that because we inputted the exact same data.frame in the function *Calculate_weights()* in the previous step, i.e. the **prepared** data, the resulting weight vector can be directly used: the order of individuals is the same. The covariate of interest is risk modifier 'x'. In order to obtain robust standard errors, the cluster term needs to be included.
```{r Fit model using weights, message = F}
# Fit the model.
fit <- coxph(Surv(y, d==1) ~ x + cluster(family_id), weights = w, data = my_dat_out)
fit
```
What does this say about the effect of the risk modifier?
```{r Examine estimates of fitted model}
# Extract estimates.
fit.summary <- summary(fit)
# Summarize findings.
cat("Covariate effect (95% CI): ",
exp(fit.summary$coefficients[1]), " (",
exp(fit.summary$coefficients[1] - 1.96*fit.summary$coefficients[4]), ", ",
exp(fit.summary$coefficients[1] + 1.96*fit.summary$coefficients[4]), ").", sep = "")
```
The risk of experiencing the event in the next instant of time is estimated to be 3.6 times higher for a unit increase in the risk modifier. The corresponding 95% confidence interval does not include 1, so this positive association is significant (using alpha = 0.05).
## References
Citation paper.
|
/scratch/gouwar.j/cran-all/cranData/wcox/vignettes/Tutorial_toy_data.Rmd
|
# Generated by using Rcpp::compileAttributes() -> do not edit by hand
# Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393
wdm_cpp <- function(x, y, method, weights, remove_missing) {
.Call(`_wdm_wdm_cpp`, x, y, method, weights, remove_missing)
}
wdm_mat_cpp <- function(x, method, weights, remove_missing) {
.Call(`_wdm_wdm_mat_cpp`, x, method, weights, remove_missing)
}
indep_test_cpp <- function(x, y, method, weights, remove_missing, alternative) {
.Call(`_wdm_indep_test_cpp`, x, y, method, weights, remove_missing, alternative)
}
rank_wtd_cpp <- function(x, weights, ties_method = "min") {
.Call(`_wdm_rank_wtd_cpp`, x, weights, ties_method)
}
perm_sum_cpp <- function(x, k) {
.Call(`_wdm_perm_sum_cpp`, x, k)
}
|
/scratch/gouwar.j/cran-all/cranData/wdm/R/RcppExports.R
|
#' Independence Tests for Weighted Dependence Measures
#'
#' Computes a (possibly weighted) dependence measure between `x` and `y` if
#' these are vectors. If `x` and `y` are matrices then the measure between the
#' columns of `x` and the columns of `y` are computed.
#'
#' @param x,y numeric vectors of data values. `x` and `y` must have the same
#' length.
#' @param method the dependence measure; see *Details* for possible values.
#' @param weights an optional vector of weights for the observations.
#' @param remove_missing if `TRUE`, all (pairswise) incomplete observations are
#' removed; if `FALSE`, the function throws an error if there are incomplete
#' observations.
#' @param alternative indicates the alternative hypothesis and must be one of
#' `"two-sided"`, `"greater"` or `"less"`. You can specify just the initial
#' letter. `"greater"` corresponds to positive association, `"less"` to
#' negative association.
#'
#' @details Available methods:
#' - `"pearson"`: Pearson correlation
#' - `"spearman"`: Spearman's \eqn{\rho}
#' - `"kendall"`: Kendall's \eqn{\tau}
#' - `"blomqvist"`: Blomqvist's \eqn{\beta}
#' - `"hoeffding"`: Hoeffding's \eqn{D}
#'
#' Partial matching of method names is enabled.
#' All methods except `"hoeffding"` work with discrete variables.
#'
#' @export
#'
#' @examples
#' x <- rnorm(100)
#' y <- rpois(100, 1) # all but Hoeffding's D can handle ties
#' w <- runif(100)
#'
#' indep_test(x, y, method = "kendall") # unweighted
#' indep_test(x, y, method = "kendall", weights = w) # weighted
#'
indep_test <- function(x, y, method = "pearson", weights = NULL,
remove_missing = TRUE, alternative = "two-sided") {
if (is.null(weights))
weights <- numeric(0)
check_indep_test_inputs(x, y, weights, remove_missing)
method <- match.arg(method, allowed_methods)
alternative <- match.arg(alternative, allowed_alternatives)
test <- indep_test_cpp(x, y, method, weights, remove_missing, alternative)
as.data.frame(test)
}
allowed_methods <- c("pearson", "kendall", "spearman", "hoeffding", "blomqvist")
allowed_alternatives <- c("two-sided", "less", "greater")
check_indep_test_inputs <- function(x, y, weights, remove_missing) {
if (!(is.numeric(x) | is.logical(x)) | (NCOL(x) != 1) )
stop("'x' must be a numeric vector")
if (!(is.numeric(y) | is.logical(y)) | (NCOL(y) != 1) )
stop("'y' must be a numeric vector")
if (!is.numeric(weights) | (NCOL(weights) != 1))
stop("'weights' must be a numeric vector")
stopifnot(is.atomic(x))
stopifnot(is.atomic(y))
stopifnot(is.atomic(weights))
if (!is.logical(remove_missing))
stop("remove_missing must be logical.")
}
|
/scratch/gouwar.j/cran-all/cranData/wdm/R/indep_test.R
|
#' Computing weighted ranks
#'
#' The weighted rank of \eqn{X_i} among \eqn{X_1, \dots, X_n} with weights
#' \eqn{w_1, \dots, w_n} is defined as
#' \deqn{\frac 1 n \sum_{j = 1}^n w_i 1[X_j \le X_i].}
#'
#' @param x a numeric vector.
#' @param weights a vector of weights (same length as `x`).
#' @param ties_method Indicates how to treat ties; same as in R, see
#' https://stat.ethz.ch/R-manual/R-devel/library/base/html/rank.html.
#'
#' @return a vector of ranks.
#' @export
#'
#' @examples
#' x <- rnorm(100)
#' w <- rexp(100)
#' rank(x)
#' rank_wtd(x, w)
rank_wtd <- function(x, weights = numeric(), ties_method = "average") {
## preprocessing of arguments
stopifnot(is.numeric(x))
rank_wtd_cpp(x, weights, ties_method)
}
|
/scratch/gouwar.j/cran-all/cranData/wdm/R/rank_wtd.R
|
#' @title \packageTitle{wdm}
#'
#' @description
#' \packageDescription{wdm}
#'
#' @details
#' The DESCRIPTION file:
#' \packageDESCRIPTION{VineCopula}
#'
#' @name wdm-package
#' @aliases wdm-package
#' @docType package
#' @useDynLib wdm, .registration = TRUE
#' @importFrom Rcpp sourceCpp
NULL
|
/scratch/gouwar.j/cran-all/cranData/wdm/R/wdm-package.R
|
#' Weighted Dependence Measures
#'
#' Computes a (possibly weighted) dependence measure between `x` and `y` if
#' these are vectors. If `x` and `y` are matrices then the measure between the
#' columns of `x` and the columns of `y` are computed.
#'
#' @param x a numeric vector, matrix or data frame.
#' @param y `NULL` (default) or a vector, matrix or data frame with compatible
#' dimensions to x. The default is equivalent to `y = x`` (but more
#' efficient).
#' @param method the dependence measure; see *Details* for possible values.
#' @param weights an optional vector of weights for the observations.
#' @param remove_missing if `TRUE`, all (pairswise) incomplete observations are
#' removed; if `FALSE`, the function throws an error if there are incomplete
#' observations.
#'
#' @details Available methods:
#' - `"pearson"`: Pearson correlation
#' - `"spearman"`: Spearman's \eqn{\rho}
#' - `"kendall"`: Kendall's \eqn{\tau}
#' - `"blomqvist"`: Blomqvist's \eqn{\beta}
#' - `"hoeffding"`: Hoeffding's \eqn{D}
#' Partial matching of method names is enabled.
#'
#' Spearman's \eqn{\rho} and Kendall's \eqn{\tau} are corrected for ties if
#' there are any.
#'
#' @export
#'
#' @examples
#' ## dependence between two vectors
#' x <- rnorm(100)
#' y <- rpois(100, 1) # all but Hoeffding's D can handle ties
#' w <- runif(100)
#' wdm(x, y, method = "kendall") # unweighted
#' wdm(x, y, method = "kendall", weights = w) # weighted
#'
#' ## dependence in a matrix
#' x <- matrix(rnorm(100 * 3), 100, 3)
#' wdm(x, method = "spearman") # unweighted
#' wdm(x, method = "spearman", weights = w) # weighted
#'
#' ## dependence between columns of two matrices
#' y <- matrix(rnorm(100 * 2), 100, 2)
#' wdm(x, y, method = "hoeffding") # unweighted
#' wdm(x, y, method = "hoeffding", weights = w) # weighted
#'
wdm <- function(x, y = NULL, method = "pearson", weights = NULL,
remove_missing = TRUE) {
## preprocessing of arguments
if (is.null(weights))
weights <- numeric(0)
if (is.data.frame(y))
y <- as.matrix(y)
if (is.data.frame(x))
x <- as.matrix(x)
check_wdm_inputs(x, y, weights, remove_missing)
method <- match.arg(method, allowed_methods)
## computations
if (is.null(y)) {
out <- wdm_mat_cpp(x, method, weights, remove_missing)
colnames(out) <- rownames(out) <- colnames(x)
} else if (NCOL(x) == 1) {
out <- wdm_cpp(x, y, method, weights, remove_missing)
} else {
out <- matrix(NA, ncol(x), ncol(y))
for (i in seq_len(ncol(x))) {
for (j in seq_len(ncol(y))) {
out[i, j] <- wdm(x[, i], y[, j], method, weights, remove_missing)
}
}
rownames(out) <- colnames(x)
colnames(out) <- colnames(y)
}
out[is.nan(out)] <- NA
out
}
allowed_methods <- c("pearson", "kendall", "spearman", "hoeffding", "blomqvist")
check_wdm_inputs <- function(x, y, weights, remove_missing) {
if (!is.matrix(x) && is.null(y))
stop("supply both 'x' and 'y' or a matrix-like 'x'")
if (!(is.numeric(x) || is.logical(x)))
stop("'x' must be numeric")
if (!is.numeric(weights) | (NCOL(weights) != 1))
stop("'weights' must be a numeric vector")
stopifnot(is.atomic(x))
stopifnot(is.atomic(weights))
if (!is.null(y)) {
if (!(is.numeric(y) || is.logical(y)))
stop("'y' must be numeric")
stopifnot(is.atomic(y))
if ((NROW(x) != NROW(y)))
stop("'x' and 'y' must have the same number of rows")
}
if (!is.logical(remove_missing))
stop("remove_missing must be logical.")
}
|
/scratch/gouwar.j/cran-all/cranData/wdm/R/wdm.R
|
is_string <- function(x) {
is.character(x) && length(x) == 1 && !is.na(x)
}
assertthat::on_failure(is_string) <- function(call, env) {
paste0(deparse(call$x), " is not a string")
}
is_string_or_null <- function(x) {
is_string(x) || is.null(x)
}
assertthat::on_failure(is_string_or_null) <- function(call, env) {
paste0(env$x, " is not a string or null")
}
is_list <- function(x) {
is.list(x)
}
assertthat::on_failure(is_list) <- function(call, env) {
paste0(deparse(call$x), " is not a list")
}
is_env <- function(x) {
is.environment(x)
}
assertthat::on_failure(is_env) <- function(call, env) {
paste0(deparse(call$x), " is not an environment")
}
is_list_of_df <- function(x) {
is_list(x) && all(vapply(x, is.data.frame, logical(1)))
}
assertthat::on_failure(is_list_of_df) <- function(call, env) {
paste0(deparse(call$x), " is not a list of data.frames")
}
is_url <- function(x) {
is_string(x) && grepl("^https?://", x, useBytes = TRUE)
}
assertthat::on_failure(is_url) <- function(call, env) {
paste0(deparse(call$x), " is not a url")
}
is_file <- function(x) {
is_string(x) && file.exists(x)
}
assertthat::on_failure(is_file) <- function(call, env) {
paste0(deparse(call$x), " is not a file")
}
is_URL_file <- function(x) {
if (is_url(x) || is_file(x)) {
TRUE
} else {
FALSE
}
}
assertthat::on_failure(is_URL_file) <- function(call, env) {
paste0(deparse(call$x), " is not a URL or file")
}
is_integer <- function(x) {
is.integer(x)
}
assertthat::on_failure(is_integer) <- function(call, env) {
paste0(deparse(call$x), " should be an integer value.")
}
is_character <- function(x) {
is.character(x)
}
assertthat::on_failure(is_character) <- function(call, env) {
paste0(deparse(call$x), " should be an character vector.")
}
is_logical <- function(x) {
is.logical(x)
}
assertthat::on_failure(is_logical) <- function(call, env) {
paste0(deparse(call$x), " should be an logical vector.")
}
is_data.frame <- function(x) {
is.data.frame(x)
}
assertthat::on_failure(is_data.frame) <- function(call, env) {
paste0(deparse(call$x), " should be a data.frame.")
}
contains_required <- function(x, required) {
is.list(x) && all(required %in% names(x))
}
assertthat::on_failure(contains_required) <- function(call, env) {
required <- eval(call$required, env)
paste0(
deparse(call$x),
" does not have one of ",
paste(required, collapse = ","),
" as required by specification."
)
}
app_dir_exists <- function(x) {
dir.exists(x)
}
assertthat::on_failure(app_dir_exists) <- function(call, env) {
paste0(env[[deparse(call$x)]], " app directory not found.")
}
|
/scratch/gouwar.j/cran-all/cranData/wdman/R/assertions.R
|
#' Start chrome driver
#'
#' Start chrome driver
#' @param port Port to run on
#' @param version what version of chromedriver to run. Default = "latest"
#' which runs the most recent version. To see other version currently
#' sourced run binman::list_versions("chromedriver")
#' @param path base URL path prefix for commands, e.g. wd/hub
#' @param check If TRUE check the versions of chromedriver available. If
#' new versions are available they will be downloaded.
#' @param verbose If TRUE, include status messages (if any)
#' @param retcommand If TRUE return only the command that would be passed
#' to \code{\link[processx]{process}}
#' @param ... pass additional options to the driver
#'
#' @return Returns a list with named elements \code{process}, \code{output},
#' \code{error}, \code{stop}, and \code{log}.
#' \code{process} is the object from calling \code{\link[processx]{process}}.
#' \code{output} and \code{error} are the functions reading the latest
#' messages from "stdout" and "stderr" since the last call whereas \code{log}
#' is the function that reads all messages.
#' Lastly, \code{stop} call the \code{kill} method in
#' \code{\link[processx]{process}} to the kill the \code{process}.
#' @export
#'
#' @examples
#' \dontrun{
#' cDrv <- chrome()
#' cDrv$output()
#' cDrv$stop()
#' }
#'
chrome <- function(port = 4567L, version = "latest", path = "wd/hub",
check = TRUE, verbose = TRUE, retcommand = FALSE, ...) {
assert_that(is_integer(port))
assert_that(is_string(version))
assert_that(is_string(path))
assert_that(is_logical(verbose))
chromecheck <- chrome_check(verbose, check = check)
chromeplat <- chromecheck[["platform"]]
chromeversion <- chrome_ver(chromeplat, version)
eopts <- list(...)
args <- c(Reduce(c, eopts[names(eopts) == "args"]))
args[["port"]] <- sprintf("--port=%s", port)
args[["url-base"]] <- sprintf("--url-base=%s", path)
args[["verbose"]] <- "--verbose"
if (retcommand) {
return(paste(c(chromeversion[["path"]], args), collapse = " "))
}
pfile <- pipe_files()
errTfile <- tempfile(fileext = ".txt")
write(character(), errTfile)
outTfile <- tempfile(fileext = ".txt")
write(character(), outTfile)
chromedrv <- spawn_tofile(
chromeversion[["path"]],
args, pfile[["out"]], pfile[["err"]]
)
if (isFALSE(chromedrv$is_alive())) {
err <- paste0(readLines(pfile[["err"]]), collapse = "\n")
stop("Chromedriver couldn't be started\n", err)
}
startlog <- generic_start_log(chromedrv,
outfile = pfile[["out"]],
errfile = pfile[["err"]]
)
if (length(startlog[["stderr"]]) > 0) {
if (any(grepl("Address already in use", startlog[["stderr"]]))) {
kill_process(chromedrv)
stop("Chrome Driver signals port = ", port, " is already in use.")
}
}
log <- as.environment(startlog)
list(
process = chromedrv,
output = function(timeout = 0L) {
infun_read(chromedrv, log, "stdout",
timeout = timeout,
outfile = pfile[["out"]], errfile = pfile[["err"]]
)
},
error = function(timeout = 0L) {
infun_read(chromedrv, log, "stderr",
timeout = timeout,
outfile = pfile[["out"]], errfile = pfile[["err"]]
)
},
stop = function() {
kill_process(chromedrv)
},
log = function() {
infun_read(chromedrv, log,
outfile = pfile[["out"]], errfile = pfile[["err"]]
)
as.list(log)
}
)
}
chrome_check <- function(verbose, check = TRUE) {
chromeyml <- system.file("yaml", "chromedriver.yml", package = "wdman")
cyml <- yaml::yaml.load_file(chromeyml)
platvec <- c("predlfunction", "binman::predl_google_storage", "platform")
cyml[[platvec]] <-
switch(Sys.info()["sysname"],
Linux = grep(os_arch("linux"), cyml[[platvec]], value = TRUE),
Windows = grep("win", cyml[[platvec]], value = TRUE),
Darwin = grep(mac_machine(), cyml[[platvec]], value = TRUE),
stop("Unknown OS")
)
# Need regex that can tell mac64 and mac64_m1 apart
if (cyml[[platvec]] %in% c("mac64", "mac64_m1")) {
platregexvec <- c("predlfunction", "binman::predl_google_storage", "platformregex")
cyml[[platregexvec]] <- paste0(cyml[[platvec]], "\\.")
}
tempyml <- tempfile(fileext = ".yml")
write(yaml::as.yaml(cyml), tempyml)
if (check) {
if (verbose) message("checking chromedriver versions:")
process_yaml(tempyml, verbose)
}
chromeplat <- cyml[[platvec]]
list(yaml = cyml, platform = chromeplat)
}
chrome_ver <- function(platform, version) {
chromever <- binman::list_versions("chromedriver")[[platform]]
chromever <- if (identical(version, "latest")) {
as.character(max(package_version(chromever)))
} else {
mtch <- match(version, chromever)
if (is.na(mtch) || is.null(mtch)) {
stop(
"version requested doesnt match versions available = ",
paste(chromever, collapse = ",")
)
}
chromever[mtch]
}
chromedir <- normalizePath(
file.path(app_dir("chromedriver"), platform, chromever)
)
chromepath <- list.files(chromedir,
pattern = "chromedriver($|.exe$)",
full.names = TRUE
)
list(version = chromever, dir = chromedir, path = chromepath)
}
|
/scratch/gouwar.j/cran-all/cranData/wdman/R/chrome.R
|
#' Start gecko driver
#'
#' Start gecko driver
#' @param port Port to run on
#' @param version what version of geckodriver to run. Default = "latest"
#' which runs the most recent version. To see other version currently
#' sourced run binman::list_versions("geckodriver")
#' @param loglevel Set Gecko log level [values: fatal, error,
#' warn, info, config, debug, trace]
#' @param check If TRUE check the versions of geckodriver available. If
#' new versions are available they will be downloaded.
#' @param verbose If TRUE, include status messages (if any)
#' @param retcommand If TRUE return only the command that would be passed
#' to \code{\link[processx]{process}}
#' @param ... pass additional options to the driver
#'
#' @return Returns a list with named elements \code{process}, \code{output},
#' \code{error}, \code{stop}, and \code{log}.
#' \code{process} is the object from calling \code{\link[processx]{process}}.
#' \code{output} and \code{error} are the functions reading the latest
#' messages from "stdout" and "stderr" since the last call whereas \code{log}
#' is the function that reads all messages.
#' Lastly, \code{stop} call the \code{kill} method in
#' \code{\link[processx]{process}} to the kill the \code{process}.
#' @export
#'
#' @examples
#' \dontrun{
#' gDrv <- gecko()
#' gDrv$output()
#' gDrv$stop()
#' }
#'
gecko <- function(port = 4567L, version = "latest", check = TRUE,
loglevel = c(
"info", "fatal", "error", "warn", "config",
"debug", "trace"
), verbose = TRUE,
retcommand = FALSE, ...) {
assert_that(is_integer(port))
assert_that(is_string(version))
assert_that(is_logical(verbose))
loglevel <- match.arg(loglevel)
geckocheck <- gecko_check(verbose, check = check)
geckoplat <- geckocheck[["platform"]]
geckoversion <- gecko_ver(geckoplat, version)
eopts <- list(...)
args <- c(Reduce(c, eopts[names(eopts) == "args"]))
args[["port"]] <- sprintf("--port=%s", port)
args[["log"]] <- sprintf("--log=%s", loglevel)
if (retcommand) {
return(paste(c(geckoversion[["path"]], args), collapse = " "))
}
pfile <- pipe_files()
geckodrv <- spawn_tofile(
geckoversion[["path"]],
args, pfile[["out"]], pfile[["err"]]
)
if (isFALSE(geckodrv$is_alive())) {
err <- paste0(readLines(pfile[["err"]]), collapse = "\n")
stop("Geckodriver couldn't be started\n", err)
}
startlog <- generic_start_log(geckodrv,
outfile = pfile[["out"]],
errfile = pfile[["err"]]
)
if (length(startlog[["stderr"]]) > 0) {
if (any(grepl("Address already in use", startlog[["stderr"]]))) {
kill_process(geckodrv)
stop("Gecko Driver signals port = ", port, " is already in use.")
}
}
log <- as.environment(startlog)
list(
process = geckodrv,
output = function(timeout = 0L) {
infun_read(geckodrv, log, "stdout",
timeout = timeout,
outfile = pfile[["out"]], errfile = pfile[["err"]]
)
},
error = function(timeout = 0L) {
infun_read(geckodrv, log, "stderr",
timeout = timeout,
outfile = pfile[["out"]], errfile = pfile[["err"]]
)
},
stop = function() {
kill_process(geckodrv)
},
log = function() {
infun_read(geckodrv, log, outfile = pfile[["out"]], errfile = pfile[["err"]])
as.list(log)
}
)
}
gecko_check <- function(verbose, check = TRUE) {
geckoyml <- system.file("yaml", "geckodriver.yml", package = "wdman")
gyml <- yaml::yaml.load_file(geckoyml)
platvec <- c("predlfunction", "binman::predl_github_assets", "platform")
gyml[[platvec]] <-
switch(Sys.info()["sysname"],
Linux = grep(os_arch("linux"), gyml[[platvec]], value = TRUE),
Windows = grep(os_arch("win"), gyml[[platvec]], value = TRUE),
Darwin = grep(mac_machine(), gyml[[platvec]], value = TRUE),
stop("Unknown OS")
)
# Need regex that can tell mac64 and macos-aarch64 apart
if (gyml[[platvec]] %in% c("macos", "macos-aarch64")) {
platregexvec <- c("predlfunction", "binman::predl_github_assets", "platformregex")
gyml[[platregexvec]] <- paste0(gyml[[platvec]], "\\.")
}
tempyml <- tempfile(fileext = ".yml")
write(yaml::as.yaml(gyml), tempyml)
if (check) {
if (verbose) message("checking geckodriver versions:")
process_yaml(tempyml, verbose)
}
geckoplat <- gyml[[platvec]]
list(yaml = gyml, platform = geckoplat)
}
gecko_ver <- function(platform, version) {
geckover <- binman::list_versions("geckodriver")[[platform]]
geckover <- if (identical(version, "latest")) {
as.character(max(semver::parse_version(geckover)))
} else {
mtch <- match(version, geckover)
if (is.na(mtch) || is.null(mtch)) {
stop(
"version requested doesnt match versions available = ",
paste(geckover, collapse = ",")
)
}
geckover[mtch]
}
geckodir <- normalizePath(
file.path(app_dir("geckodriver"), platform, geckover)
)
geckopath <- list.files(geckodir,
pattern = "geckodriver($|.exe$)",
full.names = TRUE
)
list(version = geckover, dir = geckodir, path = geckopath)
}
|
/scratch/gouwar.j/cran-all/cranData/wdman/R/gecko.R
|
#' Start IE driver server
#'
#' Start IE driver server
#' @param port Port to run on
#' @param version what version of IE driver server to run. Default = "latest"
#' which runs the most recent version. To see other version currently
#' sourced run binman::list_versions("iedriverserver")
#' @param loglevel Specifies the log level used by the server. Valid values
#' are: TRACE, DEBUG, INFO, WARN, ERROR, and FATAL. Defaults to FATAL
#' if not specified.
#' @param check If TRUE check the versions of IE driver available. If
#' new versions are available they will be downloaded.
#' @param verbose If TRUE, include status messages (if any)
#' @param retcommand If TRUE return only the command that would be passed
#' to \code{\link[processx]{process}}
#' @param ... pass additional options to the driver
#'
#' @return Returns a list with named elements \code{process}, \code{output},
#' \code{error}, \code{stop}, and \code{log}.
#' \code{process} is the object from calling \code{\link[processx]{process}}.
#' \code{output} and \code{error} are the functions reading the latest
#' messages from "stdout" and "stderr" since the last call whereas \code{log}
#' is the function that reads all messages.
#' Lastly, \code{stop} call the \code{kill} method in
#' \code{\link[processx]{process}} to the kill the \code{process}.
#' @export
#'
#' @examples
#' \dontrun{
#' ieDrv <- iedriver()
#' ieDrv$output()
#' ieDrv$stop()
#' }
#'
iedriver <- function(port = 4567L, version = "latest", check = TRUE,
loglevel = c(
"FATAL", "TRACE", "DEBUG", "INFO",
"WARN", "ERROR"
), verbose = TRUE,
retcommand = FALSE, ...) {
assert_that(is_integer(port))
assert_that(is_string(version))
assert_that(is_logical(verbose))
loglevel <- match.arg(loglevel)
iecheck <- ie_check(verbose, check = check)
ieplat <- iecheck[["platform"]]
ieversion <- ie_ver(ieplat, version)
eopts <- list(...)
args <- c(Reduce(c, eopts[names(eopts) == "args"]))
args[["port"]] <- sprintf("/port=%s", port)
args[["log-level"]] <- sprintf("/log-level=%s", loglevel)
if (retcommand) {
return(paste(c(ieversion[["path"]], args), collapse = " "))
}
pfile <- pipe_files()
iedrv <- spawn_tofile(
ieversion[["path"]],
args, pfile[["out"]], pfile[["err"]]
)
if (isFALSE(iedrv$is_alive())) {
err <- paste0(readLines(pfile[["err"]]), collapse = "\n")
stop("iedriver couldn't be started\n", err)
}
startlog <- generic_start_log(iedrv,
outfile = pfile[["out"]],
errfile = pfile[["err"]]
)
if (length(startlog[["stderr"]]) > 0) {
if (any(grepl("Address already in use", startlog[["stderr"]]))) {
kill_process(iedrv)
stop("IE Driver signals port = ", port, " is already in use.")
}
}
log <- as.environment(startlog)
list(
process = iedrv,
output = function(timeout = 0L) {
infun_read(iedrv, log, "stdout",
timeout = timeout,
outfile = pfile[["out"]], errfile = pfile[["err"]]
)
},
error = function(timeout = 0L) {
infun_read(iedrv, log, "stderr",
timeout = timeout,
outfile = pfile[["out"]], errfile = pfile[["err"]]
)
},
stop = function() {
kill_process(iedrv)
},
log = function() {
infun_read(iedrv, log, outfile = pfile[["out"]], errfile = pfile[["err"]])
as.list(log)
}
)
}
ie_check <- function(verbose, check = TRUE) {
ieyml <- system.file("yaml", "iedriverserver.yml", package = "wdman")
iyml <- yaml::yaml.load_file(ieyml)
platvec <- c(
"predlfunction", "binman::predl_google_storage",
"platform", "platformregex"
)
platmatch <-
switch(Sys.info()["sysname"],
Windows = grep(os_arch("win"), iyml[[platvec[-4]]]),
stop("IEDriverServer not available for this platform")
)
iyml[[platvec[-4]]] <- iyml[[platvec[-4]]][platmatch]
iyml[[platvec[-3]]] <- iyml[[platvec[-3]]][platmatch]
tempyml <- tempfile(fileext = ".yml")
write(yaml::as.yaml(iyml), tempyml)
if (check) {
if (verbose) message("checking iedriver versions:")
process_yaml(tempyml, verbose)
}
ieplat <- iyml[[platvec[-4]]]
list(yaml = iyml, platform = ieplat)
}
ie_ver <- function(platform, version) {
iever <- binman::list_versions("iedriverserver")[[platform]]
iever <- if (identical(version, "latest")) {
as.character(max(semver::parse_version(iever)))
} else {
mtch <- match(version, iever)
if (is.na(mtch) || is.null(mtch)) {
stop(
"version requested doesnt match versions available = ",
paste(iever, collapse = ",")
)
}
iever[mtch]
}
iedir <- normalizePath(
file.path(app_dir("iedriverserver"), platform, iever)
)
iepath <- list.files(iedir,
pattern = "IEDriverServer($|.exe$)",
full.names = TRUE
)
list(version = iever, dir = iedir, path = iepath)
}
|
/scratch/gouwar.j/cran-all/cranData/wdman/R/iedriver.R
|
#' Start phantomjs
#'
#' Start phantomjs in webdriver mode
#' @param port Port to run on
#' @param version what version of phantomjs to run. Default = "2.2.1"
#' which runs the most recent stable version. To see other version currently
#' sourced run binman::list_versions("phantomjs")
#' @param loglevel Set phantomjs log level [values: fatal, error,
#' warn, info, config, debug, trace]
#' @param check If TRUE check the versions of phantomjs available. If
#' new versions are available they will be downloaded.
#' @param verbose If TRUE, include status messages (if any)
#' @param retcommand If TRUE return only the command that would be passed
#' to \code{\link[processx]{process}}
#' @param ... pass additional options to the driver
#'
#' @return Returns a list with named elements \code{process}, \code{output},
#' \code{error}, \code{stop}, and \code{log}.
#' \code{process} is the object from calling \code{\link[processx]{process}}.
#' \code{output} and \code{error} are the functions reading the latest
#' messages from "stdout" and "stderr" since the last call whereas \code{log}
#' is the function that reads all messages.
#' Lastly, \code{stop} call the \code{kill} method in
#' \code{\link[processx]{process}} to the kill the \code{process}.
#' @export
#'
#' @examples
#' \dontrun{
#' pjs <- phantomjs()
#' pjs$output()
#' pjs$stop()
#' }
#'
phantomjs <- function(port = 4567L, version = "2.1.1", check = TRUE,
loglevel = c("INFO", "ERROR", "WARN", "DEBUG"),
verbose = TRUE, retcommand = FALSE, ...) {
warning(
"PhantomJS development is suspended until further notice: ",
"https://github.com/ariya/phantomjs/issues/15344"
)
assert_that(is_integer(port))
assert_that(is_string(version))
assert_that(is_logical(verbose))
loglevel <- match.arg(loglevel)
phantomcheck <- phantom_check(verbose, check = check)
phantomplat <- phantomcheck[["platform"]]
phantomversion <- phantom_ver(phantomplat, version)
eopts <- list(...)
args <- c(Reduce(c, eopts[names(eopts) == "args"]))
args[["webdriver"]] <- sprintf("--webdriver=%s", port)
args[["log-level"]] <- sprintf("--webdriver-loglevel=%s", loglevel)
if (retcommand) {
return(paste(c(phantomversion[["path"]], args), collapse = " "))
}
pfile <- pipe_files()
phantomdrv <- spawn_tofile(
phantomversion[["path"]],
args, pfile[["out"]], pfile[["err"]]
)
if (isFALSE(phantomdrv$is_alive())) {
err <- paste0(readLines(pfile[["err"]]), collapse = "\n")
stop("PhantomJS couldn't be started\n", err)
}
startlog <- generic_start_log(phantomdrv,
outfile = pfile[["out"]],
errfile = pfile[["err"]]
)
if (length(startlog[["stdout"]]) > 0) {
if (any(
grepl("GhostDriver - main.fail.*sourceURL", startlog[["stdout"]])
)) {
kill_process(phantomdrv)
stop("PhantomJS signals port = ", port, " is already in use.")
}
}
log <- as.environment(startlog)
list(
process = phantomdrv,
output = function(timeout = 0L) {
infun_read(phantomdrv, log, "stdout",
timeout = timeout,
outfile = pfile[["out"]], errfile = pfile[["err"]]
)
},
error = function(timeout = 0L) {
infun_read(phantomdrv, log, "stderr",
timeout = timeout,
outfile = pfile[["out"]], errfile = pfile[["err"]]
)
},
stop = function() {
kill_process(phantomdrv)
},
log = function() {
infun_read(phantomdrv, log,
outfile = pfile[["out"]], errfile = pfile[["err"]]
)
as.list(log)
}
)
}
phantom_check <- function(verbose, check = TRUE) {
phantomyml <- system.file("yaml", "phantomjs.yml", package = "wdman")
pjsyml <- yaml::yaml.load_file(phantomyml)
platvec <- c(
"predlfunction", "binman::predl_bitbucket_downloads",
"platform", "platformregex"
)
platmatch <-
switch(Sys.info()["sysname"],
Linux = grep(os_arch("linux"), pjsyml[[platvec[-4]]]),
Windows = grep("win", pjsyml[[platvec[-4]]]),
Darwin = grep("mac", pjsyml[[platvec[-4]]]),
stop("Unknown OS")
)
pjsyml[[platvec[-4]]] <- pjsyml[[platvec[-4]]][platmatch]
pjsyml[[platvec[-3]]] <- pjsyml[[platvec[-3]]][platmatch]
tempyml <- tempfile(fileext = ".yml")
write(yaml::as.yaml(pjsyml), tempyml)
if (check) {
if (verbose) message("checking phantomjs versions:")
process_yaml(tempyml, verbose)
}
phantomplat <- pjsyml[[platvec[-4]]]
list(yaml = pjsyml, platform = phantomplat)
}
phantom_ver <- function(platform, version) {
phantomver <- binman::list_versions("phantomjs")[[platform]]
phantomver <- if (identical(version, "latest")) {
as.character(max(semver::parse_version(phantomver)))
} else {
mtch <- match(version, phantomver)
if (is.na(mtch) || is.null(mtch)) {
stop(
"version requested doesnt match versions available = ",
paste(phantomver, collapse = ",")
)
}
phantomver[mtch]
}
phantomdir <- normalizePath(
file.path(app_dir("phantomjs"), platform, phantomver)
)
phantompath <- list.files(phantomdir,
pattern = "phantomjs($|\\.exe$)",
recursive = TRUE,
full.names = TRUE
)
if (file.access(phantompath, 1) < 0) {
Sys.chmod(phantompath, "0755")
}
list(version = phantomver, dir = phantomdir, path = phantompath)
}
|
/scratch/gouwar.j/cran-all/cranData/wdman/R/phantom.R
|
#' Start Selenium Server
#'
#' Start Selenium Server
#' @param port Port to run on
#' @param version what version of Selenium Server to run. Default = "latest"
#' which runs the most recent version. To see other version currently
#' sourced run binman::list_versions("seleniumserver")
#' @param chromever what version of Chrome driver to run. Default = "latest"
#' which runs the most recent version. To see other version currently
#' sourced run binman::list_versions("chromedriver"), A value of NULL
#' excludes adding the chrome browser to Selenium Server.
#' @param geckover what version of Gecko driver to run. Default = "latest"
#' which runs the most recent version. To see other version currently
#' sourced run binman::list_versions("geckodriver"), A value of NULL
#' excludes adding the firefox browser to Selenium Server.
#' @param phantomver what version of PhantomJS to run. Default = "2.2.1"
#' which runs the most recent stable version. To see other version
#' currently
#' sourced run binman::list_versions("phantomjs"), A value of NULL
#' excludes adding the PhantomJS headless browser to Selenium Server.
#' @param iedrver what version of IEDriverServer to run. Default = "latest"
#' which runs the most recent version. To see other version currently
#' sourced run binman::list_versions("iedriverserver"), A value of NULL
#' excludes adding the internet explorer browser to Selenium Server.
#' NOTE this functionality is Windows OS only.
#' @param check If TRUE check the versions of selenium available and the
#' versions of associated drivers (chromever, geckover, phantomver,
#' iedrver). If new versions are available they will be downloaded.
#' @param verbose If TRUE, include status messages (if any)
#' @param retcommand If TRUE return only the command that would be passed
#' to \code{\link[processx]{process}}
#' @param ... pass additional options to the driver
#'
#' @return Returns a list with named elements \code{process}, \code{output},
#' \code{error}, \code{stop}, and \code{log}.
#' \code{process} is the object from calling \code{\link[processx]{process}}.
#' \code{output} and \code{error} are the functions reading the latest
#' messages from "stdout" and "stderr" since the last call whereas \code{log}
#' is the function that reads all messages.
#' Lastly, \code{stop} call the \code{kill} method in
#' \code{\link[processx]{process}} to the kill the \code{process}.
#' @export
#'
#' @examples
#' \dontrun{
#' selServ <- selenium()
#' selServ$output()
#' selServ$stop()
#' }
#'
selenium <- function(port = 4567L,
version = "latest",
chromever = "latest",
geckover = "latest",
iedrver = NULL,
phantomver = "2.1.1",
check = TRUE,
verbose = TRUE,
retcommand = FALSE,
...) {
assert_that(is_integer(port))
assert_that(is_string(version))
assert_that(is_string_or_null(chromever))
assert_that(is_string_or_null(geckover))
assert_that(is_string_or_null(phantomver))
assert_that(is_logical(retcommand))
assert_that(is_logical(verbose))
javapath <- java_check()
seleniumcheck <- selenium_check(verbose, check = check)
selplat <- seleniumcheck[["platform"]]
seleniumversion <- selenium_ver(selplat, version)
eopts <- list(...)
jvmargs <- c(Reduce(c, eopts[names(eopts) == "jvmargs"]))
selargs <- c(Reduce(c, eopts[names(eopts) == "selargs"]))
jvmargs <- selenium_check_drivers(chromever, geckover, phantomver,
iedrver,
check = check,
verbose = verbose, jvmargs
)
# should be the last JVM argument
jvmargs[["jar"]] <- "-jar"
jvmargs[["selpath"]] <- shQuote(seleniumversion[["path"]])
# Selenium JAR arguments
selargs[["portswitch"]] <- "-port"
selargs[["port"]] <- port
if (retcommand) {
return(paste(c(javapath, jvmargs, selargs), collapse = " "))
}
pfile <- pipe_files()
seleniumdrv <- spawn_tofile(javapath,
args = c(jvmargs, selargs),
pfile[["out"]], pfile[["err"]]
)
if (isFALSE(seleniumdrv$is_alive())) {
err <- paste0(readLines(pfile[["err"]]), collapse = "\n")
stop("Selenium server couldn't be started\n", err)
}
startlog <- generic_start_log(seleniumdrv, # poll = 10000L,
outfile = pfile[["out"]],
errfile = pfile[["err"]]
)
if (length(startlog[["stderr"]]) > 0) {
if (any(grepl("Address already in use", startlog[["stderr"]]))) {
kill_process(seleniumdrv)
stop("Selenium server signals port = ", port, " is already in use.")
}
} else {
warning(
"No output to stderr yet detected. Please check ",
"log and that process is running manually."
)
}
log <- as.environment(startlog)
list(
process = seleniumdrv,
output = function(timeout = 0L) {
infun_read(seleniumdrv, log, "stdout",
timeout = timeout,
outfile = pfile[["out"]], errfile = pfile[["err"]]
)
},
error = function(timeout = 0L) {
infun_read(seleniumdrv, log, "stderr",
timeout = timeout,
outfile = pfile[["out"]], errfile = pfile[["err"]]
)
},
stop = function() {
kill_process(seleniumdrv)
},
log = function() {
infun_read(seleniumdrv, log,
outfile = pfile[["out"]], errfile = pfile[["err"]]
)
as.list(log)
}
)
}
java_check <- function() {
javapath <- Sys.which("java")
if (identical(unname(javapath), "")) {
stop("PATH to JAVA not found. Please check JAVA is installed.")
}
javapath
}
selenium_check <- function(verbose, check = TRUE) {
syml <- system.file("yaml", "seleniumserver.yml", package = "wdman")
if (check) {
if (verbose) message("checking Selenium Server versions:")
process_yaml(syml, verbose)
}
selplat <- "generic"
list(yaml = syml, platform = selplat)
}
selenium_ver <- function(platform, version) {
selver <- binman::list_versions("seleniumserver")[[platform]]
selver <- if (identical(version, "latest")) {
as.character(max(semver::parse_version(selver)))
} else {
mtch <- match(version, selver)
if (is.na(mtch) || is.null(mtch)) {
stop(
"version requested doesnt match versions available = ",
paste(selver, collapse = ",")
)
}
selver[mtch]
}
seldir <- normalizePath(
file.path(app_dir("seleniumserver"), platform, selver)
)
selpath <- list.files(seldir,
pattern = "selenium-server-standalone",
full.names = TRUE
)
if (file.access(selpath, 1) < 0) {
Sys.chmod(selpath, "0755")
}
list(version = selver, dir = seldir, path = selpath)
}
selenium_check_drivers <- function(chromever, geckover, phantomver,
iedrver, check, verbose, jvmargs) {
if (!is.null(chromever)) {
chromecheck <- chrome_check(verbose, check)
cver <- chrome_ver(chromecheck[["platform"]], chromever)
jvmargs[["chrome"]] <- sprintf(
"-Dwebdriver.chrome.driver=%s",
shQuote(cver[["path"]])
)
}
if (!is.null(geckover)) {
geckocheck <- gecko_check(verbose, check)
gver <- gecko_ver(geckocheck[["platform"]], geckover)
jvmargs[["gecko"]] <- sprintf(
"-Dwebdriver.gecko.driver=%s",
shQuote(gver[["path"]])
)
}
if (!is.null(phantomver)) {
phantomcheck <- phantom_check(verbose, check)
pver <- phantom_ver(phantomcheck[["platform"]], phantomver)
jvmargs[["phantom"]] <- sprintf(
"-Dphantomjs.binary.path=%s",
shQuote(pver[["path"]])
)
}
if (!is.null(iedrver)) {
iecheck <- ie_check(verbose, check)
iever <- ie_ver(iecheck[["platform"]], iedrver)
jvmargs[["internetexplorer"]] <- sprintf(
"-Dwebdriver.ie.driver=%s",
shQuote(iever[["path"]])
)
}
jvmargs
}
|
/scratch/gouwar.j/cran-all/cranData/wdman/R/selenium.R
|
os_arch <- function(string = "") {
assert_that(is_string(string))
arch <- c("32", "64")[.Machine$sizeof.pointer / 4]
paste0(string, arch)
}
infun_read <- function(handle, env, pipe = "both",
timeout = 0L, outfile, errfile) {
msg <- read_pipes(env, outfile, errfile, pipe = pipe, timeout = timeout)
if (identical(pipe, "both")) {
env[["stdout"]] <- c(env[["stdout"]], msg[["stdout"]])
env[["stderr"]] <- c(env[["stderr"]], msg[["stderr"]])
}
if (identical(pipe, "stdout")) {
env[["stdout"]] <- c(env[["stdout"]], msg)
}
if (identical(pipe, "stderr")) {
env[["stderr"]] <- c(env[["stderr"]], msg)
}
msg
}
generic_start_log <- function(handle, poll = 3000L, increment = 500L,
outfile, errfile) {
startlog <- list(stdout = character(), stderr = character())
progress <- 0L
while (progress < poll) {
begin <- Sys.time()
errchk <- tryCatch(
{
read_pipes(startlog, outfile, errfile,
timeout = min(increment, poll)
)
},
error = function(e) {
e
}
)
end <- Sys.time()
progress <-
progress + min(as.numeric(end - begin) * 1000L, increment, poll)
startlog <- Map(c, startlog, errchk)
nocontent <- identical(unlist(errchk), character())
slcontent <- sum(vapply(startlog, length, integer(1)))
if (nocontent && slcontent > 0) {
break
}
}
startlog
}
`%+%` <- function(chr1, chr2) {
paste0(chr1, chr2)
}
read_pipes <- function(env, outfile, errfile, pipe = "both",
timeout) {
Sys.sleep(timeout / 1000)
outres <- readLines(outfile)
outres <- utils::tail(outres, length(outres) - length(env[["stdout"]]))
errres <- readLines(errfile)
errres <- utils::tail(errres, length(errres) - length(env[["stderr"]]))
if (identical(pipe, "both")) {
return(list(stdout = outres, stderr = errres))
}
if (identical(pipe, "stdout")) {
return(outres)
}
if (identical(pipe, "stderr")) {
return(errres)
}
}
unix_spawn_tofile <- function(command, args, outfile, errfile, ...) {
tfile <- tempfile(fileext = ".sh")
write("#!/bin/sh", tfile)
write(paste(c(
shQuote(command), args, ">",
shQuote(outfile), "2>", shQuote(errfile)
), collapse = " "),
tfile,
append = TRUE
)
Sys.chmod(tfile)
processx::process$new(tfile, cleanup_tree = TRUE)
}
windows_spawn_tofile <- function(command, args, outfile, errfile, ...) {
tfile <- tempfile(fileext = ".bat")
write(
paste(c(
shQuote(command), args, ">",
shQuote(outfile), "2>", shQuote(errfile)
), collapse = " "),
tfile
)
processx::process$new(tfile, cleanup_tree = TRUE)
}
spawn_tofile <- function(command, args, outfile, errfile, ...) {
if (identical(.Platform[["OS.type"]], "windows")) {
windows_spawn_tofile(command, args, outfile, errfile, ...)
} else {
unix_spawn_tofile(command, args, outfile, errfile, ...)
}
}
pipe_files <- function() {
errTfile <- tempfile(fileext = ".txt")
write(character(), errTfile)
outTfile <- tempfile(fileext = ".txt")
write(character(), outTfile)
list(out = outTfile, err = errTfile)
}
kill_process <- function(p) {
# Kill a process and all its child processes, returning true if process was
# killed and false if not
r <- p$kill()
p$kill_tree()
r
}
# Figure out if installing on an Intel or M1 mac
mac_machine <- function() {
ifelse(Sys.info()[["machine"]] == "arm64", "mac(64_|os-)", "mac(64|os)$")
}
|
/scratch/gouwar.j/cran-all/cranData/wdman/R/utils.R
|
#' @title wdman
#'
#' @description Webdriver/Selenium Binary Manager
#'
#' @details There are a number of binary files associated with the
#' Webdriver/Selenium project. This package provides functions to download
#' these binaries and to manage processes involving them.
#'
#' @name wdman
#' @importFrom assertthat assert_that
#' @importFrom binman process_yaml list_versions rm_platform
#' rm_version app_dir
#' @docType package
NULL
|
/scratch/gouwar.j/cran-all/cranData/wdman/R/wdman-package.r
|
---
title: "Basics"
author: "John D Harrison"
date: "`r Sys.Date()`"
output:
rmarkdown::html_vignette:
toc: true
toc_depth: 3
vignette: >
%\VignetteIndexEntry{Basics}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
The goal of this vignette is to describe the basic functionality of the `wdman` package.
## Introduction
`wdman` (Webdriver Manager) is an R package that allows the user to manage the downloading/running of third party binaries relating to the webdriver/selenium projects. The package was inspired by a similar node package [webdriver-manager](https://www.npmjs.com/package/webdriver-manager).
The checking/downloading of binaries is handled by the [binman](https://github.com/ropensci/binman) package and the running of the binaries as processes is handled by the [processx](https://processx.r-lib.org/) package.
The `wdman` package currently manages the following binaries:
* [Selenium standalone binary](http://selenium-release.storage.googleapis.com/index.html)
* [chromedriver](https://chromedriver.storage.googleapis.com/index.html)
* [PhantomJS binary](https://phantomjs.org/download.html)
* [geckodriver](https://github.com/mozilla/geckodriver/releases)
* [iedriver](https://github.com/SeleniumHQ/selenium/wiki/InternetExplorerDriver)
Associated with the above are five functions to download/manage the binaries:
* `selenium(...)`
* `chrome(...)`
* `phantomjs(...)`
* `gecko(...)`
* `iedriver(...)`
The driver functions take a number of common arguments (verbose, check, retcommand) which we describe:
### Verbosity
Each of the driver functions has a `verbose` argument which controls message output to the user. If `verbose = TRUE` then messages are relayed to the user to inform them when drivers are checked/downloaded/ran. The default value for the driver functions is `TRUE`.
```R
selServ <- selenium(verbose = TRUE)
```
```
## checking Selenium Server versions:
## BEGIN: PREDOWNLOAD
## BEGIN: DOWNLOAD
## BEGIN: POSTDOWNLOAD
## checking chromedriver versions:
## BEGIN: PREDOWNLOAD
## BEGIN: DOWNLOAD
## BEGIN: POSTDOWNLOAD
## checking geckodriver versions:
## BEGIN: PREDOWNLOAD
## BEGIN: DOWNLOAD
## BEGIN: POSTDOWNLOAD
## checking phantomjs versions:
## BEGIN: PREDOWNLOAD
## BEGIN: DOWNLOAD
## BEGIN: POSTDOWNLOAD
selServ$stop()
## TRUE
```
versus's
```R
selServ <- selenium(verbose = FALSE)
selServ$stop()
```
```
## TRUE
```
### Check for updates
Each driver function has a `check` argument. If `check= TRUE` the function will liaise with the driver repository for any updates. If new
driver versions are available these will be downloaded. The [binman](https://github.com/ropensci/binman) package is used for this purpose.
### Command line output
For diagnostic purposes each driver function has a `retcommand` argument. If `retcommand = TRUE` the command that would have been launched as a process is instead returned as a string. As an example:
```R
selCommand <- selenium(retcommand = TRUE, verbose = FALSE, check = FALSE)
selCommand
```
```
## [1] "/usr/bin/java -Dwebdriver.chrome.driver='/Users/jkim/Library/Application Support/binman_chromedriver/mac64/80.0.3987.16/chromedriver' -Dwebdriver.gecko.driver='/Users/jkim/Library/Application Support/binman_geckodriver/macos/0.26.0/geckodriver' -Dphantomjs.binary.path='/Users/jkim/Library/Application Support/binman_phantomjs/macosx/2.1.1/phantomjs-2.1.1-macosx/bin/phantomjs' -jar '/Users/jkim/Library/Application Support/binman_seleniumserver/generic/4.0.0-alpha-2/selenium-server-standalone-4.0.0-alpha-2.jar' -port 4567"
```
```R
chromeCommand <- chrome(retcommand = TRUE, verbose = FALSE, check = FALSE)
chromeCommand
```
```
## [1] "/Users/jkim/Library/Application Support/binman_chromedriver/mac64/80.0.3987.16/chromedriver --port=4567 --url-base=wd/hub --verbose"
```
## Selenium Standalone
The `selenium` function manages the Selenium Standalone binary. It can check for updates at http://selenium-release.storage.googleapis.com/index.html and run the resulting binaries as processes.
### Running the Selenium binary
The binary takes a port argument which defaults to `port = 4567L`. There are a number of optional arguments to use a particular version of the binaries related to browsers selenium may control. By default the `selenium` function will look to use the latest version of each.
```R
selServ <- selenium(verbose = FALSE, check = FALSE)
selServ$process
```
```
## PROCESS 'file50e6163b37b8.sh', running, pid 21289.
```
The selenium function returns a list of functions and a handle representing the running process.
The returned `output`, `error` and `log` functions give access to the stdout/stderr pipes and the cumulative stdout/stderr messages respectively.
```R
selServ$log()
```
```
## $stderr
## [1] "13:25:51.744 INFO [GridLauncherV3.parse] - Selenium server version: 4.0.0-alpha-2, revision: f148142cf8"
## [2] "13:25:52.174 INFO [GridLauncherV3.lambda$buildLaunchers$3] - Launching a standalone Selenium Server on port 4567"
## [3] "13:25:54.018 INFO [WebDriverServlet.<init>] - Initialising WebDriverServlet"
## [4] "13:25:54.539 INFO [SeleniumServer.boot] - Selenium Server is up and running on port 4567"
## $stdout
## character(0)
```
The `stop` function sends a signal that terminates the process:
```R
selServ$stop()
```
```
## TRUE
```
### Available browsers
By default the `selenium` function includes paths to chromedriver/geckodriver/ phantomjs so that the Chrome/Firefox and PhantomJS browsers are available respectively. All versions (chromever, geckover etc) are given as "latest". If the user passes a value of NULL for any driver, it will be excluded.
On Windows operating systems the option to included the Internet Explorer driver is also given. This is set to `iedrver = NULL` so not ran by default. Set it to `iedrver = "latest"` or a specific version string to include it on your Windows.
## Chrome Driver
The `chrome` function manages the Chrome Driver binary. It can check for updates at https://chromedriver.storage.googleapis.com/index.html
and run the resulting binaries as processes.
**The `chrome` function runs the Chrome Driver binary as a standalone process. It takes a default `port` argument `port = 4567L`. Users can then connect directly to the chrome driver to drive a chrome browser.**
Similarly to the `selenium` function, the `chrome` function returns a list of four functions and a handle to the underlying running process.
```R
cDrv <- chrome(verbose = FALSE, check = FALSE)
cDrv$process
```
```
## PROCESS 'file534c4e940dd8.sh', running, pid 21386.
```
```R
cDrv$log()
```
```
## $stderr
## character(0)
## $stdout
## [1] "Starting ChromeDriver 80.0.3987.16 (320f6526c1632ad4f205ebce69b99a062ed78647-refs/branch-heads/3987@{#185}) on port 4567"
## [2] "Only local connections are allowed."
## [3] "Please protect ports used by ChromeDriver and related test frameworks to prevent access by malicious code."
```
```R
cDrv$stop()
```
```
## TRUE
```
## PhantomJS
The `phantomjs` function manages the PhantomJS binary. It can check for updates at https://bitbucket.org/ariya/phantomjs/downloads and run the resulting binaries as processes.
**The `phantomjs` function runs the PhantomJS binary as a standalone process in webdriver mode. It takes a default `port` argument `port = 4567L`. Users can then connect directly to the "ghostdriver" to drive a PhantomJS browser. Currently the default `version` is set to `version = "2.1.1"`. At the time of writing `2.5.0-beta` has been released. It currently does not have an up-to-date version of ghostdriver associated with it. For this reason it will be unstable/unpredictable to use it in webdriver mode. **
Similarly to the `selenium` function, the `phantomjs` function returns a list of four functions and a handle to the underlying running process.
```R
pjsDrv <- phantomjs(verbose = FALSE, check = FALSE)
pjsDrv$process
```
```
## PROCESS 'file5394b74d790.sh', running, pid 21443.
```
```R
pjsDrv$log()
```
```
## $stderr
## character(0)
## $stdout
## [1] "[INFO - 2020-01-31T21:32:04.538Z] GhostDriver - Main - running on port 4567"
```
```R
pjsDrv$stop()
```
```
## TRUE
```
## Gecko Driver
The `gecko` function manages the Gecko Driver binary. It can check for updates at https://github.com/mozilla/geckodriver/releases and run the resulting binaries as processes.
**The `gecko` function runs the Gecko Driver binary as a standalone process. It takes a default `port` argument `port = 4567L`. Users can then connect directly to the gecko driver to drive a firefox browser. Currently the default `version` is set to `version = "2.1.1"`.**
**A very IMPORTANT point to note is that geckodriver implements the W3C webdriver protocol which as at the time of writing is not finalised. Currently packages such as RSelenium implement the JSONwireprotocol which whilst similar expects different return from the underlying driver.**
**The geckodriver implementation like the W3C webdriver specification is incomplete at this point in time.**
Similarly to the `selenium` function, the `gecko` function returns a list of four functions and a handle to the underlying running process.
```R
gDrv <- gecko(verbose = FALSE, check = FALSE)
gDrv$process
```
```
## PROCESS 'file53946017eccb.sh', running, pid 21458.
```
```R
gDrv$log()
```
```
## $stderr
## character(0)
## $stdout
## character(0)
```
```R
gDrv$stop()
## TRUE
```
## IE Driver
The `iedriver` function manages the Internet Explorer Driver binary. It can check for updates at http://selenium-release.storage.googleapis.com/index.html
and run the resulting binaries as processes (the iedriver is distributed currently with the Selenium standalone binary amongst other files).
**The `chrome` function runs the Chrome Driver binary as a standalone process. It takes a default `port` argument `port = 4567L`. Users can then connect directly to the chrome driver to drive a chrome browser.**
**Please note that additional settings are required to drive an Internet Explorer browser. Security settings and zoom level need to be set correctly in the browser. The author of this document needed to set a registry entry (for ie 11). This is outlined at https://github.com/SeleniumHQ/selenium/wiki/InternetExplorerDriver in the required configuration section.**
Similarly to the `selenium` function the `gecko` function returns a list of four functions and a handle to the underlying running process.
```R
ieDrv <- iedriver(verbose = FALSE, check = FALSE)
ieDrv$process
```
```
## Process Handle
## command : C:\Users\john\AppData\Local\binman\binman_iedriverserver\win64\3.0.0\IEDriverServer.exe /port=4567 /log-level=FATAL /log-file=C:\Users\john\AppData\Local\Temp\RtmpqSdw94\file5247395f2a.txt
## system id : 7484
## state : running
```
```R
ieDrv$log()
```
```
## $stderr
## character(0)
##
## $stdout
## [1] "Started InternetExplorerDriver server (64-bit)"
## [2] "3.0.0.0"
## [3] "Listening on port 4567"
## [4] "Log level is set to FATAL"
## [5] "Log file is set to C:\\Users\\john\\AppData\\Local\\Temp\\RtmpqSdw94\\file5247395f2a.txt"
## [6] "Only local connections are allowed"
```
```R
ieDrv$stop()
```
```
## [1] TRUE
```
## Issues and problems
If you experience issues or problems running one of the drivers/functions, please try running the command in a terminal on your OS initially. You can access the command to run by using the `retcommand` argument in each of the main package functions. If you continue to have problems, consider posting an issue at https://github.com/ropensci/wdman/issues
|
/scratch/gouwar.j/cran-all/cranData/wdman/inst/doc/basics.Rmd
|
library(wdman)
tries <- list()
tries$chrome <- tryCatch({
print("chrome")
tmp <- chrome(verbose = TRUE)
print(tmp$log())
tmp$stop()
tmp
}, error = function(e) {print(e$message); e})
tries$gecko <- tryCatch({
print("gecko")
tmp <- gecko(verbose = TRUE)
print(tmp$log())
tmp$stop()
tmp
}, error = function(e) {print(e$message); e})
tries$phantomjs <- tryCatch({
print("phantomjs")
tmp <- phantomjs(verbose = TRUE)
print(tmp$log())
tmp$stop()
tmp
}, error = function(e) {print(e$message); e})
if (Sys.info()[["sysname"]] == "Windows") {
tries$iedriver <- tryCatch({
print("iedriver")
tmp <- iedriver(verbose = TRUE)
print(tmp$log())
tmp$stop()
tmp
}, error = function(e) {print(e$message); e})
}
tries$selenium <- tryCatch({
print("selenium")
tmp <- selenium(verbose = TRUE)
print(tmp$log())
tmp$stop()
tmp
}, error = function(e) {print(e$message); e})
errors <- sapply(tries, function(x) is(x, "simpleError"))
if (any(errors)) {
stop("Failing ", paste(names(errors[errors]), collapse = ", "))
}
|
/scratch/gouwar.j/cran-all/cranData/wdman/inst/etc/checks.R
|
---
title: "Basics"
author: "John D Harrison"
date: "`r Sys.Date()`"
output:
rmarkdown::html_vignette:
toc: true
toc_depth: 3
vignette: >
%\VignetteIndexEntry{Basics}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
The goal of this vignette is to describe the basic functionality of the `wdman` package.
## Introduction
`wdman` (Webdriver Manager) is an R package that allows the user to manage the downloading/running of third party binaries relating to the webdriver/selenium projects. The package was inspired by a similar node package [webdriver-manager](https://www.npmjs.com/package/webdriver-manager).
The checking/downloading of binaries is handled by the [binman](https://github.com/ropensci/binman) package and the running of the binaries as processes is handled by the [processx](https://processx.r-lib.org/) package.
The `wdman` package currently manages the following binaries:
* [Selenium standalone binary](http://selenium-release.storage.googleapis.com/index.html)
* [chromedriver](https://chromedriver.storage.googleapis.com/index.html)
* [PhantomJS binary](https://phantomjs.org/download.html)
* [geckodriver](https://github.com/mozilla/geckodriver/releases)
* [iedriver](https://github.com/SeleniumHQ/selenium/wiki/InternetExplorerDriver)
Associated with the above are five functions to download/manage the binaries:
* `selenium(...)`
* `chrome(...)`
* `phantomjs(...)`
* `gecko(...)`
* `iedriver(...)`
The driver functions take a number of common arguments (verbose, check, retcommand) which we describe:
### Verbosity
Each of the driver functions has a `verbose` argument which controls message output to the user. If `verbose = TRUE` then messages are relayed to the user to inform them when drivers are checked/downloaded/ran. The default value for the driver functions is `TRUE`.
```R
selServ <- selenium(verbose = TRUE)
```
```
## checking Selenium Server versions:
## BEGIN: PREDOWNLOAD
## BEGIN: DOWNLOAD
## BEGIN: POSTDOWNLOAD
## checking chromedriver versions:
## BEGIN: PREDOWNLOAD
## BEGIN: DOWNLOAD
## BEGIN: POSTDOWNLOAD
## checking geckodriver versions:
## BEGIN: PREDOWNLOAD
## BEGIN: DOWNLOAD
## BEGIN: POSTDOWNLOAD
## checking phantomjs versions:
## BEGIN: PREDOWNLOAD
## BEGIN: DOWNLOAD
## BEGIN: POSTDOWNLOAD
selServ$stop()
## TRUE
```
versus's
```R
selServ <- selenium(verbose = FALSE)
selServ$stop()
```
```
## TRUE
```
### Check for updates
Each driver function has a `check` argument. If `check= TRUE` the function will liaise with the driver repository for any updates. If new
driver versions are available these will be downloaded. The [binman](https://github.com/ropensci/binman) package is used for this purpose.
### Command line output
For diagnostic purposes each driver function has a `retcommand` argument. If `retcommand = TRUE` the command that would have been launched as a process is instead returned as a string. As an example:
```R
selCommand <- selenium(retcommand = TRUE, verbose = FALSE, check = FALSE)
selCommand
```
```
## [1] "/usr/bin/java -Dwebdriver.chrome.driver='/Users/jkim/Library/Application Support/binman_chromedriver/mac64/80.0.3987.16/chromedriver' -Dwebdriver.gecko.driver='/Users/jkim/Library/Application Support/binman_geckodriver/macos/0.26.0/geckodriver' -Dphantomjs.binary.path='/Users/jkim/Library/Application Support/binman_phantomjs/macosx/2.1.1/phantomjs-2.1.1-macosx/bin/phantomjs' -jar '/Users/jkim/Library/Application Support/binman_seleniumserver/generic/4.0.0-alpha-2/selenium-server-standalone-4.0.0-alpha-2.jar' -port 4567"
```
```R
chromeCommand <- chrome(retcommand = TRUE, verbose = FALSE, check = FALSE)
chromeCommand
```
```
## [1] "/Users/jkim/Library/Application Support/binman_chromedriver/mac64/80.0.3987.16/chromedriver --port=4567 --url-base=wd/hub --verbose"
```
## Selenium Standalone
The `selenium` function manages the Selenium Standalone binary. It can check for updates at http://selenium-release.storage.googleapis.com/index.html and run the resulting binaries as processes.
### Running the Selenium binary
The binary takes a port argument which defaults to `port = 4567L`. There are a number of optional arguments to use a particular version of the binaries related to browsers selenium may control. By default the `selenium` function will look to use the latest version of each.
```R
selServ <- selenium(verbose = FALSE, check = FALSE)
selServ$process
```
```
## PROCESS 'file50e6163b37b8.sh', running, pid 21289.
```
The selenium function returns a list of functions and a handle representing the running process.
The returned `output`, `error` and `log` functions give access to the stdout/stderr pipes and the cumulative stdout/stderr messages respectively.
```R
selServ$log()
```
```
## $stderr
## [1] "13:25:51.744 INFO [GridLauncherV3.parse] - Selenium server version: 4.0.0-alpha-2, revision: f148142cf8"
## [2] "13:25:52.174 INFO [GridLauncherV3.lambda$buildLaunchers$3] - Launching a standalone Selenium Server on port 4567"
## [3] "13:25:54.018 INFO [WebDriverServlet.<init>] - Initialising WebDriverServlet"
## [4] "13:25:54.539 INFO [SeleniumServer.boot] - Selenium Server is up and running on port 4567"
## $stdout
## character(0)
```
The `stop` function sends a signal that terminates the process:
```R
selServ$stop()
```
```
## TRUE
```
### Available browsers
By default the `selenium` function includes paths to chromedriver/geckodriver/ phantomjs so that the Chrome/Firefox and PhantomJS browsers are available respectively. All versions (chromever, geckover etc) are given as "latest". If the user passes a value of NULL for any driver, it will be excluded.
On Windows operating systems the option to included the Internet Explorer driver is also given. This is set to `iedrver = NULL` so not ran by default. Set it to `iedrver = "latest"` or a specific version string to include it on your Windows.
## Chrome Driver
The `chrome` function manages the Chrome Driver binary. It can check for updates at https://chromedriver.storage.googleapis.com/index.html
and run the resulting binaries as processes.
**The `chrome` function runs the Chrome Driver binary as a standalone process. It takes a default `port` argument `port = 4567L`. Users can then connect directly to the chrome driver to drive a chrome browser.**
Similarly to the `selenium` function, the `chrome` function returns a list of four functions and a handle to the underlying running process.
```R
cDrv <- chrome(verbose = FALSE, check = FALSE)
cDrv$process
```
```
## PROCESS 'file534c4e940dd8.sh', running, pid 21386.
```
```R
cDrv$log()
```
```
## $stderr
## character(0)
## $stdout
## [1] "Starting ChromeDriver 80.0.3987.16 (320f6526c1632ad4f205ebce69b99a062ed78647-refs/branch-heads/3987@{#185}) on port 4567"
## [2] "Only local connections are allowed."
## [3] "Please protect ports used by ChromeDriver and related test frameworks to prevent access by malicious code."
```
```R
cDrv$stop()
```
```
## TRUE
```
## PhantomJS
The `phantomjs` function manages the PhantomJS binary. It can check for updates at https://bitbucket.org/ariya/phantomjs/downloads and run the resulting binaries as processes.
**The `phantomjs` function runs the PhantomJS binary as a standalone process in webdriver mode. It takes a default `port` argument `port = 4567L`. Users can then connect directly to the "ghostdriver" to drive a PhantomJS browser. Currently the default `version` is set to `version = "2.1.1"`. At the time of writing `2.5.0-beta` has been released. It currently does not have an up-to-date version of ghostdriver associated with it. For this reason it will be unstable/unpredictable to use it in webdriver mode. **
Similarly to the `selenium` function, the `phantomjs` function returns a list of four functions and a handle to the underlying running process.
```R
pjsDrv <- phantomjs(verbose = FALSE, check = FALSE)
pjsDrv$process
```
```
## PROCESS 'file5394b74d790.sh', running, pid 21443.
```
```R
pjsDrv$log()
```
```
## $stderr
## character(0)
## $stdout
## [1] "[INFO - 2020-01-31T21:32:04.538Z] GhostDriver - Main - running on port 4567"
```
```R
pjsDrv$stop()
```
```
## TRUE
```
## Gecko Driver
The `gecko` function manages the Gecko Driver binary. It can check for updates at https://github.com/mozilla/geckodriver/releases and run the resulting binaries as processes.
**The `gecko` function runs the Gecko Driver binary as a standalone process. It takes a default `port` argument `port = 4567L`. Users can then connect directly to the gecko driver to drive a firefox browser. Currently the default `version` is set to `version = "2.1.1"`.**
**A very IMPORTANT point to note is that geckodriver implements the W3C webdriver protocol which as at the time of writing is not finalised. Currently packages such as RSelenium implement the JSONwireprotocol which whilst similar expects different return from the underlying driver.**
**The geckodriver implementation like the W3C webdriver specification is incomplete at this point in time.**
Similarly to the `selenium` function, the `gecko` function returns a list of four functions and a handle to the underlying running process.
```R
gDrv <- gecko(verbose = FALSE, check = FALSE)
gDrv$process
```
```
## PROCESS 'file53946017eccb.sh', running, pid 21458.
```
```R
gDrv$log()
```
```
## $stderr
## character(0)
## $stdout
## character(0)
```
```R
gDrv$stop()
## TRUE
```
## IE Driver
The `iedriver` function manages the Internet Explorer Driver binary. It can check for updates at http://selenium-release.storage.googleapis.com/index.html
and run the resulting binaries as processes (the iedriver is distributed currently with the Selenium standalone binary amongst other files).
**The `chrome` function runs the Chrome Driver binary as a standalone process. It takes a default `port` argument `port = 4567L`. Users can then connect directly to the chrome driver to drive a chrome browser.**
**Please note that additional settings are required to drive an Internet Explorer browser. Security settings and zoom level need to be set correctly in the browser. The author of this document needed to set a registry entry (for ie 11). This is outlined at https://github.com/SeleniumHQ/selenium/wiki/InternetExplorerDriver in the required configuration section.**
Similarly to the `selenium` function the `gecko` function returns a list of four functions and a handle to the underlying running process.
```R
ieDrv <- iedriver(verbose = FALSE, check = FALSE)
ieDrv$process
```
```
## Process Handle
## command : C:\Users\john\AppData\Local\binman\binman_iedriverserver\win64\3.0.0\IEDriverServer.exe /port=4567 /log-level=FATAL /log-file=C:\Users\john\AppData\Local\Temp\RtmpqSdw94\file5247395f2a.txt
## system id : 7484
## state : running
```
```R
ieDrv$log()
```
```
## $stderr
## character(0)
##
## $stdout
## [1] "Started InternetExplorerDriver server (64-bit)"
## [2] "3.0.0.0"
## [3] "Listening on port 4567"
## [4] "Log level is set to FATAL"
## [5] "Log file is set to C:\\Users\\john\\AppData\\Local\\Temp\\RtmpqSdw94\\file5247395f2a.txt"
## [6] "Only local connections are allowed"
```
```R
ieDrv$stop()
```
```
## [1] TRUE
```
## Issues and problems
If you experience issues or problems running one of the drivers/functions, please try running the command in a terminal on your OS initially. You can access the command to run by using the `retcommand` argument in each of the main package functions. If you continue to have problems, consider posting an issue at https://github.com/ropensci/wdman/issues
|
/scratch/gouwar.j/cran-all/cranData/wdman/vignettes/basics.Rmd
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.