content
stringlengths
0
14.9M
filename
stringlengths
44
136
## fitStahl.R #' Calculate log likelihood for Stahl model #' #' Calculate the log likelihood for the Stahl model for varying parameters, #' with data on crossover locations. #' #' See Housworth and Stahl (2003) and Broman and Weber (2000) for details of #' the method. #' #' If neither `nu` nor `p` has length 1, they both must have the same #' length. If one has length 1 and the other does not, the one with length 1 #' is repeated so that they both have the same length. #' #' @param xoloc A list of crossover locations (in cM), each component being a #' vector of locations for a different meiotic product. #' @param chrlen Chromosome length (in cM), either of length 1 or the same #' length as `xoloc`. #' @param nu A vector of interference parameters (\eqn{\nu}{nu}) at which to #' calculate the log likelihood. #' @param p A vector of parameter values for the proportion of crossovers from #' the no interference pathway. #' @param max.conv Maximum limit for summation in the convolutions to get #' inter-crossover distance distribution from the inter-chiasma distance #' distributions. This should be greater than the maximum number of chiasmata #' on the 4-strand bundle. #' @param integr.tol Tolerance for convergence of numerical integration. #' @param max.subd Maximum number of subdivisions in numerical integration. #' @param min.subd Minimum number of subdivisions in numerical integration. #' @return A vector of log likelihoods. #' #' The corresponding values of nu and p are saved as attributes. #' @author Karl W Broman, \email{broman@@wisc.edu} #' @seealso [qtl::fitstahl()] #' @references Housworth, E. A. and Stahl, F. W. (2003) Crossover interference #' in humans. *Am. J. Hum. Genet.* **73**, 188--197. #' #' Broman, K. W. and Weber, J. L. (2000) Characterization of human crossover #' interference. *Am. J. Hum. Genet.* **66**, 1911--1926. #' @keywords models #' @examples #' #' data(bssbsb) #' xoloc <- find.breaks(bssbsb, chr=1) #' #' loglik <- stahlLoglik(xoloc, nu=4, p=c(0.05, 0.1, 0.15)) #' #' @useDynLib xoi, .registration=TRUE #' @export stahlLoglik <- function(xoloc, chrlen=NULL, nu, p, max.conv=25, integr.tol=1e-8, max.subd=1000, min.subd=10) { if(is.data.frame(xoloc)) stop("xoloc should not be a data.frame.") if(!is.list(xoloc)) stop("xoloc should be a list.") if(is.null(chrlen) && "L" %in% names(attributes(xoloc))) chrlen <- attr(xoloc, "L") if(length(chrlen) == 1) { chrlen <- rep(chrlen, length(xoloc)) constant.chrlen <- TRUE } else { constant.chrlen <- FALSE if(length(chrlen) != length(xoloc)) stop("chrlen should have length 1 or the same as length(xoloc).") } if(length(nu)==1) { if(length(p) > 1) nu <- rep(nu, length(p)) } else { if(length(p)==1) p <- rep(p, length(nu)) else if(length(p) != length(nu)) stop("nu and p should be the same length (though either can have length 1).") } flag <- 0 for(i in seq(along=xoloc)) { thisxoloc <- unlist(xoloc[[i]]) if(any(thisxoloc < 0 | thisxoloc > chrlen[i])) { flag <- 1 break } } if(flag) stop("xoloc should be between 0 and chrlen.") # intercross? then send to stahlLoglikF2 if(is.list(xoloc[[1]])) return(stahlLoglikF2(xoloc, chrlen, nu, p, max.conv, integr.tol, max.subd, min.subd, constant.chrlen)) n <- sapply(xoloc, length) n.nu <- length(nu) loglik <- .C("R_stahl_loglik", as.integer(length(xoloc)), as.integer(n), as.double(unlist(xoloc)/100), # convert to Morgans as.double(chrlen/100), # convert to Morgasn as.integer(n.nu), as.double(nu), as.double(p), loglik=as.double(rep(0,n.nu)), as.integer(max.conv), as.double(integr.tol), as.integer(max.subd), as.integer(min.subd), as.integer(constant.chrlen), PACKAGE="xoi")$loglik attr(loglik, "nu") <- nu attr(loglik, "p") <- p loglik } # stahlLoglik for intercross stahlLoglikF2 <- function(xoloc, chrlen, nu, p, max.conv=25, integr.tol=1e-8, max.subd=1000, min.subd=10, constant.chrlen=FALSE) { n.ind <- length(xoloc) n.alternatives <- unlist(lapply(xoloc, length)) n.xo.per <- unlist(lapply(xoloc, lapply, lapply, length)) n.products <- length(n.xo.per) # = 2 * sum(n.alternatives) # expand chromosome lengths chrlen <- rep(chrlen, n.alternatives*2) n.nu <- length(nu) loglik <- .C("R_stahl_loglik_F2", as.integer(n.ind), as.integer(n.alternatives), as.integer(n.products), as.integer(n.xo.per), as.double(unlist(xoloc)/100), # convert to Morgans as.double(chrlen/100), # convert to Morgans as.integer(n.nu), as.double(nu), as.double(p), loglik=as.double(rep(0,n.nu)), as.integer(max.conv), as.double(integr.tol), as.integer(max.subd), as.integer(min.subd), as.integer(constant.chrlen), PACKAGE="xoi")$loglik attr(loglik, "nu") <- nu attr(loglik, "p") <- p loglik } ###################################################################### # the same, but with the arguments reordered and with p and nu stuck # together, and assuming they have length 1 ###################################################################### fitStahl.sub <- function(param, xoloc, chrlen, max.conv=25, integr.tol=1e-8, max.subd=1000, min.subd=10) { if(param[1] < 0 || param[2] < 0 || param[2] > 1) return(Inf) -stahlLoglik(xoloc, chrlen, param[1], param[2], max.conv, integr.tol, max.subd, min.subd) } # here, to optimize for the model with p=0 fitStahl.sub2 <- function(nu, xoloc, chrlen, max.conv=25, integr.tol=1e-8, max.subd=1000, min.subd=10) { if(nu < 0) return(Inf) -stahlLoglik(xoloc, chrlen, nu, 0, max.conv, integr.tol, max.subd, min.subd) } # function to optimize for the Stahl model #' Fit Stahl model #' #' Fit the Stahl model for crossover interference to data on crossover #' locations. #' #' See Housworth and Stahl (2003) and Broman and Weber (2000) for details of #' the method. #' #' We first use [stats::optimize()] to find the MLE with the #' contraint `p=0`, followed by use of [stats::optim()] to do a #' 2-dimensional optimization for the MLEs of the pair. #' #' @param xoloc A list of crossover locations (in cM), each component being a #' vector of locations for a different meiotic product. #' @param chrlen Chromosome length (in cM), either of length 1 or the same #' length as `xoloc`. #' @param nu Interference parameter (\eqn{\nu}{nu}). This should be a pair of #' values to be used as endpoints to first do a 1-dimensional optimization with #' \eqn{p=0}. #' @param p Starting value for the proportion of crossovers from the no #' interference pathway, for the 2-dimensional optimization. #' @param max.conv Maximum limit for summation in the convolutions to get #' inter-crossover distance distribution from the inter-chiasma distance #' distributions. This should be greater than the maximum number of chiasmata #' on the 4-strand bundle. #' @param integr.tol Tolerance for convergence of numerical integration. #' @param max.subd Maximum number of subdivisions in numerical integration. #' @param min.subd Minimum number of subdivisions in numerical integration. #' @param verbose If TRUE, print tracing information. If "\dots{}" includes #' `control`, this is ignored. #' @param \dots Further arguments sent to [stats::optim()]. #' @return A vector with the estimates of \eqn{\nu}{nu} (interference #' parameter) and \eqn{p} (proportion of crossovers coming from the no #' interference pathway), the maximized log likelihood, the estimate of nu with #' p constrained to be 0, the maximized log likelihood in this case, and the #' log likelihood ratio for comparing the model with p allowed to vary freely #' versus contrained to be 0. (Note that it's the natural log of the #' likelihood ratio, and not twice that.) #' @author Karl W Broman, \email{broman@@wisc.edu} #' @seealso [fitGamma()], [stahlLoglik()], #' [simStahl()] #' @references Housworth, E. A. and Stahl, F. W. (2003) Crossover interference #' in humans. *Am. J. Hum. Genet.* **73**, 188--197. #' #' Broman, K. W. and Weber, J. L. (2000) Characterization of human crossover #' interference. *Am. J. Hum. Genet.* **66**, 1911--1926. #' @keywords models #' @examples #' #' data(bssbsb) #' \dontshow{bssbsb <- bssbsb[,1:50]} #' #' xoloc <- find.breaks(bssbsb, chr=1) #' L <- attr(xoloc, "L") #' #' # get MLE (limiting maximum iterations to 10, just for speed in this example) #' \dontrun{mle <- fitStahl(xoloc, L, nu=c(9, 12), control=list(maxit=10))} #' \dontshow{mle <- fitStahl(xoloc, L, nu=c(9, 12), control=list(maxit=2))} #' #' @importFrom stats optimize optim #' @export fitStahl <- function(xoloc, chrlen=NULL, nu=c(1,20), p=0.02, max.conv=25, integr.tol=1e-8, max.subd=1000, min.subd=10, verbose=TRUE, ...) { if(is.data.frame(xoloc)) stop("xoloc should not be a data.frame.") if(!is.list(xoloc)) stop("xoloc should be a list.") if(is.null(chrlen) && "L" %in% names(attributes(xoloc))) chrlen <- attr(xoloc, "L") if(length(nu) > 2) { warning("nu should have length 2; using the first two values.") nu <- nu[1:2] } if(length(nu) != 2) stop("nu should have length 2.") if(length(p) > 1) { warning("p should have length 1; using the first value.") p <- p[1] } if(length(p) != 1) stop("p should have length 1.") out0 <- optimize(fitStahl.sub2, interval=c(nu[1], nu[2]), xoloc=xoloc, chrlen=chrlen, max.conv=max.conv, integr.tol=integr.tol, max.subd=max.subd, min.subd=min.subd) nu <- out0$minimum if(verbose) cat("For p=0, nuhat =", nu, "\n log lik =", -out0$objective, "\n") if(verbose>1 && !("control" %in% names(list(...)))) out <- optim(c(nu, p), fitStahl.sub, xoloc=xoloc, chrlen=chrlen, max.conv=max.conv, integr.tol=integr.tol, max.subd=max.subd, min.subd=min.subd, control=list(trace=verbose-1), ...) else out <- optim(c(nu, p), fitStahl.sub, xoloc=xoloc, chrlen=chrlen, max.conv=max.conv, integr.tol=integr.tol, max.subd=max.subd, min.subd=min.subd, ...) if(verbose) cat("\n nuhat =", out$par[1], "\n phat =", out$par[2], "\nlog lik =", -out$value, "\n") if(out0$objective <= out$value) { out <- c(out0$minimum, 0, -out0$objective, out0$minimum, -out0$objective, 0) if(verbose) cat("Inferred that p=0\n") } else { out <- c(out$par, -out$value, out0$minimum, -out0$objective, out0$objective - out$value) if(verbose) cat("Inferred that p>0\n") } names(out) <- c("nu", "p", "loglik", "nu0", "loglik0", "ln LR testing p=0") out }
/scratch/gouwar.j/cran-all/cranData/xoi/R/fitStahl.R
## gammaDensities.R #' Location of crossover given there is one #' #' Calculates the density of the location of the crossover on a random meiotic #' product, given that there is precisely one crossover, for the gamma model. #' #' Let \eqn{f(x;\nu)}{f(x;nu)} denote the density of a gamma random variable #' with parameters shape=\eqn{\nu}{nu} and rate=\eqn{2\nu}{2 nu}, and let #' \eqn{f_k(x;\nu)}{f_k(x;\nu)} denote the density of a gamma random variable #' with parameters shape=\eqn{k \nu}{k nu} and rate=\eqn{2\nu}{2 nu}. #' #' The distribution of the distance from one crossover to the next is #' \eqn{f^*(x;\nu) = \sum_{k=1}^{\infty} f_k(x;\nu)/2^k}{f*(x;nu) = sum_(k=1 to #' infty) f_k(x;\nu)/2^k}. #' #' The distribution of the distance from the start of the chromosome to the #' first crossover is \eqn{g^*(x;\nu) = 1 - F^*(x;\nu)}{g*(x;nu) = 1 - #' F*(x;nu)} where \eqn{F^*}{F*} is the cdf of \eqn{f^*}{f*}. #' #' We calculate the distribution of the location of the crossover on a product #' with a single crossover as the convolution of \eqn{g^*}{g*} with itself, and #' then rescaled to integrate to 1 on the interval (0,L). #' #' @param nu The interference parameter in the gamma model. #' @param L The length of the chromsome in cM. #' @param x If specified, points at which to calculate the density. #' @param n Number of points at which to calculate the density. The points #' will be evenly distributed between 0 and `L`. Ignored if `x` is #' specified. #' @param max.conv Maximum limit for summation in the convolutions to get #' inter-crossover distance distribution from the inter-chiasma distance #' distributions. This should be greater than the maximum number of chiasmata #' on the 4-strand bundle. #' @param integr.tol Tolerance for convergence of numerical integration. #' @param max.subd Maximum number of subdivisions in numerical integration. #' @param min.subd Minimum number of subdivisions in numerical integration. #' @return A data frame with two columns: `x` is the location (between 0 #' and `L`, in cM) at which the density was calculated and `f` is the #' density. #' @author Karl W Broman, \email{broman@@wisc.edu} #' @seealso [first.given.two()], [distance.given.two()], #' [joint.given.two()], [ioden()], [firstden()], #' [xoprob()], [gammacoi()] #' @references Broman, K. W. and Weber, J. L. (2000) Characterization of human #' crossover interference. *Am. J. Hum. Genet.* **66**, 1911--1926. #' #' Broman, K. W., Rowe, L. B., Churchill, G. A. and Paigen, K. (2002) Crossover #' interference in the mouse. *Genetics* **160**, 1123--1131. #' #' McPeek, M. S. and Speed, T. P. (1995) Modeling interference in genetic #' recombination. *Genetics* **139**, 1031--1044. #' @keywords distribution #' @examples #' #' f1 <- location.given.one(1, L=200, n=201) #' plot(f1, type="l", lwd=2, las=1, #' ylim=c(0,0.006), yaxs="i", xaxs="i", xlim=c(0,200)) #' #' f2 <- location.given.one(2.6, L=200, n=201) #' lines(f2, col="blue", lwd=2) #' #' f3 <- location.given.one(4.3, L=200, n=201) #' lines(f3, col="red", lwd=2) #' #' f4 <- location.given.one(7.6, L=200, n=201) #' lines(f4, col="green", lwd=2) #' #' @useDynLib xoi, .registration=TRUE #' @export location.given.one <- function(nu, L=103, x=NULL, n=400, max.conv=25, integr.tol=1e-8, max.subd=1000, min.subd=10) { if(nu <= 0) stop("nu should be positive.") if(is.null(x)) { x <- seq(0,L,length=n+1) x <- x[-1]-x[2]/2 } if(any(x < 0 | x > L)) { x <- x[x >= 0 & x <= L] warning("Dropping values outside of [0,L].") } x <- x/100 result <- .C("location_given_one", as.double(nu), as.double(x), y=as.double(rep(0,length(x))), as.integer(length(x)), as.double(L/100), as.integer(max.conv), as.double(integr.tol), as.integer(max.subd), as.integer(min.subd), PACKAGE="xoi") data.frame(x=x*100,f=result$y/100) } #' Location of first crossover given there are two #' #' Calculates the density of the location of the first crossover on a random #' meiotic product, given that there are precisely two crossovers, for the #' gamma model. #' #' Let \eqn{f(x;\nu)}{f(x;nu)} denote the density of a gamma random variable #' with parameters shape=\eqn{\nu}{nu} and rate=\eqn{2\nu}{2 nu}, and let #' \eqn{f_k(x;\nu)}{f_k(x;\nu)} denote the density of a gamma random variable #' with parameters shape=\eqn{k \nu}{k nu} and rate=\eqn{2\nu}{2 nu}. #' #' The distribution of the distance from one crossover to the next is #' \eqn{f^*(x;\nu) = \sum_{k=1}^{\infty} f_k(x;\nu)/2^k}{f*(x;nu) = sum_(k=1 to #' infty) f_k(x;\nu)/2^k}. #' #' The distribution of the distance from the start of the chromosome to the #' first crossover is \eqn{g^*(x;\nu) = 1 - F^*(x;\nu)}{g*(x;nu) = 1 - #' F*(x;nu)} where \eqn{F^*}{F*} is the cdf of \eqn{f^*}{f*}. #' #' We calculate the distribution of the location of the first crossover in a #' product with two crossovers by calculating the joint distribution of the #' location of the two crossovers, given that they both occur before L and the #' third occurs after L, and then integrating out the location of the second #' crossover. #' #' @param nu The interference parameter in the gamma model. #' @param L The length of the chromsome in cM. #' @param x If specified, points at which to calculate the density. #' @param n Number of points at which to calculate the density. The points #' will be evenly distributed between 0 and `L`. Ignored if `x` is #' specified. #' @param max.conv Maximum limit for summation in the convolutions to get #' inter-crossover distance distribution from the inter-chiasma distance #' distributions. This should be greater than the maximum number of chiasmata #' on the 4-strand bundle. #' @param integr.tol Tolerance for convergence of numerical integration. #' @param max.subd Maximum number of subdivisions in numerical integration. #' @param min.subd Minimum number of subdivisions in numerical integration. #' @return A data frame with two columns: `x` is the location (between 0 #' and `L`, in cM) at which the density was calculated and `f` is the #' density. #' @section Warning: **We sometimes have difficulty with the numerical #' integrals. You may need to use large `min.subd` (e.g. 25) to get #' accurate results.** #' @author Karl W Broman, \email{broman@@wisc.edu} #' @seealso [location.given.one()], [distance.given.two()], #' [joint.given.two()], [ioden()], [firstden()], #' [xoprob()], [gammacoi()] #' @references Broman, K. W. and Weber, J. L. (2000) Characterization of human #' crossover interference. *Am. J. Hum. Genet.* **66**, 1911--1926. #' #' Broman, K. W., Rowe, L. B., Churchill, G. A. and Paigen, K. (2002) Crossover #' interference in the mouse. *Genetics* **160**, 1123--1131. #' #' McPeek, M. S. and Speed, T. P. (1995) Modeling interference in genetic #' recombination. *Genetics* **139**, 1031--1044. #' @keywords distribution #' @examples #' #' f1 <- first.given.two(1, L=200, n=101) #' plot(f1, type="l", lwd=2, las=1, #' ylim=c(0,0.011), yaxs="i", xaxs="i", xlim=c(0,200)) #' #' f2 <- first.given.two(2.6, L=200, n=101) #' lines(f2, col="blue", lwd=2) #' #' \dontrun{ #' f3 <- first.given.two(4.3, L=200, n=101) #' lines(f3, col="red", lwd=2) #' #' f4 <- first.given.two(7.6, L=200, n=101) #' lines(f4, col="green", lwd=2) #' } #' #' @export first.given.two <- function(nu, L=103, x=NULL, n=400, max.conv=25, integr.tol=1e-8, max.subd=1000, min.subd=10) { if(nu <= 0) stop("nu should be positive.") if(is.null(x)) { x <- seq(0,L,length=n+1) x <- x[-1]-x[2]/2 } if(any(x < 0 | x > L)) { x <- x[x >= 0 & x <= L] warning("Dropping values outside of [0,L].") } x <- x/100 result <- .C("first_given_two", as.double(nu), as.double(L/100), as.double(x), y=as.double(rep(0,length(x))), as.integer(length(x)), as.integer(max.conv), as.double(integr.tol), as.integer(max.subd), as.integer(min.subd), PACKAGE="xoi") data.frame(x=x*100, f=result$y/100) } #' Distance between crossovers given there are two #' #' Calculates the density of the distance between the crossovers on a meiotic #' product, given that there are precisely two crossovers, for the gamma model. #' #' Let \eqn{f(x;\nu)}{f(x;nu)} denote the density of a gamma random variable #' with parameters shape=\eqn{\nu}{nu} and rate=\eqn{2\nu}{2 nu}, and let #' \eqn{f_k(x;\nu)}{f_k(x;\nu)} denote the density of a gamma random variable #' with parameters shape=\eqn{k \nu}{k nu} and rate=\eqn{2\nu}{2 nu}. #' #' The distribution of the distance from one crossover to the next is #' \eqn{f^*(x;\nu) = \sum_{k=1}^{\infty} f_k(x;\nu)/2^k}{f*(x;nu) = sum_(k=1 to #' infty) f_k(x;\nu)/2^k}. #' #' The distribution of the distance from the start of the chromosome to the #' first crossover is \eqn{g^*(x;\nu) = 1 - F^*(x;\nu)}{g*(x;nu) = 1 - #' F*(x;nu)} where \eqn{F^*}{F*} is the cdf of \eqn{f^*}{f*}. #' #' We calculate the distribution of the distance between crossovers on a #' product with two crossovers by first calculating the joint distribution of #' the location of the two crossovers, given that they both occur before L and #' the third occurs after L, and then integrating out the location of the first #' crossover. #' #' @param nu The interference parameter in the gamma model. #' @param L The length of the chromsome in cM. #' @param x If specified, points at which to calculate the density. #' @param n Number of points at which to calculate the density. The points #' will be evenly distributed between 0 and `L`. Ignored if `x` is #' specified. #' @param max.conv Maximum limit for summation in the convolutions to get #' inter-crossover distance distribution from the inter-chiasma distance #' distributions. This should be greater than the maximum number of chiasmata #' on the 4-strand bundle. #' @param integr.tol Tolerance for convergence of numerical integration. #' @param max.subd Maximum number of subdivisions in numerical integration. #' @param min.subd Minimum number of subdivisions in numerical integration. #' @return A data frame with two columns: `x` is the distance (between 0 #' and `L`, in cM) at which the density was calculated and `f` is the #' density. #' @section Warning: **We sometimes have difficulty with the numerical #' integrals. You may need to use large `min.subd` (e.g. 25) to get #' accurate results.** #' @author Karl W Broman, \email{broman@@wisc.edu} #' @seealso [location.given.one()], #' [first.given.two()],[joint.given.two()], #' [ioden()], [firstden()], [xoprob()], #' [gammacoi()] #' @references Broman, K. W. and Weber, J. L. (2000) Characterization of human #' crossover interference. *Am. J. Hum. Genet.* **66**, 1911--1926. #' #' Broman, K. W., Rowe, L. B., Churchill, G. A. and Paigen, K. (2002) Crossover #' interference in the mouse. *Genetics* **160**, 1123--1131. #' #' McPeek, M. S. and Speed, T. P. (1995) Modeling interference in genetic #' recombination. *Genetics* **139**, 1031--1044. #' @keywords distribution #' @examples #' #' f1 <- distance.given.two(1, L=200, n=101) #' plot(f1, type="l", lwd=2, las=1, #' ylim=c(0,0.0122), yaxs="i", xaxs="i", xlim=c(0,200)) #' #' f2 <- distance.given.two(2.6, L=200, n=101) #' lines(f2, col="blue", lwd=2) #' #' \dontrun{ #' f3 <- distance.given.two(4.3, L=200, n=101) #' lines(f3, col="red", lwd=2) #' #' f4 <- distance.given.two(7.6, L=200, n=101) #' lines(f4, col="green", lwd=2) #' } #' #' @export distance.given.two <- function(nu, L=103, x=NULL, n=400, max.conv=25, integr.tol=1e-8, max.subd=1000, min.subd=10) { if(nu <= 0) stop("nu should be positive.") if(is.null(x)) { x <- seq(0,L,length=n+1) x <- x[-1]-x[2]/2 } if(any(x < 0 | x > L)) { x <- x[x >= 0 & x <= L] warning("Dropping values outside of [0,L].") } x <- x/100 result <- .C("distance_given_two", as.double(nu), as.double(L/100), as.double(x), y=as.double(rep(0,length(x))), as.integer(length(x)), as.integer(max.conv), as.double(integr.tol), as.integer(max.subd), as.integer(min.subd), PACKAGE="xoi") data.frame(x=x*100, f=result$y/100) } #' Crossover locations given there are two #' #' Calculates the joint density of the crossover locations on a random meiotic #' product, given that there are precisely two crossovers, for the gamma model. #' #' Let \eqn{f(x;\nu)}{f(x;nu)} denote the density of a gamma random variable #' with parameters shape=\eqn{\nu}{nu} and rate=\eqn{2\nu}{2 nu}, and let #' \eqn{f_k(x;\nu)}{f_k(x;\nu)} denote the density of a gamma random variable #' with parameters shape=\eqn{k \nu}{k nu} and rate=\eqn{2\nu}{2 nu}. #' #' The distribution of the distance from one crossover to the next is #' \eqn{f^*(x;\nu) = \sum_{k=1}^{\infty} f_k(x;\nu)/2^k}{f*(x;nu) = sum_(k=1 to #' infty) f_k(x;\nu)/2^k}. #' #' The distribution of the distance from the start of the chromosome to the #' first crossover is \eqn{g^*(x;\nu) = 1 - F^*(x;\nu)}{g*(x;nu) = 1 - #' F*(x;nu)} where \eqn{F^*}{F*} is the cdf of \eqn{f^*}{f*}. #' #' @param nu The interference parameter in the gamma model. #' @param L The length of the chromsome in cM. #' @param x If specified, locations of the first crossover. #' @param y If specified, locations of the second crossover. #' @param n Number of points at which to calculate the density. The points #' will be evenly distributed between 0 and `L`. Ignored if `x` and #' `y` are specified. #' @param max.conv Maximum limit for summation in the convolutions to get #' inter-crossover distance distribution from the inter-chiasma distance #' distributions. This should be greater than the maximum number of chiasmata #' on the 4-strand bundle. #' @param integr.tol Tolerance for convergence of numerical integration. #' @param max.subd Maximum number of subdivisions in numerical integration. #' @param min.subd Minimum number of subdivisions in numerical integration. #' @return A data frame with three columns: `x` and `y` are the #' locations (between 0 and `L`, in cM) at which the density was #' calculated and `f` is the density. #' @section Warning: **We sometimes have difficulty with the numerical #' integrals. You may need to use large `min.subd` (e.g. 25) to get #' accurate results.** #' @author Karl W Broman, \email{broman@@wisc.edu} #' @seealso [location.given.one()], [distance.given.two()], #' [first.given.two()], [ioden()], [firstden()], #' [xoprob()], [gammacoi()] #' @references Broman, K. W. and Weber, J. L. (2000) Characterization of human #' crossover interference. *Am. J. Hum. Genet.* **66**, 1911--1926. #' #' Broman, K. W., Rowe, L. B., Churchill, G. A. and Paigen, K. (2002) Crossover #' interference in the mouse. *Genetics* **160**, 1123--1131. #' #' McPeek, M. S. and Speed, T. P. (1995) Modeling interference in genetic #' recombination. *Genetics* **139**, 1031--1044. #' @keywords distribution #' @examples #' #' # Calculate the distribution of the average of the crossover locations, #' # given that there are two and that they are separated by 20 cM #' # (for a chromosome of length 200 cM) #' L <- 200 #' d <- 20 #' x <- seq(0, L-d, by=0.5) #' y <- x+d #' #' f <- joint.given.two(4.3, L=L, x, y) #' f$f <- f$f / distance.given.two(4.3, L, d)$f #' plot((f$x+f$y)/2, f$f, type="l", xlim=c(0, L), ylim=c(0,max(f$f)), #' lwd=2, xlab="Average location", ylab="Density") #' abline(v=c(d/2,L-d/2), h=1/(L-d), lty=2, lwd=2) #' #' @export joint.given.two <- function(nu, L=103, x=NULL, y=NULL, n=20, max.conv=25, integr.tol=1e-8, max.subd=1000, min.subd=10) { if(nu <= 0) stop("nu should be positive.") if(is.null(x) && is.null(y)) { # compute on a grid x <- seq(0,L, length=n+1) x <- x[-1]-x[2]/2 y <- x x <- rep(x, n) y <- rep(y, rep(n,n)) } else if(is.null(x)) { x <- seq(0,L,length=n+1) x <- x[-1]-x[2]/2 m <- length(x) x <- rep(x, length(y)) y <- rep(y, rep(m,length(y))) } else if(is.null(y)) { y <- seq(0,L,length=n+1) y <- y[-1]-y[2]/2 m <- length(x) x <- rep(x, length(y)) y <- rep(y, rep(m,length(y))) } else if(length(x) != length(y)) { # both x and y given, but not same length m <- length(x) x <- rep(x, length(y)) y <- rep(y, rep(m,length(y))) } if(any(x < 0 | x > L | y < 0 | y > L)) { w <- (x >= 0 & x <= L & y>=0 & y <= L) x <- x[w] y <- y[w] warning("Dropping values outside of [0,L].") } # only include triangle if(any(x>y)) { w <- (x <= y) x <- x[w] y <- y[w] } x <- x/100 y <- y/100 result <- .C("joint_given_two", as.double(nu), as.double(L/100), as.double(x), as.double(y), z=as.double(rep(0,length(x))), as.integer(length(x)), as.integer(max.conv), as.double(integr.tol), as.integer(max.subd), as.integer(min.subd), PACKAGE="xoi") data.frame(x=x*100, y=y*100, f=result$z/10000) } #' Distribution of number of crossovers #' #' Calculates the probability of 0, 1, 2, or >2 crossovers for a chromosome of #' a given length, for the gamma model. #' #' Let \eqn{f(x;\nu)}{f(x;nu)} denote the density of a gamma random variable #' with parameters shape=\eqn{\nu}{nu} and rate=\eqn{2\nu}{2 nu}, and let #' \eqn{f_k(x;\nu)}{f_k(x;\nu)} denote the density of a gamma random variable #' with parameters shape=\eqn{k \nu}{k nu} and rate=\eqn{2\nu}{2 nu}. #' #' The distribution of the distance from one crossover to the next is #' \eqn{f^*(x;\nu) = \sum_{k=1}^{\infty} f_k(x;\nu)/2^k}{f*(x;nu) = sum_(k=1 to #' infty) f_k(x;\nu)/2^k}. #' #' The distribution of the distance from the start of the chromosome to the #' first crossover is \eqn{g^*(x;\nu) = 1 - F^*(x;\nu)}{g*(x;nu) = 1 - #' F*(x;nu)} where \eqn{F^*}{F*} is the cdf of \eqn{f^*}{f*}. #' #' We calculate the desired probabilities by numerical integration. #' #' @param nu The interference parameter in the gamma model. #' @param L Length of the chromosome (in cM). #' @param max.conv Maximum limit for summation in the convolutions to get #' inter-crossover distance distribution from the inter-chiasma distance #' distributions. This should be greater than the maximum number of chiasmata #' on the 4-strand bundle. #' @param integr.tol Tolerance for convergence of numerical integration. #' @param max.subd Maximum number of subdivisions in numerical integration. #' @param min.subd Minimum number of subdivisions in numerical integration. #' @return A vector of length 4, giving the probabilities of 0, 1, 2, or >2 #' crossovers, respectively, on a chromosome of length `L` cM. #' @author Karl W Broman, \email{broman@@wisc.edu} #' @seealso [location.given.one()], [first.given.two()], #' [distance.given.two()], [joint.given.two()], #' [ioden()], [firstden()], [gammacoi()] #' @references Broman, K. W. and Weber, J. L. (2000) Characterization of human #' crossover interference. *Am. J. Hum. Genet.* **66**, 1911--1926. #' #' Broman, K. W., Rowe, L. B., Churchill, G. A. and Paigen, K. (2002) Crossover #' interference in the mouse. *Genetics* **160**, 1123--1131. #' #' McPeek, M. S. and Speed, T. P. (1995) Modeling interference in genetic #' recombination. *Genetics* **139**, 1031--1044. #' @keywords distribution #' @examples #' #' xoprob(1, L=103) #' xoprob(4.3, L=103) #' #' @export xoprob <- function(nu, L=103, max.conv=25, integr.tol=1e-8, max.subd=1000, min.subd=10) { if(nu <= 0) stop("nu should be positive.") result <- .C("xoprob", as.double(nu), as.double(L/100), prob=as.double(rep(0,4)), as.integer(max.conv), as.double(integr.tol), as.integer(max.subd), as.integer(min.subd), PACKAGE="xoi") result$prob } #' Distance between crossovers #' #' Calculates the density of the distance from a given crossover to the next #' crossover, for the gamma model. #' #' Let \eqn{f(x;\nu)}{f(x;nu)} denote the density of a gamma random variable #' with parameters shape=\eqn{\nu}{nu} and rate=\eqn{2\nu}{2 nu}, and let #' \eqn{f_k(x;\nu)}{f_k(x;\nu)} denote the density of a gamma random variable #' with parameters shape=\eqn{k \nu}{k nu} and rate=\eqn{2\nu}{2 nu}. #' #' The distribution of the distance from one crossover to the next is #' \eqn{f^*(x;\nu) = \sum_{k=1}^{\infty} f_k(x;\nu)/2^k}{f*(x;nu) = sum_(k=1 to #' infty) f_k(x;\nu)/2^k}. #' #' @param nu The interference parameter in the gamma model. #' @param L Maximal distance (in cM) at which to calculate the density. Ignored #' if `x` is specified. #' @param x If specified, points at which to calculate the density. #' @param n Number of points at which to calculate the density. The points #' will be evenly distributed between 0 and `L`. Ignored if `x` is #' specified. #' @param max.conv Maximum limit for summation in the convolutions to get #' inter-crossover distance distribution from the inter-chiasma distance #' distributions. This should be greater than the maximum number of chiasmata #' on the 4-strand bundle. #' @return A data frame with two columns: `x` is the distance (between 0 #' and `L`, in cM) at which the density was calculated and `f` is the #' density. #' @author Karl W Broman, \email{broman@@wisc.edu} #' @seealso [location.given.one()], [first.given.two()], #' [distance.given.two()], [joint.given.two()], #' [firstden()], [xoprob()], [gammacoi()] #' @references Broman, K. W. and Weber, J. L. (2000) Characterization of human #' crossover interference. *Am. J. Hum. Genet.* **66**, 1911--1926. #' #' Broman, K. W., Rowe, L. B., Churchill, G. A. and Paigen, K. (2002) Crossover #' interference in the mouse. *Genetics* **160**, 1123--1131. #' #' McPeek, M. S. and Speed, T. P. (1995) Modeling interference in genetic #' recombination. *Genetics* **139**, 1031--1044. #' @keywords distribution #' @examples #' #' f1 <- ioden(1, L=200, n=201) #' plot(f1, type="l", lwd=2, las=1, #' ylim=c(0,0.014), yaxs="i", xaxs="i", xlim=c(0,200)) #' #' f2 <- ioden(2.6, L=200, n=201) #' lines(f2, col="blue", lwd=2) #' #' f3 <- ioden(4.3, L=200, n=201) #' lines(f3, col="red", lwd=2) #' #' f4 <- ioden(7.6, L=200, n=201) #' lines(f4, col="green", lwd=2) #' #' @export ioden <- function(nu, L=103, x=NULL, n=400, max.conv=25) { if(nu <= 0) stop("nu should be positive.") if(is.null(x)) { x <- seq(0,L,length=n+1) x <- x[-1]-x[2]/2 } if(any(x < 0)) { x <- x[x >= 0] warning("Dropping values < 0") } x <- x/100 result <- .C("ioden", as.double(nu), as.double(x), y=as.double(rep(0,length(x))), as.integer(length(x)), as.integer(max.conv), PACKAGE="xoi") y <- result$y data.frame(x=x*100, f=y/100) } #' Distance to a crossover #' #' Calculates the density of the distance from an arbitrary point to the next #' crossover, for the gamma model. #' #' Let \eqn{f(x;\nu)}{f(x;nu)} denote the density of a gamma random variable #' with parameters shape=\eqn{\nu}{nu} and rate=\eqn{2\nu}{2 nu}, and let #' \eqn{f_k(x;\nu)}{f_k(x;\nu)} denote the density of a gamma random variable #' with parameters shape=\eqn{k \nu}{k nu} and rate=\eqn{2\nu}{2 nu}. #' #' The distribution of the distance from one crossover to the next is #' \eqn{f^*(x;\nu) = \sum_{k=1}^{\infty} f_k(x;\nu)/2^k}{f*(x;nu) = sum_(k=1 to #' infty) f_k(x;\nu)/2^k}. #' #' The distribution of the distance from an arbitrary point to the first #' crossover is \eqn{g^*(x;\nu) = 1 - F^*(x;\nu)}{g*(x;nu) = 1 - F*(x;nu)} #' where \eqn{F^*}{F*} is the cdf of \eqn{f^*}{f*}. #' #' @param nu The interference parameter in the gamma model. #' @param L Maximal distance (in cM) at which to calculate the density. Ignored #' if `x` is specified. #' @param x If specified, points at which to calculate the density. #' @param n Number of points at which to calculate the density. The points #' will be evenly distributed between 0 and `L`. Ignored if `x` is #' specified. #' @param max.conv Maximum limit for summation in the convolutions to get #' inter-crossover distance distribution from the inter-chiasma distance #' distributions. This should be greater than the maximum number of chiasmata #' on the 4-strand bundle. #' @return A data frame with two columns: `x` is the distance (between 0 #' and `L`, in cM) at which the density was calculated and `f` is the #' density. #' @author Karl W Broman, \email{broman@@wisc.edu} #' @seealso [location.given.one()], [first.given.two()], #' [distance.given.two()], [joint.given.two()], #' [ioden()], [xoprob()], [gammacoi()] #' @references Broman, K. W. and Weber, J. L. (2000) Characterization of human #' crossover interference. *Am. J. Hum. Genet.* **66**, 1911--1926. #' #' Broman, K. W., Rowe, L. B., Churchill, G. A. and Paigen, K. (2002) Crossover #' interference in the mouse. *Genetics* **160**, 1123--1131. #' #' McPeek, M. S. and Speed, T. P. (1995) Modeling interference in genetic #' recombination. *Genetics* **139**, 1031--1044. #' @keywords distribution #' @examples #' #' f1 <- firstden(1, L=200, n=201) #' plot(f1, type="l", lwd=2, las=1, #' ylim=c(0,0.012), yaxs="i", xaxs="i", xlim=c(0,200)) #' #' f2 <- firstden(2.6, L=200, n=201) #' lines(f2, col="blue", lwd=2) #' #' f3 <- firstden(4.3, L=200, n=201) #' lines(f3, col="red", lwd=2) #' #' f4 <- firstden(7.6, L=200, n=201) #' lines(f4, col="green", lwd=2) #' #' @export firstden <- function(nu, L=103, x=NULL, n=400, max.conv=25) { if(nu <= 0) stop("nu should be positive.") if(is.null(x)) { x <- seq(0,L,length=n+1) x <- x[-1]-x[2]/2 } if(any(x < 0)) { x <- x[x >= 0] warning("Dropping values < 0") } x <- x/100 result <- .C("firstden", as.double(nu), as.double(x), y=as.double(rep(0,length(x))), as.integer(length(x)), as.integer(max.conv), PACKAGE="xoi") data.frame(x=x*100, f=result$y/100) } #' Coincidence function for the gamma model #' #' Calculates the coincidence function for the gamma model. #' #' Let \eqn{f(x;\nu)}{f(x;nu)} denote the density of a gamma random variable #' with parameters shape=\eqn{\nu}{nu} and rate=\eqn{2\nu}{2 nu}, and let #' \eqn{f_k(x;\nu)}{f_k(x;nu)} denote the density of a gamma random variable #' with parameters shape=\eqn{k \nu}{k nu} and rate=\eqn{2\nu}{2 nu}. #' #' The coincidence function for the gamma model is \eqn{C(x;\nu) = #' \sum_{k=1}^{\infty} f_k(x;\nu)/2}{C(x;nu) = sum_(k=1 to infty) f_k(x;nu)/2}. #' #' @param nu The interference parameter in the gamma model. #' @param L Maximal distance (in cM) at which to calculate the density. Ignored #' if `x` is specified. #' @param x If specified, points at which to calculate the density. #' @param n Number of points at which to calculate the density. The points #' will be evenly distributed between 0 and `L`. Ignored if `x` is #' specified. #' @param max.conv Maximum limit for summation in the convolution. This should #' be greater than the maximum number of chiasmata on the 4-strand bundle. #' @return A data frame with two columns: `x` is the distance (between 0 #' and `L`, in cM) at which the coicidence was calculated and #' `coincidence`. #' @author Karl W Broman, \email{broman@@wisc.edu} #' @seealso [stahlcoi()], [location.given.one()], #' [first.given.two()], [distance.given.two()], #' [joint.given.two()], [ioden()], [firstden()], #' [xoprob()] #' @references Broman, K. W. and Weber, J. L. (2000) Characterization of human #' crossover interference. *Am. J. Hum. Genet.* **66**, 1911--1926. #' #' Broman, K. W., Rowe, L. B., Churchill, G. A. and Paigen, K. (2002) Crossover #' interference in the mouse. *Genetics* **160**, 1123--1131. #' #' McPeek, M. S. and Speed, T. P. (1995) Modeling interference in genetic #' recombination. *Genetics* **139**, 1031--1044. #' @keywords distribution #' @examples #' #' f1 <- gammacoi(1, L=200) #' plot(f1, type="l", lwd=2, las=1, #' ylim=c(0,1.25), yaxs="i", xaxs="i", xlim=c(0,200)) #' #' f2 <- gammacoi(2.6, L=200) #' lines(f2, col="blue", lwd=2) #' #' f3 <- gammacoi(4.3, L=200) #' lines(f3, col="red", lwd=2) #' #' f4 <- gammacoi(7.6, L=200) #' lines(f4, col="green", lwd=2) #' #' @export gammacoi <- function(nu, L=103, x=NULL, n=400, max.conv=25) { if(nu <= 0) stop("nu should be positive.") if(is.null(x)) { x <- seq(0,L,length=n+1) x <- x[-1]-x[2]/2 } if(any(x < 0)) { x <- x[x >= 0] warning("Dropping values < 0") } x <- x/100 result <- .C("GammaCoincidence", as.double(nu), as.double(x), y=as.double(rep(0,length(x))), as.integer(length(x)), as.integer(max.conv), PACKAGE="xoi") data.frame(x=x*100, coincidence=result$y) } #' Coincidence function for the Stahl model #' #' Calculates the coincidence function for the Stahl model. #' #' The Stahl model is an extension to the gamma model, in which chiasmata occur #' according to two independent mechanisms. A proportion \eqn{p} come from a #' mechanism exhibiting no interference, and a proportion 1-\eqn{p} come from a #' mechanism in which chiasma locations follow a gamma model with interference #' parameter \eqn{\nu}{nu}. #' #' Let \eqn{f(x;\nu,\lambda)}{f(x;nu,lambda)} denote the density of a gamma #' random variable with parameters shape=\eqn{\nu}{nu} and #' rate=\eqn{\lambda}{lambda}. #' #' The coincidence function for the Stahl model is \eqn{C(x;\nu,p) = [p + #' \sum_{k=1}^{\infty} f(x;k\nu, }{C(x;nu,p) = [p + sum_(k=1 to infty) #' f(x;k*nu,2*(1-p)nu)]/2}\eqn{ 2(1-p)\nu)]/2}{C(x;nu,p) = [p + sum_(k=1 to #' infty) f(x;k*nu,2*(1-p)nu)]/2}. #' #' @param nu The interference parameter in the gamma model. #' @param p The proportion of chiasmata coming from the no-interference #' mechanism. #' @param L Maximal distance (in cM) at which to calculate the density. Ignored #' if `x` is specified. #' @param x If specified, points at which to calculate the density. #' @param n Number of points at which to calculate the density. The points #' will be evenly distributed between 0 and `L`. Ignored if `x` is #' specified. #' @param max.conv Maximum limit for summation in the convolution. This should #' be greater than the maximum number of chiasmata on the 4-strand bundle. #' @return A data frame with two columns: `x` is the distance (between 0 #' and `L`, in cM) at which the coicidence was calculated and #' `coincidence`. #' @author Karl W Broman, \email{broman@@wisc.edu} #' @seealso [gammacoi()], [location.given.one()], #' [first.given.two()], [distance.given.two()], #' [ioden()], [firstden()], [xoprob()] #' @references Copenhaver, G. P., Housworth, E. A. and Stahl, F. W. (2002) #' Crossover interference in Arabidopsis. *Genetics* **160**, #' 1631--1639. #' #' Housworth, E. A. and Stahl, F. W. (2003) Crossover interference in humans. #' *Am J Hum Genet* **73**, 188--197. #' @keywords distribution #' @examples #' #' f1 <- stahlcoi(1, p=0, L=200) #' plot(f1, type="l", lwd=2, las=1, #' ylim=c(0,1.25), yaxs="i", xaxs="i", xlim=c(0,200)) #' #' f2 <- stahlcoi(2.6, p=0, L=200) #' lines(f2, col="blue", lwd=2) #' #' f2s <- stahlcoi(2.6, p=0.1, L=200) #' lines(f2s, col="blue", lwd=2, lty=2) #' #' f3 <- stahlcoi(4.3, p=0, L=200) #' lines(f3, col="red", lwd=2) #' #' f3s <- stahlcoi(4.3, p=0.1, L=200) #' lines(f3s, col="red", lwd=2, lty=2) #' #' f4 <- stahlcoi(7.6, p=0, L=200) #' lines(f4, col="green", lwd=2) #' #' f4s <- stahlcoi(7.6, p=0.1, L=200) #' lines(f4s, col="green", lwd=2, lty=2) #' #' @export stahlcoi <- function(nu, p=0, L=103, x=NULL, n=400, max.conv=25) { if(nu <= 0) stop("nu should be positive.") if(length(p) > 1 || p < 0 || p > 1) stop("p should be a number between 0 and 1.") if(is.null(x)) { x <- seq(0,L,length=n+1) x <- x[-1]-x[2]/2 } if(any(x < 0)) { x <- x[x >= 0] warning("Dropping values < 0") } x <- x/100 result <- .C("StahlCoincidence", as.double(nu), as.double(p), as.double(x), y=as.double(rep(0,length(x))), as.integer(length(x)), as.integer(max.conv), PACKAGE="xoi") data.frame(x=x*100, coincidence=result$y) }
/scratch/gouwar.j/cran-all/cranData/xoi/R/gammaDensities.R
## kfunc.R #' estimate Ripley's K function #' #' estimate the 1-d version of Ripley's K function #' #' @param x list with sorted locations of the data #' @param d values at which to calculate the function #' @param lengths lengths of segments studied #' @param exclude distance to exclude #' @param tol tolerance value #' #' @return data frame with `d`, `k`, and `se` #' #' @seealso [gammacoi()], [stahlcoi()], [coincidence()] #' @keywords models #' @examples #' L <- 103 #' n <- 2000 #' map1 <- sim.map(L, n.mar=104, anchor=TRUE, include.x=FALSE, eq=TRUE) #' x <- sim.cross(map1, n.ind=n, m=6, type="bc") #' #' xoloc <- find.breaks(x) #' #' d <- seq(0, 100, by=0.1)[-1] #' kf <- kfunc(xoloc, d=d, lengths=rep(L, n)) #' #' plot(k ~ d, data=kf, type="n", yaxs="i", xaxs="i", las=1, #' ylim=c(0, max(kf$k + kf$se))) #' polygon(c(kf$d, rev(kf$d)), c(kf$k + kf$se, rev(kf$k-kf$se)), #' border=NA, col="#add8e650") #' lines(k ~ d, data=kf) #' #' @useDynLib xoi, .registration=TRUE #' @export kfunc <- function(x, d=seq(0,100,by=0.1), lengths=NULL, exclude=0, tol=1e-6) { npt <- sapply(x, length) if(!any(npt>0)) stop("Need to have some points.") x <- x[npt > 0] if(is.null(lengths)) lengths <- sapply(x, max) else lengths <- lengths[npt > 0] if(length(lengths) != length(x)) stop("length(lengths) != length(x)") if(any(d < exclude)) { warning("some d < exclude; these excluded") d <- d[d > exclude] } output <- .C("R_kfunc", as.integer(length(x)), as.integer(sapply(x, length)), as.double(unlist(x)), as.double(lengths), as.integer(length(d)), as.double(d), as.double(exclude), k=as.double(rep(0,length(d))), area=as.double(rep(0,length(d))), rate = as.double(0), as.double(tol), PACKAGE="xoi") rate <- output$rate k <- output$k area = output$area result <- data.frame(d=d, k=k, se=1/sqrt(output$area * rate)) attr(result,"rate") <- rate class(result) <- c("kfunc","data.frame") result }
/scratch/gouwar.j/cran-all/cranData/xoi/R/kfunc.R
## kwak_coincidence.R #' Estimate coincidence function #' #' Estimate coincidence function for a chromosome. #' #' @param cross Cross object; must be a backcross. See #' [qtl::read.cross()] for format details. #' @param chr Chromosome to consider (only one is allowed). If NULL, the #' first chromosome is considered. #' @param window Window size #' @param ncalc Total number of points for calculations. #' @return Data frame with columns `distance` and `coincidence`. The #' input argument `window` is kept as an attribute. #' @author Il youp Kwak #' @seealso [intensity()], [est.coi()] #' @keywords utilities #' @examples #' #' map1 <- sim.map(103, n.mar=104, anchor=TRUE, include.x=FALSE, eq=TRUE) #' x <- sim.cross(map1, n.ind=2000, m=6, type="bc") #' #' out <- coincidence(x, ncalc=101) #' plot(out, type="l", lwd=2, ylim=c(0, max(out[,2]))) #' #' @export coincidence <- function(cross, chr=NULL, window=5, ncalc=500) { if(is.null(chr)) chr <- chrnames(cross)[1] cross <- subset(cross, chr) if(nchr(cross) > 1) warning("Considering only chr ", names(cross$geno)[1]) if(crosstype(cross) != "bc") stop("coincidence() currently working only for a backcross.") g <- cross$geno[[1]]$data g[is.na(g)] <- 0 map <- cross$geno[[1]]$map xomat <- identify_xo(g)$xomat n.ind <- nind(cross) coincidenceSUB(xomat, window, map, n.ind, ncalc) } coincidenceSUB <- function(xomat, window, marker, n_ind, N) { inten <- intensitySUB(xomat, window, marker, n_ind, N) int_dat <- inten$intensity*window/100 center = inten$position n_pos <- length(marker) n_center <- length(center) n_xo <- ncol(xomat) start_d <- min(which(center >= window/2))-1 output <- .C("R_get_coincidence", as.integer(xomat), as.double(int_dat), as.double(window), as.double(center), as.integer(n_xo), as.integer(n_pos), as.integer(n_center), as.integer(start_d), as.double(marker), coincidence=as.double(rep(0,n_center)), PACKAGE="xoi") result <- data.frame(distance=center, coincidence=output$coincidence/n_ind) attr(result, "window") <- window result[!is.na(result[,2]),] }
/scratch/gouwar.j/cran-all/cranData/xoi/R/kwak_coincidence.R
## kwak_get_n_xoi.R get_n_xo <- function(sdat) { n_ind <- nrow(sdat) n_pos <- ncol(sdat) if(!is.matrix(sdat) || n_ind==0 || n_pos==0) stop("Input must be a matrix with at least one row and one column.") output <- .C("R_get_N_xo", as.integer(n_ind), as.integer(n_pos), as.integer(sdat), n_xo=as.integer(0), PACKAGE="xoi" ) output$n_xo }
/scratch/gouwar.j/cran-all/cranData/xoi/R/kwak_get_n_xo.R
## identify_xo : identify crossover. 2nd version for speed by C coding # # Input : data matrix. # Return : xo information matrix. # xomat[1,i] : observation index. # xomat[2,i] : xo strating marker. (left) # xomat[3,i] : xo ending marker. (right) # ob_ind : xo matrix index for each observation. # # ** have get_n_xo() as a sub function # return : number of crossover happened identify_xo <- function(sdat) { n_ind <- nrow(sdat) n_pos <- ncol(sdat) if(!is.matrix(sdat) || n_ind==0 || n_pos==0) stop("Input must be a matrix with at least one row and one column.") n_xo <- get_n_xo(sdat) output <- .C("R_identify_xo", as.integer(sdat), as.integer(n_ind), as.integer(n_pos), as.integer(n_xo), left = as.integer(rep(0,n_xo)), right = as.integer(rep(0,n_xo)), ind_id = as.integer(rep(0,n_xo)), ob_ind = as.integer(rep(0,n_ind)), PACKAGE="xoi" ) xomat <- rbind(output$ind_id, output$left, output$right) return(list(xomat=xomat, ob_ind=output$ob_ind)) }
/scratch/gouwar.j/cran-all/cranData/xoi/R/kwak_identify_xo.R
# kwak_intensity.R #' Estimate intensity function #' #' Estimate intensity function for a chromosome. #' #' #' @param cross Cross object; must be a backcross. See #' [qtl::read.cross()] for format details. #' @param chr Chromosome to consider (only one is allowed). If NULL, the #' first chromosome is considered. #' @param window Window size #' @param ncalc Total number of points for calculations. #' @return Data frame with columns `position` and `intensity`. The #' input argument `window` is kept as an attribute. #' @author Il youp Kwak #' @seealso [coincidence()] #' @keywords utilities #' @examples #' #' map1 <- sim.map(103, n.mar=104, anchor=TRUE, include.x=FALSE, eq=TRUE) #' x <- sim.cross(map1, n.ind=2000, m=6, type="bc") #' #' out <- intensity(x) #' plot(out, type="l", lwd=2, ylim=c(0, max(out[,2]))) #' #' @export intensity <- function(cross, chr=NULL, window=2.5, ncalc=500) { if(is.null(chr)) chr <- chrnames(cross)[1] cross <- subset(cross, chr) if(nchr(cross) > 1) warning("Considering only chr ", names(cross$geno)[1]) if(crosstype(cross) != "bc") stop("coincidence() currently working only for a backcross.") g <- cross$geno[[1]]$data g[is.na(g)] <- 0 map <- cross$geno[[1]]$map xomat <- identify_xo(g)$xomat n.ind <- nind(cross) intensitySUB(xomat, window, map, n.ind, ncalc) } intensitySUB <- function(xomat, window, marker, n_ind, N) { n_xo <- ncol(xomat) n_pos <- length(marker) center <- seq(marker[1], marker[n_pos], length=N) n_center <- length(center) xovec <- c(xomat) output <- .C("R_get_intensity", as.integer(xovec), as.double(window), as.double(center), as.integer(n_pos), as.integer(n_xo), as.integer(n_center), as.double(marker), intensity=as.double(rep(0,n_center)), as.integer(n_ind), PACKAGE="xoi") result <- data.frame(position=center, intensity=output$intensity) attr(result, "window") <- window result }
/scratch/gouwar.j/cran-all/cranData/xoi/R/kwak_intensity.R
## recrate.R #' Estimate recombination rate #' #' Obtain a smoothed estimate of the recombination rate along a chromosome, #' using the cM and Mbp position of markers. #' #' We assume constant recombination rate within each marker interval. #' #' @param genmap Vector of cM positions of markers, or a list of such vectors. #' @param phymap Vector of Mbp positions of markers, or a list of such vectors; #' same length as `genmap`. #' @param pos Vector of positions at which the recombination rate should be #' estimated, or a list of such vectors. If NULL, we use the physical #' marker positions plus a grid with 4 positions per Mbp. #' @param window Length of sliding window (in Mbp). #' @return A data.frame containing the positions and estimate recombination #' rates. #' @author Karl W Broman, \email{broman@@wisc.edu} #' @seealso [est.coi()], [intensity()] #' @keywords models #' @examples #' # create equally-spaced map #' pmap <- sim.map(100, n.mar=51, anchor=TRUE, include.x=FALSE, eq.spacing=TRUE) #' #' # simulate cross #' x <- sim.cross(pmap, type="bc", n.ind=501) #' #' # estimate map for that cross #' emap <- est.map(x) #' #' # empirical estimate of recombination rate #' rr <- est.recrate(emap[[1]], pmap[[1]], window=5) #' plot(rr, type="l", lwd=2) #' #' @useDynLib xoi, .registration=TRUE #' @export est.recrate <- function(genmap, phymap, pos=NULL, window=5) { # multiple-chromosome version if(is.list(genmap) && is.list(phymap)) { if(length(genmap) != length(phymap)) stop("length(genmap) != length(phymap)") if(is.null(pos)) { result <- apply(mapply(est.recrate, genmap, phymap, window=window), 2, as.data.frame) } else { if(length(pos) != length(genmap)) stop("length(pos) != length(genmap)") result <- apply(mapply(est.recrate, genmap, phymap, pos, window=window), 2, as.data.frame) } names(result) <- names(genmap) return(result) } if(length(genmap) != length(phymap)) stop("genmap and phymap should be the same length.") if(any(is.na(genmap) | is.na(phymap))) { drop <- is.na(genmap) | is.na(phymap) genmap <- genmap[!drop] phymap <- phymap[!drop] if(length(genmap) == 0) stop("Need multiple markers with known genetic and physical positions.") } if(length(unique(phymap)) != length(phymap)) stop("Can't have markers right on top of each other (in physical distance).") if(window < 0) stop("window should be > 0") if(is.null(pos)) { pos <- sort(c(phymap, seq(min(phymap), max(phymap), by=0.25))) pos <- unique(pos[pos >= min(phymap) & pos <= max(phymap)]) } if(any(diff(genmap)<0)) stop("genmap should be non-decreasing") if(any(diff(phymap)<0)) stop("phymap should be non-decreasing") if(any(diff(pos)<0)) stop("pos should be non-decreasing") if(any(pos < min(phymap) | pos > max(phymap))) { warning("pos should be within range of phymap") pos <- pos[pos >= min(phymap) & pos <= max(phymap)] } if(diff(range(phymap)) < window) stop("range of phymap should exceed the window length.") rate <- .C("R_est_recrate", as.integer(length(genmap)), as.double(genmap), as.double(phymap), as.integer(length(pos)), as.double(pos), rate=as.double(rep(0,length(pos))), as.double(window), as.double(rep(0, length(genmap)-1)), PACKAGE="xoi")$rate data.frame(pos=pos, rate=rate) } #' Convert recrate to scanone format #' #' Convert the result of [est.recrate()] to the format #' output by R/qtl's [qtl::scanone()] function. #' #' @param recrate A list of results from [est.recrate()] #' @param phymap A list of vectors of Mbp positions of markers #' @return A data frame with class `"scanone"`, in the format output by [qtl::scanone()]. #' @author Karl W Broman, \email{broman@@wisc.edu} #' @seealso [est.recrate()] #' @keywords models #' #' @examples #' pmap <- sim.map(100, n.mar=51, anchor=TRUE, include.x=FALSE, eq.spacing=TRUE) #' #' # simulate cross #' x <- sim.cross(pmap, type="bc", n.ind=501) #' #' # estimate map for that cross #' emap <- est.map(x) #' #' # empirical estimate of recombination rate #' rr <- est.recrate(emap[[1]], pmap[[1]], window=5) #' #' # make it a list (one component per chromosome, but here just the one chromosome) #' rr <- list("1"=rr) #' #' # convert to scanone output and plot #' rr_scanone <- recrate2scanone(rr) #' plot(rr_scanone) #' #' @export recrate2scanone <- function(recrate, phymap=NULL) { if(is.data.frame(recrate) && names(recrate)[1]=="pos" && names(recrate)[2]=="rate") recrate <- list(recrate) else { if(is.null(names(recrate))) names(recrate) <- 1:length(recrate) } npos <- sapply(recrate, nrow) chr <- factor(rep(names(recrate), npos), levels=names(recrate)) pos <- unlist(lapply(recrate, function(a) a$pos)) rate <- unlist(lapply(recrate, function(a) a$rate)) locnam <- vector("list", length(recrate)) for(i in seq(along=recrate)) locnam[[i]] <- paste("c", names(recrate)[i], ".loc", seq(along=recrate[[i]]$pos), sep="") if(!is.null(phymap)) { for(i in seq(along=recrate)) { m <- match(phymap[[i]], recrate[[i]]$pos) locnam[[i]][m] <- names(phymap[[i]]) } } result <- data.frame(chr=chr, pos=pos, "cM/Mbp"=rate) rownames(result) <- unlist(locnam) class(result) <- c("scanone", "data.frame") result }
/scratch/gouwar.j/cran-all/cranData/xoi/R/recrate.R
## simStahl.R #' Simulate crossover locations under the Stahl model #' #' Simulate crossover locations under the Stahl model. #' #' The Stahl model is an extension to the gamma model, in which chiasmata occur #' according to two independent mechanisms. A proportion \eqn{p} come from a #' mechanism exhibiting no interference, and a proportion 1-\eqn{p} come from a #' mechanism in which chiasma locations follow a gamma model with interference #' parameter \eqn{\nu}{nu}. #' #' @param n.sim Number of meiotic products to simulate. #' @param nu The interference parameter in the gamma model. #' @param p The proportion of chiasmata coming from the no-interference #' mechanism. #' @param L Chromosome length (in cM). #' @param obligate_chiasma Require an obligate chiasma (requires `nu` to #' be an integer; if nu is not an integer, it is rounded. #' @param n.bins4start We approximate the distribution of the location of the #' first crossover from the mechanism exhibiting interference using a even grid #' with this many bins. (Only if `nu` is not an integer.) #' @return A vector of length `n.sim`, each element being empty (for #' products with no crossovers) or a vector of crossover locations, in cM. An #' attribute, `L`, contains the chromosome length in cM. #' @author Karl W Broman, \email{broman@@wisc.edu} #' @seealso [fitGamma()], [qtl::sim.cross()] #' @references Copenhaver, G. P., Housworth, E. A. and Stahl, F. W. (2002) #' Crossover interference in Arabidopsis. *Genetics* **160**, #' 1631--1639. #' #' Housworth, E. A. and Stahl, F. W. (2003) Crossover interference in humans. #' *Am J Hum Genet* **73**, 188--197. #' @keywords datagen #' @examples #' #' # simulations with no interference, chromosome of length 80 cM #' xoNI <- simStahl(100, nu=1, p=0, L=80) #' #' # simulations under gamma model with nu=7.6 #' xogamma <- simStahl(100, nu=7.6, p=0, L=80) #' #' # simulations under Stahl model with nu=7.6, p=0.1 #' xostahl <- simStahl(100, nu=7.6, p=0.1, L=80) #' #' # simulations under chi-square model with nu=11 (m=10) and obligate chiasma #' xo_oblchi <- simStahl(100, nu=11, p=0, L=80, obligate_chiasma=TRUE) #' #' # simulations under Stahl model with nu=11, p=0.1, and obligate chiasma #' xo_oblchi_stahl <- simStahl(100, nu=11, p=0.1, L=80, obligate_chiasma=TRUE) #' @importFrom stats qpois dpois #' @useDynLib xoi, .registration=TRUE #' @export simStahl <- function(n.sim, nu=1, p=0, L=100, obligate_chiasma=FALSE, n.bins4start=10000) { if(nu <= 0) stop("nu should be positive.") if(p < 0 || p > 1) stop("p should be in [0,1].") if(p==1) { # if p is 1, might as well take nu == 1 nu <- 1L p <- 0 } if(n.sim <= 0) stop("n should be a positive integer.") if(L < 0) stop("L should be positive.") if(n.bins4start < 1000) { warning("n.bins4start should be large. Using 1000.") n.bins4start <- 1000 } if(nu %% 1 < 1e-6) { # if nu is very close to integer, just make it an integer nu <- as.integer(nu) } max.nxo <- qpois(1-1e-10, L)*10 if(obligate_chiasma || is.integer(nu)) { # use integer version if(!is.integer(nu)) { nu <- as.integer(round(nu)) warning("Simulations with obligate chiasma require that nu be an integer; ", "rounding nu to ", nu) } if(obligate_chiasma) Lstar <- calc_Lstar(L, nu-1, p) else Lstar <- L out <- .C("R_simStahl_int", as.integer(n.sim), as.integer(nu-1), as.double(p), as.double(L), as.double(Lstar), nxo = as.integer(rep(0,n.sim)), # number of crossovers loc = as.double(rep(0,n.sim*max.nxo)), as.integer(max.nxo), as.integer(obligate_chiasma), PACKAGE="xoi") out <- lapply(as.data.frame(rbind(out$nxo, matrix(out$loc, nrow=max.nxo))), function(a) {if(a[1]==0) return(numeric(0)); a[(1:a[1])+1] }) } else { out <- .C("simStahl", as.integer(n.sim), as.double(nu), as.double(p), as.double(L/100), nxo = as.integer(rep(0,n.sim)), # number of crossovers loc = as.double(rep(0,n.sim*max.nxo)), as.integer(max.nxo), as.integer(n.bins4start), PACKAGE="xoi") out <- lapply(as.data.frame(rbind(out$nxo, matrix(out$loc*100, nrow=max.nxo))), function(a) {if(a[1]==0) return(numeric(0)); a[(1:a[1])+1] }) } attr(out, "L") <- L names(out) <- NULL out } # calculate reduced length to give expected no. chiasmata when conditioning on >= 1 # # L and Lstar are in cM calc_Lstar <- function(L, m=0, p=0) { if(L <= 50) stop("Must have L > 50") if(m < 0) stop("Must have m==0") if(!is.integer(m) && m %% 1 > 1e-8) { warning("m must be an non-negative integer; rounding") m <- round(m) } if(p < 0 || p > 1) stop("p must be in [0, 1]") if(p==1) { # if p == 1, might as well take m=0, p=0 m <- 0 p <- 0 } func_to_zero <- function(Lstar, L, m=0, p=0) { if(m==0) denom <- 1 - exp(-Lstar/50) else { lambda1 <- Lstar/50 * (m+1) * (1-p) lambda2 <- Lstar/50 * p denom <- 1 - sum(dpois(0:m, lambda1) * (m+1 - (0:m))/(m+1)) * exp(-lambda2) } 2*L - 2*Lstar / denom } stats::uniroot(func_to_zero, c(1e-8, L), L=L, m=m, p=p, tol=sqrt(.Machine$double.eps))$root }
/scratch/gouwar.j/cran-all/cranData/xoi/R/simStahl.R
## util.R #' Estimate crossover locations #' #' Estimate the locations of crossovers in a backcross. #' #' This works only a backcross, RIL, or intercross. We use the function #' [qtl::locateXO()] in R/qtl. Crossovers are estimated to be at the #' midpoint of the interval between the nearest flanking typed markers. #' #' @param cross An object of class `cross`. (This must be a backcross, #' RIL, or intercross.) See [qtl::read.cross()] for details. #' @param chr Optional set of chromosomes on which to look for crossovers. If #' NULL, all chromosomes are considered. #' @return If only one chromosome is considered, this is a list with one #' component for each individual. If multiple chromosomes were considered, #' this is a list with one element for each chromosome, each of which is a list #' with one element for each individual, as above. #' #' For backcrosses and RIL, the componenets for the individuals are #' `numeric(0)` if there were no crossovers or a vector giving the #' crossover locations. The length of the chromosome (in cM) is saved as an #' attribute. (Note that the format is the same as the output of #' [simStahl()].) #' #' For an intercross, the components for the individuals are themselves lists #' with all possible allocations of the crossovers to the two meiotic products; #' each component of this list is itself a list with two components, #' corresponding to the two meiotic products. #' @author Karl W Broman, \email{broman@@wisc.edu} #' @seealso [convertxoloc()], [fitGamma()], #' [simStahl()] #' @keywords utilities #' @examples #' #' data(bssbsb) #' #' # crossover locations on chromosome 1 #' xoloc1 <- find.breaks(bssbsb, chr=1) #' #' # crossover locations on all chromosomes #' xoloc <- find.breaks(bssbsb) #' #' @import qtl #' @export find.breaks <- function(cross, chr=NULL) { if(!inherits(cross, "cross")) stop("Input should have class \"cross\".") type <- crosstype(cross) if(!is.null(chr)) cross <- subset(cross, chr=chr) if(type == "f2") return(find.breaks.F2(cross)) if(type != "bc" && type != "risib" && type != "riself") stop("This works only for a backcross or RIL.") v <- vector("list", nchr(cross)) thechr <- names(v) <- names(cross$geno) L <- chrlen(cross) for(i in seq(along=thechr)) { v[[i]] <- locateXO(subset(cross, chr=thechr[i])) attr(v[[i]], "L") <- L[i] } if(length(v)==1) return(v[[1]]) v } # find breakpoints in F2 find.breaks.F2 <- function(cross) { v <- vector("list", nchr(cross)) names(v) <- thechr <- names(cross$geno) L <- chrlen(cross) for(i in seq(along=thechr)) { v[[i]] <- lapply(locateXO(subset(cross, chr=thechr[i]), full.info=TRUE), inferxoloc.F2) attr(v[[i]], "L") <- L[i] } if(length(v)==1) return(v[[1]]) v } # infer strand-specific XO locations in F2 inferxoloc.F2 <- function(fullxoinfo) { # no XOs if(length(fullxoinfo)==0) return(list(list(numeric(0), numeric(0)))) # 1 XO if(nrow(fullxoinfo) == 1) return(list(list(fullxoinfo[1,1], numeric(0)))) # drop extraneous rows fullxoinfo <- fullxoinfo[c(TRUE, fullxoinfo[-nrow(fullxoinfo),4] != fullxoinfo[-1,4]),, drop=FALSE] # make sure we have midpoints fullxoinfo[,1] <- (fullxoinfo[,2]+fullxoinfo[,3])/2 xo <- fullxoinfo[,1] gleft <- fullxoinfo[,6] gright <- fullxoinfo[,7] if(gleft[1]==gright[1]+2 || gleft[1]+2==gright[1]) { result <- list(list(xo[1], xo[1])) last <- list(0) } else { result <- list(list(xo[1], numeric(0))) last <- list(1) } if(nrow(fullxoinfo)==1) return(result) for(i in 2:nrow(fullxoinfo)) { if(gleft[i]==gright[i]+2 || gleft[i]+2==gright[i]) { # A-B or B-A for(j in seq(along=result)) { result[[j]][[1]] <- c(result[[j]][[1]], xo[i]) result[[j]][[2]] <- c(result[[j]][[2]], xo[i]) } } else if(gleft[i]==2 && gright[i]==gleft[i-1]) { # A-H-A or B-H-B for(j in seq(along=result)) { result[[j]][[last[[j]]]] <- c(result[[j]][[last[[j]]]], xo[i]) } } else if(gleft[i]==2 && gright[i]!=gleft[i-1]) { # A-H-B or B-H-A for(j in seq(along=result)) { last[[j]] <- 3 - last[[j]] # put on opposite strand result[[j]][[last[[j]]]] <- c(result[[j]][[last[[j]]]], xo[i]) } } else if(gleft[i-1]==2 && gright[i]==2) { # H-B-H or H-A-H result2add <- result last2add <- last for(j in seq(along=result)) { result[[j]][[1]] <- c(result[[j]][[1]], xo[i]) last[[j]] <- 1 result2add[[j]][[2]] <- c(result2add[[j]][[2]], xo[i]) last2add[[j]] <- 2 } result <- c(result, result2add) last <- c(last, last2add) } else if(gright[i] == 2) { # A-B-H or B-A-H if(any(gleft[1:i] == 2)) { # was a previous H; consider both possibilities result2add <- result last2add <- last for(j in seq(along=result)) { result[[j]][[1]] <- c(result[[j]][[1]], xo[i]) last[[j]] <- 1 result2add[[j]][[2]] <- c(result2add[[j]][[2]], xo[i]) last2add[[j]] <- 2 } result <- c(result, result2add) last <- c(last, last2add) } else { # arbitrary for(j in seq(along=result)) { result[[j]][[1]] <- c(result[[j]][[1]], xo[i]) last[[j]] <- 1 } } } } # end loop over rows in fullxoinfo result } #' Estimate number of crossovers #' #' Estimate the number of crossovers in each meiosis in a backcross. #' #' This works only a backcross. We use the internal function (within R/qtl) #' `locate.xo`. #' #' @param cross An object of class `cross`. (This must be a backcross.) #' See [qtl::read.cross()] for details. #' @param chr Optional set of chromosomes across which to count crossovers. If #' NULL, the total number of crossovers, genome-wide, is counted. #' @return A vector with the estimated number of crossovers for each #' individual. #' @author Karl W Broman, \email{broman@@wisc.edu} #' @seealso [find.breaks()] #' @keywords utilities #' @examples #' #' data(bssbsb) #' #' # estimated number of crossovers on chr 1 #' nxo <- countxo(bssbsb, chr=1) #' #' # estimated number of crossovers genome-wide #' nxo <- countxo(bssbsb) #' #' @export countxo <- function(cross, chr=NULL) { if(!inherits(cross, "cross")) stop("Input should have class \"cross\".") type <- crosstype(cross) if(type != "bc" && type != "risib" && type != "riself") stop("This works only for a backcross or RIL.") if(!is.null(chr)) cross <- subset(cross, chr=chr) br <- find.breaks(cross) if(!is.list(br[[1]])) return(sapply(br, length)) apply(sapply(br, sapply, length),1,sum) } #' Convert format of crossover locations data #' #' Convert the format of data on crossover locations to that needed for the #' function \code{\link{fitGamma}.} #' #' #' @param breaks A list of crossover locations, as output by #' [find.breaks()] or [simStahl()]. #' @return A data frame with two columns: the inter-crossover and crossover-to #' chromosome end differences (`"distance"`) and indicators of censoring #' type (`"censor"`), with 0 = distance between crossovers, 1=start of #' chromosome to first crossover, 2 = crossover to end of chromosome, and 3 = #' whole chromosome. #' @author Karl W Broman, \email{broman@@wisc.edu} #' @seealso [find.breaks()], [fitGamma()], #' [simStahl()] #' @keywords utilities #' @examples #' #' data(bssbsb) #' #' # crossover locations on chromosome 1 #' xoloc1 <- convertxoloc(find.breaks(bssbsb, chr=1)) #' #' # crossover locations on all chromosomes #' xoloc <- convertxoloc(find.breaks(bssbsb)) #' #' @export convertxoloc <- function(breaks) { f <- function(x, L) { if(length(x)==0) return(rbind(L,3)) else { d <- diff(c(0,x,L)) cen <- c(2, rep(0,length(x)-1), 1) return(rbind(d,cen)) } } if(is.list(breaks[[1]])) { v <- vector("list", length(breaks)) names(v) <- names(breaks) for(i in 1:length(breaks)) { v[[i]] <- lapply(breaks[[i]], f, attr(breaks[[i]], "L")) v[[i]] <- matrix(unlist(v[[i]]), ncol=2, byrow=TRUE) } for(i in 2:length(v)) v[[1]] <- rbind(v[[1]],v[[i]]) v <- v[[1]] } else { v <- lapply(breaks, f, attr(breaks, "L")) v <- matrix(unlist(v), ncol=2, byrow=TRUE) } v <- as.data.frame(v) names(v) <- c("distance", "censor") v } # addlog: calculates log(sum(exp(input)) addlog <- function(..., threshold=200) { a <- unlist(list(...)) if(length(a)<=1) return(a) x <- a[1] a <- a[-1] for(i in seq(along=a)) { if(a[i] > x + threshold) x <- a[i] else if(x < a[i] + threshold) x <- a[i] + log1p(exp(x-a[i])) } x } # determine cross type crosstype <- function(cross) { type <- class(cross) type <- type[type != "cross" & type != "list"] if(length(type) > 1) { warning("cross has multiple classes") } type[1] }
/scratch/gouwar.j/cran-all/cranData/xoi/R/util.R
## xoiversion.R #' Installed version of R/xoi #' #' Print the version number of the currently installed version of R/xoi. #' #' #' @return A character string with the version number of the currently #' installed version of R/xoi. #' @author Karl W Broman, \email{broman@@wisc.edu} #' @keywords print #' @examples #' xoiversion() #' #' @export xoiversion xoiversion <- function() { version <- unlist(utils::packageVersion("xoi")) if(length(version) == 3) { # make it like #.#-# return( paste(c(version, ".", "-")[c(1,4,2,5,3)], collapse="") ) } paste(version, collapse=".") }
/scratch/gouwar.j/cran-all/cranData/xoi/R/xoiversion.R
#' Open a file, directory or URL #' #' Open a file, directory or URL, using the local platforms conventions, #' i.e. associated applications, default programs, etc. This is usually #' equivalent to double-clicking on the file in the GUI. #' #' @param target String, the path or URL to open. #' @param app Specify the app to open `target` with, and its arguments, #' in a character vector. Note that app names are platform dependent. #' @param quiet Whether to echo the command to the screen, before #' running it. #' @param ... Additional arguments, not used currently. #' #' @section Examples: #' ``` #' xopen("test.R") #' xopen("https://ps.r-lib.org") #' xopen(tempdir()) #' ``` #' @export xopen <- function(target = NULL, app = NULL, quiet = FALSE, ...) UseMethod("xopen") #' @export xopen.default <- function(target = NULL, app = NULL, quiet = FALSE, ...) { xopen2(target, app, quiet) } xopen2 <- function(target, app, quiet, timeout1 = 2000, timeout2 = 5000) { os <- get_os() fun <- switch(os, win = xopen_win, macos = xopen_macos, xopen_other) par <- fun(target, app) err <- tempfile() on.exit(unlink(err, recursive = TRUE), add = TRUE) px <- processx::process$new(par[[1]], par[[2]], stderr = err, echo_cmd = !quiet) ## Cleanup, if needed if (par[[3]]) wait_for_finish(px, target, timeout1, timeout2) invisible(px) } get_os <- function() { if (.Platform$OS.type == "windows") { "win" } else if (Sys.info()[["sysname"]] == "Darwin") { "macos" } else { "other" } } xopen_macos <- function(target, app) { cmd <- "open" args <- if (length(app)) c("-a", app[1]) args <- c(args, target) if (length(app)) args <- c(args, "--args", app[-1]) list(cmd, args, TRUE) } xopen_win <- function(target, app) { cmd <- "cmd" args <- c("/c", "start", "\"\"", "/b") target <- gsub("&", "^&", target) if (length(app)) args <- c(args, app) args <- c(args, target) list(cmd, args, TRUE) } xopen_other <- function(target, app) { if (length(app)) { cmd <- app[1] args <- app[-1] cleanup <- FALSE } else { cmd <- Sys.which("xdg-open") if (cmd == "") cmd <- system.file("xdg-open", package = "xopen") args <- character() cleanup <- TRUE } args <- c(args, target) list(cmd, args, cleanup) } #' Wait for a process to finish #' #' With timeout(s), and interaction, if the session is interactive. #' #' First we wait for 2s. If the process is still alive, then we give #' it another 5s, but first let the user know that they can interrupt #' the process. #' #' @param process The process. It should not have `stdout` or `stderr` #' pipes, because that can make it freeze. #' @param timeout1 Timeout before message. #' @param timeout2 Timeout after message. #' #' @keywords internal wait_for_finish <- function(process, target, timeout1 = 2000, timeout2 = 5000) { on.exit(process$kill(), add = TRUE) process$wait(timeout = timeout1) if (process$is_alive()) { message("Still trying to open ", encodeString(target, quote = "'"), ", you can interrupt any time") process$wait(timeout = timeout2) process$kill() } if (stat <- process$get_exit_status()) { err <- if (file.exists(ef <- process$get_error_file())) readLines(ef) stop( call. = FALSE, "Could not open ", encodeString(target, quote = "'"), "\n", "Exit status: ", stat, "\n", if (length(err) && nzchar(err)) paste("Standard error:", err, collapse = "\n")) } }
/scratch/gouwar.j/cran-all/cranData/xopen/R/package.R
# __________________ #< 455d9d59211066f8cdf61f39d7562145 ># __________________ # Utils for addins #### # Evaluate string -> apply function -> capture output apply_capture <- function(string, fn, envir = NULL) { if (is.null(envir)) { out <- capture.output(fn(eval_string(string))) } else { out <- capture.output(fn(eval_string(string, envir = envir))) } out } # parse, eval eval_string <- function(string, envir = NULL) { if (is.null(envir)) { out <- eval(parse(text = string)) } else { out <- eval(parse(text = string), envir = envir) } out } # Evaluate string and capture output capture <- function(string, envir = NULL) { apply_capture(string, identity,envir = envir) } # Insert code at selection with rstudioapi insert_code <- function(strings, prepare = TRUE, indentation = 0) { if (!(is.list(strings) || is.character(strings))) stop("'strings' should be either a list or a character vector.") # Prepare the strings for insertion if (isTRUE(prepare)) { code <- prepare_insertion(strings, indentation = indentation) } else { code <- strings } # Insert the code rstudioapi::insertText(code) } # Get user's primary selection. Warn if empty. get_selection <- function() { # Get context context <- rstudioapi::getActiveDocumentContext() # Get the selected variable name selection <- rstudioapi::primary_selection(context)[["text"]] message_if(selection == "", "Selection was empty") selection } # Get user's selection. Warn if empty. get_indentation <- function() { # Get context context <- rstudioapi::getActiveDocumentContext() selection <- rstudioapi::primary_selection(context) # Get the column of the beginning of the selection selection$range$start[[2]] - 1 # starts at 1 } # split x at each index in pos # Found on stackoverflow (TODO check) split_at <- function(x, pos) { pos <- c(1L, pos, length(x) + 1L) Map(function(x, i, j) x[i:j], list(x), head(pos, -1L), tail(pos, -1L) - 1L ) } # Get indices of list elements that are NULL get_null_indices <- function(l) { if (length(l) > 0) which(sapply(l, is.null)) else integer(0) } # Get names in a list # Remove empty and NULL elements from names list get_element_names <- function(l, remove_empty_names = TRUE) { l_names <- names(l) # Remove empty names "" if (length(l_names) > 0 && isTRUE(remove_empty_names)) { empty_indices <- which(sapply(l_names, function(x) { # Todo test which(sapply (could go wrong!) x == "" || is.null(x) })) if (length(empty_indices) > 0) { l_names <- l_names[-empty_indices] } } l_names } # For testing a list of string expectations # TODO This could be an exported function # TODO The error messages should be better eval_expectations <- function(l, envir) { plyr::l_ply(l, .fun = function(x) { eval(parse(text = x), envir = envir) }) } # Inspired by the reprex package read_clipboard <- function() { if (clipr::clipr_available()) { return(suppressWarnings(enc2utf8(clipr::read_clip()))) } warning("Cannot read clipboard.") NULL }
/scratch/gouwar.j/cran-all/cranData/xpectr/R/addin_utils.R
#' @title Inserts code for a checkmate assert collection #' @description #' \Sexpr[results=rd, stage=render]{lifecycle::badge("experimental")} #' #' RStudio Addin: #' Inserts code for initializing and reporting a #' \code{\link[checkmate:AssertCollection]{checkmate assert collection}}. #' #' See \code{`Details`} for how to set a key command. #' @param add_comments Whether to add comments around. (Logical) #' #' This makes it easy for a user to create their own addin without the comments. #' @param indentation Indentation of the code. (Numeric) #' #' \strong{N.B.} Mainly intended for testing the addin programmatically. #' @param insert Whether to insert the code via #' \code{\link[rstudioapi:rstudio-documents]{rstudioapi::insertText()}} #' or return it. (Logical) #' #' \strong{N.B.} Mainly intended for testing the addin programmatically. #' @author Ludvig Renbo Olsen, \email{r-pkgs@@ludvigolsen.dk} #' @export #' @family addins #' @return Inserts the following (excluding the \code{----}): #' #' \code{----} #' #' \code{# Check arguments ####} #' #' \code{assert_collection <- checkmate::makeAssertCollection()} #' #' \code{# checkmate::assert_ , add = assert_collection)} #' #' \code{checkmate::reportAssertions(assert_collection)} #' #' \code{# End of argument checks ####} #' #' \code{----} #' #' Returns \code{NULL} invisibly. #' @details #' \subsection{How to set up a key command in RStudio}{ #' #' After installing the package. #' Go to: #' #' \code{Tools >> Addins >> Browse Addins >> Keyboard Shortcuts}. #' #' Find \code{"Insert checkmate AssertCollection Code"} and press its field under \code{Shortcut}. #' #' Press desired key command, e.g. \code{Alt+C}. #' #' Press \code{Apply}. #' #' Press \code{Execute}. #' } assertCollectionAddin <- function(add_comments = TRUE, insert = TRUE, indentation = NULL){ # Check arguments #### assert_collection <- checkmate::makeAssertCollection() checkmate::assert_flag(x = add_comments, add = assert_collection) checkmate::assert_flag(x = insert, add = assert_collection) checkmate::assert_integerish(x = indentation, lower = 0, any.missing = FALSE, null.ok = TRUE, add = assert_collection) checkmate::reportAssertions(assert_collection) # End of argument checks #### # Get the indentation if (is.null(indentation)){ indentation <- tryCatch( get_indentation(), error = function(e) { return(0) } ) } to_insert <- c( "assert_collection <- checkmate::makeAssertCollection()", "# checkmate::assert_ , add = assert_collection)", "checkmate::reportAssertions(assert_collection)" ) # Add comments around if (isTRUE(add_comments)){ to_insert <- c( "# Check arguments ####", to_insert, "# End of argument checks ####" ) } if (isTRUE(insert)){ insert_code(to_insert, prepare = TRUE, indentation = indentation) } else { return(to_insert) } invisible() }
/scratch/gouwar.j/cran-all/cranData/xpectr/R/assert_collection_addin.R
# For overview: cmd-alt-o # __________________ #< a728fc4a8cf823f5d1f50ada4565aa66 ># __________________ # Create expectations for NULL #### create_expectations_null <- function(name = NULL, indentation = 0, add_comments = TRUE) { # Check arguments #### assert_collection <- checkmate::makeAssertCollection() add_create_exps_checks( collection = assert_collection, name = name, indentation = indentation, add_comments = add_comments ) checkmate::reportAssertions(assert_collection) # End of argument checks #### # Create test null_expectation <- create_expect_true( x = paste0("is.null(", name, ")"), spaces = 2 ) # Collect expectations and add comments expectations <- c(create_test_comment("is NULL", indentation = indentation, create_comment = add_comments), null_expectation ) expectations } # ____________________________________________________________________________ # Create expectations for function #### create_expectations_function <- function(data, name = NULL, indentation = 0, sample_n = 30, evaluate_once = FALSE, add_comments = TRUE, test_id = 10000) { # Check arguments #### assert_collection <- checkmate::makeAssertCollection() checkmate::assert_function(x = data, add = assert_collection) add_create_exps_checks( collection = assert_collection, name = name, indentation = indentation, sample_n = sample_n, evaluate_once = evaluate_once, add_comments = add_comments, test_id = test_id ) checkmate::reportAssertions(assert_collection) # End of argument checks #### # Make a copy # Used when assigning the call's output to var call_name <- name if (isTRUE(evaluate_once)){ name <- create_output_var_name(id = test_id) } # Create assignment string assign_string <- create_assignment_strings( call_name = call_name, new_name = name, evaluate_once = evaluate_once) # Create test is_fn_expectation <- create_expect_true( x = paste0("is.function(", name, ")"), spaces = 2 ) # Test the formals (arguments' names and default values) formals_expectation <- create_fn_formals_expectation( data = data, name = name, sample_n = sample_n, indentation = indentation ) # Test the function string definition_expectation <- create_deparse_expectation( data = data, name = name, sample_n = sample_n, indentation = indentation ) # Collect expectations and add comments expectations <- c(assign_string, create_test_comment("is function", indentation = indentation, create_comment = add_comments), is_fn_expectation, create_test_comment("argument names and default values", indentation = indentation, create_comment = add_comments), formals_expectation, create_test_comment("function definition", indentation = indentation, create_comment = add_comments), definition_expectation ) expectations } # __________________ #< 2451d1703a5d7b006fa4e72e2dcc59ed ># __________________ # Create expectations data frame #### create_expectations_data_frame <- function(data, name = NULL, indentation = 0, sample_n = 30, tolerance = "1e-4", round_to_tolerance = TRUE, add_comments = TRUE, evaluate_once = FALSE, test_id = NULL) { # Check arguments #### assert_collection <- checkmate::makeAssertCollection() checkmate::assert_data_frame(x = data, add = assert_collection) add_create_exps_checks( collection = assert_collection, name = name, indentation = indentation, tolerance = tolerance, sample_n = sample_n, add_comments = add_comments, evaluate_once = evaluate_once, round_to_tolerance = round_to_tolerance, test_id = test_id ) checkmate::reportAssertions(assert_collection) # End of argument checks #### if (is.null(name)) { name <- trimws(deparse(substitute(data))) } # Make a copy # Used when assigning the call's output to var call_name <- name if (isTRUE(evaluate_once)){ name <- create_output_var_name(id = test_id) } # Create assignment string assign_string <- create_assignment_strings( call_name = call_name, new_name = name, evaluate_once = evaluate_once) # Find digits for rounding if (isTRUE(round_to_tolerance)){ numeric_tolerance <- as.numeric(tolerance) digits <- ndigits(1/numeric_tolerance) # tolerance + 1 } # Create expectations # NOTE: Some must come before sampling! class_expectation <- create_class_expectation(name = name, data = data, indentation = indentation) names_expectation <- create_names_expectation(data = data, name = name, indentation = indentation) dim_expectation <- create_dim_expectation(data = data, name = name, indentation = indentation) column_types_expectation <- create_element_types_expectation(data = data, name = name, sample_n = sample_n, indentation = indentation) column_classes_expectation <- create_element_classes_expectation(data = data, name = name, sample_n = sample_n, indentation = indentation) group_key_names_expectation <- create_group_key_names_expectation(data = data, name = name, indentation = indentation) # Whether to sample data sample_data <- !is.null(sample_n) && nrow(data) > sample_n # Sample data if (isTRUE(sample_data)){ data <- smpl(data = data, n = sample_n, keep_order = TRUE) } # Create expect_equal expectations column_expectations <- plyr::llply(colnames(data), function(col_name) { # Get current column current_col <- data[[col_name]] if (is.list(current_col)) { return(NULL) } # Left side of expectation x <- paste0(name, "[[\"", col_name, "\"]]") if (isTRUE(sample_data)){ x <- paste0("xpectr::smpl(", x, ", n = ", sample_n, ")") } if (is.numeric(current_col) && isTRUE(round_to_tolerance)){ current_col <- round(current_col, digits = digits) } # Right side of expectation y <- capture.output(dput(current_col)) # In case dput spanned multiple lines # we collapse them to one string y <- collapse_strings(y) # Sanity check if (length(y) > 1) { return(NULL) } # Create expect_equal text create_expect_equal( x, y, add_tolerance = is.numeric(current_col), add_fixed = is.character(current_col), spaces = 2, tolerance = tolerance) }) null_indices <- get_null_indices(column_expectations) if (length(null_indices) > 0) { # Warn about skipped elements skipped_cols <- colnames(data)[null_indices] plural_s <- ifelse(length(skipped_cols) > 1, "s", "") warning(paste0( "Skipped column", plural_s, " ", paste0(skipped_cols, collapse = ", "), "." )) # Remove NULLS column_expectations <- column_expectations[-null_indices] } # Collect expectations and add comments expectations <- c(assign_string, create_test_comment("class", indentation = indentation, create_comment = add_comments), class_expectation, create_test_comment("column values", indentation = indentation, create_comment = add_comments), column_expectations, create_test_comment("column names", indentation = indentation, create_comment = add_comments), names_expectation, create_test_comment("column classes", indentation = indentation, create_comment = add_comments), column_classes_expectation, create_test_comment("column types", indentation = indentation, create_comment = add_comments), column_types_expectation, create_test_comment("dimensions", indentation = indentation, create_comment = add_comments), dim_expectation, create_test_comment("group keys", indentation = indentation, create_comment = add_comments), group_key_names_expectation ) expectations } # __________________ #< 64bfa943afd1c6099390df317edf6e8a ># __________________ # Create expectations matrix #### create_expectations_matrix <- function(data, name = NULL, indentation = 0, sample_n = 30, tolerance = "1e-4", round_to_tolerance = TRUE, add_comments = TRUE, evaluate_once = FALSE, test_id = NULL) { # Check arguments #### assert_collection <- checkmate::makeAssertCollection() checkmate::assert_matrix(x = data, add = assert_collection) add_create_exps_checks( collection = assert_collection, name = name, indentation = indentation, tolerance = tolerance, sample_n = sample_n, add_comments = add_comments, evaluate_once = evaluate_once, round_to_tolerance = round_to_tolerance, test_id = test_id ) checkmate::reportAssertions(assert_collection) # End of argument checks #### if (is.null(name)) { name <- trimws(deparse(substitute(data))) } # Make a copy # Used when assigning the call's output to var call_name <- name if (isTRUE(evaluate_once)){ name <- create_output_var_name(id = test_id) } # Create assignment string assign_string <- create_assignment_strings( call_name = call_name, new_name = name, evaluate_once = evaluate_once) # Create expectations # NOTE: Some must come before sampling! # Add [[1]] to class expectation as matrices also inherit from arrays # in the devel version of R! class_expectation <- create_class_expectation(name = name, data = data, suffix = ")[[1]]", indentation = indentation) type_expectation <- create_type_expectation(name = name, type = typeof(data), indentation = indentation) colnames_expectation <- create_colnames_expectation(data = data, name = name, indentation = indentation) rownames_expectation <- create_rownames_expectation(data = data, name = name, indentation = indentation) dim_expectation <- create_dim_expectation(data = data, name = name, indentation = indentation) symmetry_expectation <- tryCatch( # Doesn't work for table objects create_is_symmetric_expectation(data = data, name = name, indentation = indentation), error = function(e){return(NULL)}) # Find digits for rounding if (isTRUE(round_to_tolerance) && is.numeric(data)){ numeric_tolerance <- as.numeric(tolerance) digits <- ndigits(1/numeric_tolerance) # tolerance + 1 data <- round(data, digits = digits) } # Whether to sample data sample_data <- !is.null(sample_n) && max(dim(data)) > sample_n row_indices <- seq_len(nrow(data)) col_indices <- seq_len(ncol(data)) # Sample data (TODO Specify axis!!) if (isTRUE(sample_data)){ if (min(dim(data)) > sample_n){ slice_axis <- "column" } else { slice_axis <- ifelse(ncol(data) > nrow(data), "row", "column") } row_indices <- smpl(data = row_indices, n = sample_n, keep_order = TRUE) col_indices <- smpl(data = col_indices, n = sample_n, keep_order = TRUE) } else { # Whether to test columns or rows slice_axis <- ifelse(ncol(data) > nrow(data), "row", "column") } if (slice_axis == "row"){ slice_indices <- row_indices data <- data[, col_indices] } else if (slice_axis == "column"){ slice_indices <- col_indices data <- data[row_indices, ] } # Create expect_equal expectations slice_expectations <- plyr::llply(slice_indices, function(i) { # Get current slice if (slice_axis == "row"){ current_slice <- data[i, ] x <- paste0(name, "[", i, ", ]") } else if (slice_axis == "column"){ current_slice <- data[, i] x <- paste0(name, "[, ", i, "]") } else { stop("'slice_axis' must be 'row' or 'column'.") } # Left side of expectation if (isTRUE(sample_data)){ x <- paste0("xpectr::smpl(", x, ", n = ", sample_n, ")") } # Right side of expectation y <- capture.output(dput(current_slice)) # In case dput spanned multiple lines # we collapse them to one string y <- collapse_strings(y) # Sanity check if (length(y) != 1) { return(NULL) } # Create expect_equal text create_expect_equal(x, y, add_tolerance = is.numeric(current_slice), add_fixed = is.character(current_slice), spaces = 2, tolerance = tolerance) }) # Collect expectations and add comments expectations <- c(assign_string, create_test_comment("class", indentation = indentation, create_comment = add_comments), class_expectation, create_test_comment("type", indentation = indentation, create_comment = add_comments), type_expectation, create_test_comment(paste0(slice_axis, " values"), indentation = indentation, create_comment = add_comments), slice_expectations, create_test_comment("column names", indentation = indentation, create_comment = add_comments), colnames_expectation, create_test_comment("row names", indentation = indentation, create_comment = add_comments), rownames_expectation, create_test_comment("dimensions", indentation = indentation, create_comment = add_comments), dim_expectation, create_test_comment("symmetry", indentation = indentation, create_comment = add_comments && !is.null(symmetry_expectation)), symmetry_expectation ) expectations } # __________________ #< 57651c0852811eeaef463b8c09390020 ># __________________ # Create expectations vector #### # Only split into multiple tests when all elements are named # plus some other checks create_expectations_vector <- function(data, name = NULL, indentation = 0, sample_n = 30, tolerance = "1e-4", round_to_tolerance = TRUE, add_comments = TRUE, evaluate_once = FALSE, test_id = NULL) { # Check arguments #### assert_collection <- checkmate::makeAssertCollection() checkmate::assert_vector(x = data, add = assert_collection) add_create_exps_checks( collection = assert_collection, name = name, indentation = indentation, tolerance = tolerance, sample_n = sample_n, add_comments = add_comments, evaluate_once = evaluate_once, round_to_tolerance = round_to_tolerance, test_id = test_id ) checkmate::reportAssertions(assert_collection) # End of argument checks #### if (is.null(name)) { name <- trimws(deparse(substitute(data))) } # Make a copy # Used when assigning the call's output to var call_name <- name if (isTRUE(evaluate_once)){ name <- create_output_var_name(id = test_id) } # Create assignment string assign_string <- create_assignment_strings( call_name = call_name, new_name = name, evaluate_once = evaluate_once) # Find digits for rounding if (isTRUE(round_to_tolerance)){ numeric_tolerance <- as.numeric(tolerance) digits <- ndigits(1/numeric_tolerance) # tolerance + 1 } # Create expectations # Without sampling type_expectation <- create_type_expectation(name = name, type = typeof(data), indentation = indentation) class_expectation <- create_class_expectation(name = name, data = data, indentation = indentation) length_expectation <- create_length_expectation(data, name, indentation = indentation) sublengths_expectation <- create_sum_sub_lengths_expectation(data, name, indentation = indentation) # Whether to sample data sample_data <- !is.null(sample_n) && length(data) > sample_n # Sample data if (isTRUE(sample_data)){ data <- smpl(data = data, n = sample_n, keep_order = TRUE) } # Get non-empty and non-NULL element names element_names <- get_element_names(data, remove_empty_names = TRUE) # In order to establish whether we should test each element separately # we first check if the elements are simple and have length 1 is_simple <- checkmate::test_list( as.list(data), types = c( "logical", "integer", "double", "numeric", "complex", "atomic", "function", "null" ) ) && !any(element_lengths(data, length) > 1) all_uniquely_named <- checkmate::test_list(x = as.list(data), names = "unique") # If all elements have names # We can test each individually if (isTRUE(all_uniquely_named) && !isTRUE(is_simple) ) { element_types_expectation <- create_element_types_expectation( data = data, name = name, sample_n = sample_n, indentation = indentation ) element_classes_expectation <- create_element_classes_expectation( data = data, name = name, sample_n = sample_n, indentation = indentation ) # Create expect_equal expectations value_expectations <- plyr::llply(element_names, function(elem_name) { # Get current column current_elem <- data[[elem_name]] # Left side of expectation x <- paste0(name, "[[\"", elem_name, "\"]]") # Determine whether to sample element if (is.data.frame(current_elem)) sample_slice <- !is.null(sample_n) && nrow(current_elem) > sample_n else if (is.vector(current_elem)) sample_slice <- !is.null(sample_n) && length(current_elem) > sample_n else sample_slice <- FALSE # Sample element if (isTRUE(sample_slice)){ current_elem <- smpl(current_elem, n = sample_n, keep_order = TRUE) x <- paste0("xpectr::smpl(", x, ", n = ", sample_n, ")") } # Round to tolerance if (is.numeric(current_elem) && isTRUE(round_to_tolerance)){ current_elem <- round(current_elem, digits = digits) } # Right side of expectation y <- capture.output(dput(current_elem)) # In case dput spanned multiple lines # we collapse them to one string y <- collapse_strings(y) # sanity check if (length(y) > 1) { return(NULL) } # Create expect_equal text create_expect_equal(x, y, add_tolerance = is.numeric(current_elem), add_fixed = is.character(current_elem), spaces = 2, tolerance = tolerance) }) } else { x <- name if (isTRUE(sample_data)){ x <- paste0("xpectr::smpl(", x, ", n = ", sample_n, ")") } # Round to tolerance if (is.numeric(data) && isTRUE(round_to_tolerance)){ data <- round(data, digits = digits) } y <- capture.output(dput(data)) # In case dput spanned multiple lines # we collapse them to one string y <- collapse_strings(y) value_expectations <- list( create_expect_equal( x, y, add_tolerance = is.numeric(data), add_fixed = is.character(data), spaces = 2, tolerance = tolerance ) ) } # Note: as list(1,2,3)[-integer()] returns and empty list # We must check if there's a NULL first null_indices <- get_null_indices(value_expectations) if (length(null_indices) > 0) { # Warn about skipped elements plural_s <- ifelse(length(null_indices) > 1, "s", "") warning(paste0( "Skipped element", plural_s, " ", paste0(null_indices, collapse = ", "), "." )) # Remove NULLS value_expectations <- value_expectations[-null_indices] } # Create names expectation if (isTRUE(sample_data)){ sampled_name <- paste0("xpectr::smpl(", name, ", n = ", sample_n, ")") } else sampled_name <- name names_expectation <- create_names_expectation(data, sampled_name, indentation = indentation) if (exists("element_types_expectation")){ element_types_classes_expectations <- c( create_test_comment("element classes", indentation = indentation, create_comment = add_comments), element_classes_expectation, create_test_comment("element types", indentation = indentation, create_comment = add_comments), element_types_expectation ) } else { element_types_classes_expectations <- NULL } expectations <- c(assign_string, create_test_comment("class", indentation = indentation, create_comment = add_comments), class_expectation, create_test_comment("type", indentation = indentation, create_comment = add_comments), type_expectation, create_test_comment("values", indentation = indentation, create_comment = add_comments), value_expectations, create_test_comment("names", indentation = indentation, create_comment = add_comments), names_expectation, create_test_comment("length", indentation = indentation, create_comment = add_comments), length_expectation, create_test_comment("sum of element lengths", indentation = indentation, create_comment = add_comments), sublengths_expectation, element_types_classes_expectations ) expectations } # __________________ #< a7adafd5b429db7b53bf49e26d1a7568 ># __________________ # Create expectations side effects #### create_expectations_side_effect <- function(side_effects, name = NULL, copy_env = FALSE, indentation = 0, strip = TRUE, add_comments = TRUE, test_id = 10000) { # Check arguments #### assert_collection <- checkmate::makeAssertCollection() checkmate::assert_list( x = side_effects, all.missing = FALSE, len = 5, add = assert_collection ) checkmate::assert_names( x = names(side_effects), identical.to = c( "error", "error_class", "warnings", "messages", "has_side_effects" ), type = "named" ) add_create_exps_checks( collection = assert_collection, name = name, indentation = indentation, add_comments = add_comments ) checkmate::assert_flag( x = strip, add = assert_collection ) checkmate::assert_flag( x = copy_env, add = assert_collection ) checkmate::reportAssertions(assert_collection) # End of argument checks #### if (is.null(name)) { # TODO Not sure this would work (not used currently) name <- deparse(substitute(side_effects)) } call_name <- name name <- create_output_var_name("side_effects_", test_id) copy_env_string <- ifelse(isTRUE(copy_env), ", copy_env = TRUE", "") # Create assignment string assign_string <- create_assignment_strings( call_name = paste0("xpectr::capture_side_effects(", call_name, copy_env_string, ", reset_seed = TRUE)"), new_name = name, evaluate_once = TRUE, comment = "# Assigning side effects") expectations <- list(assign_string) if (!is.null(side_effects$error)) { err_expectation <- create_equality_expectation( data = side_effects, name = name, prefix = "", suffix = "[['error']]", add_strip = strip, add_fixed = TRUE, indentation = indentation ) err_class_expectation <- create_equality_expectation( data = side_effects, name = name, prefix = "", suffix = "[['error_class']]", add_strip = strip, add_fixed = TRUE, indentation = indentation ) expectations <- c( expectations, err_expectation, err_class_expectation ) } else { msg_expectation <- create_equality_expectation( data = side_effects, name = name, prefix = "", suffix = "[['messages']]", add_strip = strip, add_fixed = TRUE, indentation = indentation ) warns_expectation <- create_equality_expectation( data = side_effects, name = name, prefix = "", suffix = "[['warnings']]", add_strip = strip, add_fixed = TRUE, indentation = indentation ) expectations <- c( expectations, warns_expectation, msg_expectation) } # TODO add expectation of side effect counts (for warnings and messages at least) expectations <- c( create_test_comment("side effects", indentation = indentation, create_comment = add_comments), expectations ) %>% unlist() %>% as.list() } # __________________ #< ff3057d67f7da6a3155f5034c941f142 ># __________________ # Create expectations factor #### # Only split into multiple tests when all elements are named # plus some other checks create_expectations_factor <- function(data, name = NULL, indentation = 0, sample_n = 30, tolerance = "1e-4", add_comments = TRUE, evaluate_once = FALSE, test_id = NULL) { # Check arguments #### assert_collection <- checkmate::makeAssertCollection() checkmate::assert_factor(x = data, add = assert_collection) add_create_exps_checks( collection = assert_collection, name = name, indentation = indentation, tolerance = tolerance, sample_n = sample_n, add_comments = add_comments, evaluate_once = evaluate_once, test_id = test_id ) checkmate::reportAssertions(assert_collection) # End of argument checks #### if (is.null(name)) { name <- trimws(deparse(substitute(data))) } # Make a copy # Used when assigning the call's output to var call_name <- name if (isTRUE(evaluate_once)){ name <- create_output_var_name(id = test_id) } # Create assignment string assign_string <- create_assignment_strings( call_name = call_name, new_name = name, evaluate_once = evaluate_once) # Without sampling factor_expectation <- create_is_factor_expectation(name = name, indentation = indentation) length_expectation <- create_length_expectation(data = data, name = name, indentation = indentation) n_levels_expectation <- create_nlevels_expectation(data = data, name = name, indentation = indentation) # With sampling value_expectations <- create_as_character_expectation(data = data, name = name, sample_n = sample_n, indentation = indentation) levels_expectation <- create_levels_expectation(data = data, name = name, sample_n = sample_n, indentation = indentation) names_expectation <- create_names_expectation(data = data, name = name, sample_n = sample_n, indentation = indentation) expectations <- c(assign_string, create_test_comment("is factor", indentation = indentation, create_comment = add_comments), factor_expectation, create_test_comment("values", indentation = indentation, create_comment = add_comments), value_expectations, create_test_comment("names", indentation = indentation, create_comment = add_comments), names_expectation, create_test_comment("length", indentation = indentation, create_comment = add_comments), length_expectation, create_test_comment("number of levels", indentation = indentation, create_comment = add_comments), n_levels_expectation, create_test_comment("levels", indentation = indentation, create_comment = add_comments), levels_expectation ) expectations } # __________________ #< b696d526380be550b639f9efdbb1ac91 ># __________________ # Create expectations formula #### create_expectations_formula <- function(data, name = NULL, indentation = 0, add_comments = TRUE, evaluate_once = FALSE, test_id = NULL) { # Check arguments #### assert_collection <- checkmate::makeAssertCollection() checkmate::assert_formula(x = data, add = assert_collection) add_create_exps_checks( collection = assert_collection, name = name, indentation = indentation, add_comments = add_comments, evaluate_once = evaluate_once, test_id = test_id ) checkmate::reportAssertions(assert_collection) # End of argument checks #### # Make a copy # Used when assigning the call's output to var call_name <- name if (isTRUE(evaluate_once)){ name <- create_output_var_name(id = test_id) } # Create assignment string assign_string <- create_assignment_strings( call_name = call_name, new_name = name, evaluate_once = evaluate_once) # Create is_formula test is_formula_expectation <- create_expect_true( x = paste0("rlang::is_formula(", name, ")"), spaces = 2 ) # Test the formula formula_expectation <- create_formula_expectation( data = data, name = name, indentation = indentation ) # Collect expectations and add comments expectations <- c(assign_string, create_test_comment("is formula", indentation = indentation, create_comment = add_comments), is_formula_expectation, create_test_comment("formula", indentation = indentation, create_comment = add_comments), formula_expectation ) expectations } # __________________ #< 1a04985673e4647d6eb888d8bf7e76c1 ># __________________ # Create expectation fallback #### create_expectations_fallback <- function(data, name = NULL, indentation = 0, add_comments = TRUE, evaluate_once = FALSE, test_id = NULL) { # Check arguments #### assert_collection <- checkmate::makeAssertCollection() add_create_exps_checks( collection = assert_collection, name = name, indentation = indentation, add_comments = add_comments, evaluate_once = evaluate_once, test_id = test_id ) checkmate::reportAssertions(assert_collection) # End of argument checks #### # Make a copy # Used when assigning the call's output to var call_name <- name if (isTRUE(evaluate_once)){ name <- create_output_var_name(id = test_id) } # Create assignment string assign_string <- create_assignment_strings( call_name = call_name, new_name = name, evaluate_once = evaluate_once) class_expectation <- create_class_expectation(name = name, data = data, indentation = indentation) type_expectation <- create_type_expectation(name = name, type = typeof(data), indentation = indentation) names_expectation <- create_names_expectation(data = data, name = name, indentation = indentation) dput_expectation <- create_equality_expectation(data = data, name = name, prefix = "", suffix = "", indentation = indentation) # Collect expectations and add comments expectations <- c(create_test_comment("Unsupported class: using fallback tests", indentation = indentation, section = "manual", create_comment = add_comments), assign_string, create_test_comment("class", indentation = indentation, create_comment = add_comments), class_expectation, create_test_comment("type", indentation = indentation, create_comment = add_comments), type_expectation, create_test_comment("names", indentation = indentation, create_comment = add_comments), names_expectation, create_test_comment("dput() content", indentation = indentation, create_comment = add_comments), dput_expectation ) expectations } # __________________ #< 3feae1f2a76409360ca8e7fa286cbdf9 ># __________________ # Common arg checks #### # Adds common checks to assert collection add_create_exps_checks <- function(collection, name, indentation = 0, tolerance = "1e-4", round_to_tolerance = TRUE, sample_n = 30, add_wrapper_comments = TRUE, add_test_comments = TRUE, add_comments = TRUE, evaluate_once = FALSE, test_id = NULL) { checkmate::assert_string( x = name, min.chars = 1, null.ok = TRUE, add = collection ) checkmate::assert_string(x = tolerance, add = collection) checkmate::assert_count(x = indentation, add = collection) checkmate::assert_count(x = sample_n, null.ok = TRUE, add = collection) checkmate::assert_count(x = test_id, null.ok = TRUE, positive = TRUE, add = collection) checkmate::assert_flag(x = add_wrapper_comments, add = collection) checkmate::assert_flag(x = add_test_comments, add = collection) checkmate::assert_flag(x = add_comments, add = collection) checkmate::assert_flag(x = evaluate_once, add = collection) checkmate::assert_flag(x = round_to_tolerance, add = collection) } # __________________ #< 8a79652e81ccaedb871a49e1f8421c1c ># __________________ # Create output name #### create_output_var_name <- function(prefix = "output_", id = NULL){ if (is.null(id)) id <- floor(runif(1, 10000, 19999)) paste0(prefix, id) } # __________________ #< ab5891096b0ab8586b37f58552cbda23 ># __________________ # Create assignment strings #### create_assignment_strings <- function(call_name, new_name, evaluate_once, comment = "# Assigning output"){ # Check arguments #### assert_collection <- checkmate::makeAssertCollection() checkmate::assert_flag(x = evaluate_once, add = assert_collection) checkmate::assert_string(x = call_name, add = assert_collection) checkmate::assert_string(x = new_name, add = assert_collection) checkmate::reportAssertions(assert_collection) # End of argument checks #### if (isTRUE(evaluate_once)){ assign_string <- c( comment, paste0(new_name, " <- ", call_name)) } else { assign_string <- NULL } assign_string }
/scratch/gouwar.j/cran-all/cranData/xpectr/R/create_expectations.R
# __________________ #< a4e6c4b8d57e42c270d1c97b24c965f8 ># __________________ # Do if family #### #' @title Simple side effect functions #' @name stop_if #' @description #' \Sexpr[results=rd, stage=render]{lifecycle::badge("experimental")} #' #' If the \code{`condition`} is \code{TRUE}, #' generate \code{error}/\code{warning}/\code{message} with the supplied message. #' @param condition The condition to check. (Logical) #' @param message Message. (Character) #' #' Note: If \code{NULL}, the \code{`condition`} will be used as message. #' @param sys.parent.n The number of generations to go back when calling the message function. #' @author Ludvig Renbo Olsen, \email{r-pkgs@@ludvigolsen.dk} #' @return Returns \code{NULL} invisibly. #' @details #' When \code{`condition`} is \code{FALSE}, they return \code{NULL} invisibly. #' #' When \code{`condition`} is \code{TRUE}: #' #' \subsection{stop_if()}{ #' Throws error with the supplied message. #' } #' \subsection{warn_if()}{ #' Throws warning with the supplied message. #' } #' \subsection{message_if()}{ #' Generates message with the supplied message. #' } #' @examples #' # Attach packages #' library(xpectr) #' \dontrun{ #' a <- 0 #' stop_if(a == 0, "'a' cannot be 0.") #' warn_if(a == 0, "'a' was 0.") #' message_if(a == 0, "'a' was so kind to be 0.") #' } #' @importFrom rlang := NULL # NOTE Aliases only work when building the package # so use do_if to see docs add_condition_prefix <- function(m) { paste0("This was TRUE: ", m) } # __________________ #< 137557485c74acc6406cd780ee5b6edb ># __________________ # stop_if #### #' @rdname stop_if #' @export stop_if <- function(condition, message = NULL, sys.parent.n = 0L) { if (condition) { # If message is NULL, get condition if (is.null(message)) { message <- tryCatch( # Doesn't really work to do this in subfunction deparse( substitute( expr = condition, env = sys.frame(which = sys.nframe()) ) ), error = function(e) { stop("Cannot use 'condition' as message. Please provide a message.") }, warning = function(w) { stop("Cannot use 'condition' as message. Please provide a message.") } ) # Add "This was TRUE: " message <- add_condition_prefix(message) } stop( simpleError( message, call = if (p <- sys.parent(sys.parent.n+1)) sys.call(p))) } invisible() } # __________________ #< 80cb7ed785f3edf07e65abebbe27d157 ># __________________ # warn_if #### #' @rdname stop_if #' @export warn_if <- function(condition, message = NULL, sys.parent.n = 0L) { if (condition) { # If message is NULL, get condition if (is.null(message)) { message <- tryCatch( # Doesn't really work to do this in subfunction deparse( substitute( expr = condition, env = sys.frame(which = sys.nframe()) ) ), error = function(e) { stop("Cannot use 'condition' as message. Please provide a message.") }, warning = function(w) { stop("Cannot use 'condition' as message. Please provide a message.") } ) # Add "This was TRUE: " message <- add_condition_prefix(message) } warning( simpleWarning( message, call = if (p <- sys.parent(sys.parent.n+1)) sys.call(p))) } invisible() } # __________________ #< 0b979d2011c6ffa7f887ce415b9612b1 ># __________________ # message_if #### #' @rdname stop_if #' @export message_if <- function(condition, message = NULL, sys.parent.n = 0L) { if (condition) { # If message is NULL, get condition if (is.null(message)) { message <- tryCatch( # Doesn't really work to do this in subfunction deparse( substitute( expr = condition, env = sys.frame(which = sys.nframe()) ) ), error = function(e) { stop("Cannot use 'condition' as message. Please provide a message.") }, warning = function(w) { stop("Cannot use 'condition' as message. Please provide a message.") } ) # Add "This was TRUE: " message <- add_condition_prefix(message) } message( simpleMessage( paste0(message,"\n"), call = if (p <- sys.parent(sys.parent.n + 1)) sys.call(p))) } invisible() } # __________________ #< 67ff2c242b343b96414a9f3df8ab7067 ># __________________ # identity_if #### # Not sure this is useful # It seems to be no different than ifelse # Except that it doesn't check types and lengths, etc. # So perhaps look into whether it should be a "free" ifelse? # Keep internally for now identity_if <- function(condition, x, otherwise = invisible()) { if (condition) { return(x) } otherwise } # __________________ #< 53196784009271631dda5f0ea3f9e5da ># __________________ # do_if #### # Not sure this is useful # R already has lazy evaluation # And it's not easier to read than a simple for loop # Keep internally for now do_if <- function(condition, fn, ..., otherwise = invisible()) { assert_collection <- checkmate::makeAssertCollection() checkmate::assert_function(x = fn, add = assert_collection) checkmate::reportAssertions(assert_collection) if (condition) { return(fn(...)) } otherwise }
/scratch/gouwar.j/cran-all/cranData/xpectr/R/do_if.R
# __________________ #< 90a81bcce8455070cdfb04265d716dd6 ># __________________ # dput() selection addin #### #' @title Replaces selected code with its dput() output #' @description #' \Sexpr[results=rd, stage=render]{lifecycle::badge("experimental")} #' #' RStudio Addin: #' Runs \code{\link[base:dput]{dput()}} on the selected code and inserts #' it instead of the selection. #' #' See \code{`Details`} for how to set a key command. #' @author Ludvig Renbo Olsen, \email{r-pkgs@@ludvigolsen.dk} #' @param selection String of code. (Character) #' #' E.g. \code{"stop('This gives an expect_error test')"}. #' #' \strong{N.B.} Mainly intended for testing the addin programmatically. #' @param indentation Indentation of the selection. (Numeric) #' #' \strong{N.B.} Mainly intended for testing the addin programmatically. #' @param insert Whether to insert the expectations via #' \code{\link[rstudioapi:rstudio-documents]{rstudioapi::insertText()}} #' or return them. (Logical) #' #' \strong{N.B.} Mainly intended for testing the addin programmatically. #' @export #' @family addins #' @return Inserts the output of running #' \code{\link[base:dput]{dput()}} on the selected code. #' #' Does not return anything. #' @details #' \subsection{How}{ #' Parses and evaluates the selected code string, #' applies \code{\link[base:dput]{dput()}} and #' inserts the output instead of the selection. #' } #' \subsection{How to set up a key command in RStudio}{ #' #' After installing the package. #' Go to: #' #' \code{Tools >> Addins >> Browse Addins >> Keyboard Shortcuts}. #' #' Find \code{"dput() Selected"} and press its field under \code{Shortcut}. #' #' Press desired key command, e.g. \code{Alt+D}. #' #' Press \code{Apply}. #' #' Press \code{Execute}. #' } dputSelectedAddin <- function(selection = NULL, insert = TRUE, indentation = 0) { # Check arguments #### assert_collection <- checkmate::makeAssertCollection() checkmate::assert_string(x = selection, null.ok = TRUE, add = assert_collection) checkmate::assert_flag(x = insert, add = assert_collection) checkmate::assert_integerish(x = indentation, lower = 0, any.missing = FALSE, null.ok = TRUE, add = assert_collection) checkmate::reportAssertions(assert_collection) # End of argument checks #### # Get the selection and indentation if (is.null(selection)){ selection <- tryCatch(get_selection(), error = function(e){return("")}, message = function(m){return("")}) indentation <- tryCatch(get_indentation(), error = function(e){return(0)}) } # Get parent environment parent_envir <- parent.frame() # dput() and insert/return if (!is.null(selection) && selection != "") { dput_out <- apply_capture(selection, dput, envir = parent_envir) if (!isTRUE(insert)) { # Return the expectations instead of inserting them return(dput_out) } else { # Insert the expectations insert_code(dput_out, indentation = indentation) } } invisible() }
/scratch/gouwar.j/cran-all/cranData/xpectr/R/dput_addins.R
# __________________ #< 60cfc78f594e5611a6eaaf34a2b212ae ># __________________ # Element descriptors #### ## .................. #< 440b147b963f8a7fd202661bfc3b068e ># .................. ## Element lengths #### #' @title Gets the length of each element #' @description #' \Sexpr[results=rd, stage=render]{lifecycle::badge("experimental")} #' #' Applies \code{\link[base:length]{length()}} to each element of \code{`x`} (without recursion). #' @param x List with elements. #' @param keep_names Whether to keep existing names. (Logical) #' @family element descriptors #' @author Ludvig Renbo Olsen, \email{r-pkgs@@ludvigolsen.dk} #' @return The length of each element. #' @export #' @details #' Simple wrapper for \code{unlist(lapply(x, length))}. #' @examples #' # Attach packages #' library(xpectr) #' #' l <- list("a" = c(1,2,3), "b" = 1, "c" = NULL) #' #' element_lengths(l) #' element_lengths(l, keep_names = TRUE) element_lengths <- function(x, keep_names = FALSE){ unlist(lapply(x, length), use.names = keep_names) } ## .................. #< abd5e8f22decefad01cca729a155076c ># .................. ## Element types #### #' @title Gets the type of each element #' @description #' \Sexpr[results=rd, stage=render]{lifecycle::badge("experimental")} #' #' Applies \code{\link[base:typeof]{typeof()}} to each element of \code{`x`} (without recursion). #' @inheritParams element_lengths #' @family element descriptors #' @author Ludvig Renbo Olsen, \email{r-pkgs@@ludvigolsen.dk} #' @export #' @return The type of each element. #' @details #' Simple wrapper for \code{unlist(lapply(x, typeof))}. #' @examples #' # Attach packages #' library(xpectr) #' #' l <- list("a" = c(1,2,3), "b" = "a", "c" = NULL) #' #' element_types(l) #' element_types(l, keep_names = TRUE) element_types <- function(x, keep_names = FALSE){ unlist(lapply(x, typeof), use.names = keep_names) } ## .................. #< cad874f32d32a8eae09090d2894d7ad5 ># .................. ## Element classes #### #' @title Gets the class of each element #' @description #' \Sexpr[results=rd, stage=render]{lifecycle::badge("experimental")} #' #' Applies \code{\link[base:class]{class()}} to each element of \code{`x`} (without recursion). When #' \code{class()} returns multiple strings, the first class string is returned. #' @inheritParams element_lengths #' @family element descriptors #' @author Ludvig Renbo Olsen, \email{r-pkgs@@ludvigolsen.dk} #' @export #' @return The main class of each element. #' @details #' Gets first string in \code{class()} for all elements. #' @examples #' # Attach packages #' library(xpectr) #' #' l <- list("a" = c(1,2,3), "b" = "a", "c" = NULL) #' #' element_classes(l) #' element_classes(l, keep_names = TRUE) element_classes <- function(x, keep_names = FALSE){ first_class <- function(x){class(x)[[1]]} unlist(lapply(x, first_class), use.names = keep_names) } ## .................. #< 16b58b1186e423259991634cf27c01de ># .................. ## Total number of elements #### #' @title Total number of elements #' @description #' \Sexpr[results=rd, stage=render]{lifecycle::badge("experimental")} #' #' Unlists \code{`x`} recursively and finds the total number of elements. #' @param x List with elements. #' @param deduplicated Whether to only count the unique elements. (Logical) #' @family element descriptors #' @author Ludvig Renbo Olsen, \email{r-pkgs@@ludvigolsen.dk} #' @export #' @return The total number of elements in \code{`x`}. #' @details #' Simple wrapper for #' \code{length(unlist(x, recursive = TRUE, use.names = FALSE))}. #' @examples #' # Attach packages #' library(xpectr) #' #' l <- list(list(list(1, 2, 3), list(2, list(3, 2))), #' list(1, list(list(2, 4), list(7, 1, list(3, 8)))), #' list(list(2, 7, 8), list(10, 2, list(18, 1, 4)))) #' #' num_total_elements(l) #' num_total_elements(l, deduplicated = TRUE) num_total_elements <- function(x, deduplicated = FALSE){ elems <- unlist(x, recursive = TRUE, use.names = FALSE) if (isTRUE(deduplicated)) elems <- unique(elems) length(elems) }
/scratch/gouwar.j/cran-all/cranData/xpectr/R/element_descriptors.R
# __________________ #< bff1ce9ea40e521479e8d8cf57f1bc31 ># __________________ # Expectation creator wrappers #### ## .................. #< 3a9d08f950c35f0d601ec991f55cb5d6 ># .................. ## Create equality expectation #### # Creates expect_equal create_equality_expectation <- function(data, name, prefix, suffix, add_strip = FALSE, add_tolerance = FALSE, add_fixed = FALSE, indentation = 0) { # Create x x <- paste0(prefix, name, suffix) # Create y as string y_string <- paste0(prefix, "data", suffix) # Get current environment current_envir <- sys.frame(which = sys.nframe()) # Evaluate y and capture its dput y <- apply_capture( string = y_string, fn = dput, envir = current_envir) y <- collapse_strings(y) # Add strips y <- add_strip(y, strip = add_strip) x <- add_strip(x, strip = add_strip) # Create test create_expect_equal( x = x, y = y, add_tolerance = add_tolerance, add_fixed = add_fixed, spaces = 2 ) } ## .................. #< fe7d19065058acccdc4ac9d5067ca9ae ># .................. ## Create type and class expectations #### create_type_expectation <- function(name, type, prefix = "", suffix = "", indentation = 0) { # Create x x <- paste0(prefix, name, suffix) # Create test create_expect_type( x = x, type = add_quotation_marks(type), spaces = 2 ) } create_class_expectation <- function(name, data, prefix = "class(", suffix = ")", indentation = 0) { # Create x x <- paste0(prefix, name, suffix) y <- collapse_strings(capture.output(dput(class(data)))) # Create test create_expect_equal( x = x, y = y, add_fixed = TRUE, spaces = 2 ) } ## .................. #< bffc8add6da673fdf2613e0e958327cf ># .................. ## Create condition expectation #### create_condition_expectation <- function(name, prefix = "", suffix = "", indentation = 0) { # Create x x <- paste0(prefix, name, suffix) # Create test create_expect_true( x = x, spaces = 2 ) } # __________________ #< 440b147b963f8a7fd202661bfc3b068e ># __________________ # Creators #### ## .................. #< abd5e8f22decefad01cca729a155076c ># .................. ## Create names expectation #### # returns: expect_equal(names(name), c("a","b")) create_names_expectation <- function(data, name, sample_n = NULL, indentation = 0) { pref_suff <- add_smpl_string( condition = !is.null(sample_n) && length(data) > sample_n, sample_n = sample_n) create_equality_expectation( data = data, name = name, prefix = paste0("names(", pref_suff[["prefix"]]), suffix = paste0(pref_suff[["suffix"]],")"), add_fixed = TRUE, indentation = indentation ) } create_colnames_expectation <- function(data, name, sample_n = NULL, indentation = 0) { pref_suff <- add_smpl_string( condition = !is.null(sample_n) && ncol(data) > sample_n, sample_n = sample_n) create_equality_expectation( data = data, name = name, prefix = paste0("colnames(", pref_suff[["prefix"]]), suffix = paste0(pref_suff[["suffix"]],")"), add_fixed = TRUE, indentation = indentation ) } create_rownames_expectation <- function(data, name, sample_n = NULL, indentation = 0) { pref_suff <- add_smpl_string( condition = !is.null(sample_n) && nrow(data) > sample_n, sample_n = sample_n) create_equality_expectation( data = data, name = name, prefix = paste0("rownames(", pref_suff[["prefix"]]), suffix = paste0(pref_suff[["suffix"]],")"), add_fixed = TRUE, indentation = indentation ) } ## .................. #< cad874f32d32a8eae09090d2894d7ad5 ># .................. ## Create dimensions expectation #### # Does not work for all types of data! # Use for data frames only for now! create_dim_expectation <- function(data, name, indentation = 0) { create_equality_expectation( data = data, name = name, prefix = "dim(", suffix = ")", indentation = indentation ) } ## .................. #< 79a1a50b2f6fd2bc4a62237a6399b27c ># .................. ## Create length expectation #### create_length_expectation <- function(data, name, indentation = 0) { create_equality_expectation( data = data, name = name, prefix = "length(", suffix = ")", indentation = indentation ) } ## .................. #< eb074f5b5a560bb19ff907907f958da2 ># .................. ## Create group key names expectation #### create_group_key_names_expectation <- function(data, name, indentation = 0) { create_equality_expectation( data = data, name = name, prefix = "colnames(dplyr::group_keys(", suffix = "))", add_fixed = TRUE, indentation = indentation ) } ## .................. #< dff513f918fa186b2599f1f429f1339c ># .................. ## Create sum of element lengths expectation #### create_sum_sub_lengths_expectation <- function(data, name, indentation = 0) { create_equality_expectation( data = data, name = name, prefix = "sum(xpectr::element_lengths(", suffix = "))", indentation = indentation ) } ## .................. #< 1a04985673e4647d6eb888d8bf7e76c1 ># .................. ## Create number of levels expectation #### create_nlevels_expectation <- function(data, name, indentation = 0) { create_equality_expectation( data = data, name = name, prefix = "nlevels(", suffix = ")", indentation = indentation ) } ## .................. #< eeb4f402c9068c91294cf6654a6bbb3c ># .................. ## Create levels expectation #### create_levels_expectation <- function(data, name, sample_n = NULL, indentation = 0) { pref_suff <- add_smpl_string( condition = !is.null(sample_n) && nlevels(data) > sample_n, prefix = "levels(", suffix = ")", sample_n = sample_n) create_equality_expectation( data = data, name = name, prefix = pref_suff[["prefix"]], suffix = pref_suff[["suffix"]], add_fixed = TRUE, indentation = indentation ) } ## .................. #< 27e90f45361edda8544df9c663449047 ># .................. ## Create values as character expectation #### create_as_character_expectation <- function(data, name, sample_n = NULL, indentation = 0) { pref_suff <- add_smpl_string( condition = !is.null(sample_n) && length(data) > sample_n, prefix = "as.character(", suffix = ")", sample_n = sample_n) create_equality_expectation( data = data, name = name, prefix = pref_suff[["prefix"]], suffix = pref_suff[["suffix"]], add_fixed = TRUE, indentation = indentation ) } ## .................. #< 4fae33486f86ff2385ce6225efa8c6d8 ># .................. ## Create is factor expectation #### create_is_factor_expectation <- function(name, indentation = 0) { create_condition_expectation( name = name, prefix = "is.factor(", suffix = ")", indentation = indentation ) } ## .................. #< 0abc01061db56c7e4fac5af452a783f2 ># .................. ## Create column types and classes expectations #### create_element_types_expectation <- function(data, name, sample_n = NULL, indentation = 0) { pref_suff <- add_smpl_string( condition = !is.null(sample_n) && length(data) > sample_n, prefix = "xpectr::element_types(", suffix = ")", sample_n = sample_n) create_equality_expectation( data = data, name = name, prefix = pref_suff[["prefix"]], suffix = pref_suff[["suffix"]], add_fixed = TRUE, indentation = indentation ) } # Difference between class() and typeof(): # https://stackoverflow.com/questions/8855589/ # a-comprehensive-survey-of-the-types-of-things-in-r-mode-and-class-and-type create_element_classes_expectation <- function(data, name, sample_n = NULL, indentation = 0) { # Note: length of data frame is ncol why this also works there pref_suff <- add_smpl_string( condition = !is.null(sample_n) && length(data) > sample_n, prefix = "xpectr::element_classes(", suffix = ")", sample_n = sample_n) create_equality_expectation( data = data, name = name, prefix = pref_suff[["prefix"]], suffix = pref_suff[["suffix"]], add_fixed = TRUE, indentation = indentation ) } # __________________ #< abd5e8f22decefad01cca729a155076c ># __________________ # Create symmetry expectation #### create_is_symmetric_expectation <- function(data, name, indentation = 0) { negator <- ifelse(isSymmetric(data), "", "!") create_condition_expectation( name = name, prefix = paste0(negator, "isSymmetric("), suffix = ")", indentation = indentation ) } # __________________ #< 55b9eab5a484e7388a1bf336aac64ff8 ># __________________ # Create function formals expectation #### create_fn_formals_expectation <- function(data, name, sample_n = NULL, indentation = 0) { pref_suff <- add_smpl_string( condition = !is.null(sample_n) && length(formals(data)) > sample_n, prefix = "xpectr::simplified_formals(", suffix = ")", sample_n = sample_n) create_equality_expectation( data = data, name = name, prefix = pref_suff[["prefix"]], suffix = pref_suff[["suffix"]], add_fixed = TRUE, indentation = indentation ) } # __________________ #< 5f01ff7be6d77ad1ae8986bca271e1bc ># __________________ # Create deparse expectation #### create_deparse_expectation <- function(data, name, sample_n = NULL, indentation = 0) { pref_suff <- add_smpl_string( condition = !is.null(sample_n) && length(deparse(data)) > sample_n, prefix = "deparse(", suffix = ")", sample_n = sample_n) create_equality_expectation( data = data, name = name, prefix = pref_suff[["prefix"]], suffix = pref_suff[["suffix"]], add_fixed = TRUE, indentation = indentation ) } # __________________ #< 7e5326977a07eccfa83a9397413e7ea4 ># __________________ # Create formula expectation #### create_formula_expectation <- function(data, name, indentation = 0) { # Create x x <- name # Create y # Note: It's possible that deparse() would suffice, but this way # we ensure that it will fail if data is not a valid formula y <- paste0("as.formula(\"", collapse_strings(deparse(data)), "\")") y <- apply_capture(y, fn = dput) # Create test create_expect_equal( x = x, y = y, spaces = 2 ) } # __________________ #< b3caa9bbc4f32ccc4aa583dfb8bc7a47 ># __________________ # Create expect equal #### create_expect_equal <- function(x, y, add_tolerance = FALSE, add_fixed = FALSE, spaces = 2, tolerance = "1e-4", wrap_elements = TRUE) { # Create string of spaces spaces_string <- create_space_string(n = spaces) # Check that only one of the setting strings are specified stop_if(isTRUE(add_tolerance) && isTRUE(add_fixed), "Cannot add both 'tolerance' and 'fixed' setting.") if (isTRUE(add_tolerance)) { settings_string <- paste0(",\n", spaces_string, paste0("tolerance = ", tolerance)) } else if (isTRUE(add_fixed)) { settings_string <- paste0(",\n", spaces_string, "fixed = TRUE") }else { settings_string <- "" } # In case a string has \n, \t, etc. y <- escape_metacharacters(y) # Wrap elements if (isTRUE(wrap_elements)){ y <- wrap_elements_in_string(y, max_n = 65 - spaces, indentation = spaces) } # Build expect_equal test paste0( "expect_equal(\n", spaces_string, x, ",\n", spaces_string, y, settings_string, ")" ) } # __________________ #< 644f57f5e60a7e987fa4035d2fa4dd47 ># __________________ # Create expect type #### create_expect_type <- function(x, type, spaces = 2) { # Create string of spaces spaces_string <- create_space_string(n = spaces) paste0( "expect_type(\n", spaces_string, x, ",\n", spaces_string, "type = ", type, ")" ) } # __________________ #< baf0d6d5405f18b4602c2a6143be03cf ># __________________ # Create expect TRUE #### create_expect_true <- function(x, spaces = 2) { # Create string of spaces spaces_string <- create_space_string(n = spaces) paste0( "expect_true(\n", spaces_string, x, ")" ) } # __________________ #< 8045419dc30661aa4868754ca8a7a8fa ># __________________ # Create side effect expectation #### create_expect_side_effect <- function(x, y, side_effect_type = "error", spaces = 2, strip = TRUE) { # Check arguments #### assert_collection <- checkmate::makeAssertCollection() checkmate::assert_choice( x = side_effect_type, choices = c("error", "warning", "message"), add = assert_collection ) checkmate::assert_flag( x = strip, add = assert_collection ) checkmate::reportAssertions(assert_collection) # End of argument checks #### spaces_string <- create_space_string(n = spaces) expect_fn <- dplyr::case_when( side_effect_type == "error" ~ "expect_error", side_effect_type == "warning" ~ "expect_warning", side_effect_type == "message" ~ "expect_message", TRUE ~ "" # Won't get here anyway ) y <- deparse(y) y <- collapse_strings(y) y <- escape_metacharacters(y) y <- split_to_paste0(y, spaces = ifelse(isTRUE(strip), spaces + 14, spaces)) paste0( expect_fn, "(\n", spaces_string, add_strip_msg(x, strip = strip), ",\n", spaces_string, add_strip(y, strip = strip), ",\n", spaces_string, "fixed = TRUE", ")" ) } add_strip_msg <- function(x, strip) { if (isTRUE(strip)) x <- paste0("xpectr::strip_msg(", x, ")") x } add_strip <- function(x, strip) { if (isTRUE(strip)) x <- paste0("xpectr::strip(", x, ")") x } # __________________ #< ff3057d67f7da6a3155f5034c941f142 ># __________________ # Create comments #### create_test_comment <- function(what, section = "test", indentation = 0, create_comment = TRUE){ # Check arguments #### assert_collection <- checkmate::makeAssertCollection() checkmate::assert_flag(x = create_comment, add = assert_collection) checkmate::reportAssertions(assert_collection) # No need to check things if we won't be using them if (!isTRUE(create_comment)){ return(NULL) } checkmate::assert_string(x = what, add = assert_collection) checkmate::assert_count(x = indentation, add = assert_collection) checkmate::assert_choice(x = section, choices = c("intro","outro","test","manual"), add = assert_collection) checkmate::reportAssertions(assert_collection) # End of argument checks #### if (indentation > 40){ warning("indentation > 40 characters is ignored.") indentation <- 40 } # Remove newlines with more from 'what' what <- gsub("[\r\n\t\f]", "", what) # Reduce multiple consequtive whitespaces what <- gsub("[[:blank:]]+", " ", what) # Shorten too long calls from intro and outro comments if (nchar(what) > 49 - indentation){ what <- paste0(substring(what, 1, 46 - indentation), "...") } # Create " ####" string multihashtags <- paste0(create_space_string(54 - indentation - nchar(what)), "####") # We only quote in the intro and outro quote_string <- ifelse(section == "test", "", "'") if (section == "manual"){ comment <- paste0("# ", what) } else if (section == "outro"){ comment <- paste0("## Finished testing ", quote_string, what, quote_string, multihashtags) } else { comment <- paste0("# Testing ", quote_string, what, quote_string) if (section == "intro"){ comment <- c(paste0("#", comment, create_space_string(9), multihashtags), paste0("## Initially generated by xpectr")) } } comment } # __________________ #< ed1e08a9337603a4b73a3907674f5e1d ># __________________ # Add xpectr::smpl string wrapper #### add_smpl_string <- function(condition, prefix="", suffix="", sample_n=NULL) { pref_suff <- list("prefix" = prefix, "suffix" = suffix) if (isTRUE(condition)) { if(is.null(sample_n)) stop("'sample_n' cannot be NULL when condition is TRUE.") pref_suff <- list( "prefix" = paste0("xpectr::smpl(", pref_suff[["prefix"]]), "suffix" = paste0(pref_suff[["suffix"]], ", n = ", sample_n, ")") ) } pref_suff } # __________________ #< cfe8c57bf8bfa870149930c756c90bf2 ># __________________ # Wrap elements #### wrap_elements_in_string <- function(string, max_n = 60, indentation = 0){ # Check arguments #### assert_collection <- checkmate::makeAssertCollection() checkmate::assert_string(x = string, add = assert_collection) checkmate::assert_count(x = max_n, add = assert_collection) checkmate::assert_count(x = indentation, add = assert_collection) # checkmate::assert_environment(x = envir, null.ok = TRUE, add = assert_collection) checkmate::reportAssertions(assert_collection) # End of argument checks #### # Reformat and wrap the string spaces <- create_space_string(0) lines <- deparse(parse(text = string)[[1]], width.cutoff = max_n) paste0(lines, collapse = paste0("\n", spaces)) }
/scratch/gouwar.j/cran-all/cranData/xpectr/R/expectation_creators.R
# __________________ #< 843da5fbc35d01231a00f0237a49eb51 ># __________________ # Generate function call tests #### # First arg value should be valid! #' @title Generate testhat expectations for argument values in a function #' @description #' \Sexpr[results=rd, stage=render]{lifecycle::badge("experimental")} #' #' Based on a set of supplied values for each function argument, #' a set of \code{testthat} \code{expect_*} statements are generated. #' #' \strong{Included tests}: The first value supplied for an argument #' is considered the \emph{valid baseline} value. For each argument, we #' create tests for each of the supplied values, where the other arguments #' have their baseline value. #' #' When testing a function that alters non-local variables, consider enabling \code{`copy_env`}. #' #' See supported objects in \code{details}. #' @param fn Function to create tests for. #' @param args_values The arguments and the values to create tests for. #' Should be supplied as a named list of lists, like the following: #' #' \code{args_values = list(} #' #' \code{"x1" = list(1, 2, 3), } #' #' \code{"x2" = list("a", "b", "c")} #' #' \code{)} #' #' The first value for each argument (referred to as the 'baseline' value) should be valid #' (not throw an \code{error/}\code{message}/\code{warning}). #' #' \strong{N.B.} This is not checked but should lead to more meaningful tests. #' #' \strong{N.B.} Please define the list directly in the function call. #' This is currently necessary. #' @param extra_combinations Additional combinations to test. List of lists, where #' each combination is a named sublist. #' #' E.g. the following two combinations: #' #' \code{extra_combinations = list(} #' #' \code{list("x1" = 4, "x2" = "b"),} #' #' \code{list("x1" = 7, "x2" = "c")} #' #' \code{)} #' #' \strong{N.B.} Unspecified arguments gets the baseline value. #' #' If you find yourself adding many combinations, #' an additional \code{gxs_function()} call with different baseline values #' might be preferable. #' @param check_nulls Whether to try all arguments with \code{NULL}. (Logical) #' #' When enabled, you don't need to add \code{NULL} to your \code{`args_values`}, #' unless it should be the baseline value. #' @param copy_env Whether each combination should be tested in a deep copy of the environment. (Logical) #' #' Side effects will be captured in copies of the copy, why two copies of the environment will #' exist at the same time. #' #' Disabled by default to save memory but is often preferable to enable, #' e.g. when the function changes non-local variables. #' @param parallel Whether to parallelize the generation of expectations. (Logical) #' #' Requires a registered parallel backend. Like with \code{doParallel::registerDoParallel}. #' @inheritParams gxs_selection #' @author Ludvig Renbo Olsen, \email{r-pkgs@@ludvigolsen.dk} #' @family expectation generators #' @return Either \code{NULL} or the unprepared expectations as a \code{character vector}. #' @export #' @inherit gxs_selection details #' @examples #' # Attach packages #' library(xpectr) #' #' \dontrun{ #' fn <- function(x, y, z){ #' if (x>3) stop("'x' > 3") #' if (y<0) warning("'y'<0") #' if (z==10) message("'z' was 10!") #' x + y + z #' } #' #' # Create expectations #' # Note: define the list in the call #' gxs_function(fn, #' args_values = list( #' "x" = list(2, 4, NA), #' "y" = list(0, -1), #' "z" = list(5, 10)) #' ) #' #' # Add additional combinations #' gxs_function(fn, #' args_values = list( #' "x" = list(2, 4, NA), #' "y" = list(0, -1), #' "z" = list(5, 10)), #' extra_combinations = list( #' list("x" = 4, "z" = 10), #' list("y" = 1, "z" = 10)) #' ) #' } gxs_function <- function(fn, args_values, extra_combinations = NULL, check_nulls = TRUE, indentation = 0, tolerance = "1e-4", round_to_tolerance = TRUE, strip = TRUE, sample_n = 30, envir = NULL, copy_env = FALSE, assign_output = TRUE, seed = 42, add_wrapper_comments = TRUE, add_test_comments = TRUE, start_with_newline = TRUE, end_with_newline = TRUE, out = "insert", parallel = FALSE){ # Check arguments #### assert_collection <- checkmate::makeAssertCollection() checkmate::assert_function(x = fn, add = assert_collection) checkmate::assert_list(x = args_values, types = c("list"), names = "named", add = assert_collection) checkmate::assert_list(x = extra_combinations, types = c("list"), names = "unnamed", null.ok = TRUE, add = assert_collection) checkmate::assert_flag(x = check_nulls, add = assert_collection) checkmate::assert_flag(x = copy_env, add = assert_collection) checkmate::assert_string(x = tolerance, add = assert_collection) checkmate::assert_choice(x = out, choices = c("insert", "return"), add = assert_collection) checkmate::assert_flag(x = strip, add = assert_collection) checkmate::assert_flag(x = add_wrapper_comments, add = assert_collection) checkmate::assert_flag(x = add_test_comments, add = assert_collection) checkmate::assert_flag(x = start_with_newline, add = assert_collection) checkmate::assert_flag(x = end_with_newline, add = assert_collection) checkmate::assert_flag(x = assign_output, add = assert_collection) checkmate::assert_flag(x = round_to_tolerance, add = assert_collection) checkmate::assert_flag(x = parallel, add = assert_collection) checkmate::assert_count(x = indentation, add = assert_collection) checkmate::assert_count(x = sample_n, null.ok = TRUE, add = assert_collection) checkmate::assert_count(x = seed, null.ok = TRUE, add = assert_collection) checkmate::assert_environment(x = envir, null.ok = TRUE, add = assert_collection) checkmate::reportAssertions(assert_collection) checkmate::assert_names(x = names(args_values), what = "argnames", type = "unique", add = assert_collection) checkmate::reportAssertions(assert_collection) # End of argument checks #### # Get deparsed fn name fn_name <- deparse(substitute(fn)) # Understanding arg_call: # The substituted list contains each sublist # Each element in those are 1: list/c, 2: first element, 3: second element, etc. arg_call <- substitute(args_values) xcomb_call <- substitute(extra_combinations) if (!grepl("[\\(\\)]", collapse_strings(deparse(arg_call)), fixed = FALSE)){ assert_collection$push("Please define the 'arg_values' list directly in the function call.") checkmate::reportAssertions(assert_collection) } if (!is.null(extra_combinations) && !grepl("[\\(\\)]", collapse_strings(deparse(xcomb_call)), fixed = FALSE)){ assert_collection$push("Please define the 'extra_combinations' list directly in the function call.") checkmate::reportAssertions(assert_collection) } # Generate function call fn(arg = value) strings fn_calls <- generate_function_strings(fn_name = fn_name, args_values_substituted = arg_call, extra_combinations_substituted = xcomb_call, check_nulls = check_nulls) # Create unique test IDs test_ids <- generate_test_ids(n = nrow(fn_calls)) # Get parent environment if (is.null(envir)) envir <- parent.frame() # Create tests for each combination expectations <- plyr::llply(seq_len(nrow(fn_calls)), .parallel = parallel, function(r){ current_call <- fn_calls[r,] call_string <- current_call[["call"]][[1]] changed_arg <- current_call[["changed"]][[1]] comment_change <- isTRUE(add_test_comments) && !is.na(changed_arg) c(create_test_comment(call_string, indentation = indentation, create_comment = add_test_comments), create_test_comment(paste0("Changed from baseline: ", changed_arg), indentation = indentation, section = "manual", create_comment = comment_change), gxs_selection( selection = call_string, indentation = indentation, strip = strip, tolerance = tolerance, round_to_tolerance = round_to_tolerance, envir = envir, copy_env = copy_env, sample_n = sample_n, assign_output = assign_output, seed = seed, test_id = test_ids[[r]], add_test_comments = add_test_comments, add_wrapper_comments = FALSE, start_with_newline = FALSE, end_with_newline = FALSE, out = "return" ), " " ) }) %>% unlist(recursive = TRUE) # Add comments expectations <- c(create_test_comment(fn_name, section = "intro", create_comment = add_wrapper_comments), create_test_comment("different combinations of argument values", create_comment = add_test_comments), " ", expectations, create_test_comment(fn_name, section = "outro", create_comment = add_wrapper_comments)) # Add newlines before and after test block if (isTRUE(start_with_newline)) expectations <- c(" ", expectations) if (isTRUE(end_with_newline)) expectations <- c(expectations, " ") if (out == "insert") insert_code(expectations, prepare = TRUE, indentation = indentation) else return(expectations) } # __________________ #< 6b3bf3f6dd0e841216f9dd02e6b4ba8f ># __________________ # Generate function call strings #### generate_function_strings <- function(fn_name, args_values_substituted, extra_combinations_substituted, check_nulls = TRUE){ # Check arguments #### assert_collection <- checkmate::makeAssertCollection() checkmate::assert_string(x = fn_name, add = assert_collection) checkmate::assert_flag(x = check_nulls, add = assert_collection) if (grepl("[\\(\\)]", fn_name, fixed = FALSE)){ assert_collection$push("'fn_name' cannot contain parantheses. Must be a function name.") } if (!is.language(args_values_substituted)){ assert_collection$push( paste0("'args_values_substituted' must be a language object. It shou", "ld be made with substitute(args_values), where 'args_values' i", "s a named list of lists.")) } if (!is.null(extra_combinations_substituted) && !is.language(extra_combinations_substituted)){ assert_collection$push( paste0("'extra_combinations_substituted' must be a language object.")) } checkmate::reportAssertions(assert_collection) # End of argument checks #### # Get argument names arg_names <- non_empty_names(args_values_substituted) if (!is.null(extra_combinations_substituted)){ xcomb_names <- lapply(extra_combinations_substituted, non_empty_names) %>% unlist(recursive = FALSE, use.names = TRUE) %>% unique() if (length(setdiff(xcomb_names, arg_names)) > 0){ assert_collection$push( "'extra_combinations' had argument name(s) not in 'args_values'.") checkmate::reportAssertions(assert_collection) } } # Create a tibble of the substituted values tibbled_args_values <- plyr::ldply(arg_names, function(an){ plyr::llply(args_values_substituted[[an]], function(av){ paste0(deparse(av), collapse = "\n") }) %>% unlist(recursive = FALSE) %>% tibble::enframe(name = "index") %>% dplyr::mutate(arg_name = an, index = .data$index - 1) }) %>% dplyr::filter(.data$index != 0) default_values <- tibbled_args_values %>% dplyr::filter(.data$index == 1) %>% dplyr::mutate(is_default = TRUE) non_default_values <- tibbled_args_values %>% dplyr::filter(.data$index != 1) %>% dplyr::mutate(is_default = FALSE) # Generate the combinations of argument values combinations <- plyr::ldply(seq_len(nrow(non_default_values)), function(r){ current_row <- non_default_values[r,] current_arg <- current_row[1, "arg_name"] dplyr::bind_rows( default_values %>% dplyr::filter(.data$arg_name != current_arg), current_row ) %>% dplyr::mutate(combination = as.character(r)) }) %>% dplyr::bind_rows(default_values %>% dplyr::mutate(combination = "default")) # Create NULL checks if (isTRUE(check_nulls)){ null_combinations <- plyr::ldply(arg_names, function(an){ d <- default_values # Check if empty stop_if( condition = nrow(d) == 0, message = paste0("Argument ", an, " did not have a default value."), sys.parent.n = 4 ) if (d[d[["arg_name"]] == an, "value"] == "NULL"){ return(NULL) } d[d[["arg_name"]] == an, "value"] <- "NULL" # TODO check if this can go wrong? d[d[["arg_name"]] == an, "is_default"] <- FALSE d %>% dplyr::mutate(combination = an) }) combinations <- dplyr::bind_rows( combinations, null_combinations ) } num_combinations <- length(unique(combinations[["combination"]])) ## Extra combinations # Create a tibble of the substituted values if (!is.null(extra_combinations_substituted)){ tibbled_xcombs <- plyr::ldply(seq_len(length(extra_combinations_substituted)-1), function(comb){ current_combi <- extra_combinations_substituted[[comb+1]] current_arg_names <- non_empty_names(current_combi) defaults <- default_values %>% dplyr::filter(.data$arg_name %ni% current_arg_names) non_defaults <- plyr::llply(current_combi, function(arg_val){ paste0(deparse(arg_val), collapse = "\n") }) %>% unlist(recursive = FALSE) %>% tibble::enframe(name = "arg_name") %>% dplyr::mutate(index = comb, is_default = FALSE) %>% dplyr::filter(dplyr::row_number() > 1) dplyr::bind_rows(defaults, non_defaults) %>% dplyr::mutate(combination = paste0(comb + num_combinations)) }) # Add to combinations combinations <- dplyr::bind_rows(combinations, tibbled_xcombs) } # Sort by argument name order # So we call in same order as in args_values combinations <- dplyr::left_join( tibble::enframe(arg_names, name = NULL, value = "arg_name"), combinations, by = "arg_name" ) # Find the non-default arguments per combination changed_arg <- combinations %>% dplyr::filter(!.data$is_default) %>% dplyr::group_by(.data$combination) %>% dplyr::mutate(changed_string_valued = paste0(.data$arg_name, " = ", .data$value, collapse = ", "), changed_string_name_only = paste0(.data$arg_name, collapse = ", "), num_changed = dplyr::n(), changed_string = ifelse(.data$num_changed > 1, .data$changed_string_name_only, .data$changed_string_valued)) %>% dplyr::filter(dplyr::row_number() == 1) %>% dplyr::select("combination", "num_changed", "arg_name", "changed_string") # Create function calls function_calls <- combinations %>% dplyr::mutate(name_value = paste0(.data$arg_name," = ", .data$value)) %>% dplyr::group_by(.data$combination) %>% dplyr::summarise(call_strings = paste0( fn_name,"(", paste0(.data$name_value, collapse = ", "), ")")) %>% dplyr::left_join(changed_arg, by = "combination") %>% dplyr::arrange(.data$num_changed) # Create tmp arg_name for default call tmp_value <- ".___TMP_VALUE___" if (sum(is.na(function_calls[["arg_name"]]))>1) stop("Internal error: More than one 'arg_name' was 'NA'. Please report issue on GitHub.") function_calls[is.na(function_calls[["arg_name"]]), "arg_name"] <- tmp_value # Order by arg_names, not alphabetically function_calls <- dplyr::left_join( tibble::enframe(c(tmp_value, arg_names), name = NULL, value = "arg_name"), function_calls, by = "arg_name" ) %>% dplyr::filter(!is.na(.data$combination)) # Prepare output tibble function_calls %>% dplyr::select("call_strings", "changed_string") %>% dplyr::distinct(.data$call_strings, .keep_all = TRUE) %>% dplyr::rename(call = "call_strings", changed = "changed_string") } # __________________ #< 60cfc78f594e5611a6eaaf34a2b212ae ># __________________ # Generate test IDs #### generate_test_ids <- function(n, min = 10000, max = 20000){ # Create unique test IDs # Make sure not to disturb the random state if (exists(".Random.seed")) initial_seed_state <- .Random.seed if (n > 1000){ max <- max * 3 } test_ids <- head(unique(floor(runif( n * 4, # times 4 to ensure enough unique IDs min = min, max = max ))), n) # Reset random state assign_random_state(initial_seed_state) test_ids }
/scratch/gouwar.j/cran-all/cranData/xpectr/R/gxs_function.R
# __________________ #< 18e203f135e6c85c41aaa4f048f94f75 ># __________________ # Generate expectations from selection #### #' @title Generate testhat expectations from selection #' @description #' \Sexpr[results=rd, stage=render]{lifecycle::badge("experimental")} #' #' Based on the selection (string of code), a set of \code{testthat} \code{expect_*} #' statements are generated. #' #' Example: If the selected code is the name of a \code{data.frame} object, #' it will create an \code{\link[testthat:equality-expectations]{expect_equal}} #' test for each column, along with a test of the column names, #' types and classes, dimensions, grouping keys, etc. #' #' See supported objects in \code{details}. #' #' When testing a function that alters non-local variables, consider enabling \code{`copy_env`}. #' #' Feel free to suggest useful tests etc. in a GitHub issue! #' #' Addin: \code{\link[xpectr:insertExpectationsAddin]{insertExpectationsAddin()}} #' @param selection String of code. (Character) #' #' E.g. \code{"stop('This gives an expect_error test')"}. #' @param indentation Indentation of the selection. (Numeric) #' @param tolerance The tolerance for numeric tests as a string, like \code{"1e-4"}. (Character) #' @param round_to_tolerance Whether to round numeric elements to the specified tolerance. (Logical) #' #' This is currently applied to numeric columns and vectors (excluding some lists). #' @param sample_n The number of elements/rows to sample. Set to \code{NULL} to avoid sampling. #' #' Inserts \code{\link[xpectr:strip]{smpl()}} in the generated tests when sampling was used. A seed is #' set internally, setting \code{sample.kind} as \code{"Rounding"} to ensure compatibility with \code{R} versions #' \code{< 3.6.0}. #' #' The order of the elements/rows is kept intact. No replacement is used, why no oversampling will #' take place. #' #' When testing a big \code{data.frame}, sampling the rows can help keep the test files somewhat readable. #' @param strip Whether to insert #' \code{\link[xpectr:strip]{strip_msg()}} and #' \code{\link[xpectr:strip]{strip()}} #' in tests of side effects. (Logical) #' #' Sometimes testthat tests have differences in punctuation and newlines on different #' systems. By stripping both the error message and the expected message of non-alphanumeric symbols, #' we can avoid such failed tests. #' @param add_wrapper_comments Whether to add intro and outro comments. (Logical) #' @param add_test_comments Whether to add comments for each test. (Logical) #' @param assign_output Whether to assign the output of a function call or long selection #' to a variable. This will avoid recalling the function and decrease cluttering. (Logical) #' #' Heuristic: when the \code{`selection`} isn't of a string and contains a parenthesis, it is considered a function call. #' A selection with more than 30 characters will be assigned as well. #' #' The tests themselves can be more difficult to interpret, as you will #' have to look at the assignment to see the object that is being tested. #' @param seed \code{seed} to set. (Whole number) #' @param test_id Number to append to assignment names. (Whole number) #' #' For instance used to create the \code{"output_"} name: \code{output_<test_id>}. #' @inheritParams capture_side_effects #' @param copy_env Whether to work in a deep copy of the environment. (Logical) #' #' Side effects will be captured in copies of the copy, why two copies of the environment will #' exist at the same time. #' #' Disabled by default to save memory but is often preferable to enable, #' e.g. when the function changes non-local variables. #' @param out Either \code{"insert"} or \code{"return"}. #' #' \subsection{"insert" (Default)}{ #' Inserts the expectations via #' \code{\link[rstudioapi:rstudio-documents]{rstudioapi::insertText()}}. #' } #' \subsection{"return"}{ #' Returns the expectations in a \code{list}. #' #' These can be prepared for insertion with #' \code{\link[xpectr:prepare_insertion]{prepare_insertion()}}. #' } #' @param start_with_newline,end_with_newline Whether to have a newline in the beginning/end. (Logical) #' @return Either \code{NULL} or the unprepared expectations as a \code{character vector}. #' @details #' The following "types" are currently supported or intended to be supported in the future. #' Please suggest more types and tests in a GitHub issue! #' #' Note: A set of fallback tests will be generated for unsupported objects. #' #' \tabular{rrr}{ #' \strong{Type} \tab \strong{Supported} \tab \strong{Notes} \cr #' Side effects \tab Yes \tab Errors, warnings, and messages. \cr #' Vector \tab Yes \tab Lists are treated differently, depending on their structure. \cr #' Factor \tab Yes \tab \cr #' Data Frame \tab Yes \tab List columns (like nested tibbles) are currently skipped. \cr #' Matrix \tab Yes \tab Supported but could be improved. \cr #' Formula \tab Yes \tab \cr #' Function \tab Yes \tab \cr #' \code{NULL} \tab Yes \tab \cr #' Array \tab No \tab \cr #' Dates \tab No \tab Base and \code{lubridate}. \cr #' ggplot2 \tab No \tab This may be a challenge, but would be cool!\cr #' } #' @author Ludvig Renbo Olsen, \email{r-pkgs@@ludvigolsen.dk} #' @family expectation generators #' @export #' @examples #' # Attach packages #' library(xpectr) #' #' \dontrun{ #' df <- data.frame('a' = c(1, 2, 3), 'b' = c('t', 'y', 'u'), #' stringsAsFactors = FALSE) #' #' gxs_selection("stop('This gives an expect_error test!')") #' gxs_selection("warning('This gives a set of side effect tests!')") #' gxs_selection("message('This also gives a set of side effect tests!')") #' gxs_selection("stop('This: tests the -> punctuation!')", strip = FALSE) #' gxs_selection("sum(1, 2, 3, 4)") #' gxs_selection("df") #' #' tests <- gxs_selection("df", out = "return") #' for_insertion <- prepare_insertion(tests) #' rstudioapi::insertText(for_insertion) #' } gxs_selection <- function(selection, indentation = 0, tolerance = "1e-4", round_to_tolerance = TRUE, strip = TRUE, sample_n = 30, envir = NULL, copy_env = FALSE, assign_output = TRUE, seed = 42, test_id = NULL, add_wrapper_comments = TRUE, add_test_comments = TRUE, start_with_newline = TRUE, end_with_newline = TRUE, out = "insert"){ # Save random seed state if (exists(x = ".Random.seed")) initial_seed_state <- .Random.seed if (is.null(test_id)) test_id <- floor(runif(1, 10000, 20000)) # Note: Don't want to use checkmate here if (!is.null(seed) && is.numeric(seed) && length(seed) == 1){ # Set initial seed set_test_seed(seed) # Save random seed state initial_seed_state <- .Random.seed } else { assign_random_state(initial_seed_state, check_existence = TRUE) } # Check arguments #### assert_collection <- checkmate::makeAssertCollection() checkmate::assert_string(x = selection, add = assert_collection) checkmate::assert_string(x = tolerance, add = assert_collection) checkmate::assert_choice(x = out, choices = c("insert", "return"), add = assert_collection) checkmate::assert_flag(x = strip, add = assert_collection) checkmate::assert_flag(x = add_wrapper_comments, add = assert_collection) checkmate::assert_flag(x = add_test_comments, add = assert_collection) checkmate::assert_flag(x = start_with_newline, add = assert_collection) checkmate::assert_flag(x = end_with_newline, add = assert_collection) checkmate::assert_flag(x = assign_output, add = assert_collection) checkmate::assert_flag(x = round_to_tolerance, add = assert_collection) checkmate::assert_flag(x = copy_env, add = assert_collection) checkmate::assert_count(x = indentation, add = assert_collection) checkmate::assert_count(x = sample_n, null.ok = TRUE, add = assert_collection) checkmate::assert_count(x = seed, null.ok = TRUE, add = assert_collection) checkmate::assert_count(x = test_id, add = assert_collection) checkmate::assert_environment(x = envir, null.ok = TRUE, add = assert_collection) checkmate::reportAssertions(assert_collection) checkmate::assert_number(x = as.numeric(tolerance), upper = 1, add = assert_collection) checkmate::reportAssertions(assert_collection) # End of argument checks #### # Set environment if not specified if (is.null(envir)) envir <- parent.frame() # Clone environment if specified envir <- clone_env_if(envir = envir, cond = copy_env, deep = TRUE) # Check for side effects side_effects <- capture_parse_eval_side_effects(string = selection, envir = envir, copy_env = copy_env) has_side_effects <- side_effects[["has_side_effects"]] has_error <- !is.null(side_effects[["error"]]) intro_comment <- create_test_comment( selection, section = "intro", indentation = indentation, create_comment = add_wrapper_comments ) outro_comment <- create_test_comment( selection, section = "outro", indentation = indentation, create_comment = add_wrapper_comments ) seed_setting_string <- paste0("xpectr::set_test_seed(", seed, ")") expectations <- c() sfx_expectations <- c() if (isTRUE(has_side_effects)) { # Create expectations for error, warnings, and messages sfx_expectations <- create_expectations_side_effect( side_effects, name = selection, copy_env = copy_env, indentation = indentation, add_comments = add_test_comments, strip = strip, test_id = test_id) selection <- paste0("xpectr::suppress_mw(", selection, ")") } if (!isTRUE(has_error)) { # Parse and evaluate the selection obj <- tryCatch({ # Reset seed # Note: Only seems to work when setting it in globalenv # but it's the seed we started with, so it shouldn't be a problem? assign_random_state(initial_seed_state, check_existence = TRUE) # Evaluate string eval_string(selection, envir = envir) }, error = function(e) { stop(paste0("Could not parse and evaluate the selection. Threw error:", e)) }, warning = function(w) { warning(paste0( "Got the following warning while parsing and evaluating the selection: ", w )) } ) # Check if object is a side effect string # This happens when the warning/message is called last in a function if (isTRUE(has_side_effects)){ obj_is_side_effect_string <- checkmate::test_string(obj) && obj %in% unlist(side_effects[c("error", "warnings", "messages")], recursive = TRUE, use.names = FALSE) } else { obj_is_side_effect_string <- FALSE } if (!isTRUE(obj_is_side_effect_string)){ # TODO perhaps assign_once and evaluate_once aren't the most descriptive var names? # If the selection is a very long string # we might prefer to assign it once assign_once <- nchar(selection) > 30 || (grepl("[\\(\\)]", selection) && !(checkmate::test_string(x = obj) && add_quotation_marks(obj) == selection)) # If selection is a function call if (isTRUE(assign_output) && assign_once){ evaluate_once <- TRUE } else { evaluate_once <- FALSE } # Create expectations based on the type of the objects if (is.null(obj)) { expectations <- create_expectations_null(name = selection, indentation = indentation, add_comments = add_test_comments) } else if (is.data.frame(obj)) { expectations <- create_expectations_data_frame(obj, name = selection, indentation = indentation, tolerance = tolerance, round_to_tolerance = round_to_tolerance, sample_n = sample_n, add_comments = add_test_comments, evaluate_once = evaluate_once, test_id = test_id) } else if (is.matrix(obj)) { expectations <- create_expectations_matrix(obj, name = selection, indentation = indentation, tolerance = tolerance, round_to_tolerance = round_to_tolerance, sample_n = sample_n, add_comments = add_test_comments, evaluate_once = evaluate_once, test_id = test_id) } else if (is.vector(obj)) { expectations <- create_expectations_vector(obj, name = selection, indentation = indentation, tolerance = tolerance, round_to_tolerance = round_to_tolerance, sample_n = sample_n, add_comments = add_test_comments, evaluate_once = evaluate_once, test_id = test_id) } else if (is.factor(obj)) { expectations <- create_expectations_factor(obj, name = selection, indentation = indentation, tolerance = tolerance, sample_n = sample_n, add_comments = add_test_comments, evaluate_once = evaluate_once, test_id = test_id) } else if (is.function(obj)) { expectations <- create_expectations_function(obj, name = selection, indentation = indentation, sample_n = sample_n, add_comments = add_test_comments, evaluate_once = evaluate_once, test_id = test_id) } else if (rlang::is_formula(obj)) { expectations <- create_expectations_formula(obj, name = selection, indentation = indentation, add_comments = add_test_comments, evaluate_once = evaluate_once, test_id = test_id) } else { warning(paste0("The selection is not of a currently supported class '", class(obj),"'. Will generate fallback tests.")) expectations <- create_expectations_fallback(obj, name = selection, indentation = indentation, add_comments = add_test_comments, evaluate_once = evaluate_once, test_id = test_id) } } } expectations <- c(intro_comment, seed_setting_string, sfx_expectations, expectations, outro_comment) # Add newlines before and after test block if (isTRUE(start_with_newline)) expectations <- c(" ", expectations) if (isTRUE(end_with_newline)) expectations <- c(expectations, " ") if (out == "insert"){ insert_code(expectations, prepare = TRUE, indentation = indentation) } else { return(expectations) } }
/scratch/gouwar.j/cran-all/cranData/xpectr/R/gxs_selection.R
# __________________ #< 86dfaf6a7ff4d9198c3b406886f4d005 ># __________________ # Utilities #### # Get all lists in a list with a certain name # Use: list_of_lists %c% 'list_name' `%c%` <- function(x, n) lapply(x, `[[`, n) # From http://stackoverflow.com/questions/5935673/ # accessing-same-named-list-elements-of-the-list-of-lists-in-r/5936077#5936077 # Not in `%ni%` <- function(x, table) { !(x %in% table) } # Remove NAs and empty "" names non_empty_names <- function(x) { ns <- names(x) ns <- ns[!is.na(ns)] ns[nzchar(ns, keepNA = TRUE)] } # Programmatic subset function # Inspired by https://stackoverflow.com/questions/11880906/ # pass-subset-argument-through-a-function-to-subset # use: p = "x>3" # prog_subset <- function(df, subset = NULL, select = NULL, deselect = NULL, envir = NULL) { # # # TODO Doesn't work when subset refers to am external variable # # if (is.null(envir)) # # envir <- parent.frame() # # # # if (!is.null(subset)) { # # df <- subset(df, eval(parse(text = subset), envir = envir)) # # } # if (!is.null(select)) { # df <- subset(df, select = select) # } # if (!is.null(deselect)) { # df <- subset(df, select = setdiff(names(data), deselect)) # } # rownames(df) <- NULL # df # } # https://stackoverflow.com/a/55923178/11832955 # TODO Test ndigits <- function(x){ trunc_x <- floor(abs(x)) if(trunc_x != 0){ floor(log10(trunc_x)) + 1 } else { 1 } } # assign .Random.seed in global environment assign_random_state <- function(state, envir = globalenv(), check_existence = TRUE){ if (!isTRUE(check_existence) || exists(x = ".Random.seed")){ assign(x = ".Random.seed", value = state, envir = envir) } } # Get message from testthat::capture_error # copied from testthat:::cnd_message cnd_message <- function(x, disable_crayon = TRUE) { withr::local_options(c( rlang_backtrace_on_error = "none", crayon.enabled = !disable_crayon )) conditionMessage(x) } # Create deep or shallow clone of an environment # https://stackoverflow.com/a/53274519/11832955 clone_env <- function(envir, deep = TRUE) { if (isTRUE(deep)) { clone <- list2env( rapply( as.list(envir, all.names = TRUE), clone_env, classes = "environment", how = "replace" ), parent = parent.env(envir) ) } else { clone <- list2env(as.list(envir, all.names = TRUE), parent = parent.env(envir)) } attributes(clone) <- attributes(envir) clone } clone_env_if <- function(envir, cond, deep=TRUE){ if (isTRUE(cond)) clone_env(envir = envir, deep = deep) else envir } get_pkg_version <- function(pkg_name){ vs <- unlist(utils::packageVersion(pkg_name)) list("major" = vs[[1]], "minor" = vs[[2]], "patch" = vs[[3]], "dev" = ifelse(length(vs) > 3, vs[[4]], integer(0))) } is_checkmate_v2_1 <- function(){ v <- get_pkg_version("checkmate") v$major == 2 && v$minor >= 1 }
/scratch/gouwar.j/cran-all/cranData/xpectr/R/helpers.R
# __________________ #< 60cfc78f594e5611a6eaaf34a2b212ae ># __________________ # Initialize gxs_function call #### #' @title Initialize \code{gxs_function()} call #' @description #' \Sexpr[results=rd, stage=render]{lifecycle::badge("experimental")} #' #' Initializes the \code{gxs_function()} call with the arguments and default values #' of the selected function. #' #' See \code{`Details`} for how to set a key command. #' @param selection Name of function to test with \code{gxs_function()}. (Character) #' #' \strong{N.B.} Mainly intended for testing the addin programmatically. #' @param indentation Indentation of the selection. (Numeric) #' #' \strong{N.B.} Mainly intended for testing the addin programmatically. #' @param insert Whether to insert the code via #' \code{\link[rstudioapi:rstudio-documents]{rstudioapi::insertText()}} #' or return them. (Logical) #' #' \strong{N.B.} Mainly intended for testing the addin programmatically. #' @author Ludvig Renbo Olsen, \email{r-pkgs@@ludvigolsen.dk} #' @family expectation generators #' @family addins #' @export #' @return Inserts \code{\link[xpectr:gxs_function]{gxs_function()}} call for #' the selected function. #' #' Returns \code{NULL} invisibly. #' @details #' \subsection{How}{ #' Parses and evaluates the selected code string #' within the parent environment. #' When the output is a function, it extracts the formals (arguments and default values) #' and creates the initial \code{`args_values`} for \code{\link[xpectr:gxs_function]{gxs_function()}}. #' When the output is not a function, it throws an error. #' } #' \subsection{How to set up a key command in RStudio}{ #' #' After installing the package. #' Go to: #' #' \code{Tools >> Addins >> Browse Addins >> Keyboard Shortcuts}. #' #' Find \code{"Initialize gxs_function()"} and press its field under \code{Shortcut}. #' #' Press desired key command, e.g. \code{Alt+F}. #' #' Press \code{Apply}. #' #' Press \code{Execute}. #' } initializeGXSFunctionAddin <- function(selection = NULL, insert = TRUE, indentation = 0) { # Check arguments #### assert_collection <- checkmate::makeAssertCollection() checkmate::assert_string(x = selection, null.ok = TRUE, add = assert_collection) checkmate::assert_flag(x = insert, add = assert_collection) checkmate::assert_integerish(x = indentation, lower = 0, any.missing = FALSE, null.ok = TRUE, add = assert_collection) checkmate::reportAssertions(assert_collection) # End of argument checks #### # Get the selection and indentation if (is.null(selection)){ selection <- tryCatch( get_selection(), error = function(e) { return("") } ) indentation <- tryCatch( get_indentation(), error = function(e) { return(0) } ) } # Get parent environment parent_envir <- parent.frame() # Create expectations if (selection != "") { # Parse and evaluate the selection obj <- tryCatch({ # Evaluate string eval_string(selection, envir = parent_envir) }, error = function(e) { stop(paste0("Could not parse and evaluate the selection. Threw error:", e)) }, warning = function(w) { warning(paste0( "Got the following warning while parsing and evaluating the selection: ", w )) }) if (!checkmate::test_function(x = obj)){ stop("'selection' was not the name of an available function.") } # Trim trailing spaces selection <- trimws(selection, which = "both") # Extract the formals (arg names and default values) fn_formals <- formals(obj) arg_names <- names(fn_formals) # Create args_values elements args_values_strings <- plyr::llply(arg_names, function(an){ paste0("\"", an, "\" = list(", paste0(deparse(fn_formals[[an]])), ")") }) %>% unlist() %>% paste0(collapse = ",\n") %>% strsplit(split = "\n") %>% unlist(recursive = TRUE, use.names = FALSE) # Add 4 spaces in front of args_values elements spaces <- create_space_string(n = 4) args_values_strings <- paste0(spaces, args_values_strings) # Create the strings for insertion to_insert <- c( paste0("# Generate expectations for '", selection, "'"), "# Tip: comment out the gxs_function() call", "# so it is easy to regenerate the tests", "xpectr::set_test_seed(42)", "xpectr::gxs_function(", paste0(" fn = ", selection, ","), " args_values = list(\n", args_values_strings, " ),", " indentation = 2,", " copy_env = FALSE", ")", " ", "#" ) # Insert or return if (isTRUE(insert)){ insert_code(to_insert, prepare = TRUE, indentation = indentation) } else { return(to_insert) } } invisible() }
/scratch/gouwar.j/cran-all/cranData/xpectr/R/initialize_gxs_function_addin.R
# __________________ #< ae21df5a647472abc01a4d8a26621404 ># __________________ # Initialize test_that call #### #' @title Initializes \code{test_that()} call #' @description #' \Sexpr[results=rd, stage=render]{lifecycle::badge("experimental")} #' #' Inserts code for calling \code{\link[testthat:test_that]{testthat::test_that()}}. #' #' See \code{`Details`} for how to set a key command. #' @param indentation Indentation of the code. (Numeric) #' #' \strong{N.B.} Mainly intended for testing the addin programmatically. #' @param insert Whether to insert the code via #' \code{\link[rstudioapi:rstudio-documents]{rstudioapi::insertText()}} #' or return it. (Logical) #' #' \strong{N.B.} Mainly intended for testing the addin programmatically. #' @author Ludvig Renbo Olsen, \email{r-pkgs@@ludvigolsen.dk} #' @family addins #' @export #' @return Inserts code for calling #' \code{\link[testthat:test_that]{testthat::test_that()}}. #' #' Returns \code{NULL} invisibly. #' @details #' \subsection{How to set up a key command in RStudio}{ #' #' After installing the package. #' Go to: #' #' \code{Tools >> Addins >> Browse Addins >> Keyboard Shortcuts}. #' #' Find \code{"Initialize test_that()"} and press its field under \code{Shortcut}. #' #' Press desired key command, e.g. \code{Alt+T}. #' #' Press \code{Apply}. #' #' Press \code{Execute}. #' } initializeTestthatAddin <- function(insert = TRUE, indentation = NULL) { # Check arguments #### assert_collection <- checkmate::makeAssertCollection() checkmate::assert_flag(x = insert, add = assert_collection) checkmate::assert_integerish(x = indentation, lower = 0, any.missing = FALSE, null.ok = TRUE, add = assert_collection) checkmate::reportAssertions(assert_collection) # End of argument checks #### # Get the indentation if (is.null(indentation)){ indentation <- tryCatch(get_indentation(), error = function(e){return(0)}) } # Create test_that initialization strings test_that_strings <- c( " ", "test_that(\"testing ...()\", {", " xpectr::set_test_seed(42)", " ", " # ...", " ", "})", " " ) if (isTRUE(insert)){ insert_code(test_that_strings, prepare = TRUE, indentation = indentation) } else { return(test_that_strings) } invisible() }
/scratch/gouwar.j/cran-all/cranData/xpectr/R/initialize_test_that_addin.R
# __________________ #< ad4fd4c3bf0175135055204d9012d9ac ># __________________ # Navigate to test file #### #' @title Navigates to test file #' @description #' \Sexpr[results=rd, stage=render]{lifecycle::badge("experimental")} #' #' \code{RStudio} Addin: #' Extracts file name and (possibly) line number of a test file #' from a selection or from clipboard content. #' Navigates to the file and places the cursor at the line number. #' #' Supported types of strings: \code{"test_x.R:3"}, \code{"test_x.R#3"}, \code{"test_x.R"}. #' #' The string must start with \code{"test_"} and contain \code{".R"}. #' It is split at either \code{":"} or \code{"#"}, with the second element (here \code{"3"}) being #' interpreted as the line number. #' #' See \code{`Details`} for how to set a key command. #' @author Ludvig Renbo Olsen, \email{r-pkgs@@ludvigolsen.dk} #' @param selection String with file name and line number. (Character) #' #' E.g. \code{"test_x.R:3:"}, which navigates to the third line of \code{"/tests/testthat/test_x.R"}. #' #' \strong{N.B.} Mainly intended for testing the addin programmatically. #' @param navigate Whether to navigate to the file or return the extracted file name and line number. (Logical) #' #' \strong{N.B.} Mainly intended for testing the addin programmatically. #' @param abs_path Whether to return the full path or only the file name when \code{`navigate`} is \code{FALSE}. #' #' \strong{N.B.} Mainly intended for testing the addin programmatically. #' @export #' @family addins #' @return Navigates to file and line number. #' #' Does not return anything. #' @details #' \subsection{How to set up a key command in RStudio}{ #' #' After installing the package. #' Go to: #' #' \code{Tools >> Addins >> Browse Addins >> Keyboard Shortcuts}. #' #' Find \code{"Go To Test File"} and press its field under \code{Shortcut}. #' #' Press desired key command, e.g. \code{Alt+N}. #' #' Press \code{Apply}. #' #' Press \code{Execute}. #' } navigateTestFileAddin <- function(selection = NULL, navigate = TRUE, abs_path = TRUE) { # Check arguments #### assert_collection <- checkmate::makeAssertCollection() checkmate::assert_string(x = selection, null.ok = TRUE, add = assert_collection) checkmate::assert_flag(x = navigate, add = assert_collection) checkmate::assert_flag(x = abs_path, add = assert_collection) checkmate::reportAssertions(assert_collection) # End of argument checks #### # Get the selection and indentation if (is.null(selection)){ selection <- tryCatch(get_selection(), error = function(e){return("")}, message = function(m){return("")}) } if (selection == ""){ # TODO Make sure not to run on CRAN selection <- read_clipboard() } if (is.null(selection) || selection == ""){ message("selection/clipboard content was empty/unavailable.") return(invisible()) } if (!grepl(pattern = ".R", x = selection, fixed = TRUE)){ stop("selection/clipboard content did not include '.R'.") } if (grepl(pattern = ".R#", x = selection, fixed = TRUE)){ sep <- "#" } else { sep <- ":" } # Extract file name and (possibly) line number selection <- trimws(selection, which = "both") split_sel <- unlist(strsplit(selection, sep)) if (length(split_sel) > 1){ file_name <- split_sel[[1]] line_num <- split_sel[[2]] if (!grepl("^[0-9]", line_num)){ stop("line number was not a number.") } line_num <- gsub("^([0-9]+).*$", "\\1", line_num) } else { file_name <- split_sel line_num <- -1 } # File name if (substring(file_name, 1, 5) != "test_"){ stop("extracted file name must start with 'test_'.") } if (substring(file_name, nchar(file_name)-1, nchar(file_name)) != ".R"){ file_name <- paste0(file_name, ".R") } if (grepl(pattern = "[[:space:]]", x = file_name)){ stop("found white space in extracted file named.") } # Line number line_num <- tryCatch(as.integer(line_num), error = function(e){return(NA)}, warning = function(w){return(NA)}) if (is.null(line_num) || is.na(line_num)){ stop("extracted line number could not be converted to 'integer'.") } # Create absolute path full_file_path <- paste0(getwd(), "/tests/testthat/", file_name) # Navigate or return extractions if (isTRUE(navigate)){ # Open file and set cursor at line number rstudioapi::navigateToFile(file = full_file_path, line = line_num) } else { output <- list() if (isTRUE(abs_path)) output[["file"]] <- full_file_path else output[["file"]] <- file_name output[["line_number"]] <- line_num output } }
/scratch/gouwar.j/cran-all/cranData/xpectr/R/navigateTestFileAddin.R
#' xpectr: A package for generating tests for \code{testthat} unit testing #' #' A set of utilities and RStudio addins for generating tests. #' #' @author Ludvig Renbo Olsen, \email{r-pkgs@@ludvigolsen.dk} #' @docType package #' @name xpectr NULL # R CMD check NOTE handling if (getRversion() >= "2.15.1") utils::globalVariables(c(".")) # Never used, but removes R CMD check NOTEs rcmd_import_handler <- function(){ lifecycle::deprecate_soft() }
/scratch/gouwar.j/cran-all/cranData/xpectr/R/package_info.R
# __________________ #< 814bcffd276aad37f42a762e054cf5cc ># __________________ # Prepare expectations for insertion #### #' @title Prepare expectations for insertion #' @description #' \Sexpr[results=rd, stage=render]{lifecycle::badge("experimental")} #' #' Collapses a \code{list}/\code{vector} of expectation strings and adds the specified indentation. #' @param strings Expectation strings. (List or Character) #' #' As returned with \code{gxs_*} functions with \code{out = "return"}. #' @param indentation Indentation to add. (Numeric) #' @param trim_left Whether to trim whitespaces from the beginning of the collapsed string. (Logical) #' @param trim_right Whether to trim whitespaces from the end of the collapsed string. (Logical) #' @author Ludvig Renbo Olsen, \email{r-pkgs@@ludvigolsen.dk} #' @family inserters #' @return A string for insertion with \code{\link[rstudioapi:rstudio-documents]{rstudioapi::insertText()}}. #' @export #' @examples #' # Attach packages #' library(xpectr) #' #' \dontrun{ #' df <- data.frame('a' = c(1, 2, 3), 'b' = c('t', 'y', 'u'), #' stringsAsFactors = FALSE) #' #' tests <- gxs_selection("df", out = "return") #' for_insertion <- prepare_insertion(tests) #' for_insertion #' rstudioapi::insertText(for_insertion) #' } prepare_insertion <- function(strings, indentation = 0, trim_left = FALSE, trim_right = FALSE) { # Get as character vector strings <- unlist(strings, recursive = TRUE, use.names = FALSE) # Check arguments #### assert_collection <- checkmate::makeAssertCollection() checkmate::assert_character(x = strings, add = assert_collection) checkmate::assert_count(x = indentation, add = assert_collection) checkmate::assert_flag(x = trim_left, add = assert_collection) checkmate::assert_flag(x = trim_right, add = assert_collection) checkmate::reportAssertions(assert_collection) # End of argument checks #### # Create string of spaces spaces_string <- create_space_string(n = indentation) # Split by newline strings <- unlist(strsplit(strings, split = "\n"), recursive = TRUE, use.names = FALSE) # Empty single space strings strings <- gsub("^ $", "", strings) # Collapse strings string <- paste(strings, collapse = paste0("\n", spaces_string)) # Trimming to_trim <- dplyr::case_when( isTRUE(trim_left) && isTRUE(trim_right) ~ "both", isTRUE(trim_left) ~ "left", isTRUE(trim_right) ~ "right", TRUE ~ "none" ) if (to_trim != "none"){ string <- trimws(string, which = to_trim) } string }
/scratch/gouwar.j/cran-all/cranData/xpectr/R/prepare_insertion.R
# __________________ #< abd5e8f22decefad01cca729a155076c ># __________________ # Sample #### #' @title Random sampling #' @description #' \Sexpr[results=rd, stage=render]{lifecycle::badge("experimental")} #' #' Samples a \code{vector}, \code{factor} or \code{data.frame}. Useful to reduce size of testthat \code{expect_*} tests. #' Not intended for other purposes. #' #' Wraps \code{\link[base:sample]{sample.int()}}. \code{data.frame}s are sampled row-wise. #' #' The \code{seed} is set within the function with \code{sample.kind} as \code{"Rounding"} #' for compatibility with \code{R} versions \code{< 3.6.0}. On exit, the random state is restored. #' @param data \code{vector} or \code{data.frame}. (Logical) #' @param n Number of elements/rows to sample. #' #' \strong{N.B.} No replacement is used, why \code{n >} the number of elements/rows in \code{`data`} won't #' perform oversampling. #' @param keep_order Whether to keep the order of the elements. (Logical) #' @param seed \code{seed} to use. #' #' The \code{seed} is set with \code{sample.kind = "Rounding"} #' for compatibility with \code{R} versions \code{< 3.6.0}. #' @author Ludvig Renbo Olsen, \email{r-pkgs@@ludvigolsen.dk} #' @return When \code{`data`} has \code{<=`n`} elements, \code{`data`} is returned. #' Otherwise, \code{`data`} is sampled and returned. #' @export #' @examples #' # Attach packages #' library(xpectr) #' #' smpl(c(1,2,3,4,5), n = 3) #' smpl(data.frame("a" = c(1,2,3,4,5), "b" = c(2,3,4,5,6), stringsAsFactors = FALSE), n = 3) smpl <- function(data, n, keep_order = TRUE, seed = 42) { if (exists(".Random.seed")) initial_random_state <- .Random.seed # Check arguments #### assert_collection <- checkmate::makeAssertCollection() checkmate::assert_count(x = n, positive = TRUE, add = assert_collection) checkmate::assert_count(x = seed, positive = TRUE, add = assert_collection) checkmate::assert_flag(x = keep_order, add = assert_collection) checkmate::reportAssertions(assert_collection) # End of argument checks #### # Set seed to be compatible with R before and after v3.6 set_test_seed(seed) # Sample data if (is.data.frame(data)) { if (nrow(data) <= n) { if (isTRUE(keep_order)) return(data) else n <- nrow(data) } indices <- sample.int(n = nrow(data), size = n, replace = FALSE) if (isTRUE(keep_order)) indices <- sort(indices) data <- data[indices,] } else if (is.vector(data) || is.factor(data)) { if (length(data) <= n) { if (isTRUE(keep_order)) return(data) else n <- length(data) } indices <- sample.int(n = length(data), size = n, replace = FALSE) if (isTRUE(keep_order)) indices <- sort(indices) data <- data[indices] } else { stop("Only vectors, factors and data frames are currently supported.") } # Reassign the previous random state assign_random_state(initial_random_state, check_existence = TRUE) data }
/scratch/gouwar.j/cran-all/cranData/xpectr/R/sample.R
#' @title Set random seed for unit tests #' @description #' \Sexpr[results=rd, stage=render]{lifecycle::badge("experimental")} #' #' In order for tests to be compatible with \code{R} versions \code{< 3.6.0}, #' we set the \code{sample.kind} argument in \code{\link[base:Random]{set.seed()}} #' to \code{"Rounding"} when using \code{R} versions \code{>= 3.6.0}. #' @param seed Random \code{seed}. #' @param ... Named arguments to \code{\link[base:Random]{set.seed()}}. #' @author Ludvig Renbo Olsen, \email{r-pkgs@@ludvigolsen.dk} #' @author R. Mark Sharp #' @return \code{NULL}. #' @export #' @details #' Initially contributed by R. Mark Sharp (github: @@rmsharp). set_test_seed <- function(seed = 42, ...) { if ((getRversion()$major == 3 && getRversion()$minor >= 6) || getRversion()$major > 3) { args <- list(seed, sample.kind = "Rounding", ...) } else { args <- list(seed, ...) } suppressWarnings(do.call(set.seed, args)) }
/scratch/gouwar.j/cran-all/cranData/xpectr/R/set_test_seed.R
# __________________ #< 0d3e1cc7677b500a32d83bc726793163 ># __________________ # Capture side effects #### #' @title Capture side effects #' @description #' Captures \code{error}s, \code{warning}s, and \code{message}s from an expression. #' #' In case of an \code{error}, no other side effects are captured. #' #' Simple wrapper for \code{testthat}'s #' \code{\link[testthat:capture_condition]{capture_error()}}, #' \code{\link[testthat:capture_condition]{capture_warnings()}} and #' \code{\link[testthat:capture_condition]{capture_messages()}}. #' #' Note: Evaluates \code{expr} up to three times. #' @param expr Expression. #' @param envir Environment to evaluate in. Defaults to #' \code{\link[base:sys.parent]{parent.frame()}}. #' @param copy_env Whether to use deep copies of the environment when capturing side effects. (Logical) #' #' Disabled by default to save memory but is often preferable to enable, e.g. when the function #' alters non-local variables before throwing its \code{error}/\code{warning}/\code{message}. #' @param reset_seed Whether to reset the random state on exit. (Logical) #' @param disable_crayon Whether to disable \code{crayon} formatting. #' This can remove ANSI characters from the messages. (Logical) #' @author Ludvig Renbo Olsen, \email{r-pkgs@@ludvigolsen.dk} #' @return \code{named list} with the side effects. #' @family capturers #' @export #' @examples #' # Attach packages #' library(xpectr) #' #' fn <- function(raise = FALSE){ #' message("Hi! I'm Kevin, your favorite message!") #' warning("G'Day Mam! I'm a warning to the world!") #' message("Kevin is ma name! Yesss!") #' warning("Hopefully the whole world will see me :o") #' if (isTRUE(raise)){ #' stop("Lord Evil Error has arrived! Yeehaaa") #' } #' "the output" #' } #' \donttest{ #' capture_side_effects(fn()) #' capture_side_effects(fn(raise = TRUE)) #' capture_side_effects(fn(raise = TRUE), copy_env = TRUE) #' } capture_side_effects <- function(expr, envir = NULL, copy_env = FALSE, reset_seed = FALSE, disable_crayon = TRUE) { # Check arguments #### assert_collection <- checkmate::makeAssertCollection() checkmate::assert_environment(x = envir, null.ok = TRUE, add = assert_collection) checkmate::assert_flag(x = reset_seed, add = assert_collection) checkmate::assert_flag(x = copy_env, add = assert_collection) checkmate::reportAssertions(assert_collection) # End of argument checks #### # We cannot rely on lazy evaluation # as it would only be called in the first call (capture_error) sexpr <- substitute(expr) if (is.null(envir)) envir <- parent.frame() # We need a random state to be able to make the # same computation for the three evaluations if (!exists(".Random.seed")) { xpectr::set_test_seed(floor(runif(1, 0, 100000))) rm_seed <- TRUE } else { rm_seed <- FALSE } # Get current random state initial_random_state <- .Random.seed # Disable crayon (ANSI codes) withr::local_options(c(crayon.enabled = !disable_crayon)) # Capture error error <- testthat::capture_error(suppress_mw( eval(sexpr, envir = clone_env_if(envir, cond = copy_env, deep = TRUE)))) error_class = class(error) # If no error, capture messages and warnings if (is.null(error)) { # Capture messages assign_random_state(initial_random_state, check_existence = FALSE) messages <- testthat::capture_messages(suppressWarnings( eval(sexpr, envir = clone_env_if(envir, cond = copy_env, deep = TRUE)))) # Capture warnings assign_random_state(initial_random_state, check_existence = FALSE) warnings <- testthat::capture_warnings(suppressMessages( eval(sexpr, envir = clone_env_if(envir, cond = copy_env, deep = TRUE)))) } else { error <- cnd_message(error, disable_crayon = disable_crayon) messages <- NULL warnings <- NULL } # Remove or reset random state if (isTRUE(rm_seed)) { rm(".Random.seed", envir = globalenv()) } else if (isTRUE(reset_seed)) { assign_random_state(initial_random_state, check_existence = FALSE) } list( "error" = error, "error_class" = error_class, "warnings" = warnings, "messages" = messages, "has_side_effects" = any_side_effects(error, warnings, messages) ) } # __________________ #< 48a4eeb063cff1ae132cfc1682fa0d14 ># __________________ # Capture side effects from parse eval #### #' @title Capture side effects from parse eval #' @description #' Wraps string in \code{\link[xpectr:capture_side_effects]{capture_side_effects()}} #' before parsing and evaluating it. #' The side effects (\code{error}, \code{warning}s, \code{message}s) are returned in a \code{list}. #' #' When capturing an \code{error}, no other side effects are captured. #' @param string String of code that can be parsed and evaluated in \code{envir}. #' @inheritParams capture_side_effects #' @author Ludvig Renbo Olsen, \email{r-pkgs@@ludvigolsen.dk} #' @return \code{named list} with the side effects. #' @family capturers #' @export #' @examples #' # Attach package #' library(xpectr) #' #' \donttest{ #' capture_parse_eval_side_effects("stop('hi!')") #' capture_parse_eval_side_effects("warning('hi!')") #' capture_parse_eval_side_effects("message('hi!')") #' } capture_parse_eval_side_effects <- function(string, envir = NULL, copy_env = FALSE, reset_seed = FALSE, disable_crayon = TRUE) { # Check arguments #### assert_collection <- checkmate::makeAssertCollection() checkmate::assert_string(x = string, add = assert_collection) checkmate::assert_environment(x = envir, null.ok = TRUE, add = assert_collection) checkmate::reportAssertions(assert_collection) # End of argument checks #### # Set default envir if (is.null(envir)){ envir <- parent.frame() } # Get side effects # Note: Without xpectr:: it complains # that it cannot find capture_side_effects catcher_string <- paste0( "xpectr::capture_side_effects(", string, ", copy_env = ", deparse(copy_env), ", reset_seed = ", deparse(reset_seed), ", disable_crayon = ", deparse(disable_crayon), ")" ) # Parse and evaluate to get the side effects side_effects <- eval_string(catcher_string, envir = envir) side_effects } # __________________ #< 8df9505f95f75a94490f398ae5c74641 ># __________________ # Utils #### any_side_effects <- function(error, messages, warnings) { !(is.null(error) || length(error) == 0) || !(is.null(messages) || length(messages) == 0) || !(is.null(warnings) || length(warnings) == 0) }
/scratch/gouwar.j/cran-all/cranData/xpectr/R/side_effects.R
# __________________ #< d19c97fa8ab3c13382eba03991b20184 ># __________________ # Extract and simplify formals #### #' @title Extract and simplify a function's formal arguments #' @description #' \Sexpr[results=rd, stage=render]{lifecycle::badge("experimental")} #' #' Extracts \code{\link[base:formals]{formals}} and #' formats them as an easily testable \code{character vector}. #' @param fn \code{Function}. #' @author Ludvig Renbo Olsen, \email{r-pkgs@@ludvigolsen.dk} #' @return A \code{character vector} with the simplified formals. #' @export #' @examples #' # Attach packages #' library(xpectr) #' #' fn1 <- function(a = "x", b = NULL, c = NA, d){ #' paste0(a, b, c, d) #' } #' #' simplified_formals(fn1) simplified_formals <- function(fn) { # Extract formals frmls <- formals(fn) # Simplify formals char_formals <- plyr::llply(names(frmls), function(name){ # Convert default value to character if (is.character(frmls[[name]])){ val_char <- escape_metacharacters(frmls[[name]]) val_char <- add_quotation_marks(val_char) } else { val_char <- as.character(frmls[[name]]) } # Format formal if (is.null(frmls[[name]])){ out <- paste0(name, " = NULL") } else if (checkmate::test_string(val_char) && # avoid errors on NAs etc. nchar(val_char) == 0) { out <- name } else { out <- paste0(name, " = ", val_char) } out }) %>% unlist() char_formals }
/scratch/gouwar.j/cran-all/cranData/xpectr/R/simplified_formals.R
# __________________ #< 581c92a7122e86b9d99cebb6dbb6b596 ># __________________ # String utils #### # Collapse list of strings once collapse_strings <- function(strings) { if (length(strings) > 1) { strings <- paste0(strings, collapse = "") } strings } # Add extra \ before the # special metacharacters: \n \r \t \v \f escape_metacharacters <- function(string) { # TODO must be a way to do it in one gsub with groups? string <- gsub("\n", "\\n", string, fixed = TRUE) string <- gsub("\r", "\\r", string, fixed = TRUE) string <- gsub("\t", "\\t", string, fixed = TRUE) string <- gsub("\v", "\\v", string, fixed = TRUE) string <- gsub("\f", "\\f", string, fixed = TRUE) string <- gsub('"', '\\"', string, fixed = FALSE) string } add_quotation_marks <- function(string){ first <- substr(string, 1, 1) last <- substr(string, nc <- nchar(string), nc) if (first != "\"") string <- paste0("\"", string) if (last != "\"") string <- paste0(string, "\"") string } # Create string with n spaces create_space_string <- function(n = 2) { paste0(rep(" ", n), collapse = "") } # __________________ #< d29a5eb0e16cdf89ef5dcf00b1b2ed60 ># __________________ # Split/wrap string #### # Wrap text every n characters. # Rude but useful for long error messages. split_string_every <- function(string, per = 60) { # https://stackoverflow.com/a/26497700/11832955 n <- seq(1, nc <- nchar(string), by = per) splits <- substring(string, n, c(n[-1] - 1, nc)) # Extract tail backslashes tail_backslashes <- gsub(".*[^\\\\*$]", "", splits, fixed = F) # Remove tail backslashes splits <- gsub("\\\\*$", "", splits) if (sum(nchar(tail_backslashes)) == 0) return(splits) # We don't want to remove the tail slashes # from the last string, so we create a list to easily # join with the others final_backslashes <- c(rep("", n = length(tail_backslashes) - 1), tail(tail_backslashes, 1)) # Move backslashes to next string tail_backslashes <- c( "", head(tail_backslashes, length(tail_backslashes) - 1)) # Add tail backslashes at beginning of next string splits <- paste0(tail_backslashes, splits, final_backslashes) splits } # Split long string into elements in paste0 split_to_paste0 <- function(string, per = 60, tolerance = 10, spaces = 2, wrap_shorts = FALSE) { # Check arguments #### assert_collection <- checkmate::makeAssertCollection() checkmate::assert_string(x = string, add = assert_collection) checkmate::reportAssertions(assert_collection) # End of argument checks #### # We only want to split it if it is too long if (nchar(string) > per + tolerance) { splits <- split_string_every(paste0(string)) } else { string <- add_quotation_marks(string) if (isTRUE(wrap_shorts)) { string <- paste0("paste0(", string, ")") } return(string) } # Create string of spaces (7 is the length of "paste0(" ) spaces_string <- create_space_string(n = spaces + 7) # Format string string <- paste0( paste0(splits, collapse = paste0("\",\n", spaces_string, "\""))) string <- add_quotation_marks(string) paste0( "paste0(", string, ")" ) }
/scratch/gouwar.j/cran-all/cranData/xpectr/R/string_utils.R
# __________________ #< 646904aaf54daa74ea9d6d8c40429d96 ># __________________ # strip #### #' @title Strip strings of non-alphanumeric characters #' @description #' \Sexpr[results=rd, stage=render]{lifecycle::badge("experimental")} #' #' 1) Removes any character that is not alphanumeric or a space. #' #' 2) (Disabled by default): Remove numbers. #' #' 3) Reduces multiple consecutive whitespaces to a single whitespace and trims ends. #' #' Can for instance be used to simplify error messages before checking them. #' @param strings \code{vector} of strings. (Character) #' @param allow_na Whether to allow \code{strings} #' to contain \code{NA}s. (Logical) #' @param replacement What to replace blocks of punctuation with. (Character) #' @param remove_spaces Whether to remove all whitespaces. (Logical) #' @param remove_numbers Whether to remove all numbers. (Logical) #' @param remove_ansi Whether to remove ANSI control sequences. (Logical) #' @param lowercase Whether to make the strings lowercase. (Logical) #' @author Ludvig Renbo Olsen, \email{r-pkgs@@ludvigolsen.dk} #' @family strippers #' @return The stripped strings. #' @export #' @details #' 1) ANSI control sequences are removed with \code{\link[fansi:strip_ctl]{fansi::strip_ctl()}}. #' #' 2) \code{gsub("[^[:alnum:][:blank:]]", replacement, strings))} #' #' 3) \code{gsub('[0-9]+', '', strings)} (Note: only if specified!) #' #' 4) \code{trimws( gsub("[[:blank:]]+", " ", strings) )} #' (Or \code{""} if \code{remove_spaces} is \code{TRUE}) #' #' @examples #' # Attach packages #' library(xpectr) #' #' strings <- c( #' "Hello! I am George. \n\rDon't call me Frank! 123", #' " \tAs that, is, not, my, name!" #' ) #' #' strip(strings) #' strip(strings, remove_spaces = TRUE) #' strip(strings, remove_numbers = TRUE) strip <- function(strings, replacement = "", remove_spaces = FALSE, remove_numbers = FALSE, remove_ansi = TRUE, lowercase = FALSE, allow_na = TRUE) { ## .................. #< 2adf3d749542993ca3074b95c0f31e8e ># .................. ## Argument Asserts #### assert_collection <- checkmate::makeAssertCollection() checkmate::assert_flag(allow_na, add = assert_collection) checkmate::reportAssertions(assert_collection) # Must check allow_na first! checkmate::assert_character(x = strings, any.missing = allow_na, add = assert_collection) checkmate::assert_string(replacement, add = assert_collection) checkmate::assert_flag(remove_spaces, add = assert_collection) checkmate::assert_flag(remove_numbers, add = assert_collection) checkmate::assert_flag(remove_ansi, add = assert_collection) checkmate::assert_flag(lowercase, add = assert_collection) checkmate::reportAssertions(assert_collection) ## .................. #< 43d21464a1012b2a6ace37d658f5a3b6 ># .................. ## Code #### # Remove ansi escape sequence # Borrowed from crayon::strip_style if (isTRUE(remove_ansi)){ strings <- fansi::strip_ctl(strings, ctl = "all") } # Replace all non-alphanumeric and non-space strings <- gsub("[^[:alnum:][:blank:]]", replacement, strings) # Remove numbers if specified if (isTRUE(remove_numbers)){ strings <- gsub('[0-9]+', '', strings) } # Reduce multiple consecutive whitespaces # to a single whitespace (or non if specified) strings <- gsub("[[:blank:]]+", ifelse(isTRUE(remove_spaces), "", " "), strings) # Trim both ends for whitespaces strings <- trimws(strings) # Make lowercase if (isTRUE(lowercase)){ strings <- tolower(strings) } strings }
/scratch/gouwar.j/cran-all/cranData/xpectr/R/strip.R
# __________________ #< 29fde22ad2b6cc22736749f39cd5f41a ># __________________ # Strip message #### #' @title Strip side-effect messages of non-alphanumeric characters and rethrow them #' @description #' \Sexpr[results=rd, stage=render]{lifecycle::badge("experimental")} #' #' Catches side effects (\code{error}, \code{warning}s, \code{message}s), strips the message strings of #' non-alphanumeric characters with \code{\link[xpectr:strip]{strip()}} and regenerates them. #' #' When numbers in error messages vary slightly between systems #' (and this variation isn't important to catch), we can strip the numbers as well. #' #' Use case: Sometimes \code{testthat} tests have differences in punctuation and newlines on different #' systems. By stripping both the error message and the expected message #' (with \code{\link[xpectr:strip]{strip()}}), we can avoid such failed tests. #' @param x Code that potentially throws \code{warning}s, \code{message}s, or an \code{error}. #' @inheritParams strip #' @author Ludvig Renbo Olsen, \email{r-pkgs@@ludvigolsen.dk} #' @family strippers #' @export #' @return Returns \code{NULL} invisibly. #' @examples #' # Attach packages #' library(xpectr) #' library(testthat) #' #' \dontrun{ #' strip_msg(stop("this 'dot' .\n is removed! 123")) #' strip_msg(warning("this 'dot' .\n is removed! 123")) #' strip_msg(message("this 'dot' .\n is removed! 123")) #' strip_msg(message("this 'dot' .\n is removed! 123"), remove_numbers = TRUE) #' error_fn <- function(){stop("this 'dot' .\n is removed! 123")} #' strip_msg(error_fn()) #' #' # With testthat tests #' expect_error(strip_msg(error_fn()), #' strip("this 'dot' .\n is removed! 123")) #' expect_error(strip_msg(error_fn(), remove_numbers = TRUE), #' strip("this 'dot' .\n is removed! 123", remove_numbers = TRUE)) #' } strip_msg <- function(x, remove_spaces = FALSE, remove_numbers = FALSE, remove_ansi = TRUE, lowercase = FALSE){ # Catch x lexically # Needed with direct message() calls x <- substitute(x) # Create function that evaluates x in the parent to this function side_effects <- capture_side_effects(eval(x, envir = parent.frame(4))) stripper <- function(msg) { strip(msg, remove_spaces = remove_spaces, remove_numbers = remove_numbers, remove_ansi = remove_ansi, lowercase = lowercase) } # Regenerate error stop_if(checkmate::test_character(side_effects$error, min.len = 1), stripper(side_effects$error), sys.parent.n = 1) # Regenerate messages if (checkmate::test_character(side_effects$messages, min.len = 1)){ plyr::l_ply(side_effects$messages, function(m){ message_if(TRUE, stripper(m), sys.parent.n = 4) }) } # Regenerate warnings if (checkmate::test_character(side_effects$warnings, min.len = 1)){ plyr::l_ply(side_effects$warnings, function(w){ warn_if(TRUE, stripper(w), sys.parent.n = 4) }) } invisible() }
/scratch/gouwar.j/cran-all/cranData/xpectr/R/strip_side_effect_messages.R
# __________________ #< c1a5d30f3e6f0045ba8f573f35aea87d ># __________________ # Suppress messages and warnings #### #' @title Suppress warnings and messages #' @description #' \Sexpr[results=rd, stage=render]{lifecycle::badge("experimental")} #' #' Run expression wrapped in both #' \code{\link[base:message]{suppressMessages()}} and #' \code{\link[base:warning]{suppressWarnings()}}. #' @param expr Any expression to run within \code{\link[base:message]{suppressMessages()}} and #' \code{\link[base:warning]{suppressWarnings()}}. #' @author Ludvig Renbo Olsen, \email{r-pkgs@@ludvigolsen.dk} #' @return The output of \code{expr}. #' @details #' \code{suppressWarnings(suppressMessages(expr))} #' @export #' @examples #' # Attach packages #' library(xpectr) #' #' fn <- function(a, b){ #' warning("a warning") #' message("a message") #' a + b #' } #' #' suppress_mw(fn(1, 5)) suppress_mw <- function(expr){ suppressMessages( suppressWarnings( expr ) ) }
/scratch/gouwar.j/cran-all/cranData/xpectr/R/suppress_mw.R
#' Render Table of Contents #' #' From: https://gist.github.com/gadenbuie/c83e078bf8c81b035e32c3fc0cf04ee8 #' #' A simple function to extract headers from an RMarkdown or Markdown document #' and build a table of contents. Returns a markdown list with links to the #' headers using pandoc header identifiers. #' #' WARNING: This function only works with hash-tag headers. #' #' Because this function returns only the markdown list, the header for the #' Table of Contents itself must be manually included in the text. Use #' `toc_header_name` to exclude the table of contents header from the TOC, or #' set to `NULL` for it to be included. #' #' @section Usage: #' Just drop in a chunk where you want the toc to appear (set `echo=FALSE`): #' #' # Table of Contents #' #' ```{r echo=FALSE} #' render_toc("/path/to/the/file.Rmd") #' ``` #' @keywords internal #' @param filename Name of RMarkdown or Markdown document #' @param toc_header_name The table of contents header name. If specified, any #' header with this format will not be included in the TOC. Set to `NULL` to #' include the TOC itself in the TOC (but why?). #' @param base_level Starting level of the lowest header level. Any headers #' prior to the first header at the base_level are dropped silently. #' @param toc_depth Maximum depth for TOC, relative to base_level. Default is #' `toc_depth = 3`, which results in a TOC of at most 3 levels. render_toc <- function( filename, toc_header_name = "Table of Contents", base_level = NULL, toc_depth = 3) { x <- readLines(filename, warn = FALSE) x <- gsub("<a.*<img.*a>", "", x) # My addition, remove links with images in x <- paste(x, collapse = "\n") x <- paste0("\n", x, "\n") for (i in 5:3) { regex_code_fence <- paste0("\n[`]{", i, "}.+?[`]{", i, "}\n") x <- gsub(regex_code_fence, "", x) } x <- strsplit(x, "\n")[[1]] x <- x[grepl("^#+", x)] if (!is.null(toc_header_name)) { x <- x[!grepl(paste0("^#+ ", toc_header_name), x)] } if (is.null(base_level)) { base_level <- min(sapply(gsub("(#+).+", "\\1", x), nchar)) } start_at_base_level <- FALSE x <- sapply(x, function(h) { level <- nchar(gsub("(#+).+", "\\1", h)) - base_level if (level < 0) { stop( "Cannot have negative header levels. Problematic header \"", h, '" ', "was considered level ", level, ". Please adjust `base_level`." ) } if (level > toc_depth - 1) { return("") } if (!start_at_base_level && level == 0) start_at_base_level <<- TRUE if (!start_at_base_level) { return("") } if (grepl("\\{#.+\\}(\\s+)?$", h)) { # has special header slug header_text <- gsub("#+ (.+)\\s+?\\{.+$", "\\1", h) header_slug <- gsub(".+\\{\\s?#([-_.a-zA-Z]+).+", "\\1", h) } else { header_text <- gsub("#+\\s+?", "", h) header_text <- gsub("\\s+?\\{.+\\}\\s*$", "", header_text) # strip { .tabset ... } header_text <- gsub("^[^[:alpha:]]*\\s*", "", header_text) # remove up to first alpha char header_slug <- paste(strsplit(header_text, " ")[[1]], collapse = "-") header_slug <- tolower(header_slug) } paste0(strrep(" ", level * 4), "- [", header_text, "](#", header_slug, ")") }) x <- x[x != ""] knitr::asis_output(paste(x, collapse = "\n")) }
/scratch/gouwar.j/cran-all/cranData/xpectr/R/table_of_content_markdown.R
# __________________ #< c402467242308fa93e897c7ecda52e75 ># __________________ # Generate testthat tests #### #' @title Creates testthat tests for selected code #' @description #' \Sexpr[results=rd, stage=render]{lifecycle::badge("experimental")} #' #' Inserts relevant \code{expect_*} tests based #' on the evaluation of the selected code. #' #' Example: If the selected code is the name of a \code{data.frame} object, #' it will create an \code{\link[testthat:equality-expectations]{expect_equal}} #' test for each column, #' along with a test of the column names. #' #' Currently supports side effects (\code{error}, \code{warning}s, \code{message}s), #' \code{data.frame}s, and \code{vector}s. #' #' List columns in \code{data.frame}s (like nested \code{tibble}s) are currently skipped. #' #' See \code{`Details`} for how to set a key command. #' @param selection String of code. (Character) #' #' E.g. \code{"stop('This gives an expect_error test')"}. #' #' \strong{N.B.} Mainly intended for testing the addin programmatically. #' @param indentation Indentation of the selection. (Numeric) #' #' \strong{N.B.} Mainly intended for testing the addin programmatically. #' @param insert Whether to insert the expectations via #' \code{\link[rstudioapi:rstudio-documents]{rstudioapi::insertText()}} #' or return them. (Logical) #' #' \strong{N.B.} Mainly intended for testing the addin programmatically. #' @inheritParams gxs_selection #' @author Ludvig Renbo Olsen, \email{r-pkgs@@ludvigolsen.dk} #' @family expectation generators #' @family addins #' @export #' @return Inserts \code{\link[testthat:equality-expectations]{testthat::expect_*}} #' unit tests for the selected code. #' #' Returns \code{NULL} invisibly. #' @details #' \subsection{How}{ #' Parses and evaluates the selected code string #' within the parent environment (or a deep copy thereof). #' Depending on the output, it creates a set of unit tests #' (like \code{expect_equal(data[["column"]], c(1,2,3))}), #' and inserts them instead of the selection. #' } #' \subsection{How to set up a key command in RStudio}{ #' #' After installing the package. #' Go to: #' #' \code{Tools >> Addins >> Browse Addins >> Keyboard Shortcuts}. #' #' Find \code{"Insert Expectations"} and press its field under \code{Shortcut}. #' #' Press desired key command, e.g. \code{Alt+E}. #' #' Press \code{Apply}. #' #' Press \code{Execute}. #' } #' @importFrom utils capture.output head tail #' @importFrom rlang := .data #' @importFrom dplyr %>% #' @importFrom stats runif insertExpectationsAddin <- function(selection = NULL, insert = TRUE, indentation = 0, copy_env = FALSE) { # Check arguments #### assert_collection <- checkmate::makeAssertCollection() checkmate::assert_string(x = selection, null.ok = TRUE, add = assert_collection) checkmate::assert_flag(x = insert, add = assert_collection) checkmate::assert_flag(x = copy_env, add = assert_collection) checkmate::assert_integerish(x = indentation, lower = 0, any.missing = FALSE, null.ok = TRUE, add = assert_collection) checkmate::reportAssertions(assert_collection) # End of argument checks #### # Get the selection and indentation if (is.null(selection)){ selection <- tryCatch( get_selection(), error = function(e) { return("") } ) indentation <- tryCatch( get_indentation(), error = function(e) { return(0) } ) } # Get parent environment parent_envir <- parent.frame() # Create expectations if (selection != "") { generator <- function(out){ gxs_selection(selection, indentation = indentation, envir = parent_envir, out = out, copy_env = copy_env) } if (!isTRUE(insert)) { # Return the expectations instead of inserting them return(generator(out = "return")) } else { # Insert the expectations generator(out = "insert") } } invisible() } #' @rdname insertExpectationsAddin #' @export insertExpectationsCopyEnvAddin <- function(selection = NULL, insert = TRUE, indentation = 0, copy_env = TRUE){ insertExpectationsAddin( selection = selection, insert = insert, indentation = indentation, copy_env = copy_env ) }
/scratch/gouwar.j/cran-all/cranData/xpectr/R/testthat_addins.R
# __________________ #< 2708eaade73cef523d55b70d4eefdc80 ># __________________ # Wrap string addin #### #' @title Wraps the selection with paste0 #' @description #' \Sexpr[results=rd, stage=render]{lifecycle::badge("experimental")} #' #' Splits the selection every n characters #' and inserts it in a \code{\link[base:paste]{paste0()}} call. #' #' See \code{`Details`} for how to set a key command. #' @param selection String of code. (Character) #' #' \strong{N.B.} Mainly intended for testing the addin programmatically. #' @param indentation Indentation of the selection. (Numeric) #' #' \strong{N.B.} Mainly intended for testing the addin programmatically. #' @param every_n Number of characters per split. #' #' If \code{NULL}, the following is used to calculate the string width: #' #' \code{max(min(80 - indentation, 70), 50)} #' #' \strong{N.B.} Strings shorter than \code{every_n + tolerance} will not be wrapped. #' @param tolerance Tolerance. Number of characters. #' #' We may prefer not to split a string that's only a few #' characters too long. Strings shorter than \code{every_n + tolerance} #' will not be wrapped. #' @param insert Whether to insert the wrapped text via #' \code{\link[rstudioapi:rstudio-documents]{rstudioapi::insertText()}} #' or return it. (Logical) #' #' \strong{N.B.} Mainly intended for testing the addin programmatically. #' @author Ludvig Renbo Olsen, \email{r-pkgs@@ludvigolsen.dk} #' @export #' @family addins #' @return Inserts the following (with newlines and correct indentation): #' #' \code{paste0("first n chars", "next n chars")} #' #' #' Returns \code{NULL} invisibly. #' @details #' \subsection{How to set up a key command in RStudio}{ #' #' After installing the package. #' Go to: #' #' \code{Tools >> Addins >> Browse Addins >> Keyboard Shortcuts}. #' #' Find \code{"Wrap String with paste0"} and press its #' field under \code{Shortcut}. #' #' Press desired key command, e.g. \code{Alt+P}. #' #' Press \code{Apply}. #' #' Press \code{Execute}. #' } wrapStringAddin <- function(selection = NULL, indentation = 0, every_n = NULL, tolerance = 10, insert = TRUE) { ## .................. #< ba972bb3fde6730407b73845cacc3613 ># .................. ## Assert arguments #### # Add asserts assert_collection <- checkmate::makeAssertCollection() checkmate::assert_string(x = selection, null.ok = TRUE, add = assert_collection) checkmate::assert_flag(x = insert, add = assert_collection) checkmate::assert_integerish(x = indentation, lower = 0, any.missing = FALSE, null.ok = TRUE, add = assert_collection) checkmate::assert_count(x = every_n, positive = TRUE, null.ok = TRUE, add = assert_collection) checkmate::assert_count(x = tolerance, add = assert_collection) checkmate::reportAssertions(assert_collection) ## .................. #< 2b7b1d70203486ee3e9de35889785403 ># .................. ## Get selection and context #### # Get the selection and indentation if (is.null(selection)){ selection <- get_selection() indentation <- get_indentation() } # Get parent environment parent_envir <- parent.frame() ## .................. #< 4a81977d929b0be2b75c983f858a866a ># .................. ## Wrap selection #### if (selection != "") { if (is.null(every_n)){ every_n <- max(min(80 - indentation, 70), 50) } wrapped <- split_to_paste0(selection, per = every_n, tolerance = tolerance, spaces = indentation, wrap_shorts = TRUE) if (!isTRUE(insert)) { # Return the wrapped string instead of inserting it return(wrapped) } else { # Insert the wrapped insert_code(list(wrapped)) } } invisible() }
/scratch/gouwar.j/cran-all/cranData/xpectr/R/wrap_string_addin.R
## ---- include = FALSE--------------------------------------------------------- knitr::opts_chunk$set( collapse = TRUE, comment = "#>", fig.path = "man/figures/vignette_intro-", dpi = 92, fig.retina = 2 ) ## ----eval=FALSE--------------------------------------------------------------- # install.packages("xpectr") ## ----eval=FALSE--------------------------------------------------------------- # # install.packages("devtools") # devtools::install_github("ludvigolsen/xpectr") ## ----warning=FALSE, message=FALSE--------------------------------------------- library(xpectr) library(testthat) library(dplyr) # Set a seed # When R > 3.6.0, it sets sampling.kind to "Rounding" to make # tests compatible with previous versions of R set_test_seed(42) ## ----------------------------------------------------------------------------- # Some data num_vec <- 1:10 long_vec <- c(LETTERS, letters) a_factor <- factor(c("a","b","c")) df <- data.frame( 'a' = c(1, 2, 3), 'b' = c('t', 'y', 'u'), "c" = a_factor, stringsAsFactors = FALSE ) %>% dplyr::group_by(a) # A function with side effects fn <- function(raise = FALSE){ message("Hi! I'm Kevin, your favorite message!") warning("G'Day Mam! I'm a warning to the world!") message("Kevin is ma name! Yesss!") warning("Hopefully the whole world will see me :o") if (isTRUE(raise)){ stop("Lord Evil Error has arrived! Yeehaaa") } "the output" } ## ----------------------------------------------------------------------------- # Inspect num_vec num_vec ## ----eval=FALSE--------------------------------------------------------------- # # Generate expectations # gxs_selection("num_vec") # # # Inserts the following tests: # # ## Testing 'num_vec' #### # ## Initially generated by xpectr # xpectr::set_test_seed(42) # # Testing class # expect_equal( # class(num_vec), # "integer", # fixed = TRUE) # # Testing type # expect_type( # num_vec, # type = "integer") # # Testing values # expect_equal( # num_vec, # c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), # tolerance = 1e-4) # # Testing names # expect_equal( # names(num_vec), # NULL, # fixed = TRUE) # # Testing length # expect_equal( # length(num_vec), # 10L) # # Testing sum of element lengths # expect_equal( # sum(xpectr::element_lengths(num_vec)), # 10L) # ## Finished testing 'num_vec' #### # ## ----------------------------------------------------------------------------- # Inspect a_factor a_factor ## ----eval=FALSE--------------------------------------------------------------- # # Generate expectations # gxs_selection("a_factor") # # # Inserts the following tests: # # ## Testing 'a_factor' #### # ## Initially generated by xpectr # xpectr::set_test_seed(42) # # Testing is factor # expect_true( # is.factor(a_factor)) # # Testing values # expect_equal( # as.character(a_factor), # c("a", "b", "c"), # fixed = TRUE) # # Testing names # expect_equal( # names(a_factor), # NULL, # fixed = TRUE) # # Testing length # expect_equal( # length(a_factor), # 3L) # # Testing number of levels # expect_equal( # nlevels(a_factor), # 3L) # # Testing levels # expect_equal( # levels(a_factor), # c("a", "b", "c"), # fixed = TRUE) # ## Finished testing 'a_factor' #### # ## ----------------------------------------------------------------------------- # Inspect long_vec long_vec ## ----eval=FALSE--------------------------------------------------------------- # # Generate expectations # gxs_selection("long_vec") # # # Inserts the following tests: # # ## Testing 'long_vec' #### # ## Initially generated by xpectr # xpectr::set_test_seed(42) # # Testing class # expect_equal( # class(long_vec), # "character", # fixed = TRUE) # # Testing type # expect_type( # long_vec, # type = "character") # # Testing values # expect_equal( # xpectr::smpl(long_vec, n = 30), # c("C", "E", "G", "J", "K", "N", "O", "Q", "R", "S", "T", "W", "Y", # "Z", "b", "c", "d", "e", "h", "i", "j", "k", "l", "o", "p", # "r", "v", "w", "y", "z"), # fixed = TRUE) # # Testing names # expect_equal( # names(xpectr::smpl(long_vec, n = 30)), # NULL, # fixed = TRUE) # # Testing length # expect_equal( # length(long_vec), # 52L) # # Testing sum of element lengths # expect_equal( # sum(xpectr::element_lengths(long_vec)), # 52L) # ## Finished testing 'long_vec' #### # ## ----------------------------------------------------------------------------- # Inspect df df ## ----eval=FALSE--------------------------------------------------------------- # # Generate expectations # gxs_selection("df") # # # Inserts the following tests: # # ## Testing 'df' #### # ## Initially generated by xpectr # xpectr::set_test_seed(42) # # Testing class # expect_equal( # class(df), # c("grouped_df", "tbl_df", "tbl", "data.frame"), # fixed = TRUE) # # Testing column values # expect_equal( # df[["a"]], # c(1, 2, 3), # tolerance = 1e-4) # expect_equal( # df[["b"]], # c("t", "y", "u"), # fixed = TRUE) # expect_equal( # df[["c"]], # structure(1:3, levels = c("a", "b", "c"), class = "factor")) # # Testing column names # expect_equal( # names(df), # c("a", "b", "c"), # fixed = TRUE) # # Testing column classes # expect_equal( # xpectr::element_classes(df), # c("numeric", "character", "factor"), # fixed = TRUE) # # Testing column types # expect_equal( # xpectr::element_types(df), # c("double", "character", "integer"), # fixed = TRUE) # # Testing dimensions # expect_equal( # dim(df), # c(3L, 3L)) # # Testing group keys # expect_equal( # colnames(dplyr::group_keys(df)), # "a", # fixed = TRUE) # ## Finished testing 'df' #### # ## ----------------------------------------------------------------------------- # Inspect fn fn ## ----eval=FALSE--------------------------------------------------------------- # # Generate expectations # gxs_selection("fn()") # # # Inserts the following tests: # # ## Testing 'fn()' #### # ## Initially generated by xpectr # xpectr::set_test_seed(42) # # Testing side effects # # Assigning side effects # side_effects_19148 <- xpectr::capture_side_effects(fn(), reset_seed = TRUE) # expect_equal( # xpectr::strip(side_effects_19148[['warnings']]), # xpectr::strip(c("G'Day Mam! I'm a warning to the world!", "Hopefully the whole world will see me :o")), # fixed = TRUE) # expect_equal( # xpectr::strip(side_effects_19148[['messages']]), # xpectr::strip(c("Hi! I'm Kevin, your favorite message!\n", "Kevin is ma name! Yesss!\n")), # fixed = TRUE) # # Assigning output # output_19148 <- xpectr::suppress_mw(fn()) # # Testing class # expect_equal( # class(output_19148), # "character", # fixed = TRUE) # # Testing type # expect_type( # output_19148, # type = "character") # # Testing values # expect_equal( # output_19148, # "the output", # fixed = TRUE) # # Testing names # expect_equal( # names(output_19148), # NULL, # fixed = TRUE) # # Testing length # expect_equal( # length(output_19148), # 1L) # # Testing sum of element lengths # expect_equal( # sum(xpectr::element_lengths(output_19148)), # 1L) # ## Finished testing 'fn()' #### # # # In case of errors, the warnings and messages aren't tested # # gxs_selection("fn(raise = TRUE)") # # # Inserts the following tests: # # ## Testing 'fn(raise = TRUE)' #### # ## Initially generated by xpectr # xpectr::set_test_seed(42) # # Testing side effects # expect_error( # xpectr::strip_msg(fn(raise = TRUE)), # xpectr::strip("Lord Evil Error has arrived! Yeehaaa"), # fixed = TRUE) # ## Finished testing 'fn(raise = TRUE)' #### # ## ----eval=FALSE--------------------------------------------------------------- # # Define a function with arguments # fn <- function(x, y, z = 10) { # if (x > 3) stop("'x' > 3") # if (y < 0) warning("'y'<0") # if (z == 10) message("'z' was 10!") # x + y + z # } # # # Create tests for the function # # Note: We currently need to specify the list of arguments # # in the function call # gxs_function(fn = fn, # args_values = list( # "x" = list(2, 4, NA), # "y" = list(0,-1), # "z" = list(5, 10) # )) # # # Inserts the following tests: # # ## Testing 'fn' #### # ## Initially generated by xpectr # # Testing different combinations of argument values # # # Testing fn(x = 2, y = 0, z = 5) # xpectr::set_test_seed(42) # # Assigning output # output_19148 <- fn(x = 2, y = 0, z = 5) # # Testing class # expect_equal( # class(output_19148), # "numeric", # fixed = TRUE) # # Testing type # expect_type( # output_19148, # type = "double") # # Testing values # expect_equal( # output_19148, # 7, # tolerance = 1e-4) # # Testing names # expect_equal( # names(output_19148), # NULL, # fixed = TRUE) # # Testing length # expect_equal( # length(output_19148), # 1L) # # Testing sum of element lengths # expect_equal( # sum(xpectr::element_lengths(output_19148)), # 1L) # # # Testing fn(x = 4, y = 0, z = 5) # # Changed from baseline: x = 4 # xpectr::set_test_seed(42) # # Testing side effects # expect_error( # xpectr::strip_msg(fn(x = 4, y = 0, z = 5)), # xpectr::strip("'x' > 3"), # fixed = TRUE) # # # Testing fn(x = NA, y = 0, z = 5) # # Changed from baseline: x = NA # xpectr::set_test_seed(42) # # Testing side effects # expect_error( # xpectr::strip_msg(fn(x = NA, y = 0, z = 5)), # xpectr::strip("missing value where TRUE/FALSE needed"), # fixed = TRUE) # # # Testing fn(x = NULL, y = 0, z = 5) # # Changed from baseline: x = NULL # xpectr::set_test_seed(42) # # Testing side effects # expect_error( # xpectr::strip_msg(fn(x = NULL, y = 0, z = 5)), # xpectr::strip("argument is of length zero"), # fixed = TRUE) # # # Testing fn(x = 2, y = -1, z = 5) # # Changed from baseline: y = -1 # xpectr::set_test_seed(42) # # Testing side effects # # Assigning side effects # side_effects_16417 <- xpectr::capture_side_effects(fn(x = 2, y = -1, z = 5), reset_seed = TRUE) # expect_equal( # xpectr::strip(side_effects_16417[['warnings']]), # xpectr::strip("'y'<0"), # fixed = TRUE) # expect_equal( # xpectr::strip(side_effects_16417[['messages']]), # xpectr::strip(character(0)), # fixed = TRUE) # # Assigning output # output_16417 <- xpectr::suppress_mw(fn(x = 2, y = -1, z = 5)) # # Testing class # expect_equal( # class(output_16417), # "numeric", # fixed = TRUE) # # Testing type # expect_type( # output_16417, # type = "double") # # Testing values # expect_equal( # output_16417, # 6, # tolerance = 1e-4) # # Testing names # expect_equal( # names(output_16417), # NULL, # fixed = TRUE) # # Testing length # expect_equal( # length(output_16417), # 1L) # # Testing sum of element lengths # expect_equal( # sum(xpectr::element_lengths(output_16417)), # 1L) # # # Testing fn(x = 2, y = NULL, z = 5) # # Changed from baseline: y = NULL # xpectr::set_test_seed(42) # # Testing side effects # expect_error( # xpectr::strip_msg(fn(x = 2, y = NULL, z = 5)), # xpectr::strip("argument is of length zero"), # fixed = TRUE) # # # Testing fn(x = 2, y = 0, z = 10) # # Changed from baseline: z = 10 # xpectr::set_test_seed(42) # # Testing side effects # # Assigning side effects # side_effects_17365 <- xpectr::capture_side_effects(fn(x = 2, y = 0, z = 10), reset_seed = TRUE) # expect_equal( # xpectr::strip(side_effects_17365[['warnings']]), # xpectr::strip(character(0)), # fixed = TRUE) # expect_equal( # xpectr::strip(side_effects_17365[['messages']]), # xpectr::strip("'z' was 10!\n"), # fixed = TRUE) # # Assigning output # output_17365 <- xpectr::suppress_mw(fn(x = 2, y = 0, z = 10)) # # Testing class # expect_equal( # class(output_17365), # "numeric", # fixed = TRUE) # # Testing type # expect_type( # output_17365, # type = "double") # # Testing values # expect_equal( # output_17365, # 12, # tolerance = 1e-4) # # Testing names # expect_equal( # names(output_17365), # NULL, # fixed = TRUE) # # Testing length # expect_equal( # length(output_17365), # 1L) # # Testing sum of element lengths # expect_equal( # sum(xpectr::element_lengths(output_17365)), # 1L) # # # Testing fn(x = 2, y = 0, z = NULL) # # Changed from baseline: z = NULL # xpectr::set_test_seed(42) # # Testing side effects # expect_error( # xpectr::strip_msg(fn(x = 2, y = 0, z = NULL)), # xpectr::strip("argument is of length zero"), # fixed = TRUE) # # ## Finished testing 'fn' #### # ## ----eval=FALSE--------------------------------------------------------------- # initializeGXSFunctionAddin("fn") # # # Inserts the following: # # # Generate expectations for 'fn' # # Tip: comment out the gxs_function() call # # so it is easy to regenerate the tests # xpectr::set_test_seed(42) # xpectr::gxs_function( # fn = fn, # args_values = list( # "x" = list(), # "y" = list(), # "z" = list(10) # ), # identation = 2, # copy_env = FALSE # ) # # # # ## ----eval=FALSE--------------------------------------------------------------- # wrapStringAddin("This is a fairly long sentence that we would very very much like to make shorter in our test file!") # # # Inserts the following: # # paste0("This is a fairly long sentence that we would very very much ", # "like to make shorter in our test file!") # ## ----eval=FALSE--------------------------------------------------------------- # initializeTestthatAddin() # # # Inserts the following: # # test_that("testing ...()", { # xpectr::set_test_seed(42) # # # ... # # }) # ## ----eval=FALSE--------------------------------------------------------------- # assertCollectionAddin() # # # Inserts the following: # # # Check arguments #### # assert_collection <- checkmate::makeAssertCollection() # # checkmate::assert_ , add = assert_collection) # checkmate::reportAssertions(assert_collection) # # End of argument checks #### # ## ----eval=FALSE--------------------------------------------------------------- # v <- c(1, 2, 3) # # dputSelectedAddin("v") # "v" is the selected code # # # Inserts the following: # # c(1, 2, 3) #
/scratch/gouwar.j/cran-all/cranData/xpectr/inst/doc/readme.R
--- title: "README for xpectr" author: - "Ludvig Renbo Olsen" date: "`r Sys.Date()`" abstract: | This vignette is an introduction to the `xpectr` package. `xpectr` provides a set of utilities and RStudio addins for generating tests for `testthat` unit testing. &nbsp; &nbsp; Contact author at [email protected] &nbsp; &nbsp; output: rmarkdown::html_vignette: css: - !expr system.file("rmarkdown/templates/html_vignette/resources/vignette.css", package = "rmarkdown") - styles.css fig_width: 6 fig_height: 4 toc: yes number_sections: no rmarkdown::pdf_document: highlight: tango number_sections: yes toc: yes toc_depth: 4 vignette: > %\VignetteIndexEntry{Introduction_to_cvms} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>", fig.path = "man/figures/vignette_intro-", dpi = 92, fig.retina = 2 ) ``` When developing R packages, it's good practice to build a good set of unit and regression tests that will notify you when something breaks in the future. For this, the [`testthat`](https://testthat.r-lib.org/) package is commonly used. Often though, we end up writing a similar set of tests again and again, which can be both tedious and time-consuming. `xpectr` helps you by generating common `testthat` tests. Its goal is **not** to replace the active thinking process of finding meaningful tests for your functions, but to help **systematize** and **ease** that process. One such example is `gxs_function()`, which generates tests for a set of argument value combinations. This allows you to focus on the selection of argument values to test. Once the tests have been generated, you can go through each of them to ensure your function is working as intended and to add relevant tests. Note: If you comment out the call to `gxs_function()`, it is easy to later regenerate the tests. By using a diff tool, you can check that only the intended changes have been made to the file. ## Installation Install the CRAN version with: ```{r eval=FALSE} install.packages("xpectr") ``` Install the development version with: ```{r eval=FALSE} # install.packages("devtools") devtools::install_github("ludvigolsen/xpectr") ``` ## Main functions ### Generator functions These functions are used to *generate expectations* (gxs). | Function | Description | |:---------|:------------| |`gxs_selection()` |Generates `testthat::expect_*` statements from a selection (string of code)| |`gxs_function()` |Generates `testthat::expect_*` statements for combinations of supplied argument values| ### Functions for use in tests | Function | Description | |:---------|:------------| |`strip()` |Strips strings of non-alphanumeric characters | |`strip_msg()` |Strips side-effect messages of non-alphanumeric characters and rethrows them | |`suppress_mw()` |Suppresses warnings and messages | |`capture_side_effects()` |Captures errors, warnings, and messages from an expression | |`smpl()` |Samples a vector, factor or data frame with internal random seed | |`simplified_formals()` |Formats formals as easily testable character vector | |`element_lengths()`, `element_types()`, `element_classes()` |Gets the length/type/class of each element | |`num_total_elements()` |Unlists recursively and finds the total number of elements | |`set_test_seed()` |Set random seed for unit tests compatible with `R < 3.6.0` | ### Helper functions | Function | Description | |:---------|:------------| |`prepare_insertion()` |Collapses a vector of expectation strings and adds indentation | |`capture_parse_eval_side_effects()` |Wraps string in `capture_side_effects()` before parsing and evaluating it | |`stop_if()`, `warn_if()`, `message_if()` |If `TRUE`, generate error/warning/message with the supplied message | ## Addins | Addin | Description | Suggested Key Command | |:------|:------------|:-------------------------------------------------------------------| |*Insert Expectations* </br><font size="2">`insertExpectationsAddin()`</font> |Generates `testthat` `expect_*` tests from selected code (with `gxs_selection()`) |`Alt+E` | |*Initialize `test_that()`* </br><font size="2">`initializeTestthatAddin()`</font> |Inserts `testthat::test_that()` code |`Alt+T` | |*Initialize `gxs_function()`* </br><font size="2">`initializeGXSFunctionAddin()`</font> |Initializes a `gxs_function()` call with default values of a function |`Alt+F` | |*`dput()` selected* </br><font size="2">`dputSelectedAddin()`</font> |Applies `dput()` to selected code |`Alt+D` | |*Wrap string with `paste0()`* </br><font size="2">`wrapStringAddin()`</font> |Splits selected string every n characters and wraps in `paste0()` call |`Alt+P` | |*Insert `checkmate` `AssertCollection`code* </br><font size="2">`assertCollectionAddin()`</font> |Inserts code for initializing and reporting a `checkmate` `AssertCollection` |`Alt+C` | |*Navigate To Test File* </br><font size="2">`navigateTestFileAddin()`</font> |Navigates to extracted file name and line number. E.g. select or copy `test_x.R:5` and it opens `/tests/testthat/test_x.R` at line `5`.|`Alt+N` | ## Using in packages Suggestion: Add `xpectr` in the `Suggests` field in the `DESCRIPTION` file. ## Examples ```{r warning=FALSE, message=FALSE} library(xpectr) library(testthat) library(dplyr) # Set a seed # When R > 3.6.0, it sets sampling.kind to "Rounding" to make # tests compatible with previous versions of R set_test_seed(42) ``` ```{r} # Some data num_vec <- 1:10 long_vec <- c(LETTERS, letters) a_factor <- factor(c("a","b","c")) df <- data.frame( 'a' = c(1, 2, 3), 'b' = c('t', 'y', 'u'), "c" = a_factor, stringsAsFactors = FALSE ) %>% dplyr::group_by(a) # A function with side effects fn <- function(raise = FALSE){ message("Hi! I'm Kevin, your favorite message!") warning("G'Day Mam! I'm a warning to the world!") message("Kevin is ma name! Yesss!") warning("Hopefully the whole world will see me :o") if (isTRUE(raise)){ stop("Lord Evil Error has arrived! Yeehaaa") } "the output" } ``` ### gxs_selection Note: `gxs_selection()` can be used with the `Insert Expectations` addin. See `?insertExpectationsAddin` for instructions on how to set up a key command. #### Selection is a vector ##### Numeric vector ```{r} # Inspect num_vec num_vec ``` ```{r eval=FALSE} # Generate expectations gxs_selection("num_vec") # Inserts the following tests: ## Testing 'num_vec' #### ## Initially generated by xpectr xpectr::set_test_seed(42) # Testing class expect_equal( class(num_vec), "integer", fixed = TRUE) # Testing type expect_type( num_vec, type = "integer") # Testing values expect_equal( num_vec, c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), tolerance = 1e-4) # Testing names expect_equal( names(num_vec), NULL, fixed = TRUE) # Testing length expect_equal( length(num_vec), 10L) # Testing sum of element lengths expect_equal( sum(xpectr::element_lengths(num_vec)), 10L) ## Finished testing 'num_vec' #### ``` ##### Factor ```{r} # Inspect a_factor a_factor ``` ```{r eval=FALSE} # Generate expectations gxs_selection("a_factor") # Inserts the following tests: ## Testing 'a_factor' #### ## Initially generated by xpectr xpectr::set_test_seed(42) # Testing is factor expect_true( is.factor(a_factor)) # Testing values expect_equal( as.character(a_factor), c("a", "b", "c"), fixed = TRUE) # Testing names expect_equal( names(a_factor), NULL, fixed = TRUE) # Testing length expect_equal( length(a_factor), 3L) # Testing number of levels expect_equal( nlevels(a_factor), 3L) # Testing levels expect_equal( levels(a_factor), c("a", "b", "c"), fixed = TRUE) ## Finished testing 'a_factor' #### ``` ##### Long vector (sampling) By default, vectors with more than 30 elements will be sampled. This adds `smpl()`, which temporarily sets a seed to make sure the same elements are returned every time. ```{r} # Inspect long_vec long_vec ``` ```{r eval=FALSE} # Generate expectations gxs_selection("long_vec") # Inserts the following tests: ## Testing 'long_vec' #### ## Initially generated by xpectr xpectr::set_test_seed(42) # Testing class expect_equal( class(long_vec), "character", fixed = TRUE) # Testing type expect_type( long_vec, type = "character") # Testing values expect_equal( xpectr::smpl(long_vec, n = 30), c("C", "E", "G", "J", "K", "N", "O", "Q", "R", "S", "T", "W", "Y", "Z", "b", "c", "d", "e", "h", "i", "j", "k", "l", "o", "p", "r", "v", "w", "y", "z"), fixed = TRUE) # Testing names expect_equal( names(xpectr::smpl(long_vec, n = 30)), NULL, fixed = TRUE) # Testing length expect_equal( length(long_vec), 52L) # Testing sum of element lengths expect_equal( sum(xpectr::element_lengths(long_vec)), 52L) ## Finished testing 'long_vec' #### ``` #### Selection is a data frame Data frames are tested columnwise. ```{r} # Inspect df df ``` ```{r eval=FALSE} # Generate expectations gxs_selection("df") # Inserts the following tests: ## Testing 'df' #### ## Initially generated by xpectr xpectr::set_test_seed(42) # Testing class expect_equal( class(df), c("grouped_df", "tbl_df", "tbl", "data.frame"), fixed = TRUE) # Testing column values expect_equal( df[["a"]], c(1, 2, 3), tolerance = 1e-4) expect_equal( df[["b"]], c("t", "y", "u"), fixed = TRUE) expect_equal( df[["c"]], structure(1:3, levels = c("a", "b", "c"), class = "factor")) # Testing column names expect_equal( names(df), c("a", "b", "c"), fixed = TRUE) # Testing column classes expect_equal( xpectr::element_classes(df), c("numeric", "character", "factor"), fixed = TRUE) # Testing column types expect_equal( xpectr::element_types(df), c("double", "character", "integer"), fixed = TRUE) # Testing dimensions expect_equal( dim(df), c(3L, 3L)) # Testing group keys expect_equal( colnames(dplyr::group_keys(df)), "a", fixed = TRUE) ## Finished testing 'df' #### ``` #### Selection is a function call with side effects When the selected code generates an error, warning or message, we can test those as well. An error is tested with `expect_error()`, while messages and warnings are tested as character vectors, to make sure we catch additional warnings/messages. When running `testthat` unit tests on different systems, they sometimes vary in the use of punctuation and newlines (\\n). The `strip()` and `strip_msg()` functions are wrapped around the side effects to remove non-alphanumeric symbols from the tested strings. This helps the `expect_*` functions to ignore those differences. In cases where such differences are important to catch, you can set `strip = FALSE` in `gxs_selection()`. We assign the output of the function to an `output_12345` variable, so we don't have to run it more than once. The number is randomly generated and is **not** guaranteed to be unique. `suppress_mw()` suppresses the messages and warnings. ```{r} # Inspect fn fn ``` ```{r eval=FALSE} # Generate expectations gxs_selection("fn()") # Inserts the following tests: ## Testing 'fn()' #### ## Initially generated by xpectr xpectr::set_test_seed(42) # Testing side effects # Assigning side effects side_effects_19148 <- xpectr::capture_side_effects(fn(), reset_seed = TRUE) expect_equal( xpectr::strip(side_effects_19148[['warnings']]), xpectr::strip(c("G'Day Mam! I'm a warning to the world!", "Hopefully the whole world will see me :o")), fixed = TRUE) expect_equal( xpectr::strip(side_effects_19148[['messages']]), xpectr::strip(c("Hi! I'm Kevin, your favorite message!\n", "Kevin is ma name! Yesss!\n")), fixed = TRUE) # Assigning output output_19148 <- xpectr::suppress_mw(fn()) # Testing class expect_equal( class(output_19148), "character", fixed = TRUE) # Testing type expect_type( output_19148, type = "character") # Testing values expect_equal( output_19148, "the output", fixed = TRUE) # Testing names expect_equal( names(output_19148), NULL, fixed = TRUE) # Testing length expect_equal( length(output_19148), 1L) # Testing sum of element lengths expect_equal( sum(xpectr::element_lengths(output_19148)), 1L) ## Finished testing 'fn()' #### # In case of errors, the warnings and messages aren't tested gxs_selection("fn(raise = TRUE)") # Inserts the following tests: ## Testing 'fn(raise = TRUE)' #### ## Initially generated by xpectr xpectr::set_test_seed(42) # Testing side effects expect_error( xpectr::strip_msg(fn(raise = TRUE)), xpectr::strip("Lord Evil Error has arrived! Yeehaaa"), fixed = TRUE) ## Finished testing 'fn(raise = TRUE)' #### ``` ### gxs_function When testing the inputs to a function, `gxs_function()` allows us to quickly specify values to check and generates tests for each of them. The first value supplied for an argument is considered the *valid baseline* value. For each argument, we create tests for each of the supplied values, where the other arguments have their baseline value. By default, each argument is tested with the `NULL` object as well, why we only need to specify it when the baseline value should be `NULL`. It is important that we manually read through the generated tests to make sure that our function is behaving as intended, and to check if any important tests are missing. ```{r eval=FALSE} # Define a function with arguments fn <- function(x, y, z = 10) { if (x > 3) stop("'x' > 3") if (y < 0) warning("'y'<0") if (z == 10) message("'z' was 10!") x + y + z } # Create tests for the function # Note: We currently need to specify the list of arguments # in the function call gxs_function(fn = fn, args_values = list( "x" = list(2, 4, NA), "y" = list(0,-1), "z" = list(5, 10) )) # Inserts the following tests: ## Testing 'fn' #### ## Initially generated by xpectr # Testing different combinations of argument values # Testing fn(x = 2, y = 0, z = 5) xpectr::set_test_seed(42) # Assigning output output_19148 <- fn(x = 2, y = 0, z = 5) # Testing class expect_equal( class(output_19148), "numeric", fixed = TRUE) # Testing type expect_type( output_19148, type = "double") # Testing values expect_equal( output_19148, 7, tolerance = 1e-4) # Testing names expect_equal( names(output_19148), NULL, fixed = TRUE) # Testing length expect_equal( length(output_19148), 1L) # Testing sum of element lengths expect_equal( sum(xpectr::element_lengths(output_19148)), 1L) # Testing fn(x = 4, y = 0, z = 5) # Changed from baseline: x = 4 xpectr::set_test_seed(42) # Testing side effects expect_error( xpectr::strip_msg(fn(x = 4, y = 0, z = 5)), xpectr::strip("'x' > 3"), fixed = TRUE) # Testing fn(x = NA, y = 0, z = 5) # Changed from baseline: x = NA xpectr::set_test_seed(42) # Testing side effects expect_error( xpectr::strip_msg(fn(x = NA, y = 0, z = 5)), xpectr::strip("missing value where TRUE/FALSE needed"), fixed = TRUE) # Testing fn(x = NULL, y = 0, z = 5) # Changed from baseline: x = NULL xpectr::set_test_seed(42) # Testing side effects expect_error( xpectr::strip_msg(fn(x = NULL, y = 0, z = 5)), xpectr::strip("argument is of length zero"), fixed = TRUE) # Testing fn(x = 2, y = -1, z = 5) # Changed from baseline: y = -1 xpectr::set_test_seed(42) # Testing side effects # Assigning side effects side_effects_16417 <- xpectr::capture_side_effects(fn(x = 2, y = -1, z = 5), reset_seed = TRUE) expect_equal( xpectr::strip(side_effects_16417[['warnings']]), xpectr::strip("'y'<0"), fixed = TRUE) expect_equal( xpectr::strip(side_effects_16417[['messages']]), xpectr::strip(character(0)), fixed = TRUE) # Assigning output output_16417 <- xpectr::suppress_mw(fn(x = 2, y = -1, z = 5)) # Testing class expect_equal( class(output_16417), "numeric", fixed = TRUE) # Testing type expect_type( output_16417, type = "double") # Testing values expect_equal( output_16417, 6, tolerance = 1e-4) # Testing names expect_equal( names(output_16417), NULL, fixed = TRUE) # Testing length expect_equal( length(output_16417), 1L) # Testing sum of element lengths expect_equal( sum(xpectr::element_lengths(output_16417)), 1L) # Testing fn(x = 2, y = NULL, z = 5) # Changed from baseline: y = NULL xpectr::set_test_seed(42) # Testing side effects expect_error( xpectr::strip_msg(fn(x = 2, y = NULL, z = 5)), xpectr::strip("argument is of length zero"), fixed = TRUE) # Testing fn(x = 2, y = 0, z = 10) # Changed from baseline: z = 10 xpectr::set_test_seed(42) # Testing side effects # Assigning side effects side_effects_17365 <- xpectr::capture_side_effects(fn(x = 2, y = 0, z = 10), reset_seed = TRUE) expect_equal( xpectr::strip(side_effects_17365[['warnings']]), xpectr::strip(character(0)), fixed = TRUE) expect_equal( xpectr::strip(side_effects_17365[['messages']]), xpectr::strip("'z' was 10!\n"), fixed = TRUE) # Assigning output output_17365 <- xpectr::suppress_mw(fn(x = 2, y = 0, z = 10)) # Testing class expect_equal( class(output_17365), "numeric", fixed = TRUE) # Testing type expect_type( output_17365, type = "double") # Testing values expect_equal( output_17365, 12, tolerance = 1e-4) # Testing names expect_equal( names(output_17365), NULL, fixed = TRUE) # Testing length expect_equal( length(output_17365), 1L) # Testing sum of element lengths expect_equal( sum(xpectr::element_lengths(output_17365)), 1L) # Testing fn(x = 2, y = 0, z = NULL) # Changed from baseline: z = NULL xpectr::set_test_seed(42) # Testing side effects expect_error( xpectr::strip_msg(fn(x = 2, y = 0, z = NULL)), xpectr::strip("argument is of length zero"), fixed = TRUE) ## Finished testing 'fn' #### ``` ### RStudio Addins Below, we present the set of `RStudio` addins. The intention is for you to set up key commands for the ones you'd like access to. Once you get used to using them, they will speed up your testing process. #### How to set up a key command in RStudio Here's a small guide for setting up key comands in `RStudio`. We use the `Insert Expectations` addin as an example: After installing the package, go to: `Tools >> Addins >> Browse Addins >> Keyboard Shortcuts`. Find `"Insert Expectations"` and press its field under `Shortcut`. Press desired key command, e.g. `Alt+E`. Press `Apply`. Press `Execute`. #### initializeGXSFunctionAddin The `initializeGXSFunctionAddin` initializes the `gxs_function()` call with the argument names and default values of a selected function. We can then add the argument values and additional combinations we wish to test. Note, that we don't need to use the default values as our baseline values. The `Tip` comment tells us to comment out the `gxs_function()` call after running it, instead of removing it. When you change your code, it's often much quicker to regenerate the tests than to update them manually. You can then use a diff tool to check that only the intended changes were made. The `#` in the end helps the code be inserted right after the call to `gxs_function()`. Suggested keycommand: `Alt+F` ```{r eval=FALSE} initializeGXSFunctionAddin("fn") # Inserts the following: # Generate expectations for 'fn' # Tip: comment out the gxs_function() call # so it is easy to regenerate the tests xpectr::set_test_seed(42) xpectr::gxs_function( fn = fn, args_values = list( "x" = list(), "y" = list(), "z" = list(10) ), identation = 2, copy_env = FALSE ) # ``` #### wrapStringAddin The `wrapStringAddin` splits long strings and wraps them with `paste0()`. Suggested keycommand: `Alt+P` ```{r eval=FALSE} wrapStringAddin("This is a fairly long sentence that we would very very much like to make shorter in our test file!") # Inserts the following: paste0("This is a fairly long sentence that we would very very much ", "like to make shorter in our test file!") ``` #### initializeTestthatAddin Suggested keycommand: `Alt+T` ```{r eval=FALSE} initializeTestthatAddin() # Inserts the following: test_that("testing ...()", { xpectr::set_test_seed(42) # ... }) ``` #### assertCollectionAddin Suggested keycommand: `Alt+C` ```{r eval=FALSE} assertCollectionAddin() # Inserts the following: # Check arguments #### assert_collection <- checkmate::makeAssertCollection() # checkmate::assert_ , add = assert_collection) checkmate::reportAssertions(assert_collection) # End of argument checks #### ``` #### dputSelectedAddin Suggested keycommand: `Alt+D` ```{r eval=FALSE} v <- c(1, 2, 3) dputSelectedAddin("v") # "v" is the selected code # Inserts the following: c(1, 2, 3) ``` #### navigateTestFileAddin Suggested keycommand: `Alt+N` A common work process in package development is to run `Ctrl/Cmd+Shift+L`, which runs all `testthat` tests in `/tests/testthat/` in the `Build` pane. When a test fails, a message like the following is printed: `test_x.R:15: failure: x works`. If we then copy the `test_x.R:15:` part to our clipboard and run `navigateTestFileAddin()`, it will open the `test_x.R` file and place the cursor at line `15`. A service like `Travis CI` indicate the failed test with `(@test_x.R#15)`. The addin therefore also works with `test_x.R#15`. If you have additional formats you would like to request, simply open an issue.
/scratch/gouwar.j/cran-all/cranData/xpectr/inst/doc/readme.Rmd
--- title: "README for xpectr" author: - "Ludvig Renbo Olsen" date: "`r Sys.Date()`" abstract: | This vignette is an introduction to the `xpectr` package. `xpectr` provides a set of utilities and RStudio addins for generating tests for `testthat` unit testing. &nbsp; &nbsp; Contact author at [email protected] &nbsp; &nbsp; output: rmarkdown::html_vignette: css: - !expr system.file("rmarkdown/templates/html_vignette/resources/vignette.css", package = "rmarkdown") - styles.css fig_width: 6 fig_height: 4 toc: yes number_sections: no rmarkdown::pdf_document: highlight: tango number_sections: yes toc: yes toc_depth: 4 vignette: > %\VignetteIndexEntry{Introduction_to_cvms} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>", fig.path = "man/figures/vignette_intro-", dpi = 92, fig.retina = 2 ) ``` When developing R packages, it's good practice to build a good set of unit and regression tests that will notify you when something breaks in the future. For this, the [`testthat`](https://testthat.r-lib.org/) package is commonly used. Often though, we end up writing a similar set of tests again and again, which can be both tedious and time-consuming. `xpectr` helps you by generating common `testthat` tests. Its goal is **not** to replace the active thinking process of finding meaningful tests for your functions, but to help **systematize** and **ease** that process. One such example is `gxs_function()`, which generates tests for a set of argument value combinations. This allows you to focus on the selection of argument values to test. Once the tests have been generated, you can go through each of them to ensure your function is working as intended and to add relevant tests. Note: If you comment out the call to `gxs_function()`, it is easy to later regenerate the tests. By using a diff tool, you can check that only the intended changes have been made to the file. ## Installation Install the CRAN version with: ```{r eval=FALSE} install.packages("xpectr") ``` Install the development version with: ```{r eval=FALSE} # install.packages("devtools") devtools::install_github("ludvigolsen/xpectr") ``` ## Main functions ### Generator functions These functions are used to *generate expectations* (gxs). | Function | Description | |:---------|:------------| |`gxs_selection()` |Generates `testthat::expect_*` statements from a selection (string of code)| |`gxs_function()` |Generates `testthat::expect_*` statements for combinations of supplied argument values| ### Functions for use in tests | Function | Description | |:---------|:------------| |`strip()` |Strips strings of non-alphanumeric characters | |`strip_msg()` |Strips side-effect messages of non-alphanumeric characters and rethrows them | |`suppress_mw()` |Suppresses warnings and messages | |`capture_side_effects()` |Captures errors, warnings, and messages from an expression | |`smpl()` |Samples a vector, factor or data frame with internal random seed | |`simplified_formals()` |Formats formals as easily testable character vector | |`element_lengths()`, `element_types()`, `element_classes()` |Gets the length/type/class of each element | |`num_total_elements()` |Unlists recursively and finds the total number of elements | |`set_test_seed()` |Set random seed for unit tests compatible with `R < 3.6.0` | ### Helper functions | Function | Description | |:---------|:------------| |`prepare_insertion()` |Collapses a vector of expectation strings and adds indentation | |`capture_parse_eval_side_effects()` |Wraps string in `capture_side_effects()` before parsing and evaluating it | |`stop_if()`, `warn_if()`, `message_if()` |If `TRUE`, generate error/warning/message with the supplied message | ## Addins | Addin | Description | Suggested Key Command | |:------|:------------|:-------------------------------------------------------------------| |*Insert Expectations* </br><font size="2">`insertExpectationsAddin()`</font> |Generates `testthat` `expect_*` tests from selected code (with `gxs_selection()`) |`Alt+E` | |*Initialize `test_that()`* </br><font size="2">`initializeTestthatAddin()`</font> |Inserts `testthat::test_that()` code |`Alt+T` | |*Initialize `gxs_function()`* </br><font size="2">`initializeGXSFunctionAddin()`</font> |Initializes a `gxs_function()` call with default values of a function |`Alt+F` | |*`dput()` selected* </br><font size="2">`dputSelectedAddin()`</font> |Applies `dput()` to selected code |`Alt+D` | |*Wrap string with `paste0()`* </br><font size="2">`wrapStringAddin()`</font> |Splits selected string every n characters and wraps in `paste0()` call |`Alt+P` | |*Insert `checkmate` `AssertCollection`code* </br><font size="2">`assertCollectionAddin()`</font> |Inserts code for initializing and reporting a `checkmate` `AssertCollection` |`Alt+C` | |*Navigate To Test File* </br><font size="2">`navigateTestFileAddin()`</font> |Navigates to extracted file name and line number. E.g. select or copy `test_x.R:5` and it opens `/tests/testthat/test_x.R` at line `5`.|`Alt+N` | ## Using in packages Suggestion: Add `xpectr` in the `Suggests` field in the `DESCRIPTION` file. ## Examples ```{r warning=FALSE, message=FALSE} library(xpectr) library(testthat) library(dplyr) # Set a seed # When R > 3.6.0, it sets sampling.kind to "Rounding" to make # tests compatible with previous versions of R set_test_seed(42) ``` ```{r} # Some data num_vec <- 1:10 long_vec <- c(LETTERS, letters) a_factor <- factor(c("a","b","c")) df <- data.frame( 'a' = c(1, 2, 3), 'b' = c('t', 'y', 'u'), "c" = a_factor, stringsAsFactors = FALSE ) %>% dplyr::group_by(a) # A function with side effects fn <- function(raise = FALSE){ message("Hi! I'm Kevin, your favorite message!") warning("G'Day Mam! I'm a warning to the world!") message("Kevin is ma name! Yesss!") warning("Hopefully the whole world will see me :o") if (isTRUE(raise)){ stop("Lord Evil Error has arrived! Yeehaaa") } "the output" } ``` ### gxs_selection Note: `gxs_selection()` can be used with the `Insert Expectations` addin. See `?insertExpectationsAddin` for instructions on how to set up a key command. #### Selection is a vector ##### Numeric vector ```{r} # Inspect num_vec num_vec ``` ```{r eval=FALSE} # Generate expectations gxs_selection("num_vec") # Inserts the following tests: ## Testing 'num_vec' #### ## Initially generated by xpectr xpectr::set_test_seed(42) # Testing class expect_equal( class(num_vec), "integer", fixed = TRUE) # Testing type expect_type( num_vec, type = "integer") # Testing values expect_equal( num_vec, c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), tolerance = 1e-4) # Testing names expect_equal( names(num_vec), NULL, fixed = TRUE) # Testing length expect_equal( length(num_vec), 10L) # Testing sum of element lengths expect_equal( sum(xpectr::element_lengths(num_vec)), 10L) ## Finished testing 'num_vec' #### ``` ##### Factor ```{r} # Inspect a_factor a_factor ``` ```{r eval=FALSE} # Generate expectations gxs_selection("a_factor") # Inserts the following tests: ## Testing 'a_factor' #### ## Initially generated by xpectr xpectr::set_test_seed(42) # Testing is factor expect_true( is.factor(a_factor)) # Testing values expect_equal( as.character(a_factor), c("a", "b", "c"), fixed = TRUE) # Testing names expect_equal( names(a_factor), NULL, fixed = TRUE) # Testing length expect_equal( length(a_factor), 3L) # Testing number of levels expect_equal( nlevels(a_factor), 3L) # Testing levels expect_equal( levels(a_factor), c("a", "b", "c"), fixed = TRUE) ## Finished testing 'a_factor' #### ``` ##### Long vector (sampling) By default, vectors with more than 30 elements will be sampled. This adds `smpl()`, which temporarily sets a seed to make sure the same elements are returned every time. ```{r} # Inspect long_vec long_vec ``` ```{r eval=FALSE} # Generate expectations gxs_selection("long_vec") # Inserts the following tests: ## Testing 'long_vec' #### ## Initially generated by xpectr xpectr::set_test_seed(42) # Testing class expect_equal( class(long_vec), "character", fixed = TRUE) # Testing type expect_type( long_vec, type = "character") # Testing values expect_equal( xpectr::smpl(long_vec, n = 30), c("C", "E", "G", "J", "K", "N", "O", "Q", "R", "S", "T", "W", "Y", "Z", "b", "c", "d", "e", "h", "i", "j", "k", "l", "o", "p", "r", "v", "w", "y", "z"), fixed = TRUE) # Testing names expect_equal( names(xpectr::smpl(long_vec, n = 30)), NULL, fixed = TRUE) # Testing length expect_equal( length(long_vec), 52L) # Testing sum of element lengths expect_equal( sum(xpectr::element_lengths(long_vec)), 52L) ## Finished testing 'long_vec' #### ``` #### Selection is a data frame Data frames are tested columnwise. ```{r} # Inspect df df ``` ```{r eval=FALSE} # Generate expectations gxs_selection("df") # Inserts the following tests: ## Testing 'df' #### ## Initially generated by xpectr xpectr::set_test_seed(42) # Testing class expect_equal( class(df), c("grouped_df", "tbl_df", "tbl", "data.frame"), fixed = TRUE) # Testing column values expect_equal( df[["a"]], c(1, 2, 3), tolerance = 1e-4) expect_equal( df[["b"]], c("t", "y", "u"), fixed = TRUE) expect_equal( df[["c"]], structure(1:3, levels = c("a", "b", "c"), class = "factor")) # Testing column names expect_equal( names(df), c("a", "b", "c"), fixed = TRUE) # Testing column classes expect_equal( xpectr::element_classes(df), c("numeric", "character", "factor"), fixed = TRUE) # Testing column types expect_equal( xpectr::element_types(df), c("double", "character", "integer"), fixed = TRUE) # Testing dimensions expect_equal( dim(df), c(3L, 3L)) # Testing group keys expect_equal( colnames(dplyr::group_keys(df)), "a", fixed = TRUE) ## Finished testing 'df' #### ``` #### Selection is a function call with side effects When the selected code generates an error, warning or message, we can test those as well. An error is tested with `expect_error()`, while messages and warnings are tested as character vectors, to make sure we catch additional warnings/messages. When running `testthat` unit tests on different systems, they sometimes vary in the use of punctuation and newlines (\\n). The `strip()` and `strip_msg()` functions are wrapped around the side effects to remove non-alphanumeric symbols from the tested strings. This helps the `expect_*` functions to ignore those differences. In cases where such differences are important to catch, you can set `strip = FALSE` in `gxs_selection()`. We assign the output of the function to an `output_12345` variable, so we don't have to run it more than once. The number is randomly generated and is **not** guaranteed to be unique. `suppress_mw()` suppresses the messages and warnings. ```{r} # Inspect fn fn ``` ```{r eval=FALSE} # Generate expectations gxs_selection("fn()") # Inserts the following tests: ## Testing 'fn()' #### ## Initially generated by xpectr xpectr::set_test_seed(42) # Testing side effects # Assigning side effects side_effects_19148 <- xpectr::capture_side_effects(fn(), reset_seed = TRUE) expect_equal( xpectr::strip(side_effects_19148[['warnings']]), xpectr::strip(c("G'Day Mam! I'm a warning to the world!", "Hopefully the whole world will see me :o")), fixed = TRUE) expect_equal( xpectr::strip(side_effects_19148[['messages']]), xpectr::strip(c("Hi! I'm Kevin, your favorite message!\n", "Kevin is ma name! Yesss!\n")), fixed = TRUE) # Assigning output output_19148 <- xpectr::suppress_mw(fn()) # Testing class expect_equal( class(output_19148), "character", fixed = TRUE) # Testing type expect_type( output_19148, type = "character") # Testing values expect_equal( output_19148, "the output", fixed = TRUE) # Testing names expect_equal( names(output_19148), NULL, fixed = TRUE) # Testing length expect_equal( length(output_19148), 1L) # Testing sum of element lengths expect_equal( sum(xpectr::element_lengths(output_19148)), 1L) ## Finished testing 'fn()' #### # In case of errors, the warnings and messages aren't tested gxs_selection("fn(raise = TRUE)") # Inserts the following tests: ## Testing 'fn(raise = TRUE)' #### ## Initially generated by xpectr xpectr::set_test_seed(42) # Testing side effects expect_error( xpectr::strip_msg(fn(raise = TRUE)), xpectr::strip("Lord Evil Error has arrived! Yeehaaa"), fixed = TRUE) ## Finished testing 'fn(raise = TRUE)' #### ``` ### gxs_function When testing the inputs to a function, `gxs_function()` allows us to quickly specify values to check and generates tests for each of them. The first value supplied for an argument is considered the *valid baseline* value. For each argument, we create tests for each of the supplied values, where the other arguments have their baseline value. By default, each argument is tested with the `NULL` object as well, why we only need to specify it when the baseline value should be `NULL`. It is important that we manually read through the generated tests to make sure that our function is behaving as intended, and to check if any important tests are missing. ```{r eval=FALSE} # Define a function with arguments fn <- function(x, y, z = 10) { if (x > 3) stop("'x' > 3") if (y < 0) warning("'y'<0") if (z == 10) message("'z' was 10!") x + y + z } # Create tests for the function # Note: We currently need to specify the list of arguments # in the function call gxs_function(fn = fn, args_values = list( "x" = list(2, 4, NA), "y" = list(0,-1), "z" = list(5, 10) )) # Inserts the following tests: ## Testing 'fn' #### ## Initially generated by xpectr # Testing different combinations of argument values # Testing fn(x = 2, y = 0, z = 5) xpectr::set_test_seed(42) # Assigning output output_19148 <- fn(x = 2, y = 0, z = 5) # Testing class expect_equal( class(output_19148), "numeric", fixed = TRUE) # Testing type expect_type( output_19148, type = "double") # Testing values expect_equal( output_19148, 7, tolerance = 1e-4) # Testing names expect_equal( names(output_19148), NULL, fixed = TRUE) # Testing length expect_equal( length(output_19148), 1L) # Testing sum of element lengths expect_equal( sum(xpectr::element_lengths(output_19148)), 1L) # Testing fn(x = 4, y = 0, z = 5) # Changed from baseline: x = 4 xpectr::set_test_seed(42) # Testing side effects expect_error( xpectr::strip_msg(fn(x = 4, y = 0, z = 5)), xpectr::strip("'x' > 3"), fixed = TRUE) # Testing fn(x = NA, y = 0, z = 5) # Changed from baseline: x = NA xpectr::set_test_seed(42) # Testing side effects expect_error( xpectr::strip_msg(fn(x = NA, y = 0, z = 5)), xpectr::strip("missing value where TRUE/FALSE needed"), fixed = TRUE) # Testing fn(x = NULL, y = 0, z = 5) # Changed from baseline: x = NULL xpectr::set_test_seed(42) # Testing side effects expect_error( xpectr::strip_msg(fn(x = NULL, y = 0, z = 5)), xpectr::strip("argument is of length zero"), fixed = TRUE) # Testing fn(x = 2, y = -1, z = 5) # Changed from baseline: y = -1 xpectr::set_test_seed(42) # Testing side effects # Assigning side effects side_effects_16417 <- xpectr::capture_side_effects(fn(x = 2, y = -1, z = 5), reset_seed = TRUE) expect_equal( xpectr::strip(side_effects_16417[['warnings']]), xpectr::strip("'y'<0"), fixed = TRUE) expect_equal( xpectr::strip(side_effects_16417[['messages']]), xpectr::strip(character(0)), fixed = TRUE) # Assigning output output_16417 <- xpectr::suppress_mw(fn(x = 2, y = -1, z = 5)) # Testing class expect_equal( class(output_16417), "numeric", fixed = TRUE) # Testing type expect_type( output_16417, type = "double") # Testing values expect_equal( output_16417, 6, tolerance = 1e-4) # Testing names expect_equal( names(output_16417), NULL, fixed = TRUE) # Testing length expect_equal( length(output_16417), 1L) # Testing sum of element lengths expect_equal( sum(xpectr::element_lengths(output_16417)), 1L) # Testing fn(x = 2, y = NULL, z = 5) # Changed from baseline: y = NULL xpectr::set_test_seed(42) # Testing side effects expect_error( xpectr::strip_msg(fn(x = 2, y = NULL, z = 5)), xpectr::strip("argument is of length zero"), fixed = TRUE) # Testing fn(x = 2, y = 0, z = 10) # Changed from baseline: z = 10 xpectr::set_test_seed(42) # Testing side effects # Assigning side effects side_effects_17365 <- xpectr::capture_side_effects(fn(x = 2, y = 0, z = 10), reset_seed = TRUE) expect_equal( xpectr::strip(side_effects_17365[['warnings']]), xpectr::strip(character(0)), fixed = TRUE) expect_equal( xpectr::strip(side_effects_17365[['messages']]), xpectr::strip("'z' was 10!\n"), fixed = TRUE) # Assigning output output_17365 <- xpectr::suppress_mw(fn(x = 2, y = 0, z = 10)) # Testing class expect_equal( class(output_17365), "numeric", fixed = TRUE) # Testing type expect_type( output_17365, type = "double") # Testing values expect_equal( output_17365, 12, tolerance = 1e-4) # Testing names expect_equal( names(output_17365), NULL, fixed = TRUE) # Testing length expect_equal( length(output_17365), 1L) # Testing sum of element lengths expect_equal( sum(xpectr::element_lengths(output_17365)), 1L) # Testing fn(x = 2, y = 0, z = NULL) # Changed from baseline: z = NULL xpectr::set_test_seed(42) # Testing side effects expect_error( xpectr::strip_msg(fn(x = 2, y = 0, z = NULL)), xpectr::strip("argument is of length zero"), fixed = TRUE) ## Finished testing 'fn' #### ``` ### RStudio Addins Below, we present the set of `RStudio` addins. The intention is for you to set up key commands for the ones you'd like access to. Once you get used to using them, they will speed up your testing process. #### How to set up a key command in RStudio Here's a small guide for setting up key comands in `RStudio`. We use the `Insert Expectations` addin as an example: After installing the package, go to: `Tools >> Addins >> Browse Addins >> Keyboard Shortcuts`. Find `"Insert Expectations"` and press its field under `Shortcut`. Press desired key command, e.g. `Alt+E`. Press `Apply`. Press `Execute`. #### initializeGXSFunctionAddin The `initializeGXSFunctionAddin` initializes the `gxs_function()` call with the argument names and default values of a selected function. We can then add the argument values and additional combinations we wish to test. Note, that we don't need to use the default values as our baseline values. The `Tip` comment tells us to comment out the `gxs_function()` call after running it, instead of removing it. When you change your code, it's often much quicker to regenerate the tests than to update them manually. You can then use a diff tool to check that only the intended changes were made. The `#` in the end helps the code be inserted right after the call to `gxs_function()`. Suggested keycommand: `Alt+F` ```{r eval=FALSE} initializeGXSFunctionAddin("fn") # Inserts the following: # Generate expectations for 'fn' # Tip: comment out the gxs_function() call # so it is easy to regenerate the tests xpectr::set_test_seed(42) xpectr::gxs_function( fn = fn, args_values = list( "x" = list(), "y" = list(), "z" = list(10) ), identation = 2, copy_env = FALSE ) # ``` #### wrapStringAddin The `wrapStringAddin` splits long strings and wraps them with `paste0()`. Suggested keycommand: `Alt+P` ```{r eval=FALSE} wrapStringAddin("This is a fairly long sentence that we would very very much like to make shorter in our test file!") # Inserts the following: paste0("This is a fairly long sentence that we would very very much ", "like to make shorter in our test file!") ``` #### initializeTestthatAddin Suggested keycommand: `Alt+T` ```{r eval=FALSE} initializeTestthatAddin() # Inserts the following: test_that("testing ...()", { xpectr::set_test_seed(42) # ... }) ``` #### assertCollectionAddin Suggested keycommand: `Alt+C` ```{r eval=FALSE} assertCollectionAddin() # Inserts the following: # Check arguments #### assert_collection <- checkmate::makeAssertCollection() # checkmate::assert_ , add = assert_collection) checkmate::reportAssertions(assert_collection) # End of argument checks #### ``` #### dputSelectedAddin Suggested keycommand: `Alt+D` ```{r eval=FALSE} v <- c(1, 2, 3) dputSelectedAddin("v") # "v" is the selected code # Inserts the following: c(1, 2, 3) ``` #### navigateTestFileAddin Suggested keycommand: `Alt+N` A common work process in package development is to run `Ctrl/Cmd+Shift+L`, which runs all `testthat` tests in `/tests/testthat/` in the `Build` pane. When a test fails, a message like the following is printed: `test_x.R:15: failure: x works`. If we then copy the `test_x.R:15:` part to our clipboard and run `navigateTestFileAddin()`, it will open the `test_x.R` file and place the cursor at line `15`. A service like `Travis CI` indicate the failed test with `(@test_x.R#15)`. The addin therefore also works with `test_x.R#15`. If you have additional formats you would like to request, simply open an issue.
/scratch/gouwar.j/cran-all/cranData/xpectr/vignettes/readme.Rmd
### PACKAGE XPLAIN ### ### Author and maintainer: Joachim Zuckarelli ([email protected]) ### Version 0.2.2 ### ### Web tutorial: https://www.zuckarelli.de/xplain/index.html url.isvalid <- function(url){ res <- suppressWarnings(try({ con <- url(url); open.connection(con, open="r",timeout = 3) }, silent = TRUE)[1]) suppressWarnings(try(close.connection(con), silent = TRUE)) if (is.null(res)) { return(TRUE) } else { return(FALSE) } } getXMLFile <- function(xml, fun, package.name, package.calling) { # Internal function that tries to find an xplain XML file. If no xplain XML file is provided or the file provided does not exist # then it runs through # - the path of the package of the function from which xplain() is called to find a file with the name "package_of_the_calling_function.xml", # - the path of the package of the function from which xplain() is called to find a file with the name "package_of_the_explained_function.xml", # - the path of the package of the explained function to find a file with the name "package_of_the_explained_function.xml", # - the current path (working directory) to find a file with the name "package_of_the_explained_function.xml", # - the current path (working directory) to find a file with the name "explained_function.xml". # # Args: # xml: Path to the XML file as given as xml argument to xplain(). # fun: Name of the function that is being explained. # package.name: The name of the package of the explained function. # package.calling: The name of the package of the function from which xplain() is called. # # Returns: The path to the XML file or "" if no XML file was provided and none could be found or "-" if an XML file was provided but # couldn't be found. xml.exists <- FALSE if(file.exists(xml)) xml.exists <- TRUE if(!xml.exists) { if(url.isvalid(xml)) xml.exists <- TRUE } if(xml == "" || xml.exists == FALSE) { if(xml != "" && xml.exists == FALSE) xml <- "-" else xml <- "" if(package.calling != "") { if(file.exists(file.path(utils::installed.packages()[package.calling,"LibPath"],package.calling, paste(package.calling, ".xml", sep="")))) { xml <- file.path(utils::installed.packages()[package.calling,"LibPath"],package.calling, paste(package.calling, ".xml", sep="")) } else { if(file.exists(file.path(utils::installed.packages()[package.calling,"LibPath"],package.calling, paste(package.name, ".xml", sep="")))) { xml <- file.path(utils::installed.packages()[package.calling,"LibPath"],package.calling, paste(package.name, ".xml", sep="")) } } } if(xml == "" || xml == "-") { if(file.exists(file.path(utils::installed.packages()[package.name,"LibPath"],package.name, paste(package.name, ".xml", sep="")))) { xml <- file.path(utils::installed.packages()[package.name,"LibPath"],package.name, paste(package.name, ".xml", sep="")) } else { if(file.exists(file.path(getwd(), paste(package.name, ".xml", sep="")))) { xml <- file.path(getwd(), paste(package.name, ".xml", sep="")) } else { if(file.exists(file.path(getwd(), paste(fun, ".xml", sep="")))) { xml <- file.path(getwd(), paste(fun, ".xml", sep="")) } } } } } return(xml) } getLanguage <- function() { # Internal function that tries to identify the language of the user's work environment by accessing a non-existing object and # analysing the resulting error message. # Returns: Capitalized ISO country code of the language or "EN" as default if no language could be identified. lang <- Sys.getenv("LANGUAGE") if(lang == "") { lang <- "EN" # Access an object that does not exist (hopefully!) and capture the error message res <- tryCatch( { eval(parse(text = "xhajakjkula/1")) }, error = function(err) { return(err) }) # Determine the language based on the error message if(res$message == "Objekt 'xhajakjkula' nicht gefunden") lang <- "DE" if(res$message == "objet 'xhajakjkula' introuvable") lang <- "FR" if(res$message == "oggetto \"xhajakjkula\" non trovato") lang <- "IT" if(res$message == "nie znaleziono obiektu 'xhajakjkula'") lang <- "PL" if(res$message == "objeto 'xhajakjkula' no encontrado") lang <- "ES" if(res$message == "'xhajakjkula' nesnesi bulunamadi") lang <- "TR" } return(toupper(lang)) } getHierarchyLang <- function(h) { # Internal function that returns the current language from the hierarchy of languages produced by language inheritance # from hierarchically higher XML elements. # # Args: # h: Vector with the current hierarchy of languages (ISO codes). # # Returns: Language (ISO code) that is currently at the bottom in the hierarchy of languages, "" if no appicable language can be found. res <- "" for(i in length(h):1) { if(h[i] != "") { res <- h[i] break } } return(res) } getHierarchyLevel <- function(h) { # Internal function that returns the current complexity level from the hierarchy of complexity levels produced by complexity level inheritance # from hierarchically higher XML elements. # # Args: # h: Vector with the current hierarchy of complexity levels. # # Returns: Complexity level that is currently at the bottom in the hierarchy of complexity levels, -1 if no appicable complexity level can be found. res <- -1 for(i in length(h):1) { if(h[i] != 1000) { res <- h[i] break } } return(res) } outputTitle <- function(filename="", text, title.char) { # Internal function that produces the output for a xplain <title>...</title> XML element. # # Args: # filename: Name of the file to print the title to; if no filename is given the output is printed to the screen. # text: Text of the title. # title.char: Character used to underline the title. # # Returns: None. cat(file=filename, "\n", text,"\n", sep="") for(b in 1:nchar(text)) { cat(file=filename, title.char, sep="") } cat(file=filename, "\n") } outputText <- function(filename="", text, res, obj.name="", foreach="", sep="\n", top=FALSE, def=FALSE, def.frame=NULL) { # Internal function that produces the outputs for a xplain <text>...</text> XML element (including executing R code, dissolving placeholders etc.). # # Args: # filename: Name of the file to print the text to; if no filename is given the output is printed to the screen. # text: Text (value of a <text>...</text> XML element) to process. # res: Return object of the explained function. # obj.name: Name of the element of the return object of the explained function that xplain shall run through in foreach mode. # foreach: Value of the attribute "foreach" of the <text>...</text> XML element (optional). Default: "" (no foreach mode). # sep: Separator used for concluding the output (optional). Default: "\n". # top: Indicates if in foreach mode the object to be iterated through is the return object of the explained function itself # (and not the element obj.name of the return object of the explained function). # def: Indicates if the call of outputText() is made to to process a definition (a <define>...</define> XML element) (optional). In this case, no # visual output is produced. Default: FALSE. # def.frame: Dataframe holding the definitions (optional). This dataframe is appended if def=TRUE. # # Returns: The evaluated text. def.text <- "" # Determine the type of 'foreach' mode we're in if(foreach != "") { if(regexpr(".*[Cc][Oo][Ll][Ss].*[Rr][Oo][Ww][Ss].*", foreach) != -1) mode <- 1 else { if(regexpr(".*[Rr][Oo][Ww][Ss].*[Cc][Oo][Ll][Ss].*", foreach) != -1) mode <- 2 else { if(regexpr(".*[Rr][Oo][Ww][Ss].*", foreach) != -1) mode <- 3 else { if(regexpr(".*[Cc][Oo][Ll][Ss].*", foreach) != -1) mode <- 4 else { if(regexpr(".*[Ii][Tt][Ee][Mm][Ss].*", foreach) != -1) mode <- 5 } } } } } else mode <- 0 # Set the dimensions to be run through based on the 'foreach' mode dim1 <- c(1) dim2 <- c(1) if(mode %in% c(2,3,5)) { if(top == FALSE) { dim1 <- c(1:NROW(res[[obj.name]])) dim2 <- c(1:NCOL(res[[obj.name]])) } else { dim1 <- c(1:NROW(res)) dim2 <- c(1:NCOL(res)) } } if(mode %in% c(1,4)) { if(top == FALSE) { dim1 <- c(1:NCOL(res[[obj.name]])) dim2 <- c(1:NROW(res[[obj.name]])) } else { dim1 <- c(1:NCOL(res)) dim2 <- c(1:NROW(res)) } } for(d1 in dim1) { for(d2 in dim2) { # Split text in pieces with and without R code raw <- strsplit(text,"!%|%!")[[1]] for(z in 1:length(raw)) { # Replace placeholders with their definition pat <- "!\\*\\*\\s*([^\\*]+)\\s*\\*\\*!" w <- gregexpr(pat, raw[z]) if(w[[1]][1] != -1) { w1 <- regmatches(raw[z],w) # Eliminate blanks as well as the opening and closing tags (!** and **!) w2 <- gsub("\\s", "", gsub("\\*\\*!", "", gsub("!\\*\\*", "", w1[[1]]))) pat2 <- gsub("\\*\\*", "\\\\*\\\\*",w1[[1]]) for(i in 1:length(w2)) { if(length(def.frame$definition[def.frame$name==w2[i]]) != 0) raw[z] <- gsub(pat2[i], def.frame$definition[def.frame$name==w2[i]], raw[z]) } } # Replace @ and ## placeholders raw[z] <- gsub("@", "res", raw[z]) raw[z] <- gsub("##", paste0("res$",obj.name), raw[z]) raw[z] <- gsub("\\\\n", "\n", raw[z]) if(substr(raw[z], 1, 1)=="%" && substr(raw[z], nchar(raw[z]), nchar(raw[z]))=="%") { # Replace $ placeholders in iterations if(mode == 1) raw[z] <- gsub("\\$([[:blank:]])*]", paste0(d1, "\\]"), gsub("\\[([[:blank:]])*\\$",paste0("\\[", d2), raw[z])) if(mode == 2) raw[z] <- gsub("\\$([[:blank:]])*]", paste0(d2, "\\]"), gsub("\\[([[:blank:]])*\\$",paste0("\\[", d1), raw[z])) if(mode == 3 || mode == 5) raw[z] <- gsub("\\[([[:blank:]])*\\$",paste0("\\[", d1), raw[z]) if(mode == 4) raw[z] <- gsub("\\$([[:blank:]])*\\]",paste0(d1, "\\]"), raw[z]) # Execute expression exeval <- eval(parse(text=substr(raw[z], 2, nchar(raw[z])-1))) if(def == FALSE) cat(exeval, file=filename, sep="", append=TRUE) else def.text <- paste0(def.text, exeval) } else { if(def == FALSE) cat(raw[z], file=filename, sep="", append=TRUE) else def.text <- paste0(def.text, raw[z]) } # if xplain text is regular text (no R-code) } # for each component of the current xplain XML text } # Run through object along dimension 1 if(def == FALSE) cat(sep, file=filename, sep="", append=TRUE) } # Run through object along dimension 2 if(def == TRUE) return(def.text) } getPermutations <- function(s) { # Internal function that gives all permutations of a string in terms of capitalization. # # Args: # s: String to be permutated in terms of capitalization. # # Returns: All permutations of string s in terms of capitalization. vec<-c(tolower(s)) for(pos in 1:nchar(s)) { for(i in 1:length(vec)) { vec[length(vec)+1] <- vec[i] substr(vec[length(vec)],pos,pos) <- substr(toupper(vec[length(vec)]),pos,pos) } } return(vec) } getAttr <- function(node, attr.name, default) { # Internal function that reads an attribute from an XML element. getAttr() is effectively case-insensitive as it # looks for all permutations of the attribute's name in terms of capitalization. # # Args: # node: XML element to read an attribute from. # attr.name: Name of the attribute. # default: Default value returned if attribute attr.name is not found in element node. # # Returns: The value of the attribute. v <- getPermutations(attr.name) for(i in 1:length(v)) { res <- XML::xmlGetAttr(node, v[i], default=default) if(res != default) break } return(res) } cleanText <- function(text) { # Internal function that recodes characters which invalid in XML element texts (>,< and & in R code). # # Args: # text: XML element text that includes R code and potentially invalid characters. # # Returns: The original XML element text with invalid characters recoded to valid HMTL characters. fnd <- c("&", ">", "<") rpl <- c("&amp;", "&gt;", "&lt;") for (i in 1:3) { pat <- paste0("!%%.*", fnd[i], ".*(?!(!%%))%%!") ind <- gregexpr(pat,text, perl=TRUE) if(ind[[1]] != -1) { mat <- regmatches(text, ind) mat2 <- gsub(fnd[i], rpl[i], mat) text <- gsub(mat[[1]], mat2, text, fixed=TRUE) } } return(text) } #' @export xplain.getcall<-function(fun) { # This function can be called from an xplain wrapper function. It returns a string containing the call to the explained function (fun) # with all arguments provided to the wrapper function. With xplain.getcall() it is very easy to write xplain wrapper functions. # # Args: # fun: Name of the function # # Returns: String representing the call of the wrapped function, i.e. the explained function, with all arguments provided to the wrapper function. # This string can then be used as the call argument for xplain(). # Get arguments of calling function li <- as.list(sys.call(-1)) cl <- paste0(fun, "(", collapse = "") # Build argument list for explained function for(i in 2:length(li)) { if(names(li)[i] != "") { if(i != 2) cl <- paste0(cl, ", ", names(li)[i], "=", li[i]) else cl <- paste0(cl, names(li)[i], "=", li[i]) } else { if(i != 2) cl <- paste0(cl, ", ", li[i]) else cl <- paste0(cl, li[i]) } } cl<-paste0(cl, ")") return(cl) } #' @export xplain.overview <- function(xml, show.text=FALSE, preserve.seq=FALSE) { # Provides an overview of the content of a xplain XML file. # # Args: # xml: Path to the xplain XML file to be analyzed. Can be either a local path or an URL. # show.text: Indicates if the full interpretation/explanation texts shall be included in the result (optional). Default: FALSE. # preserve.seq: Indicates if the overview results for the interpretation/explanation texts shall be shown in the same sequence as they appear in the XML file (optional). # If FALSE, the results are sorted, e.g. by package, function, language and complexity level. Default: FALSE. # # Returns: Dataframe with summary information on the xplain XML file. df <- data.frame() obj.name <- "" # Get path to XML file if(xml == "") { stop(paste0("\nNo xplain XML file provided.\n")) } else { # Read XML file xml.exists <- FALSE if(file.exists(xml)) xml.exists <- TRUE if(!xml.exists) { if(url.isvalid(xml)) xml.exists <- TRUE } if(!xml.exists) stop(paste0("xplain XML file '", basename(xml),"' does not exist.")) if(file.exists(xml)) { text <- readr::read_file(xml) } else { text <- httr::content(httr::GET(xml), as = "text") } text <- cleanText(text) doc <- XML::xmlInternalTreeParse(text, asText=TRUE) # Check if XML file is a valid xplain file if(length(XML::getNodeSet(doc, "//xplain"))==0 && length(XML::getNodeSet(doc, "//XPLAIN"))==0) { stop(paste0("The file '", basename(xml), "' is not a valid xplain XML file (does not contain the <xplain> tag).")) } else { query <- paste0("//xplain/package") p <- XML::getNodeSet(doc, query) if(length(p)>0) { def.lang <-c() def.level <- c() for(i in 1:length(p)) { pack <- getAttr(p[[i]], "name", default="") def.lang[1] <- getAttr(p[[i]], "lang", default="default") def.level[1] <- as.integer(getAttr(p[[i]], "level", default=1000)) lang <- tolower(def.lang[1]) if(def.level[1] == 1000) level <- "all" else level <- paste0("<=", as.character(def.level[1])) f <- XML::xmlChildren(p[[i]]) for(n in 1:length(f)) { if(tolower(XML::xmlName(f[[n]])) == "function") { fun <- getAttr(f[[n]], "name", "") def.lang[2] <- getAttr(f[[i]], "lang", default="default") def.level[2] <- as.integer(getAttr(f[[i]], "level", default=1000)) lang <- tolower(def.lang[2]) if(def.level[2] == 1000) level <- "all" else level <- paste0("<=", as.character(def.level[2])) r <- XML::xmlChildren(f[[n]]) for(k in 1:length(r)) { if(tolower(XML::xmlName(r[[k]])) == "title" || tolower(XML::xmlName(r[[k]])) == "result" || tolower(XML::xmlName(r[[k]])) == "text") { def.lang[3] <- getAttr(r[[k]], "lang", default="default") def.level[3] <- as.integer(getAttr(r[[k]], "level", default=1000)) lang <- tolower(def.lang[3]) if(def.level[3] == 1000) level <- "all" else level <- paste0("<=", as.character(def.level[3])) } if(tolower(XML::xmlName(r[[k]])) == "title" || tolower(XML::xmlName(r[[k]])) == "text") { foreach <- getAttr(r[[k]], "foreach", default="") type <- tolower(XML::xmlName(r[[k]])) text <- XML::xmlValue(r[[k]], ignoreComments=TRUE) if(regexpr("!%%", text) != -1) contains.r <- TRUE else contains.r <- FALSE if(regexpr("@", text) != -1 || regexpr("##", text) != -1) uses.retobj <- TRUE else uses.retobj <- FALSE if(show.text == TRUE) df.add <- data.frame(pack, fun, type, lang, level, obj.name, foreach, contains.r, uses.retobj, text) else df.add <- data.frame(pack, fun, type, lang, level, obj.name, foreach, contains.r, uses.retobj) df <- rbind(df,df.add) } if(tolower(XML::xmlName(r[[k]])) == "result") { obj.name <- getAttr(r[[k]], "name", default="") if(obj.name != "") { t <- XML::xmlChildren(r[[k]]) for(z in 1:length(t)) { if(tolower(XML::xmlName(t[[z]])) == "title" || tolower(XML::xmlName(t[[z]])) == "text") { def.lang[4] <- getAttr(t[[z]], "lang", default="default") def.level[4] <- as.integer(getAttr(t[[z]], "level", default=1000)) lang <- tolower(def.lang[4]) if(def.level[4] == 1000) level <- "all" else level <- paste0("<=", as.character(def.level[4])) if(tolower(XML::xmlName(t[[z]])) == "title") type <- "title" else { if(tolower(XML::xmlName(t[[z]])) == "text") { type <- "text" foreach <- getAttr(t[[z]], "foreach", default="") } # current tag is a text tag } } # tag is 'title' or 'text' tag text <- XML::xmlValue(t[[z]], ignoreComments=TRUE) if(regexpr("!%%", text) != -1) contains.r <- TRUE else contains.r <- FALSE if(regexpr("@", text) != -1 || regexpr("##", text) != -1) uses.retobj <- TRUE else uses.retobj <- FALSE if(show.text == TRUE) df.add <- data.frame(pack, fun, type, lang, level, obj.name, foreach, contains.r, uses.retobj, text) else df.add <- data.frame(pack, fun, type, lang, level, obj.name, foreach, contains.r, uses.retobj) df <- rbind(df,df.add) length(def.lang) <- 3 length(def.level) <- 3 } # for all tags below the current 'result' tag } # object referenced by the 'result' tag does indeed exist } # tag 'results' length(def.lang) <- 2 length(def.level) <- 2 } # for all tags below the the function tag of the relevant function } # current tag is a function tag for the relevant function length(def.lang) <- 1 length(def.level) <- 1 } # for all function blocks below the relevant package } # for all blocks in XML related to the relevant package } # XML contains data for relevant package else { stop(paste0("\nNo xplain information found for any package.\n")) } } # XML file found } names(df) <- c("Package", "Function", "Type", "Language", "Level", "Result object", "Iteration", "Has R code", "Uses return obj.") if(show.text == TRUE) names(df)[length(names(df))] <- "Text" if(preserve.seq == FALSE) return(df[order(df[,1], df[,2], df[,3], df[,3], df[,5], df[,6], df[,7]),]) else return(df) } #' @export xplain <- function(call, xml="", lang = "", level = -1, filename="", sep="\n", title.char="-", before=TRUE, addfun="", addfun.args="", addfun.title="") { # Main function of the xplain package. Interprets/explains the results of a function call based on the interpretation/explanation # information given in a xplain XML file. # # Args: # call: Function call to be explained/interpreted. # xml: Path to the xplain XML file containing the interpretation/explanation information (optional). Can be either a local path or an URL. # If no path is provided or the provided file does not exist then xplain() searches for a suitable XML file in various locations: # (1) in the path of the package containing the function from which xplain() was called for a file of the name "package_of_the_calling_function.xml"; # (2) in the same path for a file with the name "package_of_the_explained_function.xml" (the function given in the "call" argument); # (3) in the path of the package containing the explained function for a file with the name "package_of_the_explained_function.xml"; # (4) in the current working directory for a file with the name "package_of_the_explained_function.xml"; and # (5) in the current working directory for a file with the name "explained_function.xml". # lang: ISO country code of the language of the interpretations/explanations that shall be shown (optional). Default: English (EN). # level: Integer number indicating the complexity level of the interpretations/explanations that shall be shown (optional). level is cumulative: # All interpretations/explanations with a level number up to the number provided are shown. Default: -1, i.e. all interpretations/explanations # are shown. # filename: File to write the xplain() output to (optional). If no filename is provided the xplain() output is shown in the console. # sep: Separator used to separate the outputs from consecutive XML text elements (<text>...</text>) (optional). Default: "\n". # title.char: Character used for underlining titles (optional). Default: "-". # before: Indicates if the results of the call of the explained function shall be shown before the interpretations/explanations (optional). Default: TRUE, # i.e. function output is shown before the interpretations/explanations. # addfun: Names of additional functions that shall be called (e.g. summary()), without brackets (optional). It is assumed that these functions take the return # object of the explained function as their first argument. Further arguments can be specified with addfun.args. Results of additional functions are # shown right after the output of the explained function. # addfun.args: Vector of arguments (beyond the return object of the explained function) for the additional functions (optional). # Example: addfun.args = "trim = 0, na.rm = FALSE". Argument must be of the same length as addfun; so addfun.args must be "" if the respective # additional function does not take any additional arguments. # addfun.title: Vector of titles that will be shown as headers to the outputs of the addional functions (optional).Argument must be of the same length as addfun; # so addfun.args must be "" if the respective the output of the additional function shall have no title. tag.open <- "!%%" tag.close <- "%%!" # Identify function and package name of the function to be explained fun <- substr(call, 1, regexpr("\\(", call)-1) package.name <- utils::packageName(environment(get(fun))) # Identify function and package name of the function calling xplain if(sys.nframe()!=1) { calling.fun <- deparse(sys.calls()[[sys.nframe()-1]]) if(regexpr(".*\\(", calling.fun)[[1]] != -1) { calling.fun <- regmatches(calling.fun, regexpr(".*\\(", calling.fun))[[1]] calling.fun <- strtrim(calling.fun, nchar(calling.fun) - 1) } package.calling <- utils::packageName(environment(get(calling.fun))) if(is.null(package.calling)) package.calling <- "" } else { calling.fun <- "" package.calling <- "" } # Get path to XML file xml <- getXMLFile(xml, fun, package.name, package.calling) if(xml == "" || xml == "-") { if(xml == "") stop(paste0("\nNo xplain XML file for function '", fun, "' found.\n")) if(xml == "-") stop(paste0("xplain XML file '", basename(xml),"' does not exist.")) } else { # Identify language of user's work environment if(lang == "") { lang <- getLanguage() } # Read XML file if(file.exists(xml)) { text <- readr::read_file(xml) } else { text <- httr::content(httr::GET(xml), as = "text") } text <- cleanText(text) doc <- XML::xmlInternalTreeParse(text, asText=TRUE) # Process call of function to be explained res <- eval(parse(text=call)) if(before == TRUE) { methods::show(res) for(i in 1:length(addfun)) { if(addfun[1] != "") { if(length(addfun.title) == length(addfun)) { if(addfun.title[i] != "") outputTitle(text=addfun.title[i], title.char = title.char) } if(length(addfun.args) == length(addfun)) { if(addfun.args[i] != "") methods::show(eval(parse(text=paste0(addfun[i],"(res, ", addfun.args[i],")")))) else methods::show(eval(parse(text=paste0(addfun[i],"(res)")))) } else methods::show(eval(parse(text=paste0(addfun[i],"(res)")))) } } } # Check if XML file is a valid xplain file if(length(XML::getNodeSet(doc, "//xplain"))==0 && length(XML::getNodeSet(doc, "//XPLAIN"))==0) { stop(paste0("The file '", basename(xml), "' is not a valid xplain XML file (does not contain the <xplain> tag).")) invisible(res) } else { query <- paste0("//xplain/package[@name='", package.name, "']") p <- XML::getNodeSet(doc, query) if(length(p)>0) { def.lang <-c() def.level <- c() def.frame <- data.frame(matrix(ncol = 2, nrow = 0)) colnames(def.frame) <- c("name", "definition") for(i in 1:length(p)) { def.lang[1] <- getAttr(p[[i]], "lang", default="") def.level[1] <- as.integer(getAttr(p[[i]], "level", default=1000)) f <- XML::xmlChildren(p[[i]]) for(n in 1:length(f)) { if(tolower(XML::xmlName(f[[n]])) == "define") { if(nrow(def.frame[def.frame$name == getAttr(f[[n]], "name", ""),]) == 0) { df <- data.frame(getAttr(f[[n]], "name", ""), outputText(text=XML::xmlValue(f[[n]], ignoreComments=TRUE), res=res, def=TRUE, def.frame=def.frame)) colnames(df) <- c("name", "definition") def.frame <- rbind(def.frame, df) } } if(tolower(XML::xmlName(f[[n]])) == "function" && getAttr(f[[n]], "name", "") == fun) { def.lang[2] <- getAttr(f[[i]], "lang", default="") def.level[2] <- as.integer(getAttr(f[[i]], "level", default=1000)) r <- XML::xmlChildren(f[[n]]) for(k in 1:length(r)) { if(tolower(XML::xmlName(r[[k]])) == "define") { if(nrow(def.frame[def.frame$name == getAttr(r[[k]], "name", ""),]) == 0) { df <- data.frame(getAttr(r[[k]], "name", ""), outputText(text=XML::xmlValue(r[[k]], ignoreComments=TRUE), res=res, def=TRUE, def.frame=def.frame)) colnames(df) <- c("name", "definition") def.frame <- rbind(def.frame, df) } } if(tolower(XML::xmlName(r[[k]])) == "title" || tolower(XML::xmlName(r[[k]])) == "result" || tolower(XML::xmlName(r[[k]])) == "text") { def.lang[3] <- getAttr(r[[k]], "lang", default="") def.level[3] <- as.integer(getAttr(r[[k]], "level", default=1000)) } if(tolower(XML::xmlName(r[[k]])) == "title") { if(tolower(getHierarchyLang(def.lang)) == tolower(lang) && (getHierarchyLevel(def.level) <= level || level==-1)) { text <- XML::xmlValue(r[[k]], ignoreComments=TRUE) outputTitle(filename, text, title.char) } } if(tolower(XML::xmlName(r[[k]])) == "text") { if(tolower(getHierarchyLang(def.lang)) == tolower(lang) && (getHierarchyLevel(def.level) <= level || level==-1)) { text <- XML::xmlValue(r[[k]], ignoreComments=TRUE) foreach <- getAttr(r[[k]], "foreach", default="") outputText(filename, text, res, foreach=foreach, sep=sep, top=TRUE, def.frame=def.frame) } } if(tolower(XML::xmlName(r[[k]])) == "result") { obj.name <- getAttr(r[[k]], "name", default="") if(obj.name != "" && obj.name %in% names(res)) { t <- XML::xmlChildren(r[[k]]) for(z in 1:length(t)) { if(tolower(XML::xmlName(t[[z]])) == "define") { if(nrow(def.frame[def.frame$name == getAttr(z[[z]], "name", ""),]) == 0) { df <- data.frame(getAttr(t[[z]], "name", ""), outputText(text=XML::xmlValue(t[[z]], ignoreComments=TRUE), res=res, def=TRUE, def.frame=def.frame)) colnames(df) <- c("name", "definition") def.frame <- rbind(def.frame, df) } } if(tolower(XML::xmlName(t[[z]])) == "title" || tolower(XML::xmlName(t[[z]])) == "text") { def.lang[4] <- getAttr(t[[z]], "lang", default="") def.level[4] <- as.integer(getAttr(t[[z]], "level", default=1000)) if(tolower(getHierarchyLang(def.lang)) == tolower(lang) && (getHierarchyLevel(def.level) <= level || level==-1)) { if(tolower(XML::xmlName(t[[z]])) == "title") { text <- XML::xmlValue(t[[z]], ignoreComments=TRUE) outputTitle(filename, text, title.char) } else { if(tolower(XML::xmlName(t[[z]])) == "text") { text <- XML::xmlValue(t[[z]], ignoreComments=TRUE) # Text validity check if(length(regmatches(text, gregexpr(tag.open, text))[[1]]) > length(regmatches(text, gregexpr(tag.close, text))[[1]])) { invisible(res) stop(paste0("XML syntax error: You have more opening R code tags (", tag.open, ") than closing tags (", tag.close,").")) } else { if(length(regmatches(text, gregexpr(tag.open, text))[[1]]) < length(regmatches(text, gregexpr(tag.close, text))[[1]])) { invisible(res) stop(paste0("XML syntax error: You have more closing R code tags (", tag.close, ") than opening tags (", tag.open,").")) } else { foreach <- getAttr(t[[z]], "foreach", default="") outputText(filename, text, res, obj.name, foreach, sep, def.frame=def.frame) } # if R-code tags are syntactically correct } # if R-code tags are syntactically correct } # current tag is a text tag } # current tag is no title tag } # tag is 'title' or 'text' tag length(def.lang) <- 3 length(def.level) <- 3 } } # for all tags below the current 'result' tag } # object referenced by the 'result' tag does indeed exist } # tag 'results' length(def.lang) <- 2 length(def.level) <- 2 } # for all tags below the the function tag of the relevant function } # current tag is a function tag for the relevant function length(def.lang) <- 1 length(def.level) <- 1 } # for all function blocks below the relevant package } # for all blocks in XML related to the relevant package } # XML contains data for relevant package else { stop(paste0("\nNo xplain information found for package '", package.name, "' in file '", xml, "'.\n")) invisible(res) } if(before == FALSE) { methods::show(res) for(i in 1:length(addfun)) { if(addfun[1] != "") { if(length(addfun.title) == length(addfun)) { if(addfun.title[i] != "") outputTitle(text=addfun.title[i], title.char = title.char) } if(length(addfun.args) == length(addfun)) { if(addfun.args[i] != "") methods::show(eval(parse(text=paste0(addfun[i],"(res, ", addfun.args[i],")")))) else methods::show(eval(parse(text=paste0(addfun[i],"(res)")))) } else methods::show(eval(parse(text=paste0(addfun[i],"(res)")))) } } } invisible(res) } # XML file found } }
/scratch/gouwar.j/cran-all/cranData/xplain/R/xplain.r
# Generated by using Rcpp::compileAttributes() -> do not edit by hand # Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393 #' Return sign #' #' @param x A numeric vector #' @export xpl_nsignC <- function(x) { .Call('_xplorerr_xpl_nsignC', PACKAGE = 'xplorerr', x) } #' Repeat data #' #' @param ln A list #' @param ly A list #' @export xpl_gvar <- function(ln, ly) { .Call('_xplorerr_xpl_gvar', PACKAGE = 'xplorerr', ln, ly) }
/scratch/gouwar.j/cran-all/cranData/xplorerr/R/RcppExports.R
#' @title Visualization #' @description Launches the visualizer app. #' @examples #' \dontrun{ #' app_visualizer() #' } #' @export #' app_visualizer <- function() { check_suggests('shiny') check_suggests('shinyBS') check_suggests('shinythemes') check_suggests('descriptr') check_suggests('dplyr') check_suggests('ggplot2') check_suggests('plotly') check_suggests('rbokeh') check_suggests('highcharter') check_suggests('purrr') check_suggests('tidyr') check_suggests('tibble') check_suggests('readxl') check_suggests('readr') check_suggests('jsonlite') check_suggests('magrittr') check_suggests('tools') check_suggests('lubridate') check_suggests('scales') check_suggests('stringr') message('Highcharts (www.highcharts.com) is a Highsoft software product which is not free for commercial and Governmental use') shiny::runApp(appDir = system.file("app-visualize", package = "xplorerr")) } #' @title Descriptive Statistics #' @description Launches the descriptive statistics app. #' @examples #' \dontrun{ #' app_descriptive() #' } #' @export #' app_descriptive <- function() { check_suggests('descriptr') check_suggests('haven') check_suggests('jsonlite') check_suggests('readr') check_suggests('readxl') check_suggests('shinyBS') check_suggests('shinycssloaders') check_suggests('shinythemes') check_suggests('stringr') check_suggests('lubridate') shiny::runApp(appDir = system.file("app-descriptr", package = "xplorerr")) } #' @title Visualize distributions #' @description Launches app for visualizing probability distributions. #' @examples #' \dontrun{ #' app_descriptive() #' } #' @export #' app_vistributions <- function() { check_suggests('vistributions') check_suggests('shinyBS') check_suggests('shinycssloaders') check_suggests('shinythemes') shiny::runApp(appDir = system.file("app-vistributions", package = "xplorerr")) } #' @title Inferential Statistics #' @description Launches the inferential statistics app. #' @examples #' \dontrun{ #' app_inference() #' } #' @export #' app_inference <- function() { check_suggests('data.table') check_suggests('magrittr') check_suggests('descriptr') check_suggests('jsonlite') check_suggests('haven') check_suggests('lubridate') check_suggests('readr') check_suggests('readxl') check_suggests('shinyBS') check_suggests('shinycssloaders') check_suggests('shinythemes') check_suggests('stringr') shiny::runApp(appDir = system.file("app-inferr", package = "xplorerr")) } #' @title Linear Regression #' @description Launches the linear regression app. #' @examples #' \dontrun{ #' app_linear_regression() #' } #' @export #' app_linear_regression <- function() { check_suggests('olsrr') check_suggests('caret') check_suggests('descriptr') check_suggests('jsonlite') check_suggests('haven') check_suggests('lubridate') check_suggests('readr') check_suggests('readxl') check_suggests('scales') check_suggests('shinyBS') check_suggests('shinycssloaders') check_suggests('shinythemes') shiny::runApp(appDir = system.file("app-olsrr", package = "xplorerr")) } #' @title Logistic Regression #' @description Launches the logistic regression app. #' @examples #' \dontrun{ #' app_logistic_regression() #' } #' @export #' app_logistic_regression <- function() { check_suggests('blorr') check_suggests('descriptr') check_suggests('jsonlite') check_suggests('haven') check_suggests('lubridate') check_suggests('readr') check_suggests('readxl') check_suggests('shinyBS') check_suggests('shinycssloaders') check_suggests('shinythemes') check_suggests('stringr') check_suggests('tidyr') shiny::runApp(appDir = system.file("app-blorr", package = "xplorerr")) } #' @title RFM Analysis #' @description Launches the RFM analyssi app. #' @examples #' \dontrun{ #' app_rfm_analysis() #' } #' @export #' app_rfm_analysis <- function() { check_suggests('rfm') check_suggests('haven') check_suggests('jsonlite') check_suggests('readr') check_suggests('readxl') check_suggests('shinyBS') check_suggests('shinycssloaders') check_suggests('shinythemes') check_suggests('stringr') check_suggests('DT') shiny::runApp(appDir = system.file("app-rfm", package = "xplorerr")) }
/scratch/gouwar.j/cran-all/cranData/xplorerr/R/launch.R
#' @importFrom utils packageVersion menu install.packages check_suggests <- function(pkg) { pkg_flag <- tryCatch(utils::packageVersion(pkg), error = function(e) NA) if (is.na(pkg_flag)) { msg <- message(paste0(pkg, ' must be installed for this functionality.')) if (interactive()) { message(msg, "\nWould you like to install it?") if (utils::menu(c("Yes", "No")) == 1) { utils::install.packages(pkg) } else { stop(paste0(pkg, ' must be installed for this functionality.'), call. = FALSE) } } else { stop(paste0(pkg, ' must be installed for this functionality.'), call. = FALSE) } } }
/scratch/gouwar.j/cran-all/cranData/xplorerr/R/utils.R
#' Dummy data set for Cochran's Q test #' #' A dataset containing information about results of three exams. #' #' @format A data frame with 15 rows and 3 variables: #' \describe{ #' \item{exam1}{result of exam1} #' \item{exam2}{result of exam2} #' \item{exam3}{result of exam3} #' } #' #' @usage data(exam) #' #' @source \url{https://www.spss-tutorials.com/spss-cochran-q-test/} "exam"
/scratch/gouwar.j/cran-all/cranData/xplorerr/R/xpl-data-exam.R
#' High School and Beyond Data Set #' #' A dataset containing demographic information and standardized test #' scores of high school students. #' #' @format A data frame with 200 rows and 10 variables: #' \describe{ #' \item{id}{id of the student} #' \item{female}{gender of the student} #' \item{race}{ethnic background of the student} #' \item{ses}{socio-economic status of the student} #' \item{schtyp}{school type} #' \item{prog}{program type} #' \item{read}{scores from test of reading} #' \item{write}{scores from test of writing} #' \item{math}{scores from test of math} #' \item{science}{scores from test of science} #' \item{socst}{scores from test of social studies} #' } #' #' @usage data(hsb) #' #' @source \url{https://nces.ed.gov/surveys/hsb/} "hsb"
/scratch/gouwar.j/cran-all/cranData/xplorerr/R/xpl-data-hsb.R
#' Dummy data set for 2 Sample Proportion test #' #' A dataset containing information about two treatments #' #' @format A data frame with 50 rows and 2 variables: #' \describe{ #' \item{treatment1}{result of treatment type 1} #' \item{treatment2}{result of treatment type 2} #' } #' #' @usage data(treatment) #' "treatment"
/scratch/gouwar.j/cran-all/cranData/xplorerr/R/xpl-data-treatment.R
#' \code{xplorerr} package #' #' R Shiny app for interactive statistical analysis #' #' See the README on #' \href{https://github.com/rsquaredacademy/xplorerr}{GitHub} #' #' @docType package #' @importFrom Rcpp sourceCpp #' @useDynLib xplorerr #' @name xplorerr NULL ## quiets concerns of R CMD check re: the .'s that appear in pipelines if(getRversion() >= "2.15.1") utils::globalVariables(c(".", "descriptr", "dplyr", "ggplot2", "highcharter", "jsonlite", "lubridate", "magrittr", "plotly", "purrr", "rbokeh", "readr", "readxl", "scales", "shiny", "shinyBS", "shinythemes", "stringr", "tibble", "tidyr", "tools"))
/scratch/gouwar.j/cran-all/cranData/xplorerr/R/xplorerr.R
.onAttach <- function(...) { if (!interactive() || stats::runif(1) > 0.1) return() pkgs <- utils::available.packages() cran_version <- package_version(pkgs["olsrr", "Version"]) local_version <- utils::packageVersion("xplorerr") behind_cran <- cran_version > local_version tips <- c( "Learn more about xplorerr at https://github.com/rsquaredacademy/xplorerr/.", "Use suppressPackageStartupMessages() to eliminate package startup messages.", "Need help getting started with regression models? Visit: https://www.rsquaredacademy.com", "Check out our interactive app for quick data exploration. Visit: https://apps.rsquaredacademy.com/." ) tip <- sample(tips, 1) if (interactive()) { if (behind_cran) { msg <- c("A new version of xplorerr is available with bug fixes and new features.") packageStartupMessage(msg, "\nWould you like to install it?") if (utils::menu(c("Yes", "No")) == 1) { utils::update.packages("xplorerr") } } else { packageStartupMessage(paste(strwrap(tip), collapse = "\n")) } } }
/scratch/gouwar.j/cran-all/cranData/xplorerr/R/zzz.R
observe({ updateSelectInput(session, inputId = "resp_bivar", choices = names(final_split$train)) updateSelectInput(session, inputId = "var_bivar", choices = names(final_split$train)) updateSelectInput(session, inputId = "resp_woe", choices = names(final_split$train)) updateSelectInput(session, inputId = "var_woe", choices = names(final_split$train)) updateSelectInput(session, inputId = "resp_woe2", choices = names(final_split$train)) updateSelectInput(session, inputId = "var_woe2", choices = names(final_split$train)) updateSelectInput(session, inputId = "resp_segdist", choices = names(final_split$train)) updateSelectInput(session, inputId = "var_segdist", choices = names(final_split$train)) updateSelectInput(session, inputId = "resp_2wayseg", choices = names(final_split$train)) updateSelectInput(session, inputId = "var1_2wayseg", choices = names(final_split$train)) updateSelectInput(session, inputId = "var2_2wayseg", choices = names(final_split$train)) }) bivar <- eventReactive(input$submit_bivar, { blorr::blr_bivariate_analysis(data = final_split$train, response = input$resp_bivar, input$var_bivar) }) woe_iv <- eventReactive(input$submit_woe, { blorr::blr_woe_iv(data = final_split$train, predictor = input$var_woe, response = input$resp_woe) }) woe_iv_2 <- eventReactive(input$submit_woe2, { blorr::blr_woe_iv_stats(data = final_split$train, response = input$resp_woe2, input$var_woe2) }) seg_dist <- eventReactive(input$submit_segdist, { blorr::blr_segment_dist(data = final_split$train, response = !! sym(as.character(input$resp_segdist)), predictor = !! sym(as.character(input$var_segdist))) }) twowayseg <- eventReactive(input$submit_2wayseg, { blorr::blr_segment_twoway(data = final_split$train, response = input$resp_2wayseg, variable_1 = input$var1_2wayseg, variable_2 = input$var2_2wayseg) }) output$bivar_out <- renderPrint({ bivar() }) output$woe_out <- renderPrint({ woe_iv() }) output$woe2_out <- renderPrint({ woe_iv_2() }) output$segdist_out <- renderPrint({ seg_dist() }) output$segdist_plot <- renderPlot({ plot(seg_dist()) }) output$twowayseg_out <- renderPrint({ twowayseg() })
/scratch/gouwar.j/cran-all/cranData/xplorerr/inst/app-blorr/logic/logic_bivar.R
observeEvent(input$sample_data_yes, { updateNavbarPage(session, 'mainpage', selected = 'tab_upload') updateNavlistPanel(session, 'navlist_up', 'tab_use_sample') }) file_upload_options <- eventReactive(input$upload_files_yes, { fluidRow( column(3, align = 'center', actionButton( inputId = 'upload_csv_file', label = 'CSV', width = '120px' ) ), column(3, align = 'center', actionButton( inputId = 'upload_xls_file', label = 'XLS', width = '120px' ) ), column(3, align = 'center', actionButton( inputId = 'upload_xlsx_file', label = 'XLSX', width = '120px' ) ), column(3, align = 'center', actionButton( inputId = 'upload_json_file', label = 'JSON', width = '120px' ) ), column(12, br()), column(3, align = 'center', actionButton( inputId = 'upload_stata_file', label = 'STATA', width = '120px' ) ), column(3, align = 'center', actionButton( inputId = 'upload_spss_file', label = 'SPSS', width = '120px' ) ), column(3, align = 'center', actionButton( inputId = 'upload_sas_file', label = 'SAS', width = '120px' ) ), column(3, align = 'center', actionButton( inputId = 'upload_rds_file', label = 'RDS', width = '120px' ) ) ) }) output$upload_file_links <- renderUI({ file_upload_options() }) observeEvent(input$upload_csv_file, { updateNavbarPage(session, 'mainpage', selected = 'tab_upload') updateNavlistPanel(session, 'navlist_up', 'tab_uploadfile') updateTabsetPanel(session, 'tab_uploadfile', selected = 'tab_upload_csv') }) observeEvent(input$upload_xls_file, { updateNavbarPage(session, 'mainpage', selected = 'tab_upload') updateNavlistPanel(session, 'navlist_up', 'tab_uploadfile') updateTabsetPanel(session, 'tabset_upload', selected = 'tab_upload_excel') }) observeEvent(input$upload_xlsx_file, { updateNavbarPage(session, 'mainpage', selected = 'tab_upload') updateNavlistPanel(session, 'navlist_up', 'tab_uploadfile') updateTabsetPanel(session, 'tabset_upload', selected = 'tab_upload_excel') }) observeEvent(input$upload_json_file, { updateNavbarPage(session, 'mainpage', selected = 'tab_upload') updateNavlistPanel(session, 'navlist_up', 'tab_uploadfile') updateTabsetPanel(session, 'tabset_upload', selected = 'tab_upload_json') }) observeEvent(input$upload_stata_file, { updateNavbarPage(session, 'mainpage', selected = 'tab_upload') updateNavlistPanel(session, 'navlist_up', 'tab_uploadfile') updateTabsetPanel(session, 'tabset_upload', selected = 'tab_upload_stata') }) observeEvent(input$upload_spss_file, { updateNavbarPage(session, 'mainpage', selected = 'tab_upload') updateNavlistPanel(session, 'navlist_up', 'tab_uploadfile') updateTabsetPanel(session, 'tabset_upload', selected = 'tab_upload_spss') }) observeEvent(input$upload_sas_file, { updateNavbarPage(session, 'mainpage', selected = 'tab_upload') updateNavlistPanel(session, 'navlist_up', 'tab_uploadfile') updateTabsetPanel(session, 'tabset_upload', selected = 'tab_upload_sas') }) observeEvent(input$upload_rds_file, { updateNavbarPage(session, 'mainpage', selected = 'tab_upload') updateNavlistPanel(session, 'navlist_up', 'tab_uploadfile') updateTabsetPanel(session, 'tabset_upload', selected = 'tab_upload_rds') })
/scratch/gouwar.j/cran-all/cranData/xplorerr/inst/app-blorr/logic/logic_dataoptions.R
# Exit --------------------------------------------------------------- observe({ if (isTRUE(input$mainpage == "exit")) { stopApp() } })
/scratch/gouwar.j/cran-all/cranData/xplorerr/inst/app-blorr/logic/logic_exit_button.R
filt_ui <- eventReactive(input$button_filt_yes, { fluidRow( column(12, align = 'center', selectInput( inputId = 'dplyr_filter', label = 'Filter:', choices = '', selected = '', width = '120px' ) ), column(12, align = 'center', selectInput( inputId = 'dplyr_filt_op', label = 'Select Operator', choices = c('<', '>', '<=', '>=', '=='), selected = '', width = '120px' ) ), column(12, align = 'center', textInput( inputId = 'dplyr_filt_val', label = 'Value', value = '20', width = '120px' ) ), column(12, align = 'center', br(), br(), actionButton(inputId = 'submit_dply_filt', label = 'Filter', width = '120px', icon = icon('check')), bsTooltip("submit_dply_filt", "Click here to filter data.", "bottom", options = list(container = "body")) ) ) }) output$filt_render <- renderUI( filt_ui() ) observeEvent(input$button_filt_yes, { updateSelectInput( session, inputId = "dplyr_filter", choices = names(final_sel$a), selected = names(final_sel$a) ) }) observeEvent(input$submit_dply_selvar, { updateSelectInput( session, inputId = "dplyr_filter", choices = names(finalsel()), selected = names(finalsel()) ) }) filt_data <- reactiveValues(p = NULL) observeEvent(input$submit_dply_selvar, { filt_data$p <- final_sel$a }) observeEvent(input$button_filt_yes, { filt_data$p <- final_sel$a }) observeEvent(input$submit_dply_filt, { filt_data$p <- filt_data$p %>% filter_(paste(input$dplyr_filter, input$dplyr_filt_op, input$dplyr_filt_val)) }) observeEvent(input$button_filt_no, { filt_data$p <- final_sel$a }) observeEvent(input$button_filt_no, { updateNavbarPage(session, 'mainpage', selected = 'tab_scr') updateNavlistPanel(session, 'navlist_trans', 'tab_screen') }) filttrans <- eventReactive(input$button_filt_yes, { fluidRow( column(6, align = 'left', actionButton(inputId='filt2dvarsel', label="Select Variables", icon = icon("long-arrow-left")) ), column(6, align = 'right', actionButton(inputId='filt2screen', label="Screen Data", icon = icon("long-arrow-right")) ) ) }) output$filt_trans <- renderUI({ filttrans() }) observeEvent(input$filt2dvarsel, { updateNavbarPage(session, 'mainpage', selected = 'tab_trans') updateNavlistPanel(session, 'navlist_trans', 'tab_selvar') }) observeEvent(input$filt2screen, { updateNavbarPage(session, 'mainpage', selected = 'tab_scr') updateNavlistPanel(session, 'navlist_trans', 'tab_screen') }) # filtered <- eventReactive(input$submit_dply_filt, { # k <- final_sel() %>% # filter_(paste(input$dplyr_filter, input$dplyr_filt_op, input$dplyr_filt_val)) # k # # k <- filter_(final_sel(), paste(input$dplyr_filter, input$dplyr_filt_op, input$dplyr_filt_val)) # # k # })
/scratch/gouwar.j/cran-all/cranData/xplorerr/inst/app-blorr/logic/logic_filter.R
observeEvent(input$model_bivar_click, { updateNavbarPage(session, 'mainpage', selected = 'tab_bivar') updateNavlistPanel(session, 'navlist_bivar', 'tab_bivar_analysis') }) observeEvent(input$model_regress_click, { updateNavbarPage(session, 'mainpage', selected = 'tab_reg') updateNavlistPanel(session, 'navlist_reg', 'tab_regress') }) observeEvent(input$model_fitstat_click, { updateNavbarPage(session, 'mainpage', selected = 'tab_reg') updateNavlistPanel(session, 'navlist_reg', 'tab_model_fit_stats') }) observeEvent(input$model_varsel_click, { updateNavbarPage(session, 'mainpage', selected = 'tab_varsel') updateNavlistPanel(session, 'navlist_varsel', 'tab_varsel_forward') }) observeEvent(input$model_validation_click, { updateNavbarPage(session, 'mainpage', selected = 'tab_valid') updateNavlistPanel(session, 'navlist_valid', 'tab_conf_matrix') }) # observeEvent(input$click_visualize, { # updateNavbarPage(session, 'mainpage', selected = 'tab_viz_lib') # }) observeEvent(input$model_resdiag_click, { updateNavbarPage(session, 'mainpage', selected = 'tab_resid') updateNavlistPanel(session, 'navlist_resid', 'tab_diag_influence') })
/scratch/gouwar.j/cran-all/cranData/xplorerr/inst/app-blorr/logic/logic_home.R
partition_ui <- eventReactive(input$button_split_yes, { fluidRow( column(12, align = 'center', numericInput( inputId = 'part_train_per', label = 'Training Set', min = 0, max = 1, value = 0.5, step = 0.01, width = '120px' ) ), column(12, align = 'center', br(), actionButton(inputId = 'submit_part_train_per', label = 'Partition', width = '120px', icon = icon('check')), bsTooltip("submit_part_train_per", "Click here to partition data.", "bottom", options = list(container = "body")) ), column(12, br(), br(), column(6, align = 'right', downloadButton("downloadTrain", "Download Training Data")), column(6, align = 'left', downloadButton("downloadTest", "Download Test Data")) ), br(), br(), column(12, align = 'center', br(), actionButton(inputId = 'start_modeling', label = 'Start Modeling', width = '140px', icon = icon('check')) ) ) }) output$ui_partition <- renderUI({ partition_ui() }) final_split <- reactiveValues(train = NULL, test = NULL) trainpart <- eventReactive(input$button_split_yes, { out <- createDataPartition( y = final_sample$d[[1]], p = input$part_train_per, list = FALSE ) as.vector(out) }) observeEvent(input$submit_part_train_per, { final_split$train <- final_sample$d[trainpart(), ] final_split$test <- final_sample$d[-trainpart(), ] }) observeEvent(input$button_split_no, { final_split$train <- final_sample$d }) output$downloadTrain <- downloadHandler( filename = function() { paste("train_data.csv", sep = "") }, content = function(file) { write.csv(final_split$train, file, row.names = FALSE) } ) output$downloadTest <- downloadHandler( filename = function() { paste("test_data.csv", sep = "") }, content = function(file) { write.csv(final_split$test, file, row.names = FALSE) } ) observeEvent(input$start_modeling, { updateNavbarPage(session, 'mainpage', selected = 'tab_home_analyze') updateNavlistPanel(session, 'navlist_home', 'tab_analyze_home') }) observeEvent(input$button_split_no, { updateNavbarPage(session, 'mainpage', selected = 'tab_home_analyze') updateNavlistPanel(session, 'navlist_home', 'tab_analyze_home') })
/scratch/gouwar.j/cran-all/cranData/xplorerr/inst/app-blorr/logic/logic_partition.R
model <- eventReactive(input$submit_regress, { data <- final_split$train k <- glm(input$regress_fmla, data = data, family = binomial(link = "logit")) k }) d_regress <- eventReactive(input$submit_regress, { data <- final_split$train k <- blr_regress(input$regress_fmla, data = data) k }) r1_title <- eventReactive(input$submit_regress, { column(12, align = 'center', h4('Regression Result')) }) output$reg1_title <- renderUI({ r1_title() }) output$regress_out <- renderPrint({ d_regress() }) # model fit statistics result <- eventReactive(input$submit_mfs, { if (input$mfs_use_prev) { k <- model() } else { data <- final_split$train k <- glm(input$mfs_fmla, data = data, family = binomial(link = "logit")) } return(blorr::blr_model_fit_stats(k)) }) output$mfs <- renderPrint({ result() }) # multiple model fit statistics mmfs_result <- eventReactive(input$submit_mmfs, { data <- final_split$train m1 <- glm(input$mmfs_fmla_1, data = data, family = binomial(link = "logit")) m2 <- glm(input$mmfs_fmla_2, data = data, family = binomial(link = "logit")) blorr::blr_multi_model_fit_stats(m1, m2) }) output$mmfs <- renderPrint({ mmfs_result() })
/scratch/gouwar.j/cran-all/cranData/xplorerr/inst/app-blorr/logic/logic_regress.R
# influence diagnostics infl_result <- eventReactive(input$submit_infl, { if (input$infl_use_prev) { k <- model() } else { data <- final_split$train k <- glm(input$infl_fmla, data = data, family = binomial(link = "logit")) } return(k) }) output$infl_out <- renderPlot({ blorr::blr_plot_diag_influence(infl_result()) }) # leverage diagnostics lev_result <- eventReactive(input$submit_lev, { if (input$lev_use_prev) { k <- model() } else { data <- final_split$train k <- glm(input$lev_fmla, data = data, family = binomial(link = "logit")) } return(k) }) output$lev_out <- renderPlot({ blorr::blr_plot_diag_leverage(lev_result()) }) # fit diagnostics fit_result <- eventReactive(input$submit_fit, { if (input$fit_use_prev) { k <- model() } else { data <- final_split$train k <- glm(input$fit_fmla, data = data, family = binomial(link = "logit")) } return(k) }) output$fit_out <- renderPlot({ blorr::blr_plot_diag_fit(fit_result()) }) # fit diagnostics dfbetas_result <- eventReactive(input$submit_dfbetas, { if (input$dfbetas_use_prev) { k <- model() } else { data <- final_split$train k <- glm(input$dfbetas_fmla, data = data, family = binomial(link = "logit")) } return(k) }) output$dfbetas_out <- renderPlot({ blorr::blr_plot_dfbetas_panel(dfbetas_result()) })
/scratch/gouwar.j/cran-all/cranData/xplorerr/inst/app-blorr/logic/logic_residual_diagnostics.R
samp_yes <- eventReactive(input$button_sample_yes, { fluidRow( column(12, align = 'center', tags$div(class = 'header', id = 'samp_div', tags$h5('How do you want to sample?') ) # h5('How do you want to sample?') ), br(), br(), column(6, align = 'right', actionButton( inputId = 'button_samp_per', label = 'Percentage', width = '120px' ) ), column(6, align = 'left', actionButton( inputId = 'button_samp_n', label = 'Observations', width = '120px' ) ) ) }) # samp_no <- eventReactive(input$button_sample_no, { # fluidRow( # br(), # tags$div(class = 'header', id = 'samp_remove_no', # tags$h6('Click on Analyze in the drop down menu to explore the data.') # ) # ) # }) output$samp_yes_no <- renderUI({ samp_yes() }) # output$samp_no_yes <- renderUI({ # samp_no() # }) samp_per_options <- eventReactive(input$button_samp_per, { fluidRow( column(12, align = 'center', numericInput( inputId = 'samp_size_per', label = 'Sample Size', min = 0, max = 1, value = 1, step = 0.01, width = '120px' ) ), column(12, align = 'center', br(), actionButton(inputId = 'submit_samp_per_size', label = 'Submit', width = '120px', icon = icon('check')), bsTooltip("submit_samp_per_size", "Click here to select variables.", "bottom", options = list(container = "body")) ) ) }) samp_obs_options <- eventReactive(input$button_samp_n, { fluidRow( column(12, align = 'center', numericInput( inputId = 'samp_size_n', label = 'Sample Size', min = 0, value = 0, step = 1, width = '120px' ) ), column(12, align = 'center', br(), actionButton(inputId = 'submit_samp_obs_size', label = 'Submit', width = '120px', icon = icon('check')), bsTooltip("submit_samp_obs_size", "Click here to select variables.", "bottom", options = list(container = "body")) ) ) }) output$samp_per_option <- renderUI({ samp_per_options() }) output$samp_obs_option <- renderUI({ samp_obs_options() }) observeEvent(input$button_sample_no, { removeUI( selector = "div:has(> #button_samp_per)" ) removeUI( selector = "div:has(> #button_samp_n)" ) removeUI( selector = "div:has(> #samp_div)" ) removeUI( selector = "div:has(> #samp_size_n)" ) removeUI( selector = "div:has(> #submit_samp_obs_size)" ) removeUI( selector = "div:has(> #samp_size_per)" ) removeUI( selector = "div:has(> #submit_samp_per_size)" ) }) observeEvent(input$button_sample_yes, { removeUI( selector = "div:has(> #samp_remove_no)" ) }) observeEvent(input$button_samp_per, { removeUI( selector = "div:has(> #samp_size_n)" ) removeUI( selector = "div:has(> #submit_samp_obs_size)" ) }) observeEvent(input$button_samp_n, { removeUI( selector = "div:has(> #samp_size_per)" ) removeUI( selector = "div:has(> #submit_samp_per_size)" ) }) observeEvent(input$button_samp_n, { updateNumericInput( session, inputId = 'samp_size_n', label = 'Sample Size', min = 0, value = nrow(filt_data$p), max = nrow(filt_data$p), step = 1 ) }) final_sample <- reactiveValues(d = NULL) samp1 <- eventReactive(input$submit_samp_per_size, { final_sample$d <- dplyr::sample_frac(filt_data$p, size = input$samp_size_per, replace = FALSE) }) samp2 <- eventReactive(input$submit_samp_obs_size, { final_sample$d <- dplyr::sample_n(filt_data$p, size = input$samp_size_n, replace = FALSE) }) observeEvent(input$submit_samp_per_size, { final_sample$d <- samp1() }) observeEvent(input$submit_samp_obs_size, { final_sample$d <- samp2() }) observeEvent(input$button_sample_no, { final_sample$d <- filt_data$p }) observeEvent(input$button_sample_no, { updateNavbarPage(session, 'mainpage', selected = 'tab_partition') }) observeEvent(input$submit_samp_obs_size, { updateNavbarPage(session, 'mainpage', selected = 'tab_partition') }) observeEvent(input$submit_samp_per_size, { updateNavbarPage(session, 'mainpage', selected = 'tab_partition') }) # output$samp_type <- renderUI({ # if (input$data_samp == 'Percentage') { # numericInput( # inputId = 'samp_size', # label = 'Sample Size', # min = 0, # max = 1, # value = 0.7, # step = 0.01 # ) # } else { # numericInput( # inputId = 'samp_size', # label = 'Sample Size', # min = 0, # value = 0, # step = 1 # ) # } # }) # observeEvent(input$finalok, { # if (input$data_samp == 'Observations') { # updateNumericInput( # inputId = 'samp_size', # label = 'Sample Size', # min = 0, # value = nrow(final()), # max = nrow(final()), # step = 1 # ) # } # }) # final_sample <- eventReactive(input$submit_samp, { # if (input$data_samp == 'Percentage') { # out <- dplyr::sample_frac(filtered(), size = input$samp_size, replace = FALSE) # } else { # out <- dplyr::sample_n(filtered(), size = input$samp_size, replace = FALSE) # } # out # })
/scratch/gouwar.j/cran-all/cranData/xplorerr/inst/app-blorr/logic/logic_sample.R
# output output$screen <- renderPrint({ ds_screener(filt_data$p) }) observeEvent(input$finalok, { updateNavbarPage(session, 'mainpage', selected = 'tab_sample') })
/scratch/gouwar.j/cran-all/cranData/xplorerr/inst/app-blorr/logic/logic_screen.R
show_but_sel <- eventReactive(input$button_selvar_yes, { column(12, align = 'center', selectInput( inputId = 'dplyr_selvar', label = '', choices = '', selected = '', multiple = TRUE, selectize = TRUE ) ) }) output$show_sel_button <- renderUI({ show_but_sel() }) sel_sub_but <- eventReactive(input$button_selvar_yes, { column(12, align = 'center', br(), br(), actionButton(inputId = 'submit_dply_selvar', label = 'Submit', width = '120px', icon = icon('check')), bsTooltip("submit_seldata", "Click here to select variables.", "bottom", options = list(container = "body")) ) }) output$sub_sel_button <- renderUI({ sel_sub_but() }) observe({ updateSelectInput( session, inputId = "dplyr_selvar", choices = names(data()), selected = names(data()) ) }) observeEvent(input$button_selvar_yes, { updateSelectInput( session, inputId = "dplyr_selvar", choices = names(final()), selected = names(final()) ) }) final_sel <- reactiveValues(a = NULL) finalsel <- eventReactive(input$submit_dply_selvar, { k <- final() %>% select(input$dplyr_selvar) k }) observeEvent(input$submit_dply_selvar, { final_sel$a <- finalsel() }) observeEvent(input$button_selvar_no, { final_sel$a <- final() }) observeEvent(input$button_selvar_no, { removeUI( selector = "div:has(> #dplyr_selvar)" ) removeUI( selector = "div:has(> #submit_dply_selvar)" ) }) observeEvent(input$button_selvar_no, { updateNavbarPage(session, 'mainpage', selected = 'tab_trans') updateNavlistPanel(session, 'navlist_trans', 'tab_filter') }) observeEvent(input$submit_dply_selvar, { updateNavbarPage(session, 'mainpage', selected = 'tab_trans') updateNavlistPanel(session, 'navlist_trans', 'tab_filter') })
/scratch/gouwar.j/cran-all/cranData/xplorerr/inst/app-blorr/logic/logic_select.R
library(stringr) output$trans_try <- renderUI({ ncol <- as.integer(ncol(uploadata$t)) lapply(1:ncol, function(i) { fluidRow( column(3, selectInput(paste("n_col_", i), label = '', width = '150px', choices = names(uploadata$t)[i], selected = names(uploadata$t)[i]) ), column(3, textInput(paste("new_name_", i), label = '', width = '150px', value = names(uploadata$t)[i]) ), column(3, selectInput(paste0("data_type_", i), label = '', width = '150px', choices = c('numeric', 'factor', 'Date', 'character', 'integer'), selected = class(uploadata$t[[i]])) ), column(3, conditionalPanel(condition = paste(paste0("input.data_type_", i), "== 'Date'"), column(4, br(), tags$h5('Format')), column(8, selectInput(paste("date_type_", i), label = '', width = '150px', choices = c('%d %m %y', '%d %m %Y', '%y %m %d', '%Y %m %d', '%d %y %m', '%d %Y %m', '%m %d %y', '%m %d %Y', '%y %d %m', '%Y %d %m', '%m %y %d', '%m %Y %d', '%d/%m/%y', '%d/%m/%Y', '%y/m /%d', '%Y/%m/%d', '%d/%y/%m', '%d/%Y/%m', '%m/%d/%y', '%m/%d/%Y', '%y/%d/%m', '%Y/%d/%m', '%m/%y/%d', '%m/%Y/%d', '%d-%m-%y', '%d-%m-%Y', '%y-m -%d', '%Y-%m-%d', '%d-%y-%m', '%d-%Y-%m', '%m-%d-%y', '%m-%d-%Y', '%y-%d-%m', '%Y-%d-%m', '%m-%y-%d', '%m-%Y-%d' ), selected = '%Y %m %d') ) ) ) ) }) }) original <- reactive({ uploadata$t }) save_names <- reactive({ names(original()) }) n <- reactive({ length(original()) }) data_types <- reactive({ ncol <- as.integer(ncol(uploadata$t)) collect <- list(lapply(1:ncol, function(i) { input[[paste0("data_type_", i)]] })) colors <- unlist(collect) }) new_names <- reactive({ ncol <- as.integer(ncol(uploadata$t)) collect <- list(lapply(1:ncol, function(i) { input[[paste("new_name_", i)]] })) colors <- unlist(collect) colnames <- str_replace(colors, " ", "_") }) # original <- reactive({ # data() # }) # save_names <- reactive({ # names(original()) # }) # n <- reactive({ # length(original()) # }) # data_types <- reactive({ # ncol <- as.integer(ncol(data())) # collect <- list(lapply(1:ncol, function(i) { # input[[paste0("data_type_", i)]] # })) # colors <- unlist(collect) # }) # new_names <- reactive({ # ncol <- as.integer(ncol(data())) # collect <- list(lapply(1:ncol, function(i) { # input[[paste("new_name_", i)]] # })) # colors <- unlist(collect) # colnames <- str_replace(colors, " ", "_") # }) copy <- eventReactive(input$apply_changes, { out <- list() for (i in seq_len(n())) { if (data_types()[i] == 'Date') { inp <- eval(parse(text = paste0('input$', paste0('date_type_', i)))) out[[i]] <- eval(parse(text = paste0("as.", data_types()[i], "(original()$", save_names()[i], ", ", inp, ")"))) } else { out[[i]] <- eval(parse(text = paste0("as.", data_types()[i], "(original()$", save_names()[i], ")"))) } } names(out) <- new_names() return(out) }) final <- eventReactive(input$apply_changes, { data.frame(copy(), stringsAsFactors = F) }) observeEvent(input$apply_changes, { updateNavbarPage(session, 'mainpage', selected = 'tab_trans') updateNavlistPanel(session, 'navlist_trans', 'tab_selvar') })
/scratch/gouwar.j/cran-all/cranData/xplorerr/inst/app-blorr/logic/logic_transform2.R
# importing data inFile1 <- reactive({ if(is.null(input$file1)) { return(NULL) } else { input$file1 } }) data1 <- reactive({ if(is.null(inFile1())) { return(NULL) } else { read.csv(inFile1()$datapath, header = input$header, sep = input$sep, quote = input$quote) } }) # importing data inFile2 <- reactive({ if(is.null(input$file2)) { return(NULL) } else { input$file2 } }) data2 <- reactive({ if(is.null(inFile2())) { return(NULL) } else { ext <- tools::file_ext(inFile2()$name) file.rename(inFile2()$datapath, paste(inFile2()$datapath, ext, sep=".")) readxl::read_excel( path = paste(inFile2()$datapath, ext, sep="."), sheet = input$sheet_n ) } }) # importing data inFile3 <- reactive({ if(is.null(input$file3)) { return(NULL) } else { input$file3 } }) data3 <- reactive({ if(is.null(inFile3())) { return(NULL) } else { jsonlite::fromJSON(inFile3()$datapath) } }) # importing data inFile4 <- reactive({ if(is.null(input$file4)) { return(NULL) } else { input$file4 } }) data4 <- reactive({ if(is.null(inFile4())) { return(NULL) } else { haven::read_sas(inFile4()$datapath) } }) inFile5 <- reactive({ if(is.null(input$file5)) { return(NULL) } else { input$file5 } }) data5 <- reactive({ if(is.null(inFile5())) { return(NULL) } else { haven::read_sav(inFile5()$datapath) } }) inFile6 <- reactive({ if(is.null(input$file6)) { return(NULL) } else { input$file6 } }) data6 <- reactive({ if(is.null(inFile6())) { return(NULL) } else { haven::read_stata(inFile6()$datapath) } }) inFile7 <- reactive({ if(is.null(input$file7)) { return(NULL) } else { input$file7 } }) data7 <- reactive({ if(is.null(inFile7())) { return(NULL) } else { readRDS(inFile7()$datapath) } }) observe({ updateSelectInput( session, inputId = 'sel_data', label = '', choices = c(input$file1$name, input$file2$name, input$file3$name, input$file4$name, input$file5$name, input$file6$name, input$file7$name), selected = '' ) }) ext_type <- reactive({ ext <- tools::file_ext(input$sel_data) }) # choosing sample data sampdata <- reactiveValues(s = NULL) observeEvent(input$german_data, { data("GermanCredit") sampdata$s <- GermanCredit }) observeEvent(input$iris_data, { sampdata$s <- iris }) observeEvent(input$mtcars_data, { sampdata$s <- descriptr::mtcarz }) observeEvent(input$hsb_data, { sampdata$s <- blorr::hsb2 }) observeEvent(input$mpg_data, { sampdata$s <- mpg }) observeEvent(input$diamonds_data, { sampdata$s <- diamonds }) uploadata <- reactiveValues(t = NULL) observeEvent(input$submit_seldata, { if (ext_type() == 'csv') { uploadata$t <- data1() } else if (ext_type() == 'xls') { uploadata$t <- data2() } else if (ext_type() == 'xlsx') { uploadata$t <- data2() } else if (ext_type() == 'json') { uploadata$t <- data3() } else if (ext_type() == 'sas7bdat') { uploadata$t <- data4() } else if (ext_type() == 'sav') { uploadata$t <- uploadata$t <- data5() } else if (ext_type() == 'dta') { uploadata$t <- data6() } else { uploadata$t <- data7() } }) observeEvent(input$use_sample_data, { uploadata$t <- sampdata$s }) observeEvent(input$use_sample_data, { updateNavbarPage(session, 'mainpage', selected = 'tab_trans') updateNavlistPanel(session, 'navlist_trans', 'tab_transform') }) observeEvent(input$submit_seldata, { updateNavbarPage(session, 'mainpage', selected = 'tab_trans') updateNavlistPanel(session, 'navlist_trans', 'tab_transform') }) observeEvent(input$csv2datasrc, { updateNavbarPage(session, 'mainpage', selected = 'tab_upload') updateNavlistPanel(session, 'navlist_up', 'tab_datasources') }) observeEvent(input$csv2datatrans, { updateNavbarPage(session, 'mainpage', selected = 'tab_trans') updateNavlistPanel(session, 'navlist_trans', 'tab_seldata') }) observeEvent(input$excel2datasrc, { updateNavbarPage(session, 'mainpage', selected = 'tab_upload') updateNavlistPanel(session, 'navlist_up', 'tab_datasources') }) observeEvent(input$excel2datatrans, { updateNavbarPage(session, 'mainpage', selected = 'tab_trans') updateNavlistPanel(session, 'navlist_trans', 'tab_seldata') }) observeEvent(input$json2datasrc, { updateNavbarPage(session, 'mainpage', selected = 'tab_upload') updateNavlistPanel(session, 'navlist_up', 'tab_datasources') }) observeEvent(input$json2datatrans, { updateNavbarPage(session, 'mainpage', selected = 'tab_trans') updateNavlistPanel(session, 'navlist_trans', 'tab_seldata') }) observeEvent(input$stata2datasrc, { updateNavbarPage(session, 'mainpage', selected = 'tab_upload') updateNavlistPanel(session, 'navlist_up', 'tab_datasources') }) observeEvent(input$stata2datatrans, { updateNavbarPage(session, 'mainpage', selected = 'tab_trans') updateNavlistPanel(session, 'navlist_trans', 'tab_seldata') }) observeEvent(input$spss2datasrc, { updateNavbarPage(session, 'mainpage', selected = 'tab_upload') updateNavlistPanel(session, 'navlist_up', 'tab_datasources') }) observeEvent(input$spss2datatrans, { updateNavbarPage(session, 'mainpage', selected = 'tab_trans') updateNavlistPanel(session, 'navlist_trans', 'tab_seldata') }) observeEvent(input$sas2datasrc, { updateNavbarPage(session, 'mainpage', selected = 'tab_upload') updateNavlistPanel(session, 'navlist_up', 'tab_datasources') }) observeEvent(input$sas2datatrans, { updateNavbarPage(session, 'mainpage', selected = 'tab_trans') updateNavlistPanel(session, 'navlist_trans', 'tab_seldata') }) observeEvent(input$rds2datasrc, { updateNavbarPage(session, 'mainpage', selected = 'tab_upload') updateNavlistPanel(session, 'navlist_up', 'tab_datasources') }) observeEvent(input$rds2datatrans, { updateNavbarPage(session, 'mainpage', selected = 'tab_trans') updateNavlistPanel(session, 'navlist_trans', 'tab_seldata') }) observeEvent(input$welcomebutton, { updateNavbarPage(session, 'mainpage', selected = 'tab_upload') })
/scratch/gouwar.j/cran-all/cranData/xplorerr/inst/app-blorr/logic/logic_upload.R
conf_result <- eventReactive(input$submit_conf, { if (input$conf_use_prev) { k <- model() } else { data <- final_split$train k <- glm(input$conf_fmla, data = data, family = binomial(link = "logit")) } if (input$conf_use_test_data) { out <- blr_confusion_matrix(k, cutoff = input$conf_cutoff, data = final_split$test) } else { out <- blr_confusion_matrix(k, cutoff = input$conf_cutoff, data = final_split$train) } return(out) }) confusion_title <- eventReactive(input$submit_conf, { column(12, align = 'center', h4('Confusion Matrix & Model Performance Measures')) }) output$conf_title <- renderUI({ confusion_title() }) output$conf_out <- renderPrint({ conf_result() }) # hosmer lemeshow test hoslem_result <- eventReactive(input$submit_hoslem, { if (input$hoslem_use_prev) { k <- model() } else { data <- final_split$train k <- glm(input$hoslem_fmla, data = data, family = binomial(link = "logit")) } if (input$hoslem_use_test_data) { out <- blr_test_hosmer_lemeshow(k, data = final_split$test) } else { out <- blr_test_hosmer_lemeshow(k, data = final_split$train) } return(out) }) output$hoslem_out <- renderPrint({ hoslem_result() }) # gains chart and roc curve lift_result <- eventReactive(input$submit_lift, { if (input$lift_use_prev) { k <- model() } else { data <- final_split$train k <- glm(input$lift_fmla, data = data, family = binomial(link = "logit")) } if (input$lift_use_test_data) { out <- blr_gains_table(k, data = final_split$test) } else { out <- blr_gains_table(k, data = final_split$train) } return(out) }) gains_title <- eventReactive(input$submit_lift, { column(12, align = 'center', h4('Gains Table & Lift Chart')) }) output$lift_title <- renderUI({ gains_title() }) output$gains_table_out <- renderPrint({ lift_result() }) output$lift_out <- renderPlot({ plot(lift_result()) }) # ROC curve roc_result <- eventReactive(input$submit_roc, { if (input$roc_use_prev) { k <- model() } else { data <- final_split$train k <- glm(input$roc_fmla, data = data, family = binomial(link = "logit")) } if (input$roc_use_test_data) { out <- blr_gains_table(k, data = final_split$test) } else { out <- blr_gains_table(k, data = final_split$train) } return(out) }) output$roc_out <- renderPlot({ blr_roc_curve(roc_result()) }) # KS chart ks_result <- eventReactive(input$submit_ks, { if (input$ks_use_prev) { k <- model() } else { data <- final_split$train k <- glm(input$ks_fmla, data = data, family = binomial(link = "logit")) } if (input$ks_use_test_data) { out <- blr_gains_table(k, data = final_split$test) } else { out <- blr_gains_table(k, data = final_split$train) } return(out) }) output$ks_out <- renderPlot({ blr_ks_chart(ks_result()) }) # lorenz curve lorenz_result <- eventReactive(input$submit_lorenz, { if (input$lorenz_use_prev) { k <- model() } else { data <- final_split$train k <- glm(input$lorenz_fmla, data = data, family = binomial(link = "logit")) } return(k) }) output$lorenz_out <- renderPlot({ blorr::blr_lorenz_curve(lorenz_result()) })
/scratch/gouwar.j/cran-all/cranData/xplorerr/inst/app-blorr/logic/logic_validation.R
model_be <- eventReactive(input$submit_varsel_be, { data <- final_split$train m <- glm(input$varsel_be_fmla, data = data, family = binomial(link = "logit")) k <- blr_step_aic_backward(m, details = as.logical(input$trace_varsel_be)) k }) output$regress_varsel_be <- renderPrint({ model_be() }) model_fe <- eventReactive(input$submit_varsel_fe, { data <- final_split$train m <- glm(input$varsel_fe_fmla, data = data, family = binomial(link = "logit")) k <- blr_step_aic_forward(m, details = as.logical(input$trace_varsel_fe)) k }) output$regress_varsel_fe <- renderPrint({ model_fe() }) model_se <- eventReactive(input$submit_varsel_se, { data <- final_split$train m <- glm(input$varsel_se_fmla, data = data, family = binomial(link = "logit")) k <- blr_step_aic_both(m, details = as.logical(input$trace_varsel_se)) k }) output$regress_varsel_se <- renderPrint({ model_se() })
/scratch/gouwar.j/cran-all/cranData/xplorerr/inst/app-blorr/logic/logic_varsel.R
output$table <- renderDataTable({ final_split$train }) observeEvent(input$view2getdata, { updateNavbarPage(session, 'mainpage', selected = 'tab_upload') updateNavlistPanel(session, 'navlist_up', 'tab_datasources') }) observeEvent(input$view2analyze, { updateNavbarPage(session, 'mainpage', selected = 'tab_eda') updateNavlistPanel(session, 'navlist_eda', 'tab_summary') })
/scratch/gouwar.j/cran-all/cranData/xplorerr/inst/app-blorr/logic/logic_view.R
library(car) library(blorr) library(caret) library(cli) library(clisymbols) library(crayon) library(checkmate) library(descriptr) library(dplyr) library(e1071) library(ggplot2) library(glue) library(grid) library(gridExtra) library(jsonlite) library(lubridate) library(magrittr) library(purrr) library(readr) library(readxl) library(rlang) library(Rcpp) library(tidyr) library(scales) library(shiny) library(stats) library(stringr) library(tibble) library(tools) library(utils) shinyServer(function(input, output, session) { source("logic/logic_dataoptions.R", local = T) source("logic/logic_upload.R", local = T) source("logic/logic_transform2.R", local = T) source("logic/logic_select.R", local = T) source("logic/logic_filter.R", local = T) source("logic/logic_screen.R", local = T) source("logic/logic_sample.R", local = T) source("logic/logic_partition.R", local = T) source("logic/logic_view.R", local = T) source("logic/logic_home.R", local = T) source("logic/logic_regress.R", local = T) source("logic/logic_bivar.R", local = T) source("logic/logic_varsel.R", local = T) source("logic/logic_validation.R", local = T) source("logic/logic_residual_diagnostics.R", local = T) source("logic/logic_exit_button.R", local = T) })
/scratch/gouwar.j/cran-all/cranData/xplorerr/inst/app-blorr/server.R
tabPanel('Two Way Segmentation', value = 'tab_2way_segment', fluidPage( fluidRow( column(6, align = 'left', h4('2 Way Segmentation') ), column(6, align = 'right', actionButton(inputId='2wayseglink1', label="Help", icon = icon("question-circle"), onclick ="window.open('https://blorr.rsquaredacademy.com/reference/blr_twoway_segment.html', '_blank')") ) ), hr(), fluidRow( column(2, align = 'right', br(), h5('Response Variable:')), column(4, align = 'left', selectInput("resp_2wayseg", label = '', choices = '', selected = '')), bsTooltip("resp_2wayseg", "Select response variable.", "left", options = list(container = "body"))) ), fluidRow( column(2, align = 'right', br(), h5('Variable 1:')), column(10, align = 'left', selectInput("var1_2wayseg", label = '', width = '660px', choices = "", selected = ""), bsTooltip("var1_2wayseg", "Select variable", "left", options = list(container = "body"))) ), fluidRow( column(2, align = 'right', br(), h5('Variable 2:')), column(10, align = 'left', selectInput("var2_2wayseg", label = '', width = '660px', choices = "", selected = ""), bsTooltip("var2_2wayseg", "Select variable", "left", options = list(container = "body"))) ), fluidRow( column(12, align = 'center', br(), br(), actionButton(inputId = 'submit_2wayseg', label = 'Submit', width = '120px', icon = icon('check')), bsTooltip("submit_2wayseg", "Click here to view two way segmentation.", "bottom", options = list(container = "body"))) ), fluidRow( br(), column(12, align = 'center', verbatimTextOutput('twowayseg_out') ) ) )
/scratch/gouwar.j/cran-all/cranData/xplorerr/inst/app-blorr/ui/ui_2way_segment.R
navbarMenu('Analyze', icon = icon('search-plus'), source('ui/ui_homes.R', local = TRUE)[[1]], source('ui/ui_bivar.R', local = TRUE)[[1]], source('ui/ui_mlr.R', local = TRUE)[[1]], source('ui/ui_varsel.R', local = TRUE)[[1]], source('ui/ui_valid.R', local = TRUE)[[1]], source('ui/ui_resid_diag.R', local = TRUE)[[1]] )
/scratch/gouwar.j/cran-all/cranData/xplorerr/inst/app-blorr/ui/ui_analyze.R
tabPanel('Bivariate Analysis', value = 'tab_bivar', icon = icon('cubes'), navlistPanel(id = 'navlist_bivar', well = FALSE, widths = c(2, 10), source('ui/ui_woe_iv.R', local = TRUE)[[1]], source('ui/ui_woe_iv_stats.R', local = TRUE)[[1]], source('ui/ui_segment_dist.R', local = TRUE)[[1]], source('ui/ui_2way_segment.R', local = TRUE)[[1]], source('ui/ui_bivar_analysis.R', local = TRUE)[[1]] ) )
/scratch/gouwar.j/cran-all/cranData/xplorerr/inst/app-blorr/ui/ui_bivar.R
tabPanel('Bivariate Analysis', value = 'tab_bivar_analysis', fluidPage( fluidRow( column(6, align = 'left', h4('Bivariate Analysis') ), column(6, align = 'right', actionButton(inputId='bivarlink1', label="Help", icon = icon("question-circle"), onclick ="window.open('https://blorr.rsquaredacademy.com/reference/blr_bivariate_analysis.html', '_blank')") ) ), hr(), fluidRow( column(2, align = 'right', br(), h5('Response Variable:')), column(4, align = 'left', selectInput("resp_bivar", label = '', choices = '', selected = '')), bsTooltip("resp_bivar", "Select response variable.", "left", options = list(container = "body"))) ), fluidRow( column(2, align = 'right', br(), h5('Variables:')), column(10, align = 'left', selectInput("var_bivar", label = '', width = '660px', choices = "", selected = "", multiple = TRUE, selectize = TRUE), bsTooltip("var_bivar", "Select variables.", "left", options = list(container = "body"))) ), fluidRow( column(12, align = 'center', br(), br(), actionButton(inputId = 'submit_bivar', label = 'Submit', width = '120px', icon = icon('check')), bsTooltip("submit_bivar", "Click here to view bivariate analysis.", "bottom", options = list(container = "body"))) ), fluidRow( br(), column(12, align = 'center', verbatimTextOutput('bivar_out') ) ) )
/scratch/gouwar.j/cran-all/cranData/xplorerr/inst/app-blorr/ui/ui_bivar_analysis.R
tabPanel('Confusion Matrix', value = 'tab_conf_matrix', fluidPage( br(), fluidRow( column(6, align = 'left', h4('Confusion Matrix') ), column(6, align = 'right', actionButton(inputId='conf1', label="Help", icon = icon("question-circle"), onclick ="window.open('https://blorr.rsquaredacademy.com/reference/blr_confusion_matrix.html', '_blank')") ) ), hr(), fluidRow( column(2, align = 'right', br(), h5('Model Formula:')), column(10, align = 'left', textInput("conf_fmla", label = '', width = '660px', value = ""), bsTooltip("conf_fmla", "Specify model formula", "left", options = list(container = "body"))) ), fluidRow( column(2, align = 'right', br(), h5('Cutoff:')), column(10, align = 'left', numericInput("conf_cutoff", label = '', min = 0, max = 1, value = 0.5, step = 0.01), bsTooltip("conf_cutoff", "Specify cutoff", "left", options = list(container = "body"))) ), fluidRow( column(2, align = 'right', br(), h5('Use previous model:')), column(2, align = 'left', br(), checkboxInput(inputId = 'conf_use_prev', label = '', value = FALSE), bsTooltip("conf_use_prev", "Use model from Regression Tab.", "left", options = list(container = "body")) ) ), fluidRow( column(2, align = 'right', br(), h5('Use test data:')), column(2, align = 'left', br(), checkboxInput(inputId = 'conf_use_test_data', label = '', value = FALSE), bsTooltip("conf_use_test_data", "Use the test/validation data.", "left", options = list(container = "body")) ) ), fluidRow( column(12, align = 'center', br(), br(), actionButton(inputId = 'submit_conf', label = 'Submit', width = '120px', icon = icon('check')), bsTooltip("submit_conf", "Click here to view confusion matrix.", "bottom", options = list(container = "body"))) ), fluidRow( br(), uiOutput('conf_title'), # column(12, align = 'center', h4('Regression Result')), hr(), column(12, align = 'center', verbatimTextOutput('conf_out')) ) ) )
/scratch/gouwar.j/cran-all/cranData/xplorerr/inst/app-blorr/ui/ui_conf_matrix.R
navbarMenu('Data', icon = icon('database'), source('ui/ui_up.R', local = TRUE)[[1]], source('ui/ui_trans.R', local = TRUE)[[1]], source('ui/ui_scr.R', local = TRUE)[[1]], source('ui/ui_sample.R', local = TRUE)[[1]], source('ui/ui_partition.R', local = TRUE)[[1]], source('ui/ui_vi.R', local = TRUE)[[1]] )
/scratch/gouwar.j/cran-all/cranData/xplorerr/inst/app-blorr/ui/ui_data.R
tabPanel('Upload File', value = 'tab_uploadfile', fluidPage( includeCSS("mystyle.css"), fluidRow( column(12, tabsetPanel(type = 'tabs', id = 'tabset_upload', tabPanel('CSV', value = 'tab_upload_csv', fluidPage( br(), fluidRow( column(8, align = 'left', h4('Upload Data'), p('Upload data from a comma or tab separated file.') ), column(4, align = 'right', actionButton(inputId='uploadlink2', label="Demo", icon = icon("video-camera"), onclick ="window.open('https://www.youtube.com/watch?v=X8b0beNJ64A#t=00m25s', '_blank')") ) ), hr(), fluidRow( column(12, align = 'center', fileInput('file1', 'Data Set:', accept = c('text/csv', '.csv', 'text/comma-separated-values,text/plain') ) ) ), fluidRow( column(12, align = 'center', checkboxInput('header', 'Header', TRUE)) ), fluidRow( column(12, align = 'center', selectInput('sep', 'Separator', choices = c('Comma' = ',', 'Semicolon' = ';', 'Tab' = '\t'), selected = ',') ) ), fluidRow( column(12, align = 'center', selectInput('quote', 'Quote', choices = c('None' = '', 'Double Quote' = '"', 'Single Quote' = "'"), selected = '') ) ), br(), br(), br(), fluidRow( column(6, align = 'left', actionButton(inputId='csv2datasrc', label="Data Sources", icon = icon("long-arrow-left")) ), column(6, align = 'right', actionButton(inputId='csv2datatrans', label="Data Selection", icon = icon("long-arrow-right")) ) ) ) ), tabPanel('Excel', value = 'tab_upload_excel', fluidPage( br(), fluidRow( column(8, align = 'left', h4('Upload Data'), p('Upload data from a .xls or .xlsx file.') ), column(4, align = 'right', actionButton(inputId='uploadlink3', label="Demo", icon = icon("video-camera"), onclick ="window.open('https://www.youtube.com/watch?v=X8b0beNJ64A#t=00m25s', '_blank')") ) ), hr(), fluidRow( column(12, align = 'center', fileInput( inputId = 'file2', label = 'Choose file:', accept = c('.xls', '.xlsx') ) ) ), fluidRow( column(12, align = 'center', numericInput( inputId = 'sheet_n', label = 'Sheet', value = 1, min = 1, step = 1, width = '120px' ) ) ), br(), br(), br(), br(), br(), br(), br(), br(), br(), fluidRow( column(6, align = 'left', actionButton(inputId='excel2datasrc', label="Data Sources", icon = icon("long-arrow-left")) ), column(6, align = 'right', actionButton(inputId='excel2datatrans', label="Data Selection", icon = icon("long-arrow-right")) ) ) ) ), tabPanel('JSON', value = 'tab_upload_json', br(), fluidPage( fluidRow( column(8, align = 'left', h4('Upload Data'), p('Upload data from a .json file.') ), column(4, align = 'right', actionButton(inputId='uploadjson', label="Demo", icon = icon("video-camera"), onclick ="window.open('https://www.youtube.com/watch?v=X8b0beNJ64A#t=00m25s', '_blank')") ) ), hr(), fluidRow( column(12, align = 'center', fileInput( inputId = 'file3', label = 'Choose file:', accept = '.json' ) ) ), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), fluidRow( column(6, align = 'left', actionButton(inputId='json2datasrc', label="Data Sources", icon = icon("long-arrow-left")) ), column(6, align = 'right', actionButton(inputId='json2datatrans', label="Data Selection", icon = icon("long-arrow-right")) ) ) ) ), tabPanel('STATA', value = 'tab_upload_stata', br(), fluidPage( fluidRow( column(8, align = 'left', h4('Upload Data'), p('Upload data from a .dta file.') ), column(4, align = 'right', actionButton(inputId='uploadstata', label="Demo", icon = icon("video-camera"), onclick ="window.open('https://www.youtube.com/watch?v=X8b0beNJ64A#t=00m25s', '_blank')") ) ), hr(), fluidRow( column(12, align = 'center', fileInput( inputId = 'file6', label = 'Choose file:', accept = '.dta' ) ) ), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), fluidRow( column(6, align = 'left', actionButton(inputId='stata2datasrc', label="Data Sources", icon = icon("long-arrow-left")) ), column(6, align = 'right', actionButton(inputId='stata2datatrans', label="Data Selection", icon = icon("long-arrow-right")) ) ) ) ), tabPanel('SPSS', value = 'tab_upload_spss', br(), fluidPage( fluidRow( column(8, align = 'left', h4('Upload Data'), p('Upload data from a .sav file.') ), column(4, align = 'right', actionButton(inputId='uploadspss', label="Demo", icon = icon("video-camera"), onclick ="window.open('https://www.youtube.com/watch?v=X8b0beNJ64A#t=00m25s', '_blank')") ) ), hr(), fluidRow( column(12, align = 'center', fileInput( inputId = 'file5', label = 'Choose file:', accept = '.sav' ) ) ), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), fluidRow( column(6, align = 'left', actionButton(inputId='spss2datasrc', label="Data Sources", icon = icon("long-arrow-left")) ), column(6, align = 'right', actionButton(inputId='spss2datatrans', label="Data Selection", icon = icon("long-arrow-right")) ) ) ) ), tabPanel('SAS', value = 'tab_upload_sas', br(), fluidPage( fluidRow( column(8, align = 'left', h4('Upload Data'), p('Upload data from a .sas7bdat file.') ), column(4, align = 'right', actionButton(inputId='uploadsas', label="Demo", icon = icon("video-camera"), onclick ="window.open('https://www.youtube.com/watch?v=X8b0beNJ64A#t=00m25s', '_blank')") ) ), hr(), fluidRow( column(12, align = 'center', fileInput( inputId = 'file4', label = 'Choose file:', accept = '.sas7bdat' ) ) ), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), fluidRow( column(6, align = 'left', actionButton(inputId='sas2datasrc', label="Data Sources", icon = icon("long-arrow-left")) ), column(6, align = 'right', actionButton(inputId='sas2datatrans', label="Data Selection", icon = icon("long-arrow-right")) ) ) ) ), tabPanel('RDS', value = 'tab_upload_rds', br(), fluidPage( fluidRow( column(8, align = 'left', h4('Upload Data'), p('Upload data from a RDS file.') ), column(4, align = 'right', actionButton(inputId='uploadrds2', label="Demo", icon = icon("video-camera"), onclick ="window.open('https://www.youtube.com/watch?v=IckaPr19Bvc#t=00m29s', '_blank')") ) ), hr(), fluidRow( column(12, align = 'center', fileInput( inputId = 'file7', label = 'Choose file:', accept = '' ) ) ), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), fluidRow( column(6, align = 'left', actionButton(inputId='rds2datasrc', label="Data Sources", icon = icon("long-arrow-left")) ), column(6, align = 'right', actionButton(inputId='rds2datatrans', label="Data Selection", icon = icon("long-arrow-right")) ) ) ) ) ) ) ) ) )
/scratch/gouwar.j/cran-all/cranData/xplorerr/inst/app-blorr/ui/ui_datafiles.R
tabPanel('Data Sources', value = 'tab_datasources', fluidPage(theme = shinytheme('cerulean'), includeCSS("mystyle.css"), fluidRow( column(12, align = 'center', h4('Use sample data or upload a file') ) ), fluidRow( column(6, align = 'right', actionButton( inputId = 'sample_data_yes', label = 'Sample Data', width = '120px' ) ), column(6, align = 'left', actionButton( inputId = 'upload_files_yes', label = 'Upload File', width = '120px' ) ) ), br(), fluidRow( column(12, align = 'center', h6('The app takes a few seconds to load. Please wait for ~12 seconds.') ) ), br(), br(), fluidRow( uiOutput('upload_file_links') ) ) )
/scratch/gouwar.j/cran-all/cranData/xplorerr/inst/app-blorr/ui/ui_dataoptions.R
tabPanel('Sample Data', value = 'tab_use_sample', fluidPage( includeCSS("mystyle.css"), fluidRow( column(12, align = 'center', h5('Click on a sample for more information') ) ), br(), fluidRow( column(4, align = 'center', actionButton( inputId = 'german_data', label = 'German Credit', width = '200px', onclick ="window.open('https://archive.ics.uci.edu/ml/datasets/Statlog+(German+Credit+Data)', 'newwindow', 'width=800,height=600')" ) ), column(4, align = 'center', actionButton( inputId = 'iris_data', label = 'Iris', width = '200px', onclick ="window.open('https://stat.ethz.ch/R-manual/R-devel/library/datasets/html/iris.html', 'newwindow', 'width=800,height=600')" ) ), column(4, align = 'center', actionButton( inputId = 'mtcars_data', label = 'mtcars', width = '200px', onclick ="window.open('https://stat.ethz.ch/R-manual/R-devel/library/datasets/html/mtcars.html', 'newwindow', 'width=800,height=600')" ) ) ), fluidRow(column(12, br())), fluidRow( column(4, align = 'center', actionButton( inputId = 'mpg_data', label = 'mpg', width = '200px', onclick ="window.open('http://ggplot2.tidyverse.org/reference/mpg.html', 'newwindow', 'width=800,height=600')" ) ), column(4, align = 'center', actionButton( inputId = 'hsb_data', label = 'hsb', width = '200px', onclick ="window.open('https://blorr.rsquaredacademy.com/reference/hsb2.html', 'newwindow', 'width=800,height=600')" ) ), column(4, align = 'center', actionButton( inputId = 'diamonds_data', label = 'diamonds', width = '200px', onclick ="window.open('http://ggplot2.tidyverse.org/reference/diamonds.html', 'newwindow', 'width=800,height=600')" ) ) ), br(), br(), br(), fluidRow( column(12, align = 'center', actionButton( inputId = 'use_sample_data', label = 'Use Sample Data', width = '200px' ) ) ) ) )
/scratch/gouwar.j/cran-all/cranData/xplorerr/inst/app-blorr/ui/ui_datasamples.R
tabPanel('DFBETAs Panel', value = 'tab_dfbetas_panel', fluidPage( br(), fluidRow( column(6, align = 'left', h4('DFBETAs Panel') ), column(6, align = 'right', actionButton(inputId='dfbetaslink', label="Help", icon = icon("question-circle"), onclick ="window.open('https://blorr.rsquaredacademy.com/reference/blr_plot_dfbetas_panel.html', '_blank')") ) ), hr(), fluidRow( column(2, align = 'right', br(), h5('Model Formula:')), column(10, align = 'left', textInput("dfbetas_fmla", label = '', width = '660px', value = ""), bsTooltip("dfbetas_fmla", "Specify model formula", "left", options = list(container = "body"))) ), fluidRow( column(2, align = 'right', br(), h5('Use previous model:')), column(2, align = 'left', br(), checkboxInput(inputId = 'dfbetas_use_prev', label = '', value = FALSE), bsTooltip("dfbetas_use_prev", "Use model from Regression Tab.", "left", options = list(container = "body")) ) ), fluidRow( column(12, align = 'center', br(), br(), actionButton(inputId = 'submit_dfbetas', label = 'Submit', width = '120px', icon = icon('check')), bsTooltip("submit_dfbetas", "Click here to view dfbetas panel plots.", "bottom", options = list(container = "body"))) ), fluidRow( br(), column(12, align = 'center', plotOutput('dfbetas_out', height = '1000px')) ) ) )
/scratch/gouwar.j/cran-all/cranData/xplorerr/inst/app-blorr/ui/ui_dfbetas_panel.R
tabPanel('Fit Diagnostics', value = 'tab_diag_fit', fluidPage( br(), fluidRow( column(6, align = 'left', h4('Fitted Values Diagnostics') ), column(6, align = 'right', actionButton(inputId='fitlink', label="Help", icon = icon("question-circle"), onclick ="window.open('https://blorr.rsquaredacademy.com/reference/blr_plot_diag_fit.html', '_blank')") ) ), hr(), fluidRow( column(2, align = 'right', br(), h5('Model Formula:')), column(10, align = 'left', textInput("fit_fmla", label = '', width = '660px', value = ""), bsTooltip("fit_fmla", "Specify model formula", "left", options = list(container = "body"))) ), fluidRow( column(2, align = 'right', br(), h5('Use previous model:')), column(2, align = 'left', br(), checkboxInput(inputId = 'fit_use_prev', label = '', value = FALSE), bsTooltip("fit_use_prev", "Use model from Regression Tab.", "left", options = list(container = "body")) ) ), fluidRow( column(12, align = 'center', br(), br(), actionButton(inputId = 'submit_fit', label = 'Submit', width = '120px', icon = icon('check')), bsTooltip("submit_fit", "Click here to view fitted values diagnostics plots.", "bottom", options = list(container = "body"))) ), fluidRow( br(), column(12, align = 'center', plotOutput('fit_out', height = '1000px')) ) ) )
/scratch/gouwar.j/cran-all/cranData/xplorerr/inst/app-blorr/ui/ui_diag_fit.R
tabPanel('Influence Diagnostics', value = 'tab_diag_influence', fluidPage( br(), fluidRow( column(6, align = 'left', h4('Influence Diagnostics') ), column(6, align = 'right', actionButton(inputId='infllink', label="Help", icon = icon("question-circle"), onclick ="window.open('https://blorr.rsquaredacademy.com/reference/blr_plot_diag_influence.html', '_blank')") ) ), hr(), fluidRow( column(2, align = 'right', br(), h5('Model Formula:')), column(10, align = 'left', textInput("infl_fmla", label = '', width = '660px', value = ""), bsTooltip("infl_fmla", "Specify model formula", "left", options = list(container = "body"))) ), fluidRow( column(2, align = 'right', br(), h5('Use previous model:')), column(2, align = 'left', br(), checkboxInput(inputId = 'infl_use_prev', label = '', value = FALSE), bsTooltip("infl_use_prev", "Use model from Regression Tab.", "left", options = list(container = "body")) ) ), fluidRow( column(12, align = 'center', br(), br(), actionButton(inputId = 'submit_infl', label = 'Submit', width = '120px', icon = icon('check')), bsTooltip("submit_infl", "Click here to view influence diagnostics plots.", "bottom", options = list(container = "body"))) ), fluidRow( br(), column(12, align = 'center', plotOutput('infl_out', height = '2000px')) ) ) )
/scratch/gouwar.j/cran-all/cranData/xplorerr/inst/app-blorr/ui/ui_diag_influence.R
tabPanel('Leverage Diagnostics', value = 'tab_diag_leverage', fluidPage( br(), fluidRow( column(6, align = 'left', h4('Leverage Diagnostics') ), column(6, align = 'right', actionButton(inputId='levlink', label="Help", icon = icon("question-circle"), onclick ="window.open('https://blorr.rsquaredacademy.com/reference/blr_plot_diag_leverage.html', '_blank')") ) ), hr(), fluidRow( column(2, align = 'right', br(), h5('Model Formula:')), column(10, align = 'left', textInput("lev_fmla", label = '', width = '660px', value = ""), bsTooltip("lev_fmla", "Specify model formula", "left", options = list(container = "body"))) ), fluidRow( column(2, align = 'right', br(), h5('Use previous model:')), column(2, align = 'left', br(), checkboxInput(inputId = 'lev_use_prev', label = '', value = FALSE), bsTooltip("lev_use_prev", "Use model from Regression Tab.", "left", options = list(container = "body")) ) ), fluidRow( column(12, align = 'center', br(), br(), actionButton(inputId = 'submit_lev', label = 'Submit', width = '120px', icon = icon('check')), bsTooltip("submit_lev", "Click here to view leverage diagnostics plots.", "bottom", options = list(container = "body"))) ), fluidRow( br(), column(12, align = 'center', plotOutput('lev_out', height = '1000px')) ) ) )
/scratch/gouwar.j/cran-all/cranData/xplorerr/inst/app-blorr/ui/ui_diag_leverage.R
# Exit ----------------------------------------------------------- tabPanel("", value = "exit", icon = icon("power-off"), br(), br(), br(), br(), br(), br(), # In case window does not close, one should see this message fluidRow(column(3), column(6, h2("Thank you for using", strong("blorr"), "!"))), fluidRow(column(3), column(6, h4("Now you should close this window."))) )
/scratch/gouwar.j/cran-all/cranData/xplorerr/inst/app-blorr/ui/ui_exit_button.R
tabPanel('Filter', value = 'tab_filter', fluidPage( fluidRow( column(6, align = 'left', h4('Filter Data'), p('Click on Yes to filter data.') ), column(6, align = 'right', actionButton(inputId='fildatalink', label="Demo", icon = icon("video-camera"), onclick ="window.open('https://www.youtube.com/watch?v=X8b0beNJ64A#t=02m34s', '_blank')") ) ), hr(), fluidRow( column(12, align = 'center', h4('Do you want to filter data?') ), column(6, align = 'right', actionButton( inputId = 'button_filt_yes', label = 'Yes', width = '120px' ) ), column(6, align = 'left', actionButton( inputId = 'button_filt_no', label = 'No', width = '120px' ) ) ), br(), br(), fluidRow( uiOutput('filt_render') ), fluidRow( uiOutput('filt_trans') ) ) )
/scratch/gouwar.j/cran-all/cranData/xplorerr/inst/app-blorr/ui/ui_filter.R
tabPanel('Lift Chart', value = 'tab_gains_table', fluidPage( br(), fluidRow( column(6, align = 'left', h4('Gains Table & Lift Chart') ), column(6, align = 'right', actionButton(inputId='liftlink', label="Help", icon = icon("question-circle"), onclick ="window.open('https://blorr.rsquaredacademy.com/reference/blr_gains_table.html', '_blank')") ) ), hr(), fluidRow( column(2, align = 'right', br(), h5('Model Formula:')), column(10, align = 'left', textInput("lift_fmla", label = '', width = '660px', value = ""), bsTooltip("lift_fmla", "Specify model formula", "left", options = list(container = "body"))) ), fluidRow( column(2, align = 'right', br(), h5('Use previous model:')), column(2, align = 'left', br(), checkboxInput(inputId = 'lift_use_prev', label = '', value = FALSE), bsTooltip("lift_use_prev", "Use model from Regression Tab.", "left", options = list(container = "body")) ) ), fluidRow( column(2, align = 'right', br(), h5('Use test data:')), column(2, align = 'left', br(), checkboxInput(inputId = 'lift_use_test_data', label = '', value = FALSE), bsTooltip("conf_use_test_data", "Use the test/validation data.", "left", options = list(container = "body")) ) ), fluidRow( column(12, align = 'center', br(), br(), actionButton(inputId = 'submit_lift', label = 'Submit', width = '120px', icon = icon('check')), bsTooltip("submit_lift", "Click here to view gains table and lift chart.", "bottom", options = list(container = "body"))) ), fluidRow( br(), uiOutput('lift_title'), # column(12, align = 'center', h4('Regression Result')), hr(), column(12, align = 'center', verbatimTextOutput('gains_table_out')) ), fluidRow( br(), column(2), column(8, align = 'center', plotOutput('lift_out')), column(2) ) ) )
/scratch/gouwar.j/cran-all/cranData/xplorerr/inst/app-blorr/ui/ui_gains_table.R
tabPanel('Home', value = 'tab_home_analyze', icon = icon('home'), navlistPanel(id = 'navlist_home', well = FALSE, widths = c(2, 10), source('ui/ui_model_home.R', local = TRUE)[[1]]) )
/scratch/gouwar.j/cran-all/cranData/xplorerr/inst/app-blorr/ui/ui_homes.R
tabPanel('Hosmer Lemeshow Test', value = 'tab_hoslem_test', fluidPage( br(), fluidRow( column(6, align = 'left', h4('Hosmer Lemeshow Test') ), column(6, align = 'right', actionButton(inputId='conf1', label="Help", icon = icon("question-circle"), onclick ="window.open('https://blorr.rsquaredacademy.com/reference/blr_hosmer_lemeshow_test.html', '_blank')") ) ), hr(), fluidRow( column(2, align = 'right', br(), h5('Model Formula:')), column(10, align = 'left', textInput("hoslem_fmla", label = '', width = '660px', value = ""), bsTooltip("hoslem_fmla", "Specify model formula", "left", options = list(container = "body"))) ), fluidRow( column(2, align = 'right', br(), h5('Use previous model:')), column(2, align = 'left', br(), checkboxInput(inputId = 'hoslem_use_prev', label = '', value = FALSE), bsTooltip("hoslem_use_prev", "Use model from Regression Tab.", "left", options = list(container = "body")) ) ), fluidRow( column(2, align = 'right', br(), h5('Use test data:')), column(2, align = 'left', br(), checkboxInput(inputId = 'hoslem_use_test_data', label = '', value = FALSE), bsTooltip("hoslem_use_test_data", "Use the test/validation data.", "left", options = list(container = "body")) ) ), fluidRow( column(12, align = 'center', br(), br(), actionButton(inputId = 'submit_hoslem', label = 'Submit', width = '120px', icon = icon('check')), bsTooltip("submit_hoslem", "Click here to view hosmer lemeshow test results.", "bottom", options = list(container = "body"))) ), fluidRow( br(), column(12, align = 'center', verbatimTextOutput('hoslem_out')) ) ) )
/scratch/gouwar.j/cran-all/cranData/xplorerr/inst/app-blorr/ui/ui_hoslem_test.R
tabPanel('KS Chart', value = 'tab_ks_chart', fluidPage( br(), fluidRow( column(6, align = 'left', h4('KS Chart') ), column(6, align = 'right', actionButton(inputId='kschartlink', label="Help", icon = icon("question-circle"), onclick ="window.open('https://blorr.rsquaredacademy.com/reference/blr_ks_chart.html', '_blank')") ) ), hr(), fluidRow( column(2, align = 'right', br(), h5('Model Formula:')), column(10, align = 'left', textInput("ks_fmla", label = '', width = '660px', value = ""), bsTooltip("ks_fmla", "Specify model formula", "left", options = list(container = "body"))) ), fluidRow( column(2, align = 'right', br(), h5('Use previous model:')), column(2, align = 'left', br(), checkboxInput(inputId = 'ks_use_prev', label = '', value = FALSE), bsTooltip("ks_use_prev", "Use model from Regression Tab.", "left", options = list(container = "body")) ) ), fluidRow( column(2, align = 'right', br(), h5('Use test data:')), column(2, align = 'left', br(), checkboxInput(inputId = 'ks_use_test_data', label = '', value = FALSE), bsTooltip("ks_use_test_data", "Use the test/validation data.", "left", options = list(container = "body")) ) ), fluidRow( column(12, align = 'center', br(), br(), actionButton(inputId = 'submit_ks', label = 'Submit', width = '120px', icon = icon('check')), bsTooltip("submit_ks", "Click here to view KS chart.", "bottom", options = list(container = "body"))) ), fluidRow( br(), column(2), column(8, align = 'center', plotOutput('ks_out')), column(2) ) ) )
/scratch/gouwar.j/cran-all/cranData/xplorerr/inst/app-blorr/ui/ui_ks_chart.R
tabPanel('Lorenz Curve', value = 'tab_lorenz_curve', fluidPage( br(), fluidRow( column(6, align = 'left', h4('Lorenz Curve & Gini Index') ), column(6, align = 'right', actionButton(inputId='lorenzlink', label="Help", icon = icon("question-circle"), onclick ="window.open('https://blorr.rsquaredacademy.com/reference/blr_lorenz_curve.html', '_blank')") ) ), hr(), fluidRow( column(2, align = 'right', br(), h5('Model Formula:')), column(10, align = 'left', textInput("lorenz_fmla", label = '', width = '660px', value = ""), bsTooltip("lorenz_fmla", "Specify model formula", "left", options = list(container = "body"))) ), fluidRow( column(2, align = 'right', br(), h5('Use previous model:')), column(2, align = 'left', br(), checkboxInput(inputId = 'lorenz_use_prev', label = '', value = FALSE), bsTooltip("lorenz_use_prev", "Use model from Regression Tab.", "left", options = list(container = "body")) ) ), fluidRow( column(12, align = 'center', br(), br(), actionButton(inputId = 'submit_lorenz', label = 'Submit', width = '120px', icon = icon('check')), bsTooltip("submit_lorenz", "Click here to view Lorenz curve.", "bottom", options = list(container = "body"))) ), fluidRow( br(), column(2), column(8, align = 'center', plotOutput('lorenz_out')), column(2) ) ) )
/scratch/gouwar.j/cran-all/cranData/xplorerr/inst/app-blorr/ui/ui_lorenz_curve.R
tabPanel('Regression', value = 'tab_reg', icon = icon('cubes'), navlistPanel(id = 'navlist_reg', well = FALSE, widths = c(2, 10), source('ui/ui_regress.R', local = TRUE)[[1]], source('ui/ui_model_fit_stats.R', local = TRUE)[[1]], source('ui/ui_multi_model_fit_stats.R', local = TRUE)[[1]] ) )
/scratch/gouwar.j/cran-all/cranData/xplorerr/inst/app-blorr/ui/ui_mlr.R
tabPanel('Model Fit Stats - I', value = 'tab_model_fit_stats', fluidPage( br(), fluidRow( column(6, align = 'left', h4('Model Fit Statistics') ), column(6, align = 'right', actionButton(inputId='cdiaglink1', label="Help", icon = icon("question-circle"), onclick ="window.open('https://blorr.rsquaredacademy.com/reference/blr_model_fit_stats.html', '_blank')") ) ), hr(), fluidRow( column(2, align = 'right', br(), h5('Model Formula:')), column(10, align = 'left', textInput("mfs_fmla", label = '', width = '660px', value = ""), bsTooltip("mfs_fmla", "Specify model formula", "left", options = list(container = "body"))) ), fluidRow( column(2, align = 'right', br(), h5('Use previous model:')), column(2, align = 'left', br(), checkboxInput(inputId = 'mfs_use_prev', label = '', value = FALSE), bsTooltip("mfs_use_prev", "Use model from Regression Tab.", "left", options = list(container = "body")) ) ), fluidRow( column(12, align = 'center', br(), br(), actionButton(inputId = 'submit_mfs', label = 'Submit', width = '120px', icon = icon('check')), bsTooltip("submit_mfs", "Click here to view model fit statistics.", "bottom", options = list(container = "body"))) ), fluidRow( br(), column(12, align = 'center', verbatimTextOutput('mfs')) ) ) )
/scratch/gouwar.j/cran-all/cranData/xplorerr/inst/app-blorr/ui/ui_model_fit_stats.R
tabPanel('Model Building', value = 'tab_model_home', fluidPage( fluidRow( br(), column(12, align = 'center', h3('What do you want to do?') ), br(), br() ), fluidRow( column(12), br(), column(3), column(4, align = 'left', h5('Bivariate Analysis') ), column(2, align = 'left', actionButton( inputId = 'model_bivar_click', label = 'Click Here', width = '120px' ) ), column(3), br(), br(), br(), column(3), column(4, align = 'left', h5('Regression') ), column(2, align = 'left', actionButton( inputId = 'model_regress_click', label = 'Click Here', width = '120px' ) ), column(3), br(), br(), br(), column(3), column(4, align = 'left', h5('Model Fit Statistics') ), column(2, align = 'left', actionButton( inputId = 'model_fitstat_click', label = 'Click Here', width = '120px' ) ), column(3), br(), br(), br(), column(3), column(4, align = 'left', h5('Variable Selection') ), column(2, align = 'left', actionButton( inputId = 'model_varsel_click', label = 'Click Here', width = '120px' ) ), column(3), br(), br(), br(), column(3), column(4, align = 'left', h5('Model Validation') ), column(2, align = 'left', actionButton( inputId = 'model_validation_click', label = 'Click Here', width = '120px' ) ), column(3), br(), br(), br(), column(3), column(4, align = 'left', h5('Residual Diagnostics') ), column(2, align = 'left', actionButton( inputId = 'model_resdiag_click', label = 'Click Here', width = '120px' ) ), column(3) ) ) )
/scratch/gouwar.j/cran-all/cranData/xplorerr/inst/app-blorr/ui/ui_model_home.R
tabPanel('Model Fit Stats - 2', value = 'tab_multi_model_fit_stats', fluidPage( br(), fluidRow( column(6, align = 'left', h4('Multiple Model Fit Statistics') ), column(6, align = 'right', actionButton(inputId='cdiaglink1', label="Help", icon = icon("question-circle"), onclick ="window.open('https://blorr.rsquaredacademy.com/reference/blr_multi_model_fit_stats.html', '_blank')") ) ), hr(), fluidRow( column(2, align = 'right', br(), h5('Model 1:')), column(10, align = 'left', textInput("mmfs_fmla_1", label = '', width = '660px', value = ""), bsTooltip("mmfs_fmla_1", "Specify model formula", "left", options = list(container = "body"))) ), fluidRow( column(2, align = 'right', br(), h5('Model 2:')), column(10, align = 'left', textInput("mmfs_fmla_2", label = '', width = '660px', value = ""), bsTooltip("mmfs_fmla_2", "Specify model formula", "left", options = list(container = "body"))) ), fluidRow( column(12, align = 'center', br(), br(), actionButton(inputId = 'submit_mmfs', label = 'Submit', width = '120px', icon = icon('check')), bsTooltip("submit_mmfs", "Click here to view multiple model fit statistics.", "bottom", options = list(container = "body"))) ), fluidRow( br(), column(12, align = 'center', verbatimTextOutput('mmfs')) ) ) )
/scratch/gouwar.j/cran-all/cranData/xplorerr/inst/app-blorr/ui/ui_multi_model_fit_stats.R
tabPanel('Partition', value = 'tab_partition', icon = icon('cut'), fluidPage( fluidRow( column(6, align = 'left', h4('Partition Data'), p('Click on Yes to partition data into training and test set.') ), column(6, align = 'right', actionButton(inputId='partitionlink', label="Demo", icon = icon("video-camera"), onclick ="window.open('https://www.youtube.com/watch?v=X8b0beNJ64A#t=04m24s', '_blank')") ) ), hr(), fluidRow( column(12, align = 'center', h4('Do you want to partition data into training set and testing set?') ) ), fluidRow( column(6, align = 'right', actionButton( inputId = 'button_split_yes', label = 'Yes', width = '120px' ) ), column(6, align = 'left', actionButton( inputId = 'button_split_no', label = 'No', width = '120px' ) ) ), br(), br(), fluidRow( uiOutput('ui_partition') ) ) )
/scratch/gouwar.j/cran-all/cranData/xplorerr/inst/app-blorr/ui/ui_partition.R
tabPanel('Regression', value = 'tab_regress', fluidPage( br(), fluidRow( column(6, align = 'left', h4('Binary Logistic Regression'), p('Maximum likelihood estimation.') ), column(6, align = 'right', actionButton(inputId='mlr1', label="Help", icon = icon("question-circle"), onclick ="window.open('https://blorr.rsquaredacademy.com/reference/blr_regress.html', '_blank')") ) ), hr(), fluidRow( column(2, align = 'right', br(), h5('Model Formula:')), column(10, align = 'left', textInput("regress_fmla", label = '', width = '660px', value = ""), bsTooltip("regress_fmla", "Specify model formula", "left", options = list(container = "body"))) ), fluidRow( column(12, align = 'center', br(), br(), actionButton(inputId = 'submit_regress', label = 'Submit', width = '120px', icon = icon('check')), bsTooltip("submit_regress", "Click here to view regression result.", "bottom", options = list(container = "body"))) ), fluidRow( br(), uiOutput('reg1_title'), # column(12, align = 'center', h4('Regression Result')), hr(), column(12, align = 'center', verbatimTextOutput('regress_out')), hr() ) ) )
/scratch/gouwar.j/cran-all/cranData/xplorerr/inst/app-blorr/ui/ui_regress.R
tabPanel('Residual Diagnostics', value = 'tab_resid', icon = icon('cubes'), navlistPanel(id = 'navlist_resid', well = FALSE, widths = c(2, 10), source('ui/ui_diag_influence.R', local = TRUE)[[1]], source('ui/ui_diag_leverage.R', local = TRUE)[[1]], source('ui/ui_diag_fit.R', local = TRUE)[[1]], source('ui/ui_dfbetas_panel.R', local = TRUE)[[1]] ) )
/scratch/gouwar.j/cran-all/cranData/xplorerr/inst/app-blorr/ui/ui_resid_diag.R
tabPanel('ROC Curve', value = 'tab_roc_curve', fluidPage( br(), fluidRow( column(6, align = 'left', h4('ROC Curve') ), column(6, align = 'right', actionButton(inputId='roclink', label="Help", icon = icon("question-circle"), onclick ="window.open('https://blorr.rsquaredacademy.com/reference/blr_roc_curve.html', '_blank')") ) ), hr(), fluidRow( column(2, align = 'right', br(), h5('Model Formula:')), column(10, align = 'left', textInput("roc_fmla", label = '', width = '660px', value = ""), bsTooltip("roc_fmla", "Specify model formula", "left", options = list(container = "body"))) ), fluidRow( column(2, align = 'right', br(), h5('Use previous model:')), column(2, align = 'left', br(), checkboxInput(inputId = 'roc_use_prev', label = '', value = FALSE), bsTooltip("roc_use_prev", "Use model from Regression Tab.", "left", options = list(container = "body")) ) ), fluidRow( column(2, align = 'right', br(), h5('Use test data:')), column(2, align = 'left', br(), checkboxInput(inputId = 'roc_use_test_data', label = '', value = FALSE), bsTooltip("roc_use_test_data", "Use the test/validation data.", "left", options = list(container = "body")) ) ), fluidRow( column(12, align = 'center', br(), br(), actionButton(inputId = 'submit_roc', label = 'Submit', width = '120px', icon = icon('check')), bsTooltip("submit_roc", "Click here to view ROC curve.", "bottom", options = list(container = "body"))) ), fluidRow( br(), column(2), column(8, align = 'center', plotOutput('roc_out')), column(2) ) ) )
/scratch/gouwar.j/cran-all/cranData/xplorerr/inst/app-blorr/ui/ui_roc_curve.R
tabPanel('Sample', value = 'tab_sample', icon = icon('random'), fluidPage( fluidRow( column(6, align = 'left', h4('Sample Data'), p('Click on Yes to create a random sample of data.') ), column(6, align = 'right', actionButton(inputId='samplelink', label="Demo", icon = icon("video-camera"), onclick ="window.open('https://www.youtube.com/watch?v=X8b0beNJ64A#t=03m47s', '_blank')") ) ), hr(), fluidRow( column(12, align = 'center', h4('Draw a random sample of the data?') ) ), fluidRow( column(6, align = 'right', actionButton( inputId = 'button_sample_yes', label = 'Yes', width = '120px' ) ), column(6, align = 'left', actionButton( inputId = 'button_sample_no', label = 'No', width = '120px' ) ) ), br(), br(), fluidRow( column(12, align = 'center', uiOutput('samp_yes_no') ), br(), br() # column(12, align = 'center', # uiOutput('samp_no_yes') # ) ), fluidRow( br(), br(), uiOutput('samp_per_option') ), fluidRow( uiOutput('samp_obs_option') ) ) )
/scratch/gouwar.j/cran-all/cranData/xplorerr/inst/app-blorr/ui/ui_sample.R
tabPanel('Screen', value = 'tab_scr', icon = icon('binoculars'), navlistPanel(id = 'navlist_scr', well = FALSE, widths = c(2, 10), source('ui/ui_screen.R', local = TRUE)[[1]] ) )
/scratch/gouwar.j/cran-all/cranData/xplorerr/inst/app-blorr/ui/ui_scr.R
tabPanel('Screen', value = 'tab_screen', fluidPage( fluidRow( column(8, align = 'left', h4('Data Screening'), p('Screen data for missing values, verify variable names and data types.') ), column(4, align = 'right', actionButton(inputId='dscreenlink1', label="Help", icon = icon("question-circle"), onclick ="window.open('www.rsquaredacademy.com/descriptr/reference/ds_screener.html', '_blank')"), actionButton(inputId='dscreenlink3', label="Demo", icon = icon("video-camera"), onclick ="window.open('https://www.youtube.com/watch?v=X8b0beNJ64A#t=03m09s', '_blank')") ) ), hr(), fluidRow( column(12, align = 'center', verbatimTextOutput('screen') ) ), fluidRow( br(), column(12, align = 'center', actionButton('finalok', 'Approve', width = '120px', icon = icon('sign-out')), bsTooltip("finalok", "Click here to approve the data.", "top", options = list(container = "body")) ) ) ) )
/scratch/gouwar.j/cran-all/cranData/xplorerr/inst/app-blorr/ui/ui_screen.R
tabPanel('Segment', value = 'tab_segment')
/scratch/gouwar.j/cran-all/cranData/xplorerr/inst/app-blorr/ui/ui_segment.R
tabPanel('Segment Distribution', value = 'tab_segment_dist', fluidPage( fluidRow( column(6, align = 'left', h4('Segment Distribution') ), column(6, align = 'right', actionButton(inputId='segdistlink1', label="Help", icon = icon("question-circle"), onclick ="window.open('https://blorr.rsquaredacademy.com/reference/blr_segment_dist.html', '_blank')") ) ), hr(), fluidRow( column(2, align = 'right', br(), h5('Response Variable:')), column(4, align = 'left', selectInput("resp_segdist", label = '', choices = '', selected = '')), bsTooltip("resp_segdist", "Select response variable.", "left", options = list(container = "body")) ), fluidRow( column(2, align = 'right', br(), h5('Predictor Variable:')), column(10, align = 'left', selectInput("var_segdist", label = '', choices = "", selected = ""), bsTooltip("var_segdist", "Select predictor.", "left", options = list(container = "body"))) ), fluidRow( column(12, align = 'center', br(), br(), actionButton(inputId = 'submit_segdist', label = 'Submit', width = '120px', icon = icon('check')), bsTooltip("submit_segdist", "Click here to view segment distribution.", "bottom", options = list(container = "body"))) ), fluidRow( br(), column(12, align = 'center', verbatimTextOutput('segdist_out') ) ), fluidRow( br(), column(12, align = 'center', plotOutput('segdist_plot', height = "500px", width = "75%") ) ) ) )
/scratch/gouwar.j/cran-all/cranData/xplorerr/inst/app-blorr/ui/ui_segment_dist.R