content
stringlengths
0
14.9M
filename
stringlengths
44
136
#Calculate statistics max3Sign <- function(T.max, cor.rec.add, cor.rec.dom, cor.add.dom) { sigma <- matrix(c(1,cor.rec.dom,cor.rec.dom,1),ncol=2) let <- 1-cor.rec.dom^2 w0 <- (cor.rec.add - cor.rec.dom * cor.add.dom)/let w1 <- (cor.add.dom - cor.rec.dom * cor.rec.add)/let wet <- sqrt(let) f1 <- function(z0) { L <- length(z0) qet <- double(L) for (i in 1:L) { qet[i] <- pnorm((T.max-cor.rec.dom*z0[i])/wet) * dnorm(z0[i]) } qet } f2 <- function(z0) { L <- length(z0) qet <- double(L) for (i in 1:L) { qet[i] <- pnorm(((T.max-w0*z0[i])/w1-cor.rec.dom*z0[i])/wet) * dnorm(z0[i]) } qet } f3 <- function(z0) { L <- length(z0) qet <- double(L) for (i in 1:L) { qet[i] <- pnorm((-T.max-cor.rec.dom*z0[i])/wet) * dnorm(z0[i]) } qet } x1 <- integrate(f1, 0, T.max*(1-w1)/w0, subdivisions=10000, rel.tol=1e-10)$value x2 <- integrate(f2, T.max*(1-w1)/w0, T.max,subdivisions=10000, rel.tol=1e-10)$value x3 <- integrate(f3, 0, T.max, subdivisions=10000, rel.tol=1e-10)$value p.value <- 1-2*(x1+x2-x3) p.value }
/scratch/gouwar.j/cran-all/cranData/AssocTests/R/MAX3Sign.R
##' Conduct MAX3 (the maximal value of the three Cochran-Armitage ##' trend tests derived for the recessive, additive, and dominant ##' models) based on the trend tests without the adjustment of the ##' covariates or based on the Wald tests with the adjustment of the ##' covariates to test for the association between a single-nucleotide ##' polymorphism and the binary phenotype. ##' ##' In an association study, the genetic inheritance models ##' (recessive, additive, or dominant) are unknown beforehand. This ##' function can account for the uncertainty of the underlying genetic ##' models and test for the association between a single-nucleotide ##' polymorphism and a binary phenotype with or without correcting for ##' the covariates. ##' @title Maximum Test: maximum value of the three Cochran-Armitage ##' trend tests under the recessive, additive, and dominant models ##' @param y a numeric vector of the observed trait values in which ##' the \emph{i}th element is for the \emph{i}th subject. The elements ##' should be \code{0} or \code{1}. ##' @param g a numeric vector of the observed genotype values (\code{0}, \code{1}, ##' or \code{2} denotes the number of risk alleles) in which the \emph{i}th ##' element is for the \emph{i}th subject. The missing value is ##' represented by \code{NA}. \code{g} has the same length as \code{y}. ##' @param covariates a numeric matrix for the covariates used in the ##' model. Each column is for one covariate. The default is \code{NULL}, that ##' is, there are no covariates to be adjusted for. ##' @param Score.test logical. If \code{TRUE}, the score tests are used. One ##' of \code{Score.test} and \code{Wald.test} should be \code{FALSE}, ##' and the other should be \code{TRUE}. The default is \code{TRUE}. ##' @param Wald.test logical. If \code{TRUE}, the Wald tests are used. One of ##' \code{Score.test} and \code{Wald.test} should be \code{FALSE}, ##' and the other should be \code{TRUE}. The default is \code{FALSE}. ##' @param rhombus.formula logical. If \code{TRUE}, the p-value for the MAX3 ##' is approximated by the rhombus formula. IF \code{FALSE}, the 2-fold ##' integration is used to calculate the p-value. The default is ##' \code{FALSE}. ##' @return A list with class "\code{htest}" containing the following components: ##' \tabular{llll}{ ##' \code{statistic} \tab \tab \tab \cr ##' \tab \tab \tab the observed value of the test statistic.\cr ##' \code{p.value} \tab \tab \tab \cr ##' \tab \tab \tab the p-value for the test.\cr ##' \code{alternative} \tab \tab \tab \cr ##' \tab \tab \tab a character string describing the alternative hypothesis.\cr ##' \code{method} \tab \tab \tab \cr ##' \tab \tab \tab a character string indicating the type of test performed.\cr ##' \code{data.name} \tab \tab \tab \cr ##' \tab \tab \tab a character string giving the names of the data. ##' } ##' @author Lin Wang, Wei Zhang, and Qizhai Li. ##' @references Lin Wang, Wei Zhang, and Qizhai Li. AssocTests: An R Package ##' for Genetic Association Studies. \emph{Journal of Statistical Software}. ##' 2020; 94(5): 1-26. ##' @references Q Li, G Zheng, Z Li, and K Yu. Efficient Approximation ##' of P Value of the Maximum of Correlated Tests, with Applications ##' to Genome-Wide Association Studies. \emph{Annals of Human ##' Genetics}. 2008; 72(3): 397-406. ##' @examples ##' y <- rep(c(0, 1), 5) ##' g <- sample(c(0, 1, 2), 10, replace = TRUE) ##' max3(y, g, covariates = NULL, Score.test = TRUE, Wald.test = FALSE, ##' rhombus.formula = FALSE) ##' max3(y, g, covariates = matrix(sample(c(0,1), 20, replace = TRUE), ncol=2), ##' Score.test = TRUE, Wald.test = FALSE, rhombus.formula = FALSE) ##' @export max3 <- function(y, g, covariates = NULL, Score.test = TRUE, Wald.test = FALSE, rhombus.formula = FALSE) { a <- deparse(substitute(y)) b <- deparse(substitute(g)) dex <- which(!is.na(g)) g <- g[dex] y <- y[dex] if (!is.null(covariates)) { covariates <- as.matrix(covariates[dex,]) N <- length(g) g <- matrix(data=g, ncol=1) outcome <- rep(y, each=3) x.mat <- ChangeX(N, g, covariates=covariates, num.test=3) L <- ncol(covariates) C.mat <- matrix(data=0, nrow=3, ncol=ncol(x.mat)) C.mat[1,L+2] <- 1 C.mat[2,2*L+4] <- 1 C.mat[3,3*L+6] <- 1 if (Wald.test) { temp <- WaldTest(x.mat, outcome, num.test=3, C.mat) T.max <- max(abs(temp[[1]])) cor.rec.add <- temp[[2]][1,2] cor.rec.dom <- temp[[2]][1,3] cor.add.dom <- temp[[2]][2,3] if (rhombus.formula) { cor1 <- c(1, cor.rec.add, cor.rec.dom) cor2 <- c(cor.rec.add, 1, cor.add.dom) cor3 <- c(cor.rec.dom, cor.add.dom, 1) cor.matrix <- rbind(cor1, cor2, cor3) p.value <- RhombusFormula(cor.matrix, T.max) }else { p.value <- max3Sign(T.max, cor.rec.add, cor.rec.dom, cor.add.dom) } }else { id.null <- c(1:(L+1), (L+3):(2*L+3), (2*L+5):(3*L+5)) temp <- ScoreTest(x.mat, outcome, num.test=3, C.mat, id.null) T.max <- max(abs(temp[[1]])) cor.rec.add <- temp[[2]][1,2] cor.rec.dom <- temp[[2]][1,3] cor.add.dom <- temp[[2]][2,3] if (rhombus.formula) { cor1 <- c(1, cor.rec.add, cor.rec.dom) cor2 <- c(cor.rec.add, 1, cor.add.dom) cor3 <- c(cor.rec.dom, cor.add.dom, 1) cor.matrix <- rbind(cor1, cor2, cor3) p.value <- RhombusFormula(cor.matrix, T.max) }else { p.value <- max3Sign(T.max, cor.rec.add, cor.rec.dom, cor.add.dom) } } }else { ri <- c(sum(g==0 & y==1), sum(g==1 & y==1), sum(g==2 & y==1)) si <- c(sum(g==0 & y==0), sum(g==1 & y==0), sum(g==2 & y==0)) # T.rec <- TrendTest(0.0, ri=ri, si=si) # T.add <- TrendTest(0.5, ri=ri, si=si) # T.dom <- TrendTest(1.0, ri=ri, si=si) T.rec <- TrendTest(ri=ri, si=si, 0.0)$test.stat T.add <- TrendTest(ri=ri, si=si, 0.5)$test.stat T.dom <- TrendTest(ri=ri, si=si, 1.0)$test.stat T.max <- max(T.rec, T.add, T.dom) p <- (ri+si)/(sum(ri+si)+1e-10) p0 <- ifelse(p[1]<1e-10, 1e-10, p[1]) p0 <- ifelse(p[1]>1-1e-10, 1-1e-10, p[1]) p1 <- ifelse(p[2]<1e-10, 1e-10, p[2]) p1 <- ifelse(p[2]>1-1e-10, 1-1e-10, p[2]) p2 <- ifelse(p[3]<1e-10, 1e-10, p[3]) p2 <- ifelse(p[3]>1-1e-10, 1-1e-10, p[3]) cor.rec.add <- p2*(2*p0+p1)/sqrt(p2*(1-p2))/sqrt(p0*(p1+2*p2)+p2*(p1+2*p0)) cor.rec.dom <- p0*p2/sqrt(p0*(1-p0))/sqrt(p2*(1-p2)) cor.add.dom <- p0*(p1+2*p2)/sqrt(p0*(1-p0))/sqrt(p0*(p1+2*p2)+p2*(p1+2*p0)) cor.matrix <- matrix(data=c(1, cor.rec.add, cor.rec.dom, cor.rec.add, 1, cor.add.dom, cor.rec.dom, cor.add.dom, 1), nrow=3, ncol=3, byrow=TRUE) #1-pmvnorm(lower=-c(T.max,T.max,T.max),upper=c(T.max,T.max,T.max),sigma=cor.matrix) if (rhombus.formula) { p.value <- RhombusFormula(cor.matrix, T.max) }else { p.value <- max3Sign(T.max, cor.rec.add, cor.rec.dom, cor.add.dom) } } pv <- min(1,p.value) structure( list(statistic=c(MAX3 = T.max), p.value = pv, alternative = "the phenotype is significantly associated with the genotype", method = "MAX3 test", data.name = paste(a, "and", b, sep=" ") ), .Names=c("statistic", "p.value", "alternative", "method", "data.name"), class="htest" ) }
/scratch/gouwar.j/cran-all/cranData/AssocTests/R/MAX3_main.R
## multidimensional scaling MDS <- function(S, n, TopK, SignEigenPoint) { H <- diag(n) - matrix(data=1, nrow=n, ncol=n)/n B <- H %*% S %*% H CL <- eigen(B) Val <- CL$values Vec <- CL$vectors # Significante Eigenvalues if (is.null(TopK)) { # TopK <- FindTopK (Val, n, SignEigenPoint) TopK <- tw(Val, n, SignEigenPoint)$SigntEigenL if (TopK < 1) TopK <- 1 TopK <- min(TopK,10) } res <- matrix(data=0, nrow=n, ncol=TopK) for (i in 1:TopK) { res[,i] <- Vec[, i]*sqrt(Val[i]) } res }
/scratch/gouwar.j/cran-all/cranData/AssocTests/R/MDS.R
## modify.normalize marker ModifyNormalization <- function (x) { x <-as.vector(x) dex <- which(!is.na(x)) row.sum <- sum(x[dex]) row.valid <- length(dex) row.mean <- row.sum/row.valid p <- (row.sum+0.5)/(1+row.valid) y <- rep(0,length(x)) y[dex] <- (x[dex]-row.mean)/sqrt(p*(1-p)) y }
/scratch/gouwar.j/cran-all/cranData/AssocTests/R/ModifyNormalization.R
##' Test for the association between a biallelic SNP and a ##' quantitative trait using the maximum value of the three ##' nonparametric trend tests derived for the recessive, additive, and ##' dominant models. It is a robust procedure against the genetic ##' models. ##' ##' Under the null hypothesis of no association, the vector of the ##' three nonparametric tests under the recessive, additive, and ##' dominant models asymptotically follows a three-dimensional normal ##' distribution. The p-value can be calculated using the function ##' \link{pmvnorm} in the R package "\pkg{mvtnorm}". ##' ##' This test is different from the MAX3 test using in the function ##' \link{max3}. On one hand, the NMAX3 applies to the quantitative ##' traits association studies. However, the MAX3 is used in the ##' case-control association studies. On the other hand, the NMAX3 is ##' based on the nonparametric trend test. However, the MAX3 is based ##' on the Cochran-Armitage trend test. ##' ##' @title NMAX3 based on the maximum value of the three nonparametric trend tests ##' under the recessive, additive, and dominant models ##' @param y a numeric vector of the observed quantitative trait ##' values in which the \emph{i}th element is the trait value of the ##' \emph{i}th subject. ##' @param g a numeric vector of the observed genotype values (\code{0}, \code{1}, ##' or \code{2} denotes the number of risk alleles) in which the \emph{i}th ##' element is the genotype value of the \emph{i}th subject for a ##' biallelic SNP. \code{g} has the same length as \code{y}. ##' @return A list with class "\code{htest}" containing the following components: ##' \tabular{llll}{ ##' \code{statistic} \tab \tab \tab \cr ##' \tab \tab \tab the observed value of the test statistic.\cr ##' \code{p.value} \tab \tab \tab \cr ##' \tab \tab \tab the p-value for the test.\cr ##' \code{alternative} \tab \tab \tab \cr ##' \tab \tab \tab a character string describing the alternative hypothesis.\cr ##' \code{method} \tab \tab \tab \cr ##' \tab \tab \tab a character string indicating the type of test performed.\cr ##' \code{data.name} \tab \tab \tab \cr ##' \tab \tab \tab a character string giving the names of the data. ##' } ##' @author Lin Wang, Wei Zhang, and Qizhai Li. ##' @references Lin Wang, Wei Zhang, and Qizhai Li. AssocTests: An R Package ##' for Genetic Association Studies. \emph{Journal of Statistical Software}. ##' 2020; 94(5): 1-26. ##' @references W Zhang and Q Li. Nonparametric Risk and Nonparametric ##' Odds in Quantitative Genetic Association Studies. \emph{Science ##' Reports (2nd revision)}. 2015. ##' @references B Freidlin, G Zheng, Z Li, and JL Gastwirth. Trend ##' Tests for Case-Control Studies of Genetic Markers: Power, Sample ##' Size and Robustness. \emph{Human Heredity}. 2002; 53:146-152. ##' @references WG Cochran. Some Methods for Strengthening the Common ##' Chi-Square Tests. \emph{Biometrics}. 1954; 10:417-451. ##' @references P Armitage. Tests for Linear Trends in Proportions and ##' Frequencies. \emph{Biometrics}. 1955; 11:375-386. ##' @examples ##' g <- rbinom(1500, 2, 0.3) ##' y <- 0.5 + 0.25 * g + rgev(1500, 0, 0, 5) ##' nmax3(y, g) ##' @export nmax3 <- function(y, g) { Z.R <- npt(y, g, 0)[[1]] Z.A <- npt(y, g, 0.5)[[1]] Z.D <- npt(y, g, 1)[[1]] T.max <- max(abs(Z.R), abs(Z.A), abs(Z.D)) corr.mat <- CorrMatNRTest(y, g) ### calculate the p-value pval <- 1-mvtnorm::pmvnorm(lower=-c(T.max,T.max,T.max),upper=c(T.max,T.max,T.max),sigma=corr.mat)[1] a <- deparse(substitute(y)) b <- deparse(substitute(g)) structure( list(statistic = c(NMAX3 = T.max), p.value = pval, alternative = "the phenotype is significantly associated with the genotype", method = "Nonparametric MAX3 test", data.name = paste(a, "and", b, sep=" ") ), .Names=c("statistic", "p.value", "alternative", "method", "data.name"), class="htest" ) }
/scratch/gouwar.j/cran-all/cranData/AssocTests/R/NMAX3_main.R
##' Test for the association between a genetic variant and a ##' non-normal distributed quantitative trait based on the ##' nonparametric risk under a specific genetic model. ##' ##' For a non-normal distributed quantitative trait, three genetic ##' models (recessive, additive and dominant) used commonly are ##' defined in terms of the nonparametric risk (NR). The recessive, ##' additive, and dominant models can be classified based on the ##' nonparametric risks. More specifically, the recessive, additive, ##' and dominant models refer to NR20 > NR10 = 1/2, NR12 = NR10>1/2, and ##' NR10 = NR20 > 1/2, respectively, where NR10 and NR20 are the ##' nonparametric risks of the groups with the genotypes 1 and 2 ##' relative to the group with the genotype 0, respectively, and NR12 ##' is the nonparametric risk of the group with the genotype 2 ##' relative to the group with the genotype 1. ##' ##' \code{varphi} can be \code{0}, \code{0.5}, or \code{1} for the recessive, additive, or ##' dominant model, respectively. When \code{varphi} is \code{0}, the test is ##' constructed under the recessive model by pooling together the ##' subjects with the genotypes 0 and 1. Similarly, when \code{varphi} ##' is \code{1}, the test is constructed under the dominant model by pooling ##' together the subjects with the genotypes 1 and 2. When ##' \code{varphi} is \code{0.5}, the test is based on the weighted sum of ##' NR10 and NR12. ##' ##' @title Nonparametric trend test based on the nonparametric ##' risk under a given genetic model ##' @param y a numeric vector of the observed quantitative trait ##' values in which the \emph{i}th element corresponds to the trait ##' value of the \emph{i}th subject. ##' @param g a numeric vector of the observed genotype values (\code{0}, \code{1}, ##' or \code{2} denotes the number of risk alleles) in which the \emph{i}th ##' element is the genotype value of the \emph{i}th subject for a ##' biallelic SNP. \code{g} has the same length as \code{y}. ##' @param varphi a numeric value which represents the genetic ##' model. It should be \code{0}, \code{0.5}, or \code{1}, which indicates that the ##' calculation is performed under the recessive, additive, or ##' dominant model, respectively. ##' @return A list with class "\code{htest}" containing the following components: ##' \tabular{llll}{ ##' \code{statistic} \tab \tab \tab \cr ##' \tab \tab \tab the observed value of the test statistic.\cr ##' \code{p.value} \tab \tab \tab \cr ##' \tab \tab \tab the p-value for the test.\cr ##' \code{alternative} \tab \tab \tab \cr ##' \tab \tab \tab a character string describing the alternative hypothesis.\cr ##' \code{method} \tab \tab \tab \cr ##' \tab \tab \tab a character string indicating the type of test performed.\cr ##' \code{data.name} \tab \tab \tab \cr ##' \tab \tab \tab a character string giving the names of the data. ##' } ##' @author Lin Wang, Wei Zhang, and Qizhai Li. ##' @references Lin Wang, Wei Zhang, and Qizhai Li. AssocTests: An R Package ##' for Genetic Association Studies. \emph{Journal of Statistical Software}. ##' 2020; 94(5): 1-26. ##' @examples ##' g <- rbinom(1500, 2, 0.3) ##' y <- 0.5 + 0.25 * g + rgev(1500, 0, 0, 5) ##' npt(y, g, 0.5) ##' @export npt <- function(y, g, varphi) { if(varphi==0.5) { n0 <- sum(g==0) n1 <- sum(g==1) n2 <- sum(g==2) n <- n0 + n1 + n2 Y0 <- y[g==0] Y1 <- y[g==1] Y2 <- y[g==2] # genotype 1 relative to genotype 0 d0 <- 1:n0 d1 <- (n0+1):(n0+n1) RK1 <- rank(c(Y0,Y1)) rr1 <- ( sum(RK1[d1]) - n1*(n1+1)/2 ) / (n0*n1) #genotype 2 relative to genotype 0 d2 <- (n0+1):(n0+n2) RK2 <- rank(c(Y0,Y2)) rr2 <- ( sum(RK2[d2])- n2*(n2+1)/2 ) / (n0*n2) # genotype 2 relative to genotype 1 d3 <- (n1+1):(n1+n2) RK12 <- rank(c(Y1,Y2)) r12 <- (sum(RK12[d3])-n2*(n2+1)/2 ) /(n1*n2) # standard deviation temp1 <- rep(NA, n0) temp2 <- rep(NA, n0) for (i in 1:n0) { temp1[i] <- ( sum(Y1>Y0[i])/n1 - 1/2 )^2 temp2[i] <- ( sum(Y2>Y0[i])/n2 - 1/2 )^2 } temp3 <- rep(NA, n1) temp4 <- rep(NA, n2) for (j in 1:n1) { temp3[j] <- ( sum(Y0<Y1[j])/n0 - 1/2 )^2 } for (j in 1:n2) { temp4[j] <- ( sum(Y0<Y2[j])/n0 - 1/2 )^2 } temp5 <- rep(NA, n1) temp6 <- rep(NA, n1) for (j in 1:n1) { temp5[j] <- sum(Y0<Y1[j])/n0 - 1/2 temp6[j] <- sum(Y2>Y1[j])/n2 - 1/2 } temp7 <- temp6^2 temp8 <- rep(NA, n2) for(k in 1:n2) { temp8[k] <- (sum(Y1<Y2[k])/n1 - 1/2)^2 } ##the variance of the test for the Additive model rr1.var <- 1/(n0*n1) * ( (n1-1)/n0 *sum(temp1) + (n0-1)/n1*sum(temp3) + 1/4 ) rr2.var <- 1/(n0*n2) * ( (n2-1)/n0 *sum(temp2) + (n0-1)/n2*sum(temp4) + 1/4 ) r12.var <- 1/(n1*n2) * ( (n2-1)/n1 *sum(temp7) + (n1-1)/n2*sum(temp8) + 1/4 ) cov12 <- (1/n1)^2*sum(temp5*temp6) # estimate the final probability P(Y2>Y1) a1 <- sqrt((n0+n1)/rr1.var) a2 <- sqrt((n1+n2)/r12.var) w1 <- a1/(a1+a2) w2 <- a2/(a1+a2) eta1 <- w1*rr1 + w2*r12 eta1.var <- w1^2*rr1.var+ w2^2*r12.var+ 2*w1*w2*cov12 z <- (eta1-0.5)/sqrt(eta1.var) p.val <- 2*(1-pnorm(abs(z))) } else { #### under the recessive model or dominant model g[g==1] <- 2*varphi n0 <- sum(g==0) n2 <- sum(g==2) Y0 <- y[g==0] Y2 <- y[g==2] # genotype 2 relative to genotype 0 d2 <- (n0+1):(n0+n2) RK2 <- rank(c(Y0,Y2)) rr2 <- ( sum(RK2[d2])- n2*(n2+1)/2 ) / (n0*n2) # standard deviation temp2 <- rep(NA, n0) for (i in 1:n0) { temp2[i] <- ( sum(Y2>Y0[i])/n2 - 1/2 )^2 } temp4 <- rep(NA, n2) for (j in 1:n2) { temp4[j] <- ( sum(Y0<Y2[j])/n0 - 1/2 )^2 } rr2.var <- 1/(n0*n2) * ( (n2-1)/n0 *sum(temp2) + (n0-1)/n2*sum(temp4) + 1/4 ) rr2.sd <- sqrt(rr2.var) z <- (rr2-0.5)/rr2.sd p.val <- 2*(1-pnorm(abs(z))) } a <- deparse(substitute(y)) b <- deparse(substitute(g)) structure( list(statistic = c(NPT = z), p.value = p.val, alternative = "the phenotype is significantly associated with the genotype", method = "Nonparametric trend test", data.name = paste(a, "and", b, sep=" ") ), .Names=c("statistic", "p.value", "alternative", "method", "data.name"), class="htest" ) }
/scratch/gouwar.j/cran-all/cranData/AssocTests/R/NPT_main.R
##' Identify the clustered and continuous patterns of the genetic ##' variation using the PCoC, which calculates the principal ##' coordinates and the clustering of the subjects for correcting for ##' PS. ##' ##' The hidden population structure is a possible confounding effect ##' in the large-scale genome-wide association studies. Cases and ##' controls might have systematic differences because of the ##' unrecognized population structure. The PCoC procedure uses the ##' techniques from the multidimensional scaling and the clustering to ##' correct for the population stratification. The PCoC could be seen ##' as an extension of the EIGENSTRAT. ##' @title PCoC for correcting for population stratification ##' @param genoFile a txt file containing the genotypes (0, 1, 2, or ##' 9). The element of the file in Row \emph{i} and Column \emph{j} ##' represents the genotype at the \emph{i}th marker of the \emph{j}th ##' subject. 0, 1, and 2 denote the number of risk alleles, and 9 ##' (default) is for the missing genotype. ##' @param outFile.txt a txt file for saving the result of this ##' function. The default is "\code{pcoc.result.txt}". ##' @param n.MonteCarlo the number of times for the Monte Carlo ##' procedure. The default is \code{1000}. ##' @param num.splits the number of groups into which the markers are ##' split. The default is \code{10}. ##' @param miss.val the number representing the missing data in the ##' input data. The default is \code{9}. The element 9 for the missing data ##' in the \code{genoFile} should be changed according to the value of ##' \code{miss.val}. ##' @return A list of \code{principal.coordinates} and ##' \code{cluster}. \code{principal.coordinates} is the principal ##' coordinates and \code{cluster} is the clustering of the ##' subjects. If the number of clusters is only one, ##' \code{cluster} is omitted. ##' @author Lin Wang, Wei Zhang, and Qizhai Li. ##' @references Lin Wang, Wei Zhang, and Qizhai Li. AssocTests: An R Package ##' for Genetic Association Studies. \emph{Journal of Statistical Software}. ##' 2020; 94(5): 1-26. ##' @references Q Li and K Yu. Improved Correction for Population ##' Stratification in Genome-Wide Association Studies by Identifying ##' Hidden Population Structures. \emph{Genetic Epidemiology}. 2008; ##' 32(3): 215-226. ##' @references KV Mardia, JT Kent, and JM Bibby. Multivariate ##' Analysis. \emph{New York: Academic Press}. 1976. ##' @examples ##' pcocG.eg <- matrix(rbinom(4000, 2, 0.5), ncol = 40) ##' write.table(pcocG.eg, file = "pcocG.eg.txt", quote = FALSE, ##' sep = "", row.names = FALSE, col.names = FALSE) ##' pcoc(genoFile = "pcocG.eg.txt", outFile.txt = "pcoc.result.txt", ##' n.MonteCarlo = 50, num.splits = 10, miss.val = 9) ##' file.remove("pcocG.eg.txt", "pcoc.result.txt") ##' @export pcoc <- function(genoFile, outFile.txt="pcoc.result.txt", n.MonteCarlo = 1000, num.splits=10, miss.val=9) { ## read genotype file xStr <- readLines(con=genoFile) num.subject <- nchar(xStr[1]) num.marker <- length(xStr) ## calculate the lines of used to calculate similarity matrix each time if (num.splits==1) { num.lines <- num.marker cum.lines <- c(0,num.marker) }else { num.lines <- rep(0, num.splits) y <- floor(num.marker/num.splits) num.lines[1:(num.splits-1)] <- y num.lines[num.splits] <- num.marker - y*(num.splits-1) cum.lines <- cumsum(c(0, num.lines)) } ## calculate similarity matrix S <- matrix(data=0, nrow=num.subject, ncol=num.subject) for (i in 1:num.splits) { w <- (cum.lines[i]+1):cum.lines[i+1] x <- matrix(unlist(lapply(xStr[w], Str2Num)), nrow=num.lines[i], ncol=num.subject, byrow=TRUE) is.na(x[x==miss.val])<-T S <- S + SimilarityMatrix(x, num.lines[i]) rm(w,x) } S <- S/num.marker X <- MDS(S, num.subject, TopK=NULL, SignEigenPoint=2.0234) k <- FindCNumRandom(X, num.subject, kG=10, n.MonteCarlo) if (k>1) { F <- cluster::clara(X, k, samples=20, medoids.x=FALSE)$clustering V <- list(principal.coordinates=X, cluster=factor(F)) V1 <- data.frame(X, factor(F)) } else { V <- list(principal.coordinates=X) V1 <- data.frame(X) } write(t(V1), file=outFile.txt, ncolumns=ncol(V1), sep="\t") V }
/scratch/gouwar.j/cran-all/cranData/AssocTests/R/PCoC_main.R
## rhombus formula RhombusFormula <- function(cor.matrix, obs) { if (obs<=1e-4) return(1) cor.matrix[cor.matrix>1-1e-10] <- 1-1e-10 cor.matrix[cor.matrix<-1+1e-10] <- -1+1e-10 k <- ncol(cor.matrix) # number of statistics len.matrix <- acos(cor.matrix) loc.g <- function(x) { x^2 #+ 2*x^4/3 + 17*x^6/45 + 41*x^8/320 + 61*x^10/1728 + 3721*x^12/518400 } loc.f <- function(L, x) { if (L<=pi/2) qet <- 2*(pnorm(x*L/2)-0.5) + exp(-(x^2)*loc.g(L/2)/2)*(pnorm(x*(pi-L)/2)-pnorm(x*L/2)) else qet <- exp(-(x^2)*loc.g((pi-L)/2)/2)*(pnorm(x*L/2)-pnorm(x*(pi-L)/2)) + 2*(pnorm(x*(pi-L)/2)-0.5) qet/x } loc.phi <- function(dex) { L <- len.matrix[dex[1],dex[2]] loc.f(L, obs) } loc.app <- function(x) { b <- 0 for (i in k:2) { y <- cbind(x[1:(i-1)], x[i]) a <- apply(y,1,loc.phi) b <- b + min(a) } b } comb <- matrix(unlist(combinat::permn(k)),ncol=k, byrow=TRUE) #???????? res <- apply(comb, 1, loc.app) pv <- (k-2)*(pnorm(obs)-pnorm(-obs)-1) + 4*dnorm(obs)*min(res) min(max(pv, 0),1) }
/scratch/gouwar.j/cran-all/cranData/AssocTests/R/RhombusFormula.R
##' Conduct the single-marker test in an association study to test for ##' the association between the genotype at a biallelic marker and a ##' trait. ##' ##' Single-marker analysis is a core in many gene-based or ##' pathway-based procedures, such as the truncated p-value ##' combination and the minimal p-value. ##' @title Single-marker test ##' @param y a numeric vector of the observed trait values in which ##' the \emph{i}th element is for the \emph{i}th subject. The elements ##' could be discrete (\code{0} or \code{1}) or continuous. The missing value is ##' represented by \code{NA}. ##' @param g a numeric vector of the observed genotype values (\code{0}, \code{1}, ##' or \code{2} denotes the number of risk alleles) in which the \emph{i}th ##' element is for the \emph{i}th subject. The missing value is ##' represented by \code{NA}. \code{g} has the same length as \code{y}. ##' @param covariates an optional data frame, list or environment ##' containing the covariates used in the model. The default is \code{NULL}, ##' that is, there are no covariates. ##' @param min.count a critical value to decide which method is used ##' to calculate the p-value when the trait is discrete and \code{covariates ##' = NULL}. If the minimum number of the elements given a specific ##' trait value and a specific genotype value is less than ##' \code{min.count}, the Fisher's exact test is adopted; otherwise, the ##' Wald test is adopted. The default is \code{5}. ##' @param missing.rate the highest missing value rate of the genotype ##' values that this function can tolerate. The default is \code{0.2}. ##' @param y.continuous logical. If \code{TRUE}, \code{y} is continuous; ##' otherwise, \code{y} is discrete. The default is \code{FALSE}. ##' @return \code{smt} returns a list with class "\code{htest}". ##' ##' If y is continuous, the list contains the following components: ##' \tabular{llll}{ ##' \code{statistic} \tab \tab \tab \cr ##' \tab \tab \tab the observed value of the test statistic.\cr ##' \code{p.value} \tab \tab \tab \cr ##' \tab \tab \tab the p-value for the test.\cr ##' \code{alternative} \tab \tab \tab \cr ##' \tab \tab \tab a character string describing the alternative hypothesis.\cr ##' \code{method} \tab \tab \tab \cr ##' \tab \tab \tab a character string indicating the type of test performed.\cr ##' \code{data.name} \tab \tab \tab \cr ##' \tab \tab \tab a character string giving the names of the data. \cr ##' \code{sample.size} \tab \tab \tab \cr ##' \tab \tab \tab a vector giving the numbers of the subjects with the genotypes \code{0}, \code{1}, and \code{2} (\code{n0}, \cr ##' \tab \tab \tab \code{n1}, and \code{n2}, respectively). ##' } ##' If y is discrete, the list contains the following components: ##' \tabular{llll}{ ##' \code{statistic} \tab \tab \tab \cr ##' \tab \tab \tab the observed value of the test statistic.\cr ##' \code{p.value} \tab \tab \tab \cr ##' \tab \tab \tab the p-value for the test.\cr ##' \code{alternative} \tab \tab \tab \cr ##' \tab \tab \tab a character string describing the alternative hypothesis.\cr ##' \code{method} \tab \tab \tab \cr ##' \tab \tab \tab a character string indicating the type of test performed.\cr ##' \code{data.name} \tab \tab \tab \cr ##' \tab \tab \tab a character string giving the names of the data. \cr ##' \code{sample.size} \tab \tab \tab \cr ##' \tab \tab \tab a vector giving \cr ##' \tab \tab \tab the number of subjects with the trait value \code{1} and the genotype \code{0} (\code{r0}), \cr ##' \tab \tab \tab the number of subjects with the trait value \code{1} and the genotype \code{1} (\code{r1}), \cr ##' \tab \tab \tab the number of subjects with the trait value \code{1} and the genotype \code{2} (\code{r2}), \cr ##' \tab \tab \tab the number of subjects with the trait value \code{0} and the genotype \code{0} (\code{s0}), \cr ##' \tab \tab \tab the number of subjects with the trait value \code{0} and the genotype \code{1} (\code{s1}), \cr ##' \tab \tab \tab and the number of subjects with the trait value \code{0} and the genotype \code{2} (\code{s2}).\cr ##' \code{bad.obs} \tab \tab \tab \cr ##' \tab \tab \tab a vector giving the number of missing genotype values with the trait value \code{1} \cr ##' \tab \tab \tab (\code{r.miss}), the number of missing genotype values with the trait value \code{0} \cr ##' \tab \tab \tab (\code{s.miss}), and the total number of the missing genotype values (\code{n.miss}). ##' } ##' @author Lin Wang, Wei Zhang, and Qizhai Li. ##' @references Lin Wang, Wei Zhang, and Qizhai Li. AssocTests: An R Package ##' for Genetic Association Studies. \emph{Journal of Statistical Software}. ##' 2020; 94(5): 1-26. ##' @examples ##' y <- rep(c(0, 1), 25) ##' g <- sample(c(0, 1, 2), 50, replace = TRUE) ##' smt(y, g, covariates = NULL, min.count=5, ##' missing.rate=0.20, y.continuous = FALSE) ##' @export smt <- function(y, g, covariates=NULL, min.count=5, missing.rate=0.20, y.continuous=FALSE) { # g is the genotype vector taking 0, 1 and 2 # y is the outcome a <- deparse(substitute(y)) b <- deparse(substitute(g)) dex <- !is.na(g) & !is.na(y) g.valid <- g[dex] y.valid <- y[dex] # y is continuous if (y.continuous) { n0 <- sum(g.valid==0) n1 <- sum(g.valid==1) n2 <- sum(g.valid==2) if(is.null(covariates)) { temp <- lm(y~g) } else { temp <- lm(y~.+g, data=covariates) } a.1 <- summary(temp)$coefficients t.1 <- dim(a.1) p.value <- a.1[t.1[1], t.1[2]] res <- structure( list(p.value = p.value, alternative = "the phenotype is significantly associated with the genotype", method = "Single-marker test", data.name = paste(a, "and", b, sep=" "), sample.size = c(n0=n0, n1=n1, n2=n2) ), .Names=c("p.value", "alternative", "method", "data.name", "sample.size"), class="htest" ) return(res) } else { r0 <- sum(g.valid==0 & y.valid==1) r1 <- sum(g.valid==1 & y.valid==1) r2 <- sum(g.valid==2 & y.valid==1) s0 <- sum(g.valid==0 & y.valid==0) s1 <- sum(g.valid==1 & y.valid==0) s2 <- sum(g.valid==2 & y.valid==0) addr <- !is.na(y) u <- g[addr] v <- y[addr] r.miss <- sum(is.na(u[v==1])) s.miss <- sum(is.na(u[v==0])) n.miss <- sum(is.na(g)) # missing rate m.r <- sum(is.na(g))/length(g) if (m.r>=missing.rate) { res <- structure( list(p.value = -9999, alternative = "the phenotype is significantly associated with the genotype", method = "Single-marker test", data.name = paste(a, "and", b, sep=" "), sample.size = c(r0=r0, r1=r1, r2=r2, s0=s0, s1=s1, s2=s2), bad.obs = c(r.miss=r.miss, s.miss=s.miss, n.miss=n.miss) ), .Names=c("p.value", "alternative", "method", "data.name", "sample.size", "bad.obs"), class="htest" ) return(res) } else { if (min(CalExpect(matrix(c(r0,r1,r2,s0,s1,s2),nrow=2,byrow=TRUE)))>=min.count) { if (is.null(covariates)) { temp <- glm(y~g, family=binomial(link="logit")) } else { temp <- glm(y~.+g, family=binomial(link="logit"), data=covariates) } a.1 <- summary(temp)$coefficients t.1 <- dim(a.1) p.value <- a.1[t.1[1], t.1[2]] } else { if (s0 >= s2) { H <- matrix(c(r0,r1+r2,s0,s1+s2),ncol=2, byrow=TRUE) if (min(CalExpect(H))<min.count) { p.value <- fisher.test(H)$p.value } else { g[g==2] <- 1 if (is.null(covariates)) { temp <- glm(y~g, family=binomial(link="logit")) } else { temp <- glm(y~.+g, family=binomial(link="logit"), data=covariates) } a.1 <- summary(temp)$coefficients t.1 <- dim(a.1) p.value <- a.1[t.1[1], t.1[2]] } } else { H <- matrix(c(r0+r1,r2,s0+s1,s2),ncol=2,byrow=TRUE) if (min(CalExpect(H))<min.count) { p.value <- fisher.test(H)$p.value } else { g[g==1] <- 0 g[g==2] <- 1 if (is.null(covariates)) { temp <- glm(y~g, family=binomial(link="logit")) } else { temp <- glm(y~.+g, family=binomial(link="logit"), data=covariates) } a.1 <- summary(temp)$coefficients t.1 <- dim(a.1) p.value <- a.1[t.1[1], t.1[2]] } } } res <- structure( list(p.value = p.value, alternative = "the phenotype is significantly associated with the genotype", method = "Single-marker test", data.name = paste(a, "and", b, sep=" "), sample.size = c(r0=r0, r1=r1, r2=r2, s0=s0, s1=s1, s2=s2), bad.obs = c(r.miss=r.miss, s.miss=s.miss, n.miss=n.miss) ), .Names=c("p.value", "alternative", "method", "data.name", "sample.size", "bad.obs"), class="htest" ) return(res) } } }
/scratch/gouwar.j/cran-all/cranData/AssocTests/R/SMT_main.R
## id.null gives the column id under the null model ScoreTest <- function(x.mat, y, num.test=3, C.mat, id.null) { x.mat<-as.matrix(x.mat) num.subj<-dim(x.mat)[1]/num.test num.para<-dim(x.mat)[2] list.1<-num.test *(c(1:num.subj)-1)+1 ## to get the estimate from the null model x.mat.null<-data.frame(x.mat[list.1, id.null]) y0 <- y[list.1] model.null<-glm(y0~-1+., data=x.mat.null, family=binomial) model.sum<-summary(model.null) ## to get the bread.mat under the null p.vec<-rep(model.null$fitted.values, each=num.test) D.mat<-p.vec *(1-p.vec) temp.0<-scale(t(x.mat), center=F, scale=1/D.mat) temp.1<-temp.0 %*% x.mat ### inverse of information matrix bread.mat<-solve(temp.1) ## get the meat under the null res.vec<-y-p.vec score.mat<-scale(t(x.mat), center=F, scale=1/res.vec) score.vec<-apply(score.mat, 1, sum) score.vec<-matrix(score.vec, ncol=1, nrow=num.para) ## see Generalized estiation equations book page 87 list.mat<-matrix(0, ncol=num.test, nrow=num.subj) for (i in 1:num.test) { list.mat[,i]<-list.1 + (i-1) } acc.mat<-matrix(0, ncol=num.subj, nrow=num.para) for (i in 1:num.test) { acc.mat<-acc.mat + score.mat[, list.mat[,i]] } meat.mat<-acc.mat %*% t(acc.mat) sand.cov<-bread.mat %*% meat.mat %*% bread.mat score.select<-C.mat %*% score.vec bread.select<-C.mat %*% bread.mat %*% t(C.mat) sand.select<-C.mat %*% sand.cov %*% t(C.mat) temp.2<-solve(bread.select) cov.select<-temp.2 %*% sand.select %*% t(temp.2) #list(score.select=score.select, cov.select=cov.select) beta.cov <- cov.select beta.sd <- sqrt(diag(beta.cov)) T <- score.select/beta.sd cor.mat <- beta.cov/(cbind(beta.sd)%*%rbind(beta.sd)) list(T, cor.mat) }
/scratch/gouwar.j/cran-all/cranData/AssocTests/R/ScoreTest.R
## eigenstrat Correlation Matrix SimilarityMatrix <- function(x, k) { x <- x/2 if( k>1 ) { z <- apply(x, 1, ModifyNormalization) } else { z <- ModifyNormalization(x) z <- matrix(z, ncol=1) } z %*% t(z) }
/scratch/gouwar.j/cran-all/cranData/AssocTests/R/SimilarityMatrix.R
## transite a string into a serial of numbers Str2Num <- function(S) { y <- as.numeric(strsplit(S, '')[[1]]) return(y) }
/scratch/gouwar.j/cran-all/cranData/AssocTests/R/Str2Num.R
##' Find the significant eigenvalues of a matrix. ##' ##' @title Tracy-Widom test ##' @param eigenvalues a numeric vector whose elements are the ##' eigenvalues of a matrix. The values should be sorted in the ##' descending order. ##' @param eigenL the number of eigenvalues. ##' @param criticalpoint a numeric value corresponding to the ##' significance level. If the significance level is 0.05, 0.01, ##' 0.005, or 0.001, the \code{criticalpoint} should be set to be \code{0.9793}, ##' \code{2.0234}, \code{2.4224}, or \code{3.2724}, accordingly. The default is \code{2.0234}. ##' @return A list with class "\code{htest}" containing the following components: ##' \tabular{llll}{ ##' \code{statistic} \tab \tab \tab \cr ##' \tab \tab \tab a vector of the Tracy-Widom statistics.\cr ##' \code{alternative} \tab \tab \tab \cr ##' \tab \tab \tab a character string describing the alternative hypothesis.\cr ##' \code{method} \tab \tab \tab \cr ##' \tab \tab \tab a character string indicating the type of test performed.\cr ##' \code{data.name} \tab \tab \tab \cr ##' \tab \tab \tab a character string giving the name of the data. \cr ##' \code{SigntEigenL} \tab \tab \tab \cr ##' \tab \tab \tab the number of significant eigenvalues. ##' } ##' @author Lin Wang, Wei Zhang, and Qizhai Li. ##' @references Lin Wang, Wei Zhang, and Qizhai Li. AssocTests: An R Package ##' for Genetic Association Studies. \emph{Journal of Statistical Software}. ##' 2020; 94(5): 1-26. ##' @references N Patterson, AL Price, and D Reich. Population ##' Structure and Eigenanalysis. \emph{PloS Genetics}. 2006; 2(12): ##' 2074-2093. ##' @references CA Tracy and H Widom. Level-Spacing Distributions and ##' the Airy Kernel. \emph{Communications in Mathematical ##' Physics}. 1994; 159(1): 151-174. ##' @references A Bejan. Tracy-Widom and Painleve II: Computational ##' Aspects and Realisation in S-Plus. In \emph{First Workshop of the ERCIM ##' Working Group on Computing and Statistics}. 2008, Neuchatel, Switzerland. ##' @references A Bejan. Largest eigenvalues and sample covariance matrices. ##' \emph{MSc Dissertation, the university of Warwick}. 2005. (This function ##' was written by A Bejan and publicly downloadable.) ##' @examples ##' tw(eigenvalues = c(5, 3, 1, 0), eigenL = 4, criticalpoint = 2.0234) ##' @export tw <- function(eigenvalues, eigenL, criticalpoint=2.0234) { a <- deparse(substitute(eigenvalues)) dex <- which(eigenvalues <= 1e-8) eigenvalues[dex] <- 1e-8 L1 <- rev(cumsum(rev(eigenvalues))) L2 <- rev(cumsum(rev(eigenvalues^2))) N <- eigenL:1 S2 <- N^2*L2/(L1^2) v <- N*(N+2)/(S2-N) # Effective number of markers L <- N*eigenvalues/L1 v.st <- sqrt(v-1) N.st <- sqrt(N) mu <- (v.st+N.st)^2/v sig <- (v.st+N.st)/v * (1/v.st+1/N.st)^(1/3) twstat <-(L-mu)/sig #sink(output) #cat("TWstat = ", twstat, '\n') #sink() d <- which(twstat < criticalpoint)[1] if (length(d)==0) { d <- -100 }else { d <- d-1 } structure( list(statistic = c(TW = twstat), alternative = "the eigenvalue is significant", method = "Tracy-Widom test", data.name = a, SigntEigenL = d ), .Names=c("statistic", "alternative", "method", "data.name", "SigntEigenL"), class="htest" ) }
/scratch/gouwar.j/cran-all/cranData/AssocTests/R/TW_main.R
TrendTest <- function(ri, si, varphi = 0.5) { phi <- c(0,varphi,1) ni <- ri + si + 1e-10 r <- sum(ri) s1 <- sum(si) n <- r + s1 numerator <- sqrt(n) * sum(phi*(s1*ri-r*si)) denominator <- sqrt(r*s1*(n*sum(phi^2*ni)-(sum(phi*ni))^2)) z <- numerator/denominator pv = pnorm(-abs(z)) * 2 list(test.stat=z, p.val=pv) }
/scratch/gouwar.j/cran-all/cranData/AssocTests/R/TrendTest.R
## generate uniform distribution random samples UniformSample <- function(para) { runif(para[1], min=para[2], max=para[3]) }
/scratch/gouwar.j/cran-all/cranData/AssocTests/R/UniformSample.R
UniformTest <- function(H) { x <- H[1,1] y <- H[1,2] n1 <- sum(H[,1]) n2 <- sum(H[,2]) shape1 <- y + 1 shape2 <- n2-y+1 L <- qbeta(1e-10, shape1, shape2) U <- qbeta(1-1e-10, shape1, shape2) f <- function(k) { g <- function(p) { temp <- dbinom(k, n1, p) * dbeta(p, shape1, shape2) temp } qet <- integrate(g, lower=L, upper=U, subdivisions=100000, rel.tol=1e-10, abs.tol=1e-10)$value qet } b <- 0:x z <- sapply(b, f) z0 <- z[x+1] if (x<n1) { m <- x+1 a <- f(m) z <- c(z,a) while(a>=z0) { m <- m+1 if (m>n1) { break } a <- f(m) z <- c(z,a) } } pv<- 1 - sum(z[z>z0]) pv }
/scratch/gouwar.j/cran-all/cranData/AssocTests/R/UniformTest.R
WaldTest <- function(x.mat, y, num.test=3, C.mat) { x.mat<-as.matrix(x.mat) num.subj<-dim(x.mat)[1]/num.test num.para<-dim(x.mat)[2] ## to get the estimate model.full<-glm(y~-1+., data=data.frame(x.mat), family=binomial) model.sum<-summary(model.full) parms<-model.sum$coefficients[,1] parms<-matrix(parms, ncol=1, nrow=num.para) bread.mat<-model.sum$cov.scaled res.vec<-y-model.full$fitted.values score.mat<-scale(t(x.mat), center=F, scale=1/res.vec) ## accumulate seveal m of them list.mat<-matrix(0, ncol=num.test, nrow=num.subj) list.1<-num.test *(c(1:num.subj)-1)+1 for (i in 1:num.test) { list.mat[,i]<-list.1 + (i-1) } acc.mat<-matrix(0, ncol=num.subj, nrow=num.para) for (i in 1:num.test) { acc.mat<-acc.mat + score.mat[, list.mat[,i]] } meat.mat<-acc.mat %*% t(acc.mat) sand.cov<-bread.mat %*% meat.mat %*% bread.mat para.select<-C.mat %*% parms cov.select<-C.mat %*% sand.cov %*% t(C.mat) beta.cov <- cov.select beta.sd <- sqrt(diag(beta.cov)) T <- para.select/beta.sd cor.mat <- beta.cov/(cbind(beta.sd)%*%rbind(beta.sd)) list(T, cor.mat) }
/scratch/gouwar.j/cran-all/cranData/AssocTests/R/WaldTest.R
#' Asthma data sets from National Health and Nutritional Examination Survey #' #' Data sets and examples for National Health and Nutritional Examination Survey. #' #' It has two main goals: #' #' \itemize{ #' \item Provide data in an efficient way. #' \item Help doctors reproduce the results of "Serum cadmium and lead, current wheeze, and lung function in a nationwide study of adults in the United States". #' } #' #' @useDynLib AsthmaNHANES, .registration = TRUE #' @import rlang #' @importFrom assertthat assert_that is.flag on_failure<- #' @importFrom glue glue #' @importFrom Rcpp cppFunction Rcpp.plugin.maker #' @importFrom stats setNames update #' @importFrom utils head tail #' @importFrom methods is #' @importFrom pkgconfig get_config "_PACKAGE"
/scratch/gouwar.j/cran-all/cranData/AsthmaNHANES/R/AsthmaNHANES.R
#' @title Metal Data #' @docType data #' @name metal #' @keywords metal #' @format The metal data frame has 30,442 rows and 27 columns. #' \describe{ #' \item{RIAGENDR}{Gender of the sample person} #' \item{RIDAGEYR}{Best age in years of the sample person at time of screening} #' \item{RIDRETH1}{Recode of reported race and ethnicity information #' \item{WTMEC5YR}{Both interviewed and MEC examined sample persons} #' \item{SDMVPSU}{Masked Variance Unit Pseudo-PSU variable for variance estimation} #' \item{SDMVSTRA}{Masked variance unit pseudo-stratum variable for variance estimation} #' \item{BMXBMI}{Body mass index (kg/m^2)} #' \item{LBXBPB}{Lead (ug/dL)} #' \item{LBXBCD}{Cadmium (ug/L)} #' \item{LBXCOT}{Cotinine (ng/mL)} #' \item{MCQ010}{Ever been told you have asthma} #' \item{RDQ070}{Wheezing or whistling in chest - past year} #' \item{SMQ040}{Do you now smoke cigarettes?} #' \item{SMQ020}{Smoked at least 100 cigarettes in life} #' \item{MCQ035}{Still have asthma?} #' \item{OCD390G}{Kind of work you have done the longest} #' \item{HIQ011}{Covered by health insurance} #' \item{MCQ300B}{Close relative had asthma?} #' \item{INDHHIN2}{Annual household income} #' \item{ENQ090}{Close relative had asthma?} #' \item{ENXTR1Q}{Trial 1 FENO measurement (ppb)} #' \item{SPXNFVC}{Baseline 1st test spirometry, forced vital capacity} #' \item{SPXNFEV1}{Baseline 1st test spirometry, forced expiratory volume in the first 1 second} #' \item{SPDBRONC}{Best test FEV1/FVC ratio below Lower Limit of Normal and/or less than 0.7} #' \item{SPXBFVC}{Bronchodilator 2nd test spirometry, forced vital capacity} #' \item{SPXBFEV1}{Bronchodilator 2nd test spirometry, forced expiratory volume in the first 1 second} #' \item{LBXVIDMS}{25-hydroxyvitamin D2 and D3} #' } "metal" #' @title Percent Data #' @docType data #' @name percent #' @keywords percent #' @format The percent data frame has 40,979 rows and 6 columns. #' \describe{ #' \item{FEV1FVC_percent_predicted}{Percent predicted FEV1/FVC} #' \item{FEV1FVC_z_score}{Z score of FEV1/FVC} #' \item{FEV1_percent_predicted}{Percent predicted FEV1} #' \item{FEV1_z_score}{Z score of FEV1} #' \item{FVC_percent_predicted}{Percent predicted FVC} #' \item{FVC_z_score}{Z score of FVC} #' } "percent"
/scratch/gouwar.j/cran-all/cranData/AsthmaNHANES/R/data.R
#' AsyK #' #' Kernel Density Estimation #' #' @description A collection of functions related to density estimation by using Chen's (2000) idea. For observing estimated values see \code{\link{Laplace}} and \code{\link{RIG}}. Plots by using these kernels can be drawn by \code{\link{plot.Laplace}} and \code{\link{plot.RIG}}. Mean squared errors (MSE) can be calculated by \code{\link{mse}}. #' Here we also present a normal scale rule bandwidth which is given by Silverman (1986) for non-normal data. #'@author Javaria Ahmad Khan, Atif Akbar. "_PACKAGE" #' Estimated Density Values by Reciprocal Inverse Gaussian kernel #' #' Estimated Kernel density values by using Reciprocal Inverse Gaussian Kernel. #' @details Scaillet 2003. proposed Reciprocal Inverse Gaussian kerenl. He claimed that his proposed kernel share the same properties as those of gamma kernel estimator. #' \deqn{K_{RIG \left( \ln{ax}4\ln {(\frac{1}{h})} \right)}(y)=\frac{1}{\sqrt {2\pi y}} exp\left[-\frac{x-h}{2h} \left(\frac{y}{x-h}-2+\frac{x-h}{y}\right)\right]} #' @param y a numeric vector of positive values. #' @param x scheme for generating grid points #' @param k gird points. #' @param h the bandwidth #' @import stats #' @examples #' #Data can be simulated or real data #' ## Number of grid points "k" should be at least equal to the data size. #' ### If user define the generating scheme of gridpoints than number of gridpoints should #' ####be equal or greater than "k" #' ###### otherwise NA will be produced. #' y <- rexp(100, 1) #' xx <- seq(min(y) + 0.05, max(y), length = 100) #' h <- 2 #' den <- RIG(x = xx, y = y, k = 200, h = h) #' #' ##If scheme for generating gridpoints is unknown #' y <- rexp(50, 1) #' h <- 3 #' den <- RIG(y = y, k = 90, h = h) #' #'\dontrun{ #'##If user do not mention the number of grid points #'y <- rexp(23, 1) #'xx <- seq(min(y) + 0.05, max(y), length = 90) #'#any bandwidth can be used #'require(KernSmooth) #'h <- dpik(y) #'den <- RIG(x = xx, y = y, h = h) #'} #'#if bandwidth is missing #'y <- rexp(100, 1) #'xx <- seq(min(y) + 0.05, max(y), length = 100) #'den <- RIG(x = xx, y = y, k = 90) #' @return \item{x}{grid points} #' \item{y}{estimated values of density} #' @author Javaria Ahmad Khan, Atif Akbar. #' @references Scaillet, O. 2004. Density estimation using inverse and reciprocal inverse Gaussian kernels. \emph{Nonparametric Statistics}, \strong{16}, 217-226. #' @seealso To examine RIG density plot see \code{\link{plot.RIG}} and for Mean Squared Error \code{\link{mse}}. Similarly, for Laplace kernel \code{\link{Laplace}}. #' @export RIG <- function(x = NULL, y, k = NULL, h = NULL){ n <- length(y) if(is.null(x)) x = seq(min(y) + 0.05, max(y), length = k) if(is.null(k)) k = length(y) if(is.null(h)) h = 0.79 * IQR(y) * length(y) ^ (-1/5) fhat <- rep(0, k) KRIG <- matrix(rep(0, k * n), ncol = k) for(j in 1:k) { for(i in 1:n) { KRIG[i, j] <- 1/(sqrt(2 * pi * h * y[i])) * exp(((-1 *(y[i] - h))/(2 * h) * (x[j]/(y[i] - h) - 2 +(y[i] - h)/x[j]))) } fhat<- colMeans(KRIG) } results <- list(x = x, y = fhat) class ( results ) <-c('list', 'RIG') results } #' Density Plot by Reciprocal Inverse Gaussian kernel #' #' Plot density by using Reciprocal Inverse Gaussian Kernel. #' @param x an object of class "RIG" #' @param \dots Not presently used in this implementation #' @import graphics #' @import stats #' @examples #' y <- rexp(200, 1) #' h <- 0.79 * IQR(y) * length(y) ^ (-1/5) #' xx <- seq(min(y) + 0.05, max(y), length = 200) #' den <- RIG(x = xx, y = y, k = 200, h = h) #' plot(den, type = "l") #' #' #' ##other details can also be added #' y <- rexp(200, 1) #' h <- 0.79 * IQR(y) * length(y) ^ (-1/5) #' den <- RIG(x = xx, y = y, k = 200, h = h) #' plot(den, type = "s", ylab = "Density Function", lty = 1, xlab = "Time") #' #' ## To add true density along with estimated #' d1 <- density(y, bw = h) #' lines(d1, type = "p", col = "red") #' legend("topright", c("Real Density", "Density by RIG Kernel"), #' col = c("red", "black"), lty = c(1, 2)) #' @return nothing #' @author Javaria Ahmad Khan, Atif Akbar. #' @references Scaillet, O. 2004. Density estimation using inverse and reciprocal inverse Gaussian kernels. \emph{Nonparametric Statistics}, \strong{16}, 217-226. #' @seealso To examine RIG estimated values for density see \code{\link{RIG}} and for Mean Squared Error \code{\link{mse}}. Similarly, for plot of Laplace kernel \code{\link{plot.Laplace}}. #' @export plot.RIG <- function(x,...) { plot(x$x, x$y,...) } #' Estimate Density Values by Laplace kernel #' #' Estimated Kernel density values by using Laplace Kernel. #' @details Laplace kernel is developed by Khan and Akbar. Kernel is developed by using Chen's idea. Laplace kernel is; #' \deqn{K_{Laplace\left(x,h^{\frac{1}{2}}\right)} (u)=\frac{1}{2\sqrt h}exp \left(-\frac{|{u-x}|}{\sqrt h}\right)} #' @param y a numeric vector of positive values. #' @param x scheme for generating grid points #' @param k gird points. #' @param h the bandwidth #' @import stats #' @examples #' #Data can be simulated or real data #' ## Number of grid points "k" should be at least equal to the data size. #' ### If user define the generating scheme of gridpoints than number of gridpoints should #' ####be equal or greater than "k" #' ###### otherwise NA will be produced. #' y <- rexp(100, 1) #' xx <- seq(min(y) + 0.05, max(y), length = 100) #' h <- 2 #' den <- Laplace(x = xx, y = y, k = 200, h = h) #' #' ##If scheme for generating gridpoints is unknown #' y <- rexp(50, 1) #' h <- 3 #'den <- Laplace(y = y, k = 90, h = h) #' #'##If user do not mention the number of grid points #'y <- rexp(23, 1) #'xx <- seq(min(y) + 0.05, max(y), length = 90) #' #'\dontrun{ #'#any bandwidth can be used #'require(KernSmooth) #'h <- dpik(y) #'den <- Laplace(x = xx, y = y, h = h) #'} #' #'#if bandwidth is missing #'y <- rexp(100, 1) #'xx <- seq(min(y) + 0.05, max(y), length = 100) #'den <- Laplace(x = xx, y = y, k = 90) #' @return \item{x}{grid points} #' \item{y}{estimated values of density} #' @author Javaria Ahmad Khan, Atif Akbar. #' @references Khan, J. A.; Akbar, A. Density Estimation by Laplace Kernel. \emph{Working paper, Department of Statistics, Bahauddin Zakariya University, Multan, Pakistan.} #' @seealso To examine Laplace density plot see \code{\link{plot.Laplace}} and for Mean Squared Error \code{\link{mse}}. Similarly, for RIG kernel \code{\link{RIG}}. #' @export Laplace <- function(x = NULL, y, k = NULL, h = NULL){ n <- length(y) if(is.null(x)) x = seq(min(y) + 0.05, max(y), length = k) if(is.null(k)) k = length(y) if(is.null(h)) h = 0.79 * IQR(y) * length(y) ^ (-1/5) KLaplace <- matrix(rep(0, k * n), ncol = k) ######Lap##### for(j in 1:k) { for(i in 1:n) { KLaplace[i, j] <-(1/(2 * sqrt(h))) * exp( - (abs(y[i] - (x[j]))) / sqrt(h)) } } fhat <- fhat<- colMeans(KLaplace) results <- list(x = x, y = fhat) class ( results ) <-c('list', 'Laplace') results } #' Density Plot by Laplace kernel #' #' Plot density by using Laplace Kernel. #' @param x an object of class "Laplace" #' @param \dots Not presently used in this implementation #' @import graphics #' @import stats #' @examples #' y <- rexp(100, 1) #' h <- 0.79 * IQR(y) * length(y) ^ (-1/5) #' xx <- seq(min(y) + 0.05, max(y), length = 100) #' den <- Laplace(x = xx, y = y, k = 100, h = h) #' plot(den, type = "l") #' #' #' ##other details can also be added #' y <- rexp(100, 1) #' h <- 0.79 * IQR(y) * length(y) ^ (-1/5) #' den <- Laplace(x = xx, y = y, k = 100, h = h) #' plot(den, type = "s", ylab = "Density Function", lty = 1, xlab = "Time") #' #' ## To add true density along with estimated #' d1 <- density(y, bw = h) #' lines(d1, type = "p", col = "red") #' legend("topright", c("Real Density", "Density by RIG Kernel"), #' col = c("red", "black"), lty = c(1, 2)) #' @return nothing #' @author Javaria Ahmad Khan, Atif Akbar. #' @references Khan, J. A.; Akbar, A. Density Estimation by Laplace Kernel. \emph{Working paper, Department of Statistics, Bahauddin Zakariya University, Multan, Pakistan.} #' @seealso To examine Laplace estimated values for density see \code{\link{Laplace}} and for Mean Squared Error \code{\link{mse}}. Similarly, for plot of Laplace kernel \code{\link{plot.RIG}}. #' @export plot.Laplace <- function(x,...) { plot(x$x, x$y,...) } #' Calculate Mean Squared Error( MSE) by using different Kernels #' #' This function calculates the mean squared error (MSE) by using user specified kernel.This function is same as provided in package "DELTD". For details see \url{https://CRAN.R-project.org/package=DELTD}. #' @param kernel type of kernel which is to be used #' @param type mention distribution of vector.If exponential distribution then use \code{"Exp"}. #' If use gamma distribution then use \code{"Gamma"}.If Weibull distribution then use \code{"Weibull"}. #' @import stats #' @importFrom DELTD mse #' @author Javaria Ahmad Khan, Atif Akbar. #' @references \url{https://CRAN.R-project.org/package=DELTD} #' #' @return Mean Squared Error (MSE) #' @export #' MSE<-function(kernel,type) DELTD::mse(kernel, type) #' Bandwidth Calculation. #' #' Calculate Bandwidth proposed by Silverman for non-normal data. #' @param y a numeric vector of positive values. #' @import graphics #' @import stats #' @author Javaria Ahmad Khan, Atif Akbar. #' @references Silverman, B. W. 1986. \emph{Density Estimation}. Chapman & Hall/ CRC, London. #' @examples #' y <- rexp(10, 1) #' NSR(y) #' @return h #' @export NSR <- function(y){ return(0.79 * IQR(y) * length(y) ^ (-1/5)) }
/scratch/gouwar.j/cran-all/cranData/AsyK/R/AsyK.R
#' Asymmetric Second Order Rotatable Designs #' @param v Number of input factors, v(>2) #' @param number_of_pairs Number of pairs of input factors for which asymmetry is required #' @param z A vector of real number and its length equals to number_of_pairs #' @param type Type of central composite design i.e. ccc or cci. "ccc" is for Central Composite Circumscribed designs and "cci" is for Central Composite Inscribed designs #' @param randomization It is for generating the randomized layout of the design. It takes either TRUE or FALSE and by default, it is set to FALSE #' @param variance This is for generating the moment matrix and prediction variance of the design based on a second order model. It gives unique prediction variance along with its frequencies. It takes either TRUE or FALSE and by default, it is set to FALSE #'@description This function generates ASORDs through the orthogonal transformation of central composite designs as per the procedure given by J.S. Mehta and M.N. Das (1968). It would be providing two types of asymmetric designs for a given number of treatments (v). It requires four input parameters viz., v(>2); number_of_pairs(>0); z= vector of real number of length equals to number_of_pairs; type="ccc" or "cci" and randomization=TRUE or FALSE. #' @return #' Asymmetric Second Order Rotatable Designs (ASORDs) for a given v. #' #' @examples #' #'library(AsymmetricSORDs) #'Asords(5,2,c(2,3),"ccc",TRUE) #' #'@references #'1) J.S. Mehta and M.N. Das (1968)." Asymmetric rotatable designs and orthogonal transformations". #' #'2)M. Hemavathi, Eldho Varghese, Shashi Shekhar & Seema Jaggi (2020)<DOI: 10.1080/02664763.2020.1864817>." Sequential asymmetric third order rotatable designs (SATORDs)". #' #'3) M. Hemavathi, Shashi Shekhar, Eldho Varghese, Seema Jaggi, Bikas Sinha & Nripes Kumar Mandal (2022)<DOI: 10.1080/03610926.2021.1944213>." Theoretical developments in response surface designs: an informative review and further thoughts". #'@export Asords<-function(v,number_of_pairs,z,type,randomization=FALSE,variance=FALSE){ np<-number_of_pairs B<-matrix(0,nrow=v,ncol=v) s=1 ss=1 while(s<=np*2){ d<-z[ss] D<-matrix(c(1/(sqrt(1+d^2)),d/(sqrt(1+d^2)),-d/(sqrt(1+d^2)),1/(sqrt(1+d^2))),ncol=2,byrow=T) B[s:(s+1),s:(s+1)]<-t(D) s=s+2 ss=ss+1 } nxt<-s while(nxt<=v){ B[nxt,nxt]<-1 nxt=nxt+1 } #variance=F k<-2^v a<-(k)^(1/4) cbn<-(factorial(v))/(factorial(2)*factorial((v-2))) nc<-4*(2^(v/2))+4-2*v nc<-round(nc) ###########################factorial i=1 matf<-matrix(,nrow=k,ncol=0) while(i<=v){ x<-c((rep(-1,(2^(v-i)))),(rep(1,(2^(v-i))))) x1<-t(rep(x,k/length(x))) matf<-cbind(matf,t(x1)) i=i+1 } #######################################axial matA<-matrix(,nrow=0,ncol=v) d1<-diag(a,nrow=v,ncol=v) d2<-diag(-a,nrow=v,ncol=v) d=1 while(d<=v){ matA<-rbind(matA,d1[d,],d2[d,]) d=d+1 } matA<-matA*(-1) ####################################### matfA<-rbind(matf,matA) ############################central matfAc<-rbind(matfA,matrix(0,nrow=nc,ncol=v)) #################################square terms ccc<-matfAc cci<-matfAc ccf<-matfAc ########################## #######################################randomization if(randomization==T){ mat3<-matrix(,nrow=(k+(2*v)+nc),ncol=v) rand<-sample(1:(k+(2*v)+nc),(k+(2*v)+nc),replace = FALSE) for(m in rand){ x11<-matrix(,nrow=1,ncol=v) x11<-matfAc[m,] mat3<-rbind(mat3,(x11)) } ########################## matfAc<-mat3 rownames(matfAc)<-NULL #if(randomization==TRUE){ ccc<-matfAc[((k+(2*v)+nc+1)):(2*(k+(2*v)+nc)),] cci<-matfAc[((k+(2*v)+nc+1)):(2*(k+(2*v)+nc)),] ccf<-matfAc[((k+(2*v)+nc+1)):(2*(k+(2*v)+nc)),] #final<-matfAc } # } ####################CCC ###################### ######################################x prime x if(type=="ccc"){ final<-ccc } ######################## #######CCI if(type=="cci"){ cci<-cci/a final<-cci } ############CCF if(type=="ccf"){ #ccf<-matfAc ccf[ccf==a]<-1 ccf[ccf==-a]<- -1 final<-ccf } #############adding columns(sq terms + interactions) ########################### #print("Asymmetric Rotatable Design",quote=F) message("Asymmetric Rotatable Design") final<-final%*%B print(final) ############### p=1 while(p<=v){ x1<-matrix(,nrow=nrow(final),ncol=0) x1<-(final[,p])^2 final<-cbind(final,x1) p=p+1 } b1=1 b2=1 while(b1<v){ b2=b1+1 while(b2<=v){ mat2<-matrix(,nrow=0,ncol=1) mat2<-final[,b1]*final[,b2] final<-cbind(final,mat2) b2=b2+1 } b1=b1+1 } ########## x_prime_x<-t(final)%*% final moment_mat<-(1/nrow(final))*x_prime_x rownames(moment_mat)<-NULL colnames(moment_mat)<-NULL k1=1 var<-c() while(k1<=k+2*v+nc){ V=t(final[k1,]) b<-t(V) v_y_hat<-V %*%solve(x_prime_x) %*% b var<-c(var,v_y_hat) k1<-k1+1 } if(variance==TRUE){ #print("Moment Matrix",quote=FALSE) message("Moment Matrix") print(moment_mat) variance_of_esitmated_response<-round(var,digits = 3 ) print(table(variance_of_esitmated_response)) } }
/scratch/gouwar.j/cran-all/cranData/AsymmetricSORDs/R/Asords.R
#' Central Composite Designs (CCD) with coded levels #' @param v Number of input factors, v(>2) #' @param type Type of central composite design i.e. ccc or cci or ccf. "ccc" is for Central Composite Circumscribed designs, "cci" is for Central Composite Inscribed designs and "ccf" is for Central Composite Face Centered designs #' @param randomization It is for generating the randomized layout of the design. It takes either TRUE or FALSE and by default, it is set to FALSE #' @param variance This is for generating the moment matrix and prediction variance of the design based on a second order model. It gives unique prediction variance along with its frequencies. It takes either TRUE or FALSE and by default, it is set to FALSE #'@description This function generates Central Composite Designs (CCD) with coded levels for a given number of input factors (v). The CCD constitute combinations of factorial points, axial points and center points. Three types of CCD can be generated using this function i.e. ccc or cci or ccf. "ccc" is for Central Composite Circumscribed designs, "cci" is for Central Composite Inscribed designs and "ccf" is for Central Composite Face Centered designs. It gives the randomized layout of the design along with the moment matrix and prediction variance. #' @return Central Composite Designs (CCD) for a given number of input factors (v) with coded levels #' @note Here, the factorial portion consists of 2^v (full factorial) combinations and there is no upper limit for the number of input factors, v (>2). To get a CCD with smaller runs, one may use fractional factorial (of resolution V) in place of full factorial. #' @examples #' #'library(AsymmetricSORDs) #'CCD_coded(5,'ccc',FALSE,FALSE) #'CCD_coded(6,"cci",FALSE,FALSE) #' #'@references #'1) G.E.P. Box and K.B. Wilson (1951)." On the experimental attainment of optimum conditions". #' #'2) M. Hemavathi, Shashi Shekhar, Eldho Varghese, Seema Jaggi, Bikas Sinha & Nripes Kumar Mandal (2022)<DOI: 10.1080/03610926.2021.1944213>. "Theoretical developments in response surface designs: an informative review and further thoughts". #'@export CCD_coded<-function(v,type,randomization=FALSE,variance=FALSE){ v type randomization variance k<-2^v a<-(k)^(1/4) cbn<-(factorial(v))/(factorial(2)*factorial((v-2))) nc<-4*(2^(v/2))+4-2*v nc<-round(nc) ###########################factorial i=1 matf<-matrix(,nrow=k,ncol=0) while(i<=v){ x<-c((rep(-1,(2^(v-i)))),(rep(1,(2^(v-i))))) x1<-t(rep(x,k/length(x))) matf<-cbind(matf,t(x1)) i=i+1 } #######################################axial matA<-matrix(,nrow=0,ncol=v) d1<-diag(a,nrow=v,ncol=v) d2<-diag(-a,nrow=v,ncol=v) d=1 while(d<=v){ matA<-rbind(matA,d1[d,],d2[d,]) d=d+1 } matA<-matA*(-1) ####################################### matfA<-rbind(matf,matA) ############################central matfAc<-rbind(matfA,matrix(0,nrow=nc,ncol=v)) #################################square terms p=1 while(p<=v){ x1<-matrix(,nrow=nrow(matfAc),ncol=0) x1<-(matfAc[,p])^2 matfAc<-cbind(matfAc,x1) p=p+1 } b1=1 b2=1 while(b1<v){ b2=b1+1 while(b2<=v){ mat2<-matrix(,nrow=0,ncol=1) mat2<-matfAc[,b1]*matfAc[,b2] matfAc<-cbind(matfAc,mat2) b2=b2+1 } b1=b1+1 } ########################### matfAc<-cbind(matrix(1,nrow=nrow(matfAc),ncol=1),matfAc) colnames(matfAc)<-NULL # cccsd<-matfAc if(randomization==T){ mat3<-matrix(,nrow=0,ncol=1+v+v+cbn) rand<-sample(1:(k+(2*v)+nc),(k+(2*v)+nc),replace = FALSE) for(m in rand){ x11<-matrix(,nrow=1,ncol=1+v+cbn+v) x11<-matfAc[m,] mat3<-rbind(mat3,x11) } ########################## matfAc<-mat3 rownames(matfAc)<-NULL cccrand<-matfAc } ######################################x prime x if(type=="ccc"){ if(randomization==FALSE){ # print("CCC (Standard)",quote=F) message("CCC (Standard)") print(cccsd[,2:(v+1)]) matfAc<-cccsd }else{ # print("CCC (Randomized)",quote=F) message("CCC (Randomized)") print(cccrand[,2:(v+1)]) matfAc<-cccrand } x_prime_x<-t(matfAc)%*% matfAc #################################variance k1=1 var<-c() while(k1<=(k+2*v+nc)) { V=t(matfAc[k1,]) b<-t(V) v_y_hat<-V %*%solve(x_prime_x) %*% b var<-c(var,v_y_hat) k1<-k1+1 } if(variance==TRUE){ variance_of_esitmated_response<-round(var,digits = 3 ) v1<-table(variance_of_esitmated_response) } } ######################## #######CCI if(type=="cci"){ cci<-matfAc[,2:(v+1)]/a #############adding columns(sq terms + interactions) p=1 while(p<=v){ x1<-matrix(,nrow=nrow(cci),ncol=0) x1<-(cci[,p])^2 cci<-cbind(cci,x1) p=p+1 } ############################## b1=1 b2=2 while(b1<b2){ while(b2<=v){ mat2<-matrix(,nrow=k,ncol=0) mat2<-cci[,b1]*cci[,b2] cci<-cbind(cci,mat2) b2=b2+1 } b2=b2-1 b1=b1+1 } ########################### cci<-cbind(matrix(1,nrow=nrow(cci),ncol=1),cci) colnames(cci)<-NULL ########## x_prime_x<-t(cci)%*% cci k1=1 var<-c() while(k1<=k+2*v+nc) { V=t(cci[k1,]) b<-t(V) v_y_hat<-V %*%solve(x_prime_x) %*% b var<-c(var,v_y_hat) k1<-k1+1 } if(randomization==T){ #print("CCI (Randomized)",quote=F) message("CCI (Randomized)") }else{ #print("CCI (Standard)",quote=F) message("CCI (Standard)") } print(cci[,2:(v+1)]) if(variance==TRUE){ #if(unique==FALSE){ variance_of_esitmated_response<-round(var,digits = 3 ) v2<-table(variance_of_esitmated_response) } } ############CCF if(type=="ccf"){ ccf<-matfAc[,2:(v+1)] ccf[ccf==a]<-1 ccf[ccf==-a]<- -1 #############adding columns(sq terms + interactions) p=1 while(p<=v){ x1<-matrix(,nrow=nrow(ccf),ncol=0) x1<-(ccf[,p])^2 ccf<-cbind(ccf,x1) p=p+1 } ############################## b1=1 b2=2 while(b1<b2){ while(b2<=v){ mat2<-matrix(,nrow=k,ncol=0) mat2<-ccf[,b1]*ccf[,b2] ccf<-cbind(ccf,mat2) b2=b2+1 } b2=b2-1 b1=b1+1 } ########################### ccf<-cbind(matrix(1,nrow=nrow(ccf),ncol=1),ccf) colnames(ccf)<-NULL ########## x_prime_x<-t(ccf)%*% ccf k1=1 var<-c() while(k1<=k+2*v+nc) { V=t(ccf[k1,]) b<-t(V) v_y_hat<-V %*%solve(x_prime_x) %*% b var<-c(var,v_y_hat) k1<-k1+1 } variance_of_esitmated_response<-round(var,digits = 3 ) v3<-table(variance_of_esitmated_response) if(randomization==T){ # print("CCF (Randomized)",quote=F) message("CCF (Randomized)") }else{ #print("CCF (Standard)",quote=F) message("CCF (Standard)") } print(ccf[,2:(v+1)]) } if(type=="ccf"){ final<-ccf[,2:(v+1)] } if(type=="cci"){ final<-cci[,2:(v+1)] } if(type=="ccc"){ final<-matfAc[,2:(v+1)] } if(variance==TRUE){ x_matrix<-final x_matrix<-cbind(matrix(1,nrow=nrow(x_matrix),ncol=1),x_matrix) colnames(x_matrix)<-NULL x_prime_x<-t(x_matrix)%*%x_matrix moment_mat<-(1/nrow(x_matrix))*x_prime_x #print("Moment Matrix",quote=FALSE) message("Moment Matrix") print(moment_mat) if(type=="ccf"){ print(v3) } if(type=="cci"){ print(v2) } if(type=="ccc"){ print(v1) } } }
/scratch/gouwar.j/cran-all/cranData/AsymmetricSORDs/R/CCD_coded.R
#' Central Composite Designs (CCD) with original levels #' #' @param v Number of input factors, v(>2) #' @param type Type of central composite design i.e. ccc or cci or ccf. "ccc" is for Central Composite Circumscribed designs, "cci" is for Central Composite Inscribed designs and "ccf" is for Central Composite Face Centered designs #' @param randomization It is for generating the randomized layout of the design. It takes either TRUE or FALSE and by default, it is set to FALSE #' @param variance This is for generating the moment matrix and prediction variance of the design based on a second order model. It gives unique prediction variance along with its frequencies. It takes either TRUE or FALSE and by default, it is set to FALSE #'@param min_L A vector of minimum levels of the factors #'@param max_L A vector of maximum levels of the factors #'@description This function generates Central Composite Designs (CCD) with original levels along with coded levels for a given number of input factors (v). The CCD constitute combinations of factorial points, axial points and center points. Three types of CCDs can be generated using this function i.e. ccc or cci or ccf. "ccc" is for Central Composite Circumscribed designs, "cci" is for Central Composite Inscribed designs and "ccf" is for Central Composite Face Centered designs. It gives the randomized layout of the design along with the moment matrix and prediction variance. #' @return Central Composite Designs (CCD) for a given number of input factors (v) with original levels #' @note Here, the factorial portion consists of 2^v (full factorial) combinations and there is no upper limit for the number of input factors,v (>2). To get a CCD with smaller runs, one may use fractional factorial (of resolution V) in place of full factorial. #' @examples #' #'library(AsymmetricSORDs) #'CCD_original(5,'ccc',c(10,15,20,25,30),c(15,20,25,30,35),FALSE,FALSE) #' #'@references #'1) G.E.P. Box and K.B. Wilson (1951)." On the experimental attainment of optimum conditions". #' #'2) M. Hemavathi, Shashi Shekhar, Eldho Varghese, Seema Jaggi, Bikas Sinha & Nripes Kumar Mandal (2022)<DOI: 10.1080/03610926.2021.1944213>. "Theoretical developments in response surface designs: an informative review and further thoughts". #'@export CCD_original<-function(v,type,min_L,max_L,randomization=FALSE,variance=FALSE){ k<-2^v a<-(k)^(1/4) cbn<-(factorial(v))/(factorial(2)*factorial((v-2))) nc<-4*(2^(v/2))+4-2*v nc<-round(nc) aa<-c(-((2^v)^(1/4)), -1, 0, 1,((2^v)^(1/4))) a_CCC<-aa ##########Circumscribed (CCC)############# a_CCI<-aa/((2^v)^(1/4))##########Inscribed (CCI)############# a_CCF<-c(-1, -1, 0, 1,1)##########Face Centered (CCF)############# ####################################CCC if(type=="ccc"){ x_ccc<-matrix(,length(min_L),ncol=5) for (j in 1:length(min_L)) { for (i in 1:5) { x_ccc[j,i]<-(((max_L[j]-min_L[j])/2)*a_CCC[i])+((min_L[j]+max_L[j])/2) } } } #########################CCI if(type=="cci"){ x_cci<-matrix(,length(min_L),ncol=5) for (j in 1:length(min_L)) { for (i in 1:5) { x_cci[j,i]<-(((max_L[j]-min_L[j])/2)*a_CCI[i])+((min_L[j]+max_L[j])/2) } } } #############################CCF if(type=="ccf"){ x_ccf<-matrix(,length(min_L),ncol=5) for (j in 1:length(min_L)) { for (i in 1:5) { x_ccf[j,i]<-(((max_L[j]-min_L[j])/2)*a_CCF[i])+((min_L[j]+max_L[j])/2) } } } ###########################factorial i=1 matf<-matrix(,nrow=k,ncol=0) while(i<=v){ x<-c((rep(-1,(2^(v-i)))),(rep(1,(2^(v-i))))) x1<-t(rep(x,k/length(x))) matf<-cbind(matf,t(x1)) i=i+1 } #######################################axial matA<-matrix(,nrow=0,ncol=v) d1<-diag(a,nrow=v,ncol=v) d2<-diag(-a,nrow=v,ncol=v) d=1 while(d<=v){ matA<-rbind(matA,d1[d,],d2[d,]) d=d+1 } matA<-matA*(-1) ####################################### matfA<-rbind(matf,matA) ############################central matfAc<-rbind(matfA,matrix(0,nrow=nc,ncol=v)) #################################square terms ########################### cccsd<-matfAc ########################## #######################################randomization mat3<-matrix(,nrow=(k+(2*v)+nc),ncol=v) rand<-sample(1:(k+(2*v)+nc),(k+(2*v)+nc),replace = FALSE) for(m in rand){ x1<-matrix(,nrow=1,ncol=v) x1<-matfAc[m,] mat3<-rbind(mat3,t(x1)) } ########################## matfAc<-mat3[((k+(2*v)+nc+1):(2*(k+(2*v)+nc))),] rownames(matfAc)<-NULL cccrand<-matfAc ####################CCC ###################### ######################################x prime x if(type=="ccc"){ if(randomization==FALSE){ #print("CCC coded (Standard)") message("CCC coded (Standard)") print(cccsd) matfAc<-cccsd}else{ #print("CCC coded (Randomized)") message("CCC coded (Randomized)") print(cccrand) matfAc<-cccrand } } ######################## #######CCI if(type=="cci"){ cci<-matfAc/a #############adding columns(sq terms + interactions) if(randomization==T){ #print("CCI coded (Randomized)") message("CCI coded (Randomized)") }else{ #print("CCI coded (Standard)") message("CCI coded (Standard)") } print(cci) } ############CCF if(type=="ccf"){ ccf<-matfAc ccf[ccf==a]<-1 ccf[ccf==-a]<- -1 if(randomization==T){ #print("CCF coded (Randomized)") message("CCF coded (Randomized)") }else{ #print("CCF coded (Standard)") message("CCF coded (Standard)") } print(ccf) } if(type=="ccc"){ raw<-matfAc } if(type=="cci"){ raw<-cci } if(type=="ccf"){ raw<-ccf } s=1 while(s<=v){ if(type=="ccc"){ o<-c(x_ccc[s,]) raw[which(raw[,s]==0),s]<-o[3] raw[which(raw[,s]==-1),s]<-o[2] raw[which(raw[,s]==-a),s]<-o[1] raw[which(raw[,s]==1),s]<-o[4] raw[which(raw[,s]==a),s]<-o[5] s=s+1 } if(type=="cci"){ o<-c(x_cci[s,]) raw[which(raw[,s]==0),s]<-o[3] raw[which(raw[,s]==-1),s]<-o[1] raw[which(raw[,s]==-1/a),s]<-o[2] raw[which(raw[,s]==1),s]<-o[5] raw[which(raw[,s]==1/a),s]<-o[4] s=s+1 } if(type=="ccf"){ o<-c(x_ccf[s,]) raw[which(raw[,s]==0),s]<-o[3] raw[which(raw[,s]==-1),s]<-o[1] raw[which(raw[,s]==-1),s]<-o[2] raw[which(raw[,s]==1),s]<-o[5] raw[which(raw[,s]==1),s]<-o[4] s=s+1 } } if(type=="ccc"){ if(randomization==T){ #print("CCC original (Randomized)") message("CCC original (Randomized)") }else{ #print("CCC original (Standard)") message("CCC original (Standard)") } } if(type=="cci"){ if(randomization==T){ #print("CCI original (Randomized)") message("CCI original (Randomized)") }else{ #print("CCI original (Standard)") message("CCI original (Standard)") } } if(type=="ccf"){ if(randomization==T){ #print("CCF original (Randomized)") message("CCF original (Randomized)") }else{ # print("CCF original (Standard)") message("CCF original (Standard)") } } print(raw) ############################# p=1 while(p<=v){ x1<-matrix(,nrow=nrow(raw),ncol=0) x1<-(raw[,p])^2 raw<-cbind(raw,x1) p=p+1 } b1=1 b2=1 while(b1<v){ b2=b1+1 while(b2<=v){ mat2<-matrix(,nrow=0,ncol=1) mat2<-raw[,b1]*raw[,b2] raw<-cbind(raw,mat2) b2=b2+1 } b1=b1+1 } x_matrix<-raw x_matrix<-cbind(matrix(1,nrow=nrow(x_matrix),ncol=1),x_matrix) colnames(x_matrix)<-NULL x_prime_x<-t(x_matrix)%*%x_matrix moment_mat<-(1/nrow(x_matrix))*x_prime_x if(variance==TRUE){ #print("Moment Matrix",quote=FALSE) message("Moment Matrix") print(moment_mat) k1=1 var<-c() while(k1<=k+2*v+nc){ V=t(x_matrix[k1,]) b<-t(V) v_y_hat<-V%*%solve(x_prime_x) %*% b var<-c(var,v_y_hat) k1<-k1+1 } variance_of_esitmated_response<-round(var,digits = 3 ) print(table(variance_of_esitmated_response)) } }
/scratch/gouwar.j/cran-all/cranData/AsymmetricSORDs/R/CCD_original.R
#' Function for generating the moment matrix and variance of the predicted response #' #' @param matrix Design matrix with the coefficients of the corresponding input factors #'@description This function generates the moment matrix and variance of the predicted response for a given design based on a second-order model, for measuring the rotatability of the design. The input should be the specified form of a design matrix with the coefficients of the corresponding input factors. A minimum number of centre points is to be used to ensure the non-singularity of X`X. #' @return The moment matrix and the prediction variance for a given design based on a second-order model #' It gives unique prediction variance along with its frequencies. #' @examples #' \dontrun{ #'library(AsymmetricSORDs) #'Pred.var(matrix) #'} #'@references #'1) G.E.P. Box and K.B. Wilson (1951).' On the experimental attainment of optimum conditions'. #' #'2) M. Hemavathi, Shashi Shekhar, Eldho Varghese, Seema Jaggi, Bikas Sinha & Nripes Kumar Mandal (2022)<DOI: 10.1080/03610926.2021.1944213>.' Theoretical developments in response surface designs: an informative review and further thoughts'. #'@export Pred.var<-function(matrix){ mat<-matrix v<-ncol(mat) p=1 while(p<=v){ x1<-matrix(,nrow=nrow(mat),ncol=0) x1<-(mat[,p])^2 mat<-cbind(mat,x1) p=p+1 } b1=1 b2=1 while(b1<v){ b2=b1+1 while(b2<=v){ mat2<-matrix(,nrow=0,ncol=1) mat2<-mat[,b1]*mat[,b2] mat<-cbind(mat,mat2) b2=b2+1 } b1=b1+1 } x_matrix<-mat x_matrix<-cbind(matrix(1,nrow=nrow(x_matrix),ncol=1),x_matrix) colnames(x_matrix)<-NULL x_prime_x<-t(x_matrix)%*%x_matrix moment_mat<-(1/nrow(x_matrix))*x_prime_x # print("Moment Matrix",quote=FALSE) message("Moment Matrix") print(moment_mat) k1=1 var<-c() while(k1<=nrow(x_matrix)) { V=t(x_matrix[k1,]) b<-t(V) v_y_hat<-V %*%solve(x_prime_x) %*% b var<-c(var,v_y_hat) k1<-k1+1 } variance_of_esitmated_response<-round(var,digits = 4 ) print(table(variance_of_esitmated_response)) }
/scratch/gouwar.j/cran-all/cranData/AsymmetricSORDs/R/Pred.var.R
#' Second Order Rotatable Designs with coded levels #' @param v Number of input factors,v(3<=v<=16) #' @param n0 Number of centre points, n0 (>0) #' @param randomization It is for generating the randomized layout of the design. It takes either TRUE or FALSE and by default, it is set to FALSE #' @param variance This is for generating the moment matrix and prediction variance of the design based on a second order model. It gives unique prediction variance along with its frequencies. It takes either TRUE or FALSE and by default, it is set to FALSE #'@description This function generates second order rotatable designs given in Das and Narasimham (1962) for a given number of input factors, v (3<=v<=16) with coded levels of the factors. It gives the randomized layout of the design along with the moment matrix and prediction variance. Here, all the factors are having 5-levels except for v=7, which gives a rotatable design with 3-levels for each factor. #' @return Second-Order Rotatable Designs with coded levels #' #' @examples #' #'library(AsymmetricSORDs) #'SORD_coded(4,3,FALSE,FALSE) #' #'@references #'1) M. N. Das and V. L. Narasimham (1962). "Construction of rotatable designs through balanced incomplete block designs". #' #'2) M. Hemavathi, Shashi Shekhar, Eldho Varghese, Seema Jaggi, Bikas Sinha & Nripes Kumar Mandal (2022)<DOI: 10.1080/03610926.2021.1944213> "Theoretical developments in response surface designs: an informative review and further thoughts". #'@export SORD_coded<-function(v,n0,randomization=FALSE,variance=FALSE){ if(v>2 && v<17){ n_zero<-n0 if(v==3){ bibd<-matrix(c(1,3,2,3,1,2),nrow=3,byrow=TRUE) b<-2^(1/4) matA<-matrix(,nrow=0,ncol=v) d1<-diag(b,nrow=v,ncol=v) d2<-diag(-b,nrow=v,ncol=v) d=1 while(d<=v){ matA<-rbind(matA,d1[d,],d2[d,]) d=d+1 } matA<-matA*(-1) ####################### } if(v==4){ bibd<-matrix(c(2,3,4,1,3,4,1,2,4,1,2,3),nrow=4,byrow=TRUE) b<-sqrt(2*sqrt(3)) ############################ matA<-matrix(,nrow=0,ncol=v) d1<-diag(b,nrow=v,ncol=v) d2<-diag(-b,nrow=v,ncol=v) d=1 while(d<=v){ matA<-rbind(matA,d1[d,],d2[d,]) d=d+1 } matA<-matA*(-1) ############################# } if(v==5){ bibd<-matrix(c(1,5,3,5,4,5,1,4,1,3,3,4,1,2,2,5,2,4,2,3),nrow=10,byrow=TRUE) b=sqrt(1/(2*sqrt(2))) fractional<-matrix(c(1,-1,1,1,1,-1,1,-1,-1,-1,1,1,-1,-1,-1,1,-1,1,1,-1,1,1,-1,-1,1,-1,1,1,-1,1,-1,-1,1,-1,-1,1,-1,1,-1,-1,1,1,1,1,-1,-1,1,-1,-1,-1,1,1,-1,-1,1,-1,1,-1,1,-1,1,1,1,-1,1,-1,-1,-1,1,1,1,1,-1,-1,1,-1,-1,1,1,-1 ),nrow=16,byrow=FALSE) fractional<-fractional*b ################ } if(v==6){ bibd<-matrix(c(1,6,3,5,3,6,4,6,1,5,5,6,1,4,4,5,3,4,1,3,2,6,1,2,2,5,2,4,2,3),nrow=15,byrow=TRUE) ############ b=sqrt(1/(2*sqrt(2))) fractional<-matrix(c(1,-1,1,-1,-1,1,-1,1,-1,-1,1,1,1,1,1,-1,-1,-1,1,-1,-1,-1,1,1,1,1,1,1,-1,-1,-1,-1,1,1,1,-1,-1,1,-1,1,-1,1,-1,-1,1,-1,-1,-1,1,1,1,-1,1,-1,-1,-1,1,1,-1,-1,1,1,-1,1,1,-1,-1,-1,1,-1,1,1,1,-1,-1,-1,-1,1,1,-1,1,-1,1,-1,1,1,1,1,-1,1,-1,-1,1,-1,-1,1,1,-1,-1,1,1,-1,1,-1,-1,-1,-1,1,1,-1,1,-1,-1,1,-1,-1,1,-1,-1,1,1,1,-1,1,-1,1,1,1,-1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,-1,1,1,-1,1,-1,-1,1,1,1,1,1,1,-1,-1,1,-1,1,-1,-1,1,-1,-1,-1,1,1,1,1,1,1,1,-1,1,1,1,-1,-1,-1,1,-1,1,-1,-1,1,-1,-1,-1,1,1,-1),nrow=32,byrow=FALSE) fractional<-fractional*b ################# } if(v==7){ bibd<-matrix(c(1,2,4,2,3,5,3,4,6,4,5,7,5,6,1,6,7,2,7,1,3),nrow=7,byrow=TRUE) bibd<-rbind(bibd,bibd) } if(v==8){ bibd<-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ncol=v) d2<-diag(-b,nrow=v,ncol=v) d=1 while(d<=v){ matA<-rbind(matA,d1[d,],d2[d,]) d=d+1 } matA<-matA*(-1) } if(v==12){ bibd<-matrix(c(3,4,6,7,11,12,2,3,4,5,6,8,1,3,4,5,7,9,2,4,6,9,10,11,1,2,4,5,9,11,5,6,8,9,10,12,2,5,6,7,8,9,4,5,7,8,10,11,2,4,6,7,10,12,3,4,7,8,9,12,1,3,4,5,6,10,2,3,7,9,10,11,1,3,6,8,10,11,1,2,3,7,8,10,3,5,9,10,11,12,2,3,5,8,11,12,1,2,3,6,9,12,1,6,7,8,9,11,1,5,6,7,11,12,1,2,5,7,10,12,1,2,4,8,11,12,1,4,8,9,10,12),nrow=22,byrow=TRUE) b=sqrt(8) fractional<-matrix(c(1,-1,1,-1,-1,1,-1,1,-1,-1,1,1,1,1,1,-1,-1,-1,1,-1,-1,-1,1,1,1,1,1,1,-1,-1,-1,-1,1,1,1,-1,-1,1,-1,1,-1,1,-1,-1,1,-1,-1,-1,1,1,1,-1,1,-1,-1,-1,1,1,-1,-1,1,1,-1,1,1,-1,-1,-1,1,-1,1,1,1,-1,-1,-1,-1,1,1,-1,1,-1,1,-1,1,1,1,1,-1,1,-1,-1,1,-1,-1,1,1,-1,-1,1,1,-1,1,-1,-1,-1,-1,1,1,-1,1,-1,-1,1,-1,-1,1,-1,-1,1,1,1,-1,1,-1,1,1,1,-1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,-1,1,1,-1,1,-1,-1,1,1,1,1,1,1,-1,-1,1,-1,1,-1,-1,1,-1,-1,-1,1,1,1,1,1,1,1,-1,1,1,1,-1,-1,-1,1,-1,1,-1,-1,1,-1,-1,-1,1,1,-1),nrow=32,byrow=FALSE) #fractional<-fractional*b matA<-matrix(,nrow=0,ncol=v) d1<-diag(b,nrow=v,ncol=v) d2<-diag(-b,nrow=v,ncol=v) d=1 while(d<=v){ matA<-rbind(matA,d1[d,],d2[d,]) d=d+1 } matA<-matA*(-1)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1,-1,1,-1,-1,1,1,1,1,1,1,1,-1,1,1,-1,-1,1,-1,-1,1,1,1,-1,-1,-1,1,-1,1,1,1,1,-1,-1,-1,1,-1,-1,-1,-1,-1,-1,-1,1,1,-1,-1,1,-1,1,1,1,-1,-1,-1,-1,1,-1,1,-1, -1,-1,1,1,1,1,1,-1,-1,-1,1,1,-1,-1,-1,1,1,-1,1,1,-1,1,-1,-1,-1,-1,1,-1,-1,1,1,-1,-1,1,1,-1,-1,1,1,-1,1,-1,1,1,1,1,-1,-1,1,-1,-1,1,-1,-1,-1,-1,-1,-1,1,1,-1,1,-1,1,1,-1,1,1,1,1,1,1,-1,1,1,-1,1,-1,-1,1,-1,1,-1,1,1,1,1,-1,1,-1,1,1,1,1,1,-1,1,1,-1,1,1,-1,-1,-1,1,1,1,-1,1,-1,-1,-1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,1,1,1,1,-1,-1,1,-1,-1,1,1,1,-1,1,-1,1,-1,-1,1,1,-1,-1,-1,-1,-1,-1,1,-1,-1,1,-1,-1,-1,1,1,-1,1,-1,1,1,-1,-1,-1,-1,1,-1,-1,1,-1,-1,1,-1,1,-1,1,-1,-1,1,1,1,1,-1,-1,-1,-1,1,1,1,1,-1,-1,-1,-1,1,1,1,1,-1,1,-1,-1,1,-1,-1,1,1 ) ,nrow=1024,byrow=FALSE) b<-sqrt(3/16) fractional<-fractional*b ############# } if(v==14){ bibd<-matrix(c(2,13,2,14,3,5,3,6,3,7,3,8,3,9,1,10,3,10,3,11,1,11,3,13,3,12,3,14,4,6,4,7,4,8,4,9,4,10,4,11,4,13,4,14,4,12,5,8,5,9,1,12,5,10,5,11,5,12,5,13,5,14,6,10,6,11,6,12,6,13,6,14,7,11,7,12,7,13,1,14,7,14,1,13,8,14,8,13,8,12,9,13,9,14,13,14,12,14,12,13,11,14,11,13,11,12,10,14,10,13,10,12,10,11,9,12,9,11,9,10,1,9,8,11,1,8,8,10,8,9,7,10,7,9,7,8,6,9,6,8,6,7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,-1,-1,-1,1,1,1,1,1,1,-1,1,-1,-1,1,1,-1,-1,1,1,-1,1,1,-1,1,-1,1,1,-1,-1,1,-1,-1,1,-1,-1,-1,1,1,-1,1,-1,-1,1,1,1,1,-1,-1,-1,1,-1,1,-1,-1,-1,1,-1) ,nrow=1024,byrow=FALSE) b<-sqrt(5/16) fractional<-fractional*b ############# } #v=15 if(v==15){ bibd<-matrix(c(1,2,5,8,11,13,14,5,6,7,8,10,14,15,1,3,4,6,7,13,14,1,4,6,8,11,12,15,5,6,7,9,11,12,13,1,3,5,9,12,14,15,1,3,7,8,9,10,11,4,8,9,10,12,13,14,3,4,5,10,11,13,15,2,4,7,9,11,14,15,1,2,6,9,10,13,15,2,3,4,5,6,8,9,2,3,7,8,12,13,15,1,2,4,5,7,10,12,2,3,6,10,11,12,14),nrow=15,byrow=TRUE) ############# fractional<-matrix(c(1 , -1 , 1 , 1 , -1 , -1 , -1 , 1 , 1 , 1 , -1 , -1 , -1 , -1 , 1 , 1 , -1 , 1 , 1 , 1 , 1 , -1 , -1 , 1 , -1 , 1 , 1 , 1 , 1 , 1 , 1 , -1 , -1 , 1 , -1 , 1 , 1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , 1 , 1 , 1 , -1 , -1 , -1 , 1 , 1 , 1 , -1 , -1 , -1 , -1 , 1 , -1 , -1 , -1 , 1 , 1 , 1, 1 , 1 , -1 , -1 , -1 , 1 , -1 , 1 , 1 , 1 , 1 , 1 , -1 , 1 , 1 , -1 , -1 , -1 , -1 , -1 , 1 , 1 , 1 , 1 , -1 , -1 , 1 , -1 , -1 , -1 , -1 , -1 , -1 , 1 , -1 , -1 , 1 , 1 , -1 , 1 , -1 , 1 , -1 , 1 , 1 , 1 , 1 , -1 , -1 , 1 , -1 , -1 , 1 , 1 , 1 , 1 , -1 , -1 , -1 , -1 , 1 , -1 , 1 , 1 , -1 , -1 , 1 , 1 , 1 , -1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , -1 , 1 , -1 , 1 , 1 , 1 , -1 , -1 , -1 , 1 , 1 , 1 , -1 , 1 , 1 , 1 , -1 , 1 , -1 , -1 , 1 , -1 , -1 , -1 , 1 , 1 , 1 , 1 , 1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , 1 , 1 , -1 , 1 , -1 , -1 , 1 , 1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , 1 , -1 , -1 , -1 , 1 , 1 , 1 , -1 , 1 , 1 , -1 , -1 , -1 , 1 , -1 , -1 , -1 , 1 , -1 , 1 , 1 , -1 , 1 , 1 , 1 , 1 , -1 , -1 , 1 , -1 , -1 , -1 , 1 , -1 , 1 , -1 , -1 , -1 , 1 , -1 , -1 , 1 , 1 , -1 , -1 , 1 , 1 , -1 , 1 , -1 , 1 , 1 , -1 , 1 , 1 , -1 , 1 , -1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , -1 , -1 , 1 , 1 , -1 , 1 , 1 , -1 , -1 , -1 , -1 , 1 , 1 , -1 , -1 , -1 , -1 , 1 , 1 , 1 , -1 , 1 , 1 , 1 , 1 , 1 , -1 , -1 , 1 , -1 , -1 , -1 , -1 , -1 , 1 , 1 , 1 , -1 , -1 , -1 , -1 , -1 , 1 , -1 , 1 , 1 , -1 , -1 , -1 , -1 , 1 , -1 , -1 , 1 , 1 , 1 , 1 , -1 , 1 , 1 , 1 , 1 , -1 , 1 , -1 , -1 , -1 , 1 , -1 , 1 , -1 , 1 , 1 , 1 , -1 , 1 , 1 , -1 , 1 , -1 , 1 , 1 , 1 , -1 , -1 , -1 , -1 , 1 , -1 , 1 , 1 , 1 , -1 , 1 , -1 , 1 , 1 , 1 , -1 , -1 , 1 , -1 , -1 , 1 , -1 , -1 , -1 , 1 , -1 , 1 , -1 , -1 , 1 , -1 , -1 , -1 , 1 , -1 , 1 , 1 , -1 , 1 , 1 , -1 , 1 , -1 , 1 , 1 , -1 , -1 , -1 , 1 , 1 , -1 , 1 , 1 , 1 , 1 , -1 , 1 , -1 , 1 , -1 , 1 , -1 , 1 , -1 , 1 , 1 , -1 , -1 , -1 , -1 , -1 , 1 , -1 , -1 , 1 , -1 , 1 , 1 , -1 , 1 , -1 , 1 , 1 , 1 , -1 , -1 , 1 , -1 , 1 , 1 , 1 , -1 , -1 , -1 , 1 , 1 , -1 , -1 , 1 , -1 , 1 , -1 , -1 , -1 , 1 ) ,nrow=64,byrow=FALSE) b<-sqrt(8) ############### matA<-matrix(,nrow=0,ncol=v) d1<-diag(b,nrow=v,ncol=v) d2<-diag(-b,nrow=v,ncol=v) d=1 while(d<=v){ matA<-rbind(matA,d1[d,],d2[d,]) d=d+1 } matA<-matA*(-1) ################ } if(v==16){ bibd<-matrix(c(3,4,9,11,13,15,2,7,8,9,11,12,1,7,8,13,15,16,2,5,6,9,13,16,1,5,6,11,12,15,1,4,6,7,9,10,4,6,8,12,13,14,1,2,3,4,5,8,3,5,7,10,12,13,4,5,7,11,14,16,2,4,10,12,15,16,1,3,9,12,14,16,2,3,6,7,14,15,3,6,8,10,11,16,1,2,10,11,13,14,5,8,9,10,14,15),nrow=16,byrow=TRUE) ############ fractional<-matrix(c(1,-1,1,-1,-1,1,-1,1,-1,-1,1,1,1,1,1,-1,-1,-1,1,-1,-1,-1,1,1,1,1,1,1,-1,-1,-1,-1,1,1,1,-1,-1,1,-1,1,-1,1,-1,-1,1,-1,-1,-1,1,1,1,-1,1,-1,-1,-1,1,1,-1,-1,1,1,-1,1,1,-1,-1,-1,1,-1,1,1,1,-1,-1,-1,-1,1,1,-1,1,-1,1,-1,1,1,1,1,-1,1,-1,-1,1,-1,-1,1,1,-1,-1,1,1,-1,1,-1,-1,-1,-1,1,1,-1,1,-1,-1,1,-1,-1,1,-1,-1,1,1,1,-1,1,-1,1,1,1,-1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,-1,1,1,-1,1,-1,-1,1,1,1,1,1,1,-1,-1,1,-1,1,-1,-1,1,-1,-1,-1,1,1,1,1,1,1,1,-1,1,1,1,-1,-1,-1,1,-1,1,-1,-1,1,-1,-1,-1,1,1,-1),nrow=32,byrow=FALSE) ######### } b=nrow(bibd) kk=ncol(bibd) cc<-c(1:v) incident<-matrix(0,nrow=v, ncol=b) vv=1 while(vv<=v){ ###########raw position of a element x<-which(bibd %in% c(cc[vv])) #########################position identify only k=1 while(k<=length(x)){ if(x[k]%%b!=0){ x[k]<-x[k]%%b }else{ x[k]<-b } # if(x[k]>b){ # x[k]<-x[k]%%b # } k=k+1 } ################ ss=1 while(ss<=length(x)){ incident[vv,x[ss]]<-1 ss=ss+1 } vv=vv+1 } N_prime<-t(incident) #########################factorial form k=2^kk i=1 matf<-matrix(,nrow=k,ncol=0) while(i<=kk){ x<-c((rep(-1,(2^(kk-i)))),(rep(1,(2^(kk-i))))) x1<-t(rep(x,k/length(x))) matf<-cbind(matf,t(x1)) i=i+1 } ###############v=11 if(v==11){ matf<-fractional } ##############v=12 if(v==12){ matf<-fractional } ######################for v=15 if(v==15){ final<-matrix(,nrow=0,ncol=ncol(N_prime)) s=1 y<-(1:kk) while(s<=nrow(N_prime)){ ss=1 x<-which(N_prime[s,]==1) mat<-matrix(0,nrow=nrow(fractional),ncol=ncol(N_prime)) for(i in x){ mat[,i]<-fractional[,ss] #fi<-mat ss=ss+1 } final<-rbind(final,mat) s=s+1 } final<-rbind(final,matA) } #################v=16 if(v==16){ final<-matrix(,nrow=0,ncol=ncol(N_prime)) s=1 y<-(1:kk) while(s<=nrow(N_prime)){ ss=1 x<-which(N_prime[s,]==1) mat<-matrix(0,nrow=nrow(fractional),ncol=ncol(N_prime)) for(i in x){ mat[,i]<-fractional[,ss] #fi<-mat ss=ss+1 } final<-rbind(final,mat) s=s+1 } #print(final) } ########################## BBD solved if(v!=15 && v!=16){ final<-matrix(,nrow=0,ncol=ncol(N_prime)) s=1 y<-(1:kk) while(s<=nrow(N_prime)){ ss=1 x<-which(N_prime[s,]==1) mat<-matrix(0,nrow=nrow(matf),ncol=ncol(N_prime)) for(i in x){ mat[,i]<-matf[,ss] #fi<-mat ss=ss+1 } final<-rbind(final,mat) s=s+1 } } ################b part if(v==3){ final<-rbind(final,matA) } if(v==4){ final<-rbind(final,matA) } if(v==5){ final<-rbind(final,fractional) } if(v==6){ final<-rbind(final,fractional) } # if(v==7){ # final<-rbind(final,matA) # } if(v==8){ final<-rbind(final,fractional) } if(v==9){ final<-rbind(final,fractional) } if(v==11){ final<-rbind(final,matA) } if(v==12){ final<-rbind(final,matA) } if(v==13){ final<-rbind(final,fractional) } if(v==14){ final<-rbind(final,fractional) } ############### #if(n_zero!=0){ central_runs<-matrix(0,nrow=n0,ncol=ncol(final)) final<-rbind(final,central_runs) #} ################### if(randomization==F){ #print("SORD (Standard)",quote=FALSE) message("SORD (Standard)") print(final) }else{ mat3<-matrix(,nrow=0,ncol=v) rand<-sample(1:nrow(final),nrow(final),replace = FALSE) for(m in rand){ x11<-matrix(,nrow=1,ncol=v) x11<-final[m,] mat3<-rbind(mat3,x11) } rownames(mat3)<-NULL #print("SORD (Randomized)",quote=FALSE) message("SORD (Randomized)") print(mat3) final<-mat3 } mat<-final #####################full X matrix ######################### p=1 while(p<=v){ x1<-matrix(,nrow=nrow(mat),ncol=0) x1<-(mat[,p])^2 mat<-cbind(mat,x1) p=p+1 } ####################################full X matrix b1=1 b2=1 while(b1<v){ b2=b1+1 while(b2<=v){ mat2<-matrix(,nrow=0,ncol=1) mat2<-mat[,b1]*mat[,b2] mat<-cbind(mat,mat2) b2=b2+1 } b1=b1+1 } x_matrix<-mat ################################### ########### x_matrix<-cbind(matrix(1,nrow=nrow(x_matrix),ncol=1),x_matrix) colnames(x_matrix)<-NULL x_prime_x<-t(x_matrix)%*%x_matrix moment_mat<-(1/nrow(x_matrix))*x_prime_x if(variance==T){ #print("Moment Matrix",quote=FALSE) message("Moment Matrix") print(moment_mat) k1=1 var<-c() while(k1<=nrow(x_matrix)) { V=t(x_matrix[k1,]) b<-t(V) v_y_hat<-V %*%solve(x_prime_x) %*% b var<-c(var,v_y_hat) k1<-k1+1 } variance_of_esitmated_response<-round(var,digits = 3 ) print(table(variance_of_esitmated_response)) } }else{ #print("Please enter a correct value",quote=F) message("Please enter a correct value") } }
/scratch/gouwar.j/cran-all/cranData/AsymmetricSORDs/R/SORD_coded.R
#' Second Order Rotatable Designs with original levels #' #' @param v Number of input factors,v(3<=v<=16) #' @param n0 Number of centre points,n0(>0) #' @param min_L A vector of minimum levels of the factors #' @param max_L A vector of maximum levels of the factors #' @param randomization It is for generating the randomized layout of the design. It takes either TRUE or FALSE and by default, it is set to FALSE #' @param variance This is for generating the moment matrix and prediction variance of the design based on a second order model. It gives unique prediction variance along with its frequencies. It takes either TRUE or FALSE and by default, it is set to FALSE #' @description This function generates second order rotatable designs given in Das and Narasimham (1962) for a given number of input factors (3<=v<=16) with original levels along with coded levels of the factors. It gives the randomized layout of the design along with the moment matrix and prediction variance. Here, all the factors are having 5-levels except for v=7, which gives a rotatable design with 3-levels for each factor. #'@examples #' #'library(AsymmetricSORDs) #'SORD_original(4,3,c(10,15,20,25),c(15,20,25,30),FALSE,FALSE) #' #'@return Second-Order Rotatable Designs with original levels #'@references #'1) M. N. Das and V. L. Narasimham (1962). "Construction of rotatable designs through balanced incomplete block designs". #' #'2) M. Hemavathi, Shashi Shekhar, Eldho Varghese, Seema Jaggi, Bikas Sinha & Nripes Kumar Mandal (2022)<DOI: 10.1080/03610926.2021.1944213> "Theoretical developments in response surface designs: an informative review and further thoughts". #'@export SORD_original<-function(v,n0,min_L,max_L,randomization=FALSE,variance=FALSE){ if(v>2 && v<17){ if(v==3){ bibd<-matrix(c(1,3,2,3,1,2),nrow=3,byrow=TRUE) b<-2^(1/4) matA<-matrix(,nrow=0,ncol=v) d1<-diag(b,nrow=v,ncol=v) d2<-diag(-b,nrow=v,ncol=v) d=1 while(d<=v){ matA<-rbind(matA,d1[d,],d2[d,]) d=d+1 } matA<-matA*(-1) ####################### } if(v==4){ bibd<-matrix(c(2,3,4,1,3,4,1,2,4,1,2,3),nrow=4,byrow=TRUE) b<-sqrt(2*sqrt(3)) ############################ matA<-matrix(,nrow=0,ncol=v) d1<-diag(b,nrow=v,ncol=v) d2<-diag(-b,nrow=v,ncol=v) d=1 while(d<=v){ matA<-rbind(matA,d1[d,],d2[d,]) d=d+1 } matA<-matA*(-1) ############################# } if(v==5){ bibd<-matrix(c(1,5,3,5,4,5,1,4,1,3,3,4,1,2,2,5,2,4,2,3),nrow=10,byrow=TRUE) b=sqrt(1/(2*sqrt(2))) fractional<-matrix(c(1,-1,1,1,1,-1,1,-1,-1,-1,1,1,-1,-1,-1,1,-1,1,1,-1,1,1,-1,-1,1,-1,1,1,-1,1,-1,-1,1,-1,-1,1,-1,1,-1,-1,1,1,1,1,-1,-1,1,-1,-1,-1,1,1,-1,-1,1,-1,1,-1,1,-1,1,1,1,-1,1,-1,-1,-1,1,1,1,1,-1,-1,1,-1,-1,1,1,-1 ),nrow=16,byrow=FALSE) fractional<-fractional*b ################ } if(v==6){ bibd<-matrix(c(1,6,3,5,3,6,4,6,1,5,5,6,1,4,4,5,3,4,1,3,2,6,1,2,2,5,2,4,2,3),nrow=15,byrow=TRUE) ############ b=sqrt(1/(2*sqrt(2))) fractional<-matrix(c(1,-1,1,-1,-1,1,-1,1,-1,-1,1,1,1,1,1,-1,-1,-1,1,-1,-1,-1,1,1,1,1,1,1,-1,-1,-1,-1,1,1,1,-1,-1,1,-1,1,-1,1,-1,-1,1,-1,-1,-1,1,1,1,-1,1,-1,-1,-1,1,1,-1,-1,1,1,-1,1,1,-1,-1,-1,1,-1,1,1,1,-1,-1,-1,-1,1,1,-1,1,-1,1,-1,1,1,1,1,-1,1,-1,-1,1,-1,-1,1,1,-1,-1,1,1,-1,1,-1,-1,-1,-1,1,1,-1,1,-1,-1,1,-1,-1,1,-1,-1,1,1,1,-1,1,-1,1,1,1,-1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,-1,1,1,-1,1,-1,-1,1,1,1,1,1,1,-1,-1,1,-1,1,-1,-1,1,-1,-1,-1,1,1,1,1,1,1,1,-1,1,1,1,-1,-1,-1,1,-1,1,-1,-1,1,-1,-1,-1,1,1,-1),nrow=32,byrow=FALSE) fractional<-fractional*b ################# } if(v==7){ bibd<-matrix(c(1,2,4,2,3,5,3,4,6,4,5,7,5,6,1,6,7,2,7,1,3),nrow=7,byrow=TRUE) bibd<-rbind(bibd,bibd) } if(v==8){ bibd<-matrix(c(1,6,3,5,3,6,3,7,3,8,4,5,4,6,4,8,1,7,1,8,4,7,7,8,6,8,6,7,5,8,5,7,5,6,1,5,1,4,3,4,2,8,2,7,2,6,1,3,2,5,2,4,1,2,2,3),nrow=28,byrow=TRUE) ################### fractional<-matrix(c(1,1,-1,1,-1,-1,-1,-1, -1,-1,1,1,1,-1,-1,-1,1,-1, 1,1,1,-1,1,1,1,-1,-1,-1,1,1,-1, -1,1,-1,1,-1,1,1,1,-1,-1,-1,1,-1, -1,1,1,-1,1,1,-1,1,1,1,-1,1,-1,-1, -1,1,-1,-1,1,1,-1,-1,1,1,1,-1,1,-1, -1,1,-1,1,1,1,1,-1,-1,-1,1,-1,1,1,1, 1,-1,1,1,1,1,1,-1,-1,1,1,1,1,-1,1,-1, -1,-1,1,1,-1,-1,-1,-1,1,-1,1,-1,1,-1, -1,-1,-1,1,1,-1,-1,-1,-1,1,-1,1,-1,1,-1,-1, 1,-1,-1,-1,1,1,-1,-1,-1,1,1,1,-1,1,1,1,-1,-1, 1,-1,1,1,-1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,1,-1,-1, 1,-1,-1,1,-1,1,1,1,1,-1,-1,-1,1,-1,-1,1,-1,-1,1,1 ,1,1,1,1,1,1,-1,-1,1,-1,1,-1,1,-1,1,-1,1,1,1,1, 1,-1,-1,1,1,-1,-1,-1,-1,-1,1,-1,-1,-1,1,-1,-1,1,1,-1,1,-1,1, 1,-1,-1,-1,-1,-1,1,-1,1,1,-1,-1,-1,1,1,-1,1,1,1,1,-1,1,-1,1,1, 1,1,1,-1,-1,1,1,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1,1,1,1,1,1,1,-1,1,1,1,-1,-1,-1,1,-1,1,-1,-1,1,-1,-1,-1,1,1,-1),nrow=32,byrow=FALSE) #fractional<-fractional*b matA<-matrix(,nrow=0,ncol=v) d1<-diag(b,nrow=v,ncol=v) d2<-diag(-b,nrow=v,ncol=v) d=1 while(d<=v){ matA<-rbind(matA,d1[d,],d2[d,]) d=d+1 } matA<-matA*(-1) } if(v==13){ bibd<-matrix(c(1,3,8,9,1,4,5,7,7,9,10,11,7,8,12,13,5,6,8,10,1,6,11,12,4,6,9,13,3,5,11,13,1,2,10,13,3,4,10,12,2,5,9,12,2,4,8,11,2,3,6,7),nrow=13,byrow=TRUE) #################### fractional<-matrix(c(1,-1,1,-1,-1,-1,-1,-1,-1,-1,1,-1,-1,1,-1,1,1,-1,1,-1,1,-1,1,-1,-1,-1,1,-1,-1,-1,1,-1,-1,-1,-1,1,-1,1,1,1,-1,-1,-1,1,1,1,-1,1,-1,-1,1,-1,-1,1,1,1,1,-1,1,-1,-1,-1,1,-1,1,1,1,-1,-1,1,1,1,1,-1,-1,-1,-1,1,-1,-1,1,1,1,-1,1,-1,1,1,-1,-1,-1,-1,-1,1,1,-1,1,-1,1,1,-1,-1,-1,-1,-1,1,-1,1,-1,-1,-1,-1,1,1,-1,-1,-1,-1,1,-1,1, 1,1,-1,-1,-1,1,-1,1,1,1,-1,-1,1,1,-1,-1,1,-1,-1,1,-1,-1,-1,-1,-1,-1,-1,-1,1,1,1,1,1,-1,-1,-1,-1,-1,1,1,1,-1,-1,-1,1,-1,1,-1,-1,1,1,1,-1,-1,-1,1,1,1,-1,-1,-1,-1,1,1,1,1,-1,-1,-1,-1,1,-1,1,-1,1,-1,-1,1,1,-1,1,1,-1,-1,-1,-1,1,-1,1,1,-1,1,-1,-1,1,1,-1,1,1,-1,-1,1,-1,1,-1,-1,1,1,-1,-1,1,-1,-1,-1,1,-1,1,1,1,1,1,-1,1,1,-1,-1,1,1,1,-1,-1,-1,1,1,-1,1,-1,-1,1,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1,1,-1,-1,-1,1,-1,-1,-1,1,-1,-1,1,1,-1,-1,-1,-1,1,-1,-1,1,-1,1,-1,-1,1,1,1,-1,-1,-1,1,-1,1,-1,-1,1,1,1,-1,-1,-1,-1,-1,1,1,1,-1,1,-1,1,1,1,1,1,1,-1,1,-1,-1,1,1,1,1,-1,1,-1,-1,1,1,-1,1,-1,-1,-1,-1,-1,-1,1,1,-1,-1,-1,-1,1,1,1,1,1,1,-1,1,-1,-1,1,1,-1,-1,1,1,-1,1,1,-1,1,-1,1,1,-1,-1,1,-1,-1,1,-1,-1,-1,1,1,-1,1,-1,-1,1,1,1,1,-1,-1,-1,1,-1,1,-1,-1,-1,1,-1) ,nrow=1024,byrow=FALSE) b<-sqrt(5/16) fractional<-fractional*b ############# } if(v==15){ bibd<-matrix(c(1,2,5,8,11,13,14,5,6,7,8,10,14,15,1,3,4,6,7,13,14,1,4,6,8,11,12,15,5,6,7,9,11,12,13,1,3,5,9,12,14,15,1,3,7,8,9,10,11,4,8,9,10,12,13,14,3,4,5,10,11,13,15,2,4,7,9,11,14,15,1,2,6,9,10,13,15,2,3,4,5,6,8,9,2,3,7,8,12,13,15,1,2,4,5,7,10,12,2,3,6,10,11,12,14),nrow=15,byrow=TRUE) ############# fractional<-matrix(c(1 , -1 , 1 , 1 , -1 , -1 , -1 , 1 , 1 , 1 , -1 , -1 , -1 , -1 , 1 , 1 , -1 , 1 , 1 , 1 , 1 , -1 , -1 , 1 , -1 , 1 , 1 , 1 , 1 , 1 , 1 , -1 , -1 , 1 , -1 , 1 , 1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , 1 , 1 , 1 , -1 , -1 , -1 , 1 , 1 , 1 , -1 , -1 , -1 , -1 , 1 , -1 , -1 , -1 , 1 , 1 , 1, 1 , 1 , -1 , -1 , -1 , 1 , -1 , 1 , 1 , 1 , 1 , 1 , -1 , 1 , 1 , -1 , -1 , -1 , -1 , -1 , 1 , 1 , 1 , 1 , -1 , -1 , 1 , -1 , -1 , -1 , -1 , -1 , -1 , 1 , -1 , -1 , 1 , 1 , -1 , 1 , -1 , 1 , -1 , 1 , 1 , 1 , 1 , -1 , -1 , 1 , -1 , -1 , 1 , 1 , 1 , 1 , -1 , -1 , -1 , -1 , 1 , -1 , 1 , 1 , -1 , -1 , 1 , 1 , 1 , -1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , -1 , 1 , -1 , 1 , 1 , 1 , -1 , -1 , -1 , 1 , 1 , 1 , -1 , 1 , 1 , 1 , -1 , 1 , -1 , -1 , 1 , -1 , -1 , -1 , 1 , 1 , 1 , 1 , 1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , 1 , 1 , -1 , 1 , -1 , -1 , 1 , 1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , 1 , -1 , -1 , -1 , 1 , 1 , 1 , -1 , 1 , 1 , -1 , -1 , -1 , 1 , -1 , -1 , -1 , 1 , -1 , 1 , 1 , -1 , 1 , 1 , 1 , 1 , -1 , -1 , 1 , -1 , -1 , -1 , 1 , -1 , 1 , -1 , -1 , -1 , 1 , -1 , -1 , 1 , 1 , -1 , -1 , 1 , 1 , -1 , 1 , -1 , 1 , 1 , -1 , 1 , 1 , -1 , 1 , -1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , -1 , -1 , 1 , 1 , -1 , 1 , 1 , -1 , -1 , -1 , -1 , 1 , 1 , -1 , -1 , -1 , -1 , 1 , 1 , 1 , -1 , 1 , 1 , 1 , 1 , 1 , -1 , -1 , 1 , -1 , -1 , -1 , -1 , -1 , 1 , 1 , 1 , -1 , -1 , -1 , -1 , -1 , 1 , -1 , 1 , 1 , -1 , -1 , -1 , -1 , 1 , -1 , -1 , 1 , 1 , 1 , 1 , -1 , 1 , 1 , 1 , 1 , -1 , 1 , -1 , -1 , -1 , 1 , -1 , 1 , -1 , 1 , 1 , 1 , -1 , 1 , 1 , -1 , 1 , -1 , 1 , 1 , 1 , -1 , -1 , -1 , -1 , 1 , -1 , 1 , 1 , 1 , -1 , 1 , -1 , 1 , 1 , 1 , -1 , -1 , 1 , -1 , -1 , 1 , -1 , -1 , -1 , 1 , -1 , 1 , -1 , -1 , 1 , -1 , -1 , -1 , 1 , -1 , 1 , 1 , -1 , 1 , 1 , -1 , 1 , -1 , 1 , 1 , -1 , -1 , -1 , 1 , 1 , -1 , 1 , 1 , 1 , 1 , -1 , 1 , -1 , 1 , -1 , 1 , -1 , 1 , -1 , 1 , 1 , -1 , -1 , -1 , -1 , -1 , 1 , -1 , -1 , 1 , -1 , 1 , 1 , -1 , 1 , -1 , 1 , 1 , 1 , -1 , -1 , 1 , -1 , 1 , 1 , 1 , -1 , -1 , -1 , 1 , 1 , -1 , -1 , 1 , -1 , 1 , -1 , -1 , -1 , 1 ) ,nrow=64,byrow=FALSE) b<-sqrt(8) ############### matA<-matrix(,nrow=0,ncol=v) d1<-diag(b,nrow=v,ncol=v) d2<-diag(-b,nrow=v,ncol=v) d=1 while(d<=v){ matA<-rbind(matA,d1[d,],d2[d,]) d=d+1 } matA<-matA*(-1) ################ } if(v==16){ bibd<-matrix(c(3,4,9,11,13,15,2,7,8,9,11,12,1,7,8,13,15,16,2,5,6,9,13,16,1,5,6,11,12,15,1,4,6,7,9,10,4,6,8,12,13,14,1,2,3,4,5,8,3,5,7,10,12,13,4,5,7,11,14,16,2,4,10,12,15,16,1,3,9,12,14,16,2,3,6,7,14,15,3,6,8,10,11,16,1,2,10,11,13,14,5,8,9,10,14,15),nrow=16,byrow=TRUE) ############ fractional<-matrix(c(1,-1,1,-1,-1,1,-1,1,-1,-1,1,1,1,1,1,-1,-1,-1,1,-1,-1,-1,1,1,1,1,1,1,-1,-1,-1,-1,1,1,1,-1,-1,1,-1,1,-1,1,-1,-1,1,-1,-1,-1,1,1,1,-1,1,-1,-1,-1,1,1,-1,-1,1,1,-1,1,1,-1,-1,-1,1,-1,1,1,1,-1,-1,-1,-1,1,1,-1,1,-1,1,-1,1,1,1,1,-1,1,-1,-1,1,-1,-1,1,1,-1,-1,1,1,-1,1,-1,-1,-1,-1,1,1,-1,1,-1,-1,1,-1,-1,1,-1,-1,1,1,1,-1,1,-1,1,1,1,-1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,-1,1,1,-1,1,-1,-1,1,1,1,1,1,1,-1,-1,1,-1,1,-1,-1,1,-1,-1,-1,1,1,1,1,1,1,1,-1,1,1,1,-1,-1,-1,1,-1,1,-1,-1,1,-1,-1,-1,1,1,-1),nrow=32,byrow=FALSE) ######### } bb=nrow(bibd) kk=ncol(bibd) cc<-c(1:v) incident<-matrix(0,nrow=v, ncol=bb) vv=1 while(vv<=v){ ###########raw position of a element x<-which(bibd %in% c(cc[vv])) #########################position identify only k=1 while(k<=length(x)){ if(x[k]%%bb!=0){ x[k]<-x[k]%%bb }else{ x[k]<-bb } # if(x[k]>b){ # x[k]<-x[k]%%b # } k=k+1 } ################ ss=1 while(ss<=length(x)){ incident[vv,x[ss]]<-1 ss=ss+1 } vv=vv+1 } N_prime<-t(incident) #########################factorial form k=2^kk i=1 matf<-matrix(,nrow=k,ncol=0) while(i<=kk){ x<-c((rep(-1,(2^(kk-i)))),(rep(1,(2^(kk-i))))) x1<-t(rep(x,k/length(x))) matf<-cbind(matf,t(x1)) i=i+1 } ###############v=11 if(v==11){ matf<-fractional } ##############v=12 if(v==12){ matf<-fractional } ######################for v=15 if(v==15){ final<-matrix(,nrow=0,ncol=ncol(N_prime)) s=1 y<-(1:kk) while(s<=nrow(N_prime)){ ss=1 x<-which(N_prime[s,]==1) mat<-matrix(0,nrow=nrow(fractional),ncol=ncol(N_prime)) for(i in x){ mat[,i]<-fractional[,ss] #fi<-mat ss=ss+1 } final<-rbind(final,mat) s=s+1 } final<-rbind(final,matA) } #################v=16 if(v==16){ final<-matrix(,nrow=0,ncol=ncol(N_prime)) s=1 y<-(1:kk) while(s<=nrow(N_prime)){ ss=1 x<-which(N_prime[s,]==1) mat<-matrix(0,nrow=nrow(fractional),ncol=ncol(N_prime)) for(i in x){ mat[,i]<-fractional[,ss] #fi<-mat ss=ss+1 } final<-rbind(final,mat) s=s+1 } } ########################## BBD solved if(v!=15 && v!=16){ final<-matrix(,nrow=0,ncol=ncol(N_prime)) s=1 y<-(1:kk) while(s<=nrow(N_prime)){ ss=1 x<-which(N_prime[s,]==1) mat<-matrix(0,nrow=nrow(matf),ncol=ncol(N_prime)) for(i in x){ mat[,i]<-matf[,ss] #fi<-mat ss=ss+1 } final<-rbind(final,mat) s=s+1 } } ################b part if(v==3){ final<-rbind(final,matA) } if(v==4){ final<-rbind(final,matA) } if(v==5){ final<-rbind(final,fractional) } if(v==6){ final<-rbind(final,fractional) } if(v==8){ final<-rbind(final,fractional) } if(v==9){ final<-rbind(final,fractional) } if(v==11){ final<-rbind(final,matA) } if(v==12){ final<-rbind(final,matA) } if(v==13){ final<-rbind(final,fractional) } if(v==14){ final<-rbind(final,fractional) } ############### #if(n_zero!=0){ central_runs<-matrix(0,nrow=n0,ncol=ncol(final)) final<-rbind(final,central_runs) #} ################### if(randomization==F){ # print("SORD coded (Standard)",quote=FALSE) message("SORD coded (Standard)") print(final) }else{ mat3<-matrix(,nrow=0,ncol=v) rand<-sample(1:nrow(final),nrow(final),replace = FALSE) for(m in rand){ x11<-matrix(,nrow=1,ncol=v) x11<-final[m,] mat3<-rbind(mat3,x11) } rownames(mat3)<-NULL #print("SORD coded (Randomized)",quote=FALSE) message("SORD coded (Randomized)") print(mat3) final<-mat3 } ############unique value identify if(v!=7){ uq<-c(-b,-1,0,1,b) original<-matrix(,length(min_L),ncol=5) for (j in 1:length(min_L)){ for (i in 1:5){ original[j,i]<-(((max_L[j]-min_L[j])/2)*uq[i])+((min_L[j]+max_L[j])/2) } } } ff<-final if(v==7){ min<-t(t(min_L)) max<-t(t(max_L)) mid<-matrix(,nrow=0,ncol=1) for(i in 1:length(min_L)){ x<-matrix(,nrow=1,ncol=0) x<-(min_L[i]+max_L[i])/2 mid<-rbind(mid,(x)) } original1<-cbind(min,mid,max) uq<-c(-1,0,1) s=1 while(s<=v){ o<-c(original1[s,]) ff[which(ff[,s]==0),s]<-o[2] ff[which(ff[,s]==-1),s]<-o[1] #ff[which(ff[,s]==-b),s]<-o[1] ff[which(ff[,s]==1),s]<-o[3] # ff[which(ff[,s]==b),s]<-o[5] s=s+1 } } #################### if(v!=7){ s=1 while(s<=v){ o<-c(original[s,]) ff[which(ff[,s]==0),s]<-o[3] ff[which(ff[,s]==-1),s]<-o[2] ff[which(ff[,s]==-b),s]<-o[1] ff[which(ff[,s]==1),s]<-o[4] ff[which(ff[,s]==b),s]<-o[5] s=s+1 } } ################## final<-ff ##################### if(randomization==F){ #print("SORD original (Standard)",quote=FALSE) message("SORD original (Standard)") print(final) }else{ #print("SORD original (Randomized)",quote=FALSE) message("SORD original (Randomized)") print(final) final<-mat3 } mat<-final #####################full X matrix ######################### p=1 while(p<=(v)){ x1<-matrix(,nrow=nrow(mat),ncol=0) x1<-(mat[,p])^2 mat<-cbind(mat,x1) p=p+1 } b1=1 b2=1 while(b1<(v)){ b2=b1+1 while(b2<=(v)){ mat2<-matrix(,nrow=0,ncol=1) mat2<-mat[,(b1)]*mat[,(b2)] mat<-cbind(mat,mat2) b2=b2+1 } b1=b1+1 } x_matrix<-mat ################################### ########### x_matrix<-cbind(matrix(1,nrow=nrow(x_matrix),ncol=1),x_matrix) colnames(x_matrix)<-NULL x_prime_x<-t(x_matrix)%*%x_matrix moment_mat<-(1/nrow(x_matrix))*x_prime_x if(variance==T){ #print("Moment Matrix",quote=FALSE) message("Moment Matrix") print(moment_mat) ############ k1=1 var<-c() while(k1<=nrow(x_matrix)){ V=t(x_matrix[k1,]) b<-t(V) v_y_hat<-V %*%solve(x_prime_x) %*% b var<-c(var,v_y_hat) k1<-k1+1 } variance_of_esitmated_response<-round(var,digits = 3 ) print(table(variance_of_esitmated_response)) } }else{ #print("Please enter a correct value",quote=F) message("Please enter a correct value") } }
/scratch/gouwar.j/cran-all/cranData/AsymmetricSORDs/R/SORD_original.R
#----------------------------------------------------------------------# # SD : Estimate the standard deviation for parameter estimates # #----------------------------------------------------------------------# # # # data.y : Matrix of responses. It is assumed that the first column # # contains integer patient IDs, the second column contains # # the time of measurement, and the third column contains # # the value of the measurement. # # # # data.x : Matrix of covariates. It is assumed that the first column# # contains integer patient IDs, the second column contains # # the time of measurement, and the remaining columns # # contain the values of the covariates. # # # # bandwidth : a vector or numeric object of bandwidths # # # # kType : a character. One of "epan", "uniform", or "gauss". # # Specifies the form of the kernel function. # # # # lType : a character. One of "identity", "log", "logistic". # # Specifies the form of the link function. # # # # bHat : an object of class numeric # # parameter estimates. # # # # xIs : an object of class list. # # v - which elements of x match y[i]'s id # # n - number of elements that match. # # # # yIs : an object of class list. # # v - which elements of y match patientID[i] # # n - number of elements that match. # # # # nPatients : an object of class numeric. # # the number of patients in dataset. # # # # distanceFunction : an object of class character. # # name of the distance function to use for calculation # # # # tt : If provided, a vector of times at which to evaluate the # # kernel # # # #----------------------------------------------------------------------# # # # Returns a vector of standard deviations. # # # #----------------------------------------------------------------------# SD <- function(bHat, data.y, data.x, bandwidth, kType, lType, nPatients, xIs, yIs, distanceFunction, tt = NULL) { #------------------------------------------------------------------# # Minimize u-function to estimate parameters # #------------------------------------------------------------------# argList <- list("xIs" = xIs, "data.x" = data.x, "data.y" = data.y, "bandwidth" = bandwidth, "kType" = kType, "tt" = tt) dis <- do.call(what = distanceFunction, args = argList) xIs <- dis$xIs dis <- dis$dis res <- cmp_duFunc(pars = bHat, data.y = data.y, data.x = data.matrix(data.x[, 3L:ncol(data.x), drop=FALSE]), kernel = dis, lType = lType, xIs = xIs, yIs = yIs, nPatients = nPatients) dU <- res$du var <- res$var var <- t(var) %*% var invdU <- try(solve(dU), silent = TRUE) if( is(invdU, 'try-error') ) { cat("unable to invert derivative of estimating equation\n") stop(attr(invdU,"condition"), call. = FALSE) } var <- invdU %*% var %*% t(invdU) return(sqrt( diag(var) )) }
/scratch/gouwar.j/cran-all/cranData/AsynchLong/R/SD.R
#----------------------------------------------------------------------# # asynchHK : Half-Kernel Time-invariant coefficients # #----------------------------------------------------------------------# # # # data.x : Matrix of covariates. It is assumed that the first column# # contains integer patient IDs, the second column contains # # the time of measurement, and the remaining columns # # contain the values of the covariates. # # # # data.y : Matrix of responses. It is assumed that the first column # # contains integer patient IDs, the second column contains # # the time of measurement, and the third column contains # # the value of the measurement. # # # # kType : a character. One of "epan", "uniform", or "gauss". # # Specifies the form of the kernel function. # # # # lType : a character. One of "identity", "log", "logistic". # # Specifies the form of the link function. # # # # bw : a vector or numeric object of bandwidths # # # # nCores : a numeric. Number of cores to use for auto-tune # # implementation # # # #----------------------------------------------------------------------# asynchHK <- function(data.x, data.y, kType = "epan", lType = "identity", bw = NULL, nCores = 1, verbose = TRUE, ...){ #------------------------------------------------------------------# # Process and verify input datasets # #------------------------------------------------------------------# data.x <- preprocessX(data.x = data.x) data.y <- preprocessY(data.y = data.y) #------------------------------------------------------------------# # Scale times # #------------------------------------------------------------------# rge <- range(c(data.y[,2L],data.x[,2L])) data.y[,2L] <- (data.y[,2L] - rge[1L])/(rge[2L] - rge[1L]) data.x[,2L] <- (data.x[,2L] - rge[1L])/(rge[2L] - rge[1L]) if( is.null(x = bw) ) { result <- kernelAuto(data.x = data.x, data.y = data.y, kType = kType, lType = lType, time = NULL, distanceFunction = "distanceHK", nCores = nCores, verbose = verbose, ...) } else { result <- kernelFixed(data.y = data.y, data.x = data.x, bandwidth = bw, kType = kType, lType = lType, time = NULL, distanceFunction = "distanceHK", verbose = verbose, ...) } return( result ) }
/scratch/gouwar.j/cran-all/cranData/AsynchLong/R/asynchHK.R
#----------------------------------------------------------------------# # asynchLV : Last Value Carried Forward # #----------------------------------------------------------------------# # # # data.x : Matrix of covariates. It is assumed that the first column# # contains integer patient IDs, the second column contains # # the time of measurement, and the remaining columns # # contain the values of the covariates. # # # # data.y : Matrix of responses. It is assumed that the first column # # contains integer patient IDs, the second column contains # # the time of measurement, and the third column contains # # the value of the measurement. # # # # lType : a character. One of "identity", "log", "logistic". # # Specifies the form of the link function. # # # #----------------------------------------------------------------------# asynchLV <- function(data.x, data.y, lType = "identity", verbose = TRUE, ...) { #------------------------------------------------------------------# # Process and verify input datasets # #------------------------------------------------------------------# data.x <- preprocessX(data.x = data.x) data.y <- preprocessY(data.y = data.y) #------------------------------------------------------------------# # Scale times # #------------------------------------------------------------------# rge <- range(c(data.y[,2L],data.x[,2L])) data.y[,2L] <- (data.y[,2L] - rge[1L])/(rge[2L] - rge[1L]) data.x[,2L] <- (data.x[,2L] - rge[1L])/(rge[2L] - rge[1L]) result <- kernelFixed(data.y = data.y, data.x = data.x, bandwidth = 0.01, kType = NULL, lType = lType, time = NULL, distanceFunction = "distanceLV", verbose = verbose, ...) return( result ) }
/scratch/gouwar.j/cran-all/cranData/AsynchLong/R/asynchLV.R
#----------------------------------------------------------------------# # asynchTD : Time-dependent coefficients # #----------------------------------------------------------------------# # # # data.x : Matrix of covariates. It is assumed that the first column# # contains integer patient IDs, the second column contains # # the time of measurement, and the remaining columns # # contain the values of the covariates. # # # # data.y : Matrix of responses. It is assumed that the first column # # contains integer patient IDs, the second column contains # # the time of measurement, and the third column contains # # the value of the measurement. # # # # times : A vector of time points. # # # # kType : a character. One of "epan", "uniform", or "gauss". # # Specifies the form of the kernel function. # # # # lType : a character. One of "identity", "log", "logistic". # # Specifies the form of the link function. # # # # bw : a numeric or NULL. Kernel bandwidth. # # If NULL, autotune is used to determine optimal bandwidth.# # # # nCores : a numeric. Number of cores to use for auto-tune # # implementation # # # #----------------------------------------------------------------------# asynchTD <- function(data.x, data.y, times, kType = "epan", lType = "identity", bw = NULL, nCores = 1, verbose = TRUE, ...) { #------------------------------------------------------------------# # Process and verify input datasets # #------------------------------------------------------------------# data.x <- preprocessX(data.x = data.x) data.y <- preprocessY(data.y = data.y) #------------------------------------------------------------------# # Scale times. # #------------------------------------------------------------------# rge <- range(c(data.y[,2L],data.x[,2L])) data.y[,2L] <- (data.y[,2L] - rge[1L])/(rge[2L] - rge[1L]) data.x[,2L] <- (data.x[,2L] - rge[1L])/(rge[2L] - rge[1L]) nTimes <- length(times) #------------------------------------------------------------------# # Assumes patient id and measurement time columns # #------------------------------------------------------------------# nCov <- ncol(data.x) - 2L bHat <- matrix(data = 0.0, nrow = nTimes, ncol = nCov, dimnames = list(NULL,colnames(data.x)[3L:(nCov+2L)])) sdVec <- bHat optH <- bHat minMSE <- bHat if( !is.null(x = bw) ) { if( length(bw) > 1L ) { stop("Only a single bandwidth can be provided.") } } for( var in 1L:nTimes ) { cat("Time point: ", times[var], "\n") if( is.null(x = bw) ) { result <- kernelAuto(data.x = data.x, data.y = data.y, kType = kType, lType = lType, time = times[var], distanceFunction = "distanceTD", nCores = nCores, verbose = verbose, ...) bHat[var,] <- result$betaHat sdVec[var,] <- result$stdErr optH[var,] <- result$optBW minMSE[var,] <- result$minMSE } else { result <- kernelFixed(data.y = data.y, data.x = data.x, bandwidth = bw, kType = kType, lType = lType, time = times[var], distanceFunction = "distanceTD", verbose = verbose, ...) bHat[var,] <- result$betaHat sdVec[var,] <- result$stdErr } } plotTD(bHat, sdVec, times) zv <- bHat/sdVec pv <- 2.0*pnorm(-abs(zv)) if( is.null(x = bw) ) { return( list( "betaHat" = bHat, "stdErr" = sdVec, "zValue" = zv, "pValue" = pv, "optBW" = optH, "minMSE" = minMSE ) ) } else { return( list( "betaHat" = bHat, "stdErr" = sdVec, "zValue" = zv, "pValue" = pv ) ) } }
/scratch/gouwar.j/cran-all/cranData/AsynchLong/R/asynchTD.R
#----------------------------------------------------------------------# # asynchTI : Time-invariant coefficients # #----------------------------------------------------------------------# # # # data.x : Matrix of covariates. It is assumed that the first column# # contains integer patient IDs, the second column contains # # the time of measurement, and the remaining columns # # contain the values of the covariates. # # # # data.y : Matrix of responses. It is assumed that the first column # # contains integer patient IDs, the second column contains # # the time of measurement, and the third column contains # # the value of the measurement. # # # # kType : a character. One of "epan", "uniform", or "gauss". # # Specifies the form of the kernel function. # # # # lType : a character. One of "identity", "log", "logistic". # # Specifies the form of the link function. # # # # bw : a vector or numeric object of bandwidths # # # # nCores : a numeric. Number of cores to use for auto-tune # # implementation # # # #----------------------------------------------------------------------# asynchTI <- function(data.x, data.y, kType = "epan", lType = "identity", bw = NULL, nCores = 1, verbose = TRUE, ...) { #------------------------------------------------------------------# # Process and verify input datasets # #------------------------------------------------------------------# data.x <- preprocessX(data.x = data.x) data.y <- preprocessY(data.y = data.y) #------------------------------------------------------------------# # Scale times # #------------------------------------------------------------------# rge <- range(c(data.y[,2L],data.x[,2L])) data.y[,2L] <- (data.y[,2L] - rge[1L])/(rge[2L] - rge[1L]) data.x[,2L] <- (data.x[,2L] - rge[1L])/(rge[2L] - rge[1L]) if( is.null(x = bw) ) { result <- kernelAuto(data.x = data.x, data.y = data.y, kType = kType, lType = lType, time = NULL, distanceFunction = "distanceTI", nCores = nCores, verbose = verbose, ...) } else { result <- kernelFixed(data.y = data.y, data.x = data.x, bandwidth = bw, kType = kType, lType = lType, time = NULL, distanceFunction = "distanceTI", verbose = verbose, ...) } return( result ) }
/scratch/gouwar.j/cran-all/cranData/AsynchLong/R/asynchTI.R
#----------------------------------------------------------------------# # asynchWLV : Weighted Last Value Time-invariant coefficients # #----------------------------------------------------------------------# # # # data.x : Matrix of covariates. It is assumed that the first column# # contains integer patient IDs, the second column contains # # the time of measurement, and the remaining columns # # contain the values of the covariates. # # # # data.y : Matrix of responses. It is assumed that the first column # # contains integer patient IDs, the second column contains # # the time of measurement, and the third column contains # # the value of the measurement. # # # # kType : a character. One of "epan", "uniform", or "gauss". # # Specifies the form of the kernel function. # # # # lType : a character. One of "identity", "log", "logistic". # # Specifies the form of the link function. # # # # bw : a vector or numeric object of bandwidths # # # # nCores : a numeric. Number of cores to use for auto-tune # # implementation # # # #----------------------------------------------------------------------# asynchWLV <- function(data.x, data.y, kType = "epan", lType = "identity", bw = NULL, nCores = 1, verbose = TRUE, ...){ #------------------------------------------------------------------# # Process and verify input datasets # #------------------------------------------------------------------# data.x <- preprocessX(data.x = data.x) data.y <- preprocessY(data.y = data.y) #------------------------------------------------------------------# # Scale times # #------------------------------------------------------------------# rge <- range(c(data.y[,2L],data.x[,2L])) data.y[,2L] <- (data.y[,2L] - rge[1L])/(rge[2L] - rge[1L]) data.x[,2L] <- (data.x[,2L] - rge[1L])/(rge[2L] - rge[1L]) if( is.null(x = bw) ) { result <- kernelAuto(data.x = data.x, data.y = data.y, kType = kType, lType = lType, time = NULL, distanceFunction = "distanceWLV", nCores = nCores, verbose = verbose, ...) } else { result <- kernelFixed(data.y = data.y, data.x = data.x, bandwidth = bw, kType = kType, lType = lType, time = NULL, distanceFunction = "distanceWLV", verbose = verbose, ...) } return( result ) }
/scratch/gouwar.j/cran-all/cranData/AsynchLong/R/asynchWLV.R
#----------------------------------------------------------------------# # betaHat : uses R's optim to estimate parameters # #----------------------------------------------------------------------# # # # data.y : Matrix of responses. It is assumed that the first column # # contains integer patient IDs, the second column contains # # the time of measurement, and the third column contains # # the value of the measurement. # # # # data.x : Matrix of covariates. It is assumed that the first column# # contains integer patient IDs, the second column contains # # the time of measurement, and the remaining columns # # contain the values of the covariates. # # # # bandwidth : a vector or numeric object of bandwidths # # # # kType : a character. One of "epan", "uniform", or "gauss". # # Specifies the form of the kernel function. # # # # lType : a character. One of "identity", "log", "logistic". # # Specifies the form of the link function. # # # # nPatients : an object of class numeric. # # the number of patients in dataset. # # # # xIs : an object of class list. # # v - which elements of x match y[i]'s id # # n - number of elements that match. # # # # yIs : an object of class list. # # v - which elements of y match patientID[i] # # n - number of elements that match. # # # # distanceFunction : an object of class character. # # name of the distance function to use for calculation # # # # tt : If provided, a vector of times at which to evaluate the # # kernel # # # # # # guess : If provided, initial guess for beta # #----------------------------------------------------------------------# # # # Returns a vector of parameter estimates. # # # #----------------------------------------------------------------------# betaHat <- function(data.y, data.x, bandwidth, kType, lType, nPatients, xIs, yIs, distanceFunction, tt, guess = NULL) { #------------------------------------------------------------------# # Determine the number of covariates & initialize parameter # # estimates. Note that an intercept term is assumed here. # #------------------------------------------------------------------# nCov <- ncol(data.x) - 2L if( is.null(x = guess) ) { beta <- array(runif(nCov, min=0.0, max=0.5)) } else { beta <- guess } #------------------------------------------------------------------# # Minimize u-function to estimate parameters # #------------------------------------------------------------------# argList <- list("xIs" = xIs, "data.x" = data.x, "data.y" = data.y, "bandwidth" = bandwidth, "kType" = kType, "tt" = tt) dis <- do.call(what = distanceFunction, args = argList) xIs <- dis$xIs dis <- dis$dis if( lType == 'identity' ) { par <- uFuncIden(data.y = data.y, data.x = data.matrix(data.x[,3L:ncol(data.x), drop=FALSE]), kernel = dis, xIs = xIs, yIs = yIs, nPatients = nPatients) } else { opt <- stats::optim(par = beta, fn = optFunc, gr = doptFunc, method = "Nelder-Mead", data.y = data.y, data.x = data.matrix(data.x[,3L:ncol(data.x), drop=FALSE]), kernel = dis, lType = lType, xIs = xIs, yIs = yIs, nPatients = nPatients) if(opt$convergence != 0) { warning(paste("optim did not converge. Code: ", opt$convergence, "\nMessage: ", opt$message, "\nvalue: ", opt$value), call. = FALSE) } par <- opt$par } return(par) }
/scratch/gouwar.j/cran-all/cranData/AsynchLong/R/betaHat.R
distanceLV <- function(xIs, data.x, data.y, ...) { dis <- list() for( i in 1L:nrow(data.y) ) { dis[[i]] <- 0.0 if( xIs[[i]]$n < 0.5 ) next xtime <- data.x[xIs[[i]]$v,2L] xtime[ xtime > data.y[i,2L]] <- NA tst <- which.max(xtime) if( length(tst) < 0.5 ) { xIs[[i]]$v <- array(dim=0L) xIs[[i]]$n <- 0L next } dis[[i]] <- 1.0 xIs[[i]]$v <- xIs[[i]]$v[tst] xIs[[i]]$n <- 1L } return(list("dis" = dis, "xIs" = xIs)) } distanceTI <- function(xIs, data.x, data.y, bandwidth, kType, ...) { dis <- list() nCov <- ncol(data.x) - 2L lbw <- length(bandwidth) spr <- isTRUE(all.equal(lbw,nCov)) for( i in 1L:nrow(data.y) ) { if( xIs[[i]]$n < 0.5 ) next mat <- matrix(data = 0.0, nrow = xIs[[i]]$n, ncol = nCov) kernelTime <- data.y[i,2L] - data.x[xIs[[i]]$v,2L] for( k in 1:lbw ) { mat[,k] <- local_kernel(t = kernelTime, h = bandwidth[k], kType = kType) } if( !spr ) mat[,2L:nCov] <- mat[,1L] dis[[i]] <- mat } return(list("dis" = dis, "xIs" = xIs)) } distanceTD <- function(xIs, data.x, data.y, bandwidth, kType, tt, ...) { lbw <- length(bandwidth) if( !isTRUE(all.equal(lbw,(ncol(data.x)-2L))) ) { bandwidth <- rep(bandwidth, ncol(data.x)-2L) } lbw <- length(bandwidth) funcXY <- function(x, dfx, dfy) { kernelTime <- c(tt - dfx[,2L],tt - dfy[,2L]) return(local_kernel(t = kernelTime, h = bandwidth[x], kType = kType)) } nx <- nrow(data.x) ny <- nrow(data.y) disXY <- apply(X = array(1L:lbw), MARGIN = 1L, FUN = funcXY, dfx = data.x, dfy = data.y) disX <- disXY[1:nx,,drop=FALSE] disY <- disXY[(nx+1):(nx+ny),,drop=FALSE] dis <- lapply(X = 1L:ny, FUN = function(x){ disY[x,]*disX[xIs[[x]]$v,,drop=FALSE] }) return(list("dis" = dis, "xIs" = xIs)) } distanceWLV <- function(xIs, data.x, data.y, bandwidth, kType, ...) { dis <- list() nCov <- ncol(data.x) - 2L lbw <- length(bandwidth) spr <- isTRUE(all.equal(lbw,nCov)) for( i in 1L:nrow(data.y) ) { dis[[i]] <- 0.0 if( xIs[[i]]$n < 0.5 ) next xtime <- data.x[xIs[[i]]$v,2L] xtime[ xtime > data.y[i,2L]] <- NA tst <- which.max(xtime) if( length(tst) < 0.5 ) { xIs[[i]]$v <- array(dim=0L) xIs[[i]]$n <- 0L next } xtime <- xtime[tst] xIs[[i]]$v <- xIs[[i]]$v[tst] xIs[[i]]$n <- 1L kernelTime <- data.y[i,2L] - xtime mat <- matrix(data = 0.0, nrow = 1L, ncol = nCov) for( k in 1:lbw ) { mat[,k] <- local_kernel(t = kernelTime, h = bandwidth[k], kType = kType) } if( !spr ) mat[,2L:nCov] <- mat[,1L] dis[[i]] <- mat } return(list("dis" = dis, "xIs" = xIs)) } distanceHK <- function(xIs, data.x, data.y, bandwidth, kType, ...) { dis <- list() nCov <- ncol(data.x) - 2L lbw <- length(bandwidth) spr <- isTRUE(all.equal(lbw,nCov)) for( i in 1L:nrow(data.y) ) { if( xIs[[i]]$n < 0.5 ) next xtime <- data.x[xIs[[i]]$v,2L] tst <- xtime < data.y[i,2L] mat <- matrix(data = 0.0, nrow = xIs[[i]]$n, ncol = nCov) kernelTime <- data.y[i,2L] - data.x[xIs[[i]]$v,2L] for( k in 1L:lbw ) { mat[,k] <- local_kernel(t = kernelTime, h = bandwidth[k], kType = kType) } if( !spr ) mat[,2L:nCov] <- mat[,1L] dis[[i]] <- mat*tst } return(list("dis" = dis, "xIs" = xIs)) }
/scratch/gouwar.j/cran-all/cranData/AsynchLong/R/distances.R
#----------------------------------------------------------------------# # duFunc : Derivative of the estimating equation # #----------------------------------------------------------------------# # # # pars : Current parameter estimates # # # # data.y : Matrix of responses. It is assumed that the first column # # contains integer patient IDs, the second column contains # # the time of measurement, and the third column contains # # the value of the measurement. # # # # data.x : Matrix of covariates. The columns contain only the values# # of the covariates. # # # # kernel : a character. One of "TD" = time dependent, # # "TI" = time-invariant or "LV" = last value. # # This specifies how the kernel is used # # # # lType : a character. One of "identity", "log", "logistic". # # Specifies the form of the link function. # # # # xIs : list of length nrow(data.y), the elements of which list # # the rows of data.x corresponding the patient in the ith # # row of data.y # # # # yIs : an object of class list. # # v - which elements of y match patientID[i] # # n - number of elements that match. # # # # nPatients : an object of class numeric. # # the number of patients in dataset. # # # #----------------------------------------------------------------------# # # # Returns the value of the estimating equations. # # # #----------------------------------------------------------------------# duFunc <- function(pars, data.y, data.x, kernel, lType, xIs, yIs, nPatients) { nrdx <- nrow(data.x) nCov <- length(pars) xbeta <- as.vector(data.x %*% pars) if( lType == "identity" ) { mu <- xbeta dmu <- data.x } else if( lType == "log" ) { exb <- exp(xbeta) mu <- exb dmu <- exb * data.x } else if( lType == "logistic" ) { exb <- exp(-xbeta) mu <- 1.0 / {1.0 + exb} dmu <- data.x * exb / {{1.0 + exb} * {1.0 + exb}} } else { stop("unsupported link function") } estEq <- matrix(data = 0.0, nrow = nPatients, ncol = nCov) destEq <- matrix(data = 0.0, nrow = nCov, ncol = nCov) ones <- matrix(data = 1.0, nrow = 1L, ncol = nrow(data.x)) for( i in 1L:nPatients ) { ly <- yIs[[i]]$n if( ly < 0.5 ) next for( j in 1L:ly ) { k <- yIs[[ i ]]$v[j] lx <- xIs[[ k ]]$n if( lx < 0.5 ) next xI <- xIs[[ k ]]$v tempM <- data.x[xI,,drop=FALSE] * kernel[[ k ]] estEq[i,] <- estEq[i,] + ones[1L,1L:lx,drop=FALSE] %*% { tempM * {data.y[k,3L] - mu[xI]}} for( p in 1L:nCov ){ destEq[p,] <- destEq[p,] - ones[1L,1L:lx,drop=FALSE] %*% {dmu[xI,p] * tempM} } } } return(list(du=destEq, u=colSums(estEq), var=estEq)) } cmp_duFunc <- compiler::cmpfun(duFunc)
/scratch/gouwar.j/cran-all/cranData/AsynchLong/R/duFunc.R
#----------------------------------------------------------------------# # kernelAuto : autotune bandwidths for all methods # #----------------------------------------------------------------------# # # # data.x : Matrix of covariates. It is assumed that the first column# # contains integer patient IDs, the second column contains # # the time of measurement, and the remaining columns # # contain the values of the covariates. # # # # data.y : Matrix of responses. It is assumed that the first column # # contains integer patient IDs, the second column contains # # the time of measurement, and the third column contains # # the value of the measurement. # # # # kType : a character. One of "epan", "uniform", or "gauss". # # Specifies the form of the kernel function. # # # # lType : a character. One of "identity", "log", "logistic". # # Specifies the form of the link function. # # # # times : a numeric or vector object containing time points # # # # distanceFunction : a character object giving the distance function # # to be used. # # # # nCores : a numeric. Number of cores to use for auto-tune # # implementation # # # #----------------------------------------------------------------------# # # # Returns a list. Values are for optimal bandwidth # # # # betaHat : matrix, row k contains parameter estimates for kth time # # point # # sd : matrix, row k contains standard deviations for kth time # # point # # zValue : matrix, row k contains z-values for kth time point # # pValue : matrix, row k contains p-values for kth time point # # optBW : matrix, row k contains optimal bw for kth time point # # minMSE : matrix, row k contains minimum standard error for kth # # time point # # # #----------------------------------------------------------------------# kernelAuto <- function(data.x, data.y, kType, lType, time, distanceFunction, nCores, verbose, ...){ #------------------------------------------------------------------# # Number of covariates (assumes column of ids and measurement times# #------------------------------------------------------------------# nCov <- ncol(data.x) - 2L patientIDs <- sort(unique(data.y[,1L])) nPatients <- length(patientIDs) #------------------------------------------------------------------# # For each response, determine which covariates are for the same # # sample and the number of measurements. # #------------------------------------------------------------------# xIs <- list() for( i in 1L:nrow(data.y) ) { xIs[[i]] <- list() xIs[[i]]$v <- which( data.x[,1L] == data.y[i,1L] ) xIs[[i]]$n <- as.integer(round(length(xIs[[i]]$v),0L)) } #------------------------------------------------------------------# # For each response, determine which response measurements are for # # the same sample and the number of measurements. # #------------------------------------------------------------------# yIs <- list() for( i in 1L:nPatients ) { yIs[[i]] <- list() yIs[[i]]$v <- which( data.y[,1L] == patientIDs[i] ) yIs[[i]]$n <- as.integer(round(length(yIs[[i]]$v),0L)) } #------------------------------------------------------------------# # Calculate range of bandwidths to be considered. # #------------------------------------------------------------------# range <- c(data.x[, 2L], data.y[,2L]) bw <- seq(from = 2*(stats::quantile(x = range, probs = 0.75) - stats::quantile(x = range, probs = 0.25)) * nPatients^(-0.7), to = 2*(stats::quantile(x = range, probs = 0.75) - stats::quantile(x = range, probs = 0.25)) * nPatients^(-0.3), length = 50) lbd <- length(bw) #------------------------------------------------------------------# # Assign each patient to a cross validation group # #------------------------------------------------------------------# cvlabel <- sample(x = rep( c(1L:2L), length.out = nPatients )) #------------------------------------------------------------------# # initialize matrices for parameter estimates & standard deviations# #------------------------------------------------------------------# betaHat0 <- matrix(data = 0.0, nrow = lbd, ncol = nCov) #------------------------------------------------------------------# # initialize matrices for variance estimate # #------------------------------------------------------------------# hatV <- matrix(data = 0.0, nrow = lbd, ncol = nCov) guess0 <- NULL guess1 <- NULL guess2 <- NULL tempFunc <- function(x, data.y, data.x, bw, kType, lType, nPatients, xIs, yIs, tt, guess0, guess1, guess2, distanceFunction, cvlabel){ betaHat0 <- betaHat(data.y = data.y, data.x = data.x, bandwidth = bw[x], kType = kType, lType = lType, nPatients = nPatients, xIs = xIs, yIs = yIs, tt = time, guess = guess0, distanceFunction = distanceFunction) tst <- cvlabel == 1L betaHat1 <- betaHat(data.y = data.y, data.x = data.x, bandwidth = bw[x], kType = kType, lType = lType, nPatients = sum(tst), xIs = xIs, yIs = yIs[tst], tt = time, guess = guess1, distanceFunction = distanceFunction) tst <- cvlabel == 2L betaHat2 <- betaHat(data.y = data.y, data.x = data.x, bandwidth = bw[x], kType = kType, lType = lType, nPatients = sum(tst), xIs = xIs, yIs = yIs[tst], tt = time, guess = guess2, distanceFunction = distanceFunction) betaDiff <- betaHat2 - betaHat1 hatV <- nPatients * bw[x] * ( betaDiff * betaDiff ) * 0.25 return( list( "beta0" = betaHat0, "beta1" = betaHat1, "beta2" = betaHat2, "hatV" = hatV) ) } if( nCores > 1.1 ) { cl <- makeCluster(nCores) res <- parLapply(cl, 1L:lbd, tempFunc, data.y = data.y, data.x = data.x, bw = bw, kType = kType, lType = lType, nPatients = nPatients, xIs = xIs, yIs = yIs, tt = time, guess0 = NULL, guess1 = NULL, guess2 = NULL, distanceFunction = distanceFunction, cvlabel = cvlabel) stopCluster(cl) for( bd in 1L:lbd ) { betaHat0[bd,] <- res[[bd]]$beta0 hatV[bd,] <- res[[bd]]$hatV } } else { for( bd in 1L:lbd ) { res <- tempFunc(data.y = data.y, data.x = data.x, bw = bw[bd], kType = kType, lType = lType, nPatients = nPatients, xIs = xIs, yIs = yIs, tt = time, guess0 = guess0, guess1 = guess1, guess2 = guess2, distanceFunction = distanceFunction, cvlabel = cvlabel) betaHat0[bd,] <- res$beta0 guess0 <- res$beta0 guess1 <- res$beta1 guess2 <- res$beta2 hatV[bd,] <- res$hatV } } hatC <- array(data = 0.0, dim = nCov) for( p in 1L:nCov ) { hatC[p] <- lm( betaHat0[,p] ~ bw^2 )$coef[2] } #------------------------------------------------------------------# # MSE = hat(C) * hat(C) * bw^2 + hat(V) # #------------------------------------------------------------------# MSE <- bw^4 %o% ( hatC * hatC ) + hatV #------------------------------------------------------------------# # Identify minimum MSE # #------------------------------------------------------------------# mseFunc <- function(x) { tst <- x > 0.0 if( sum(tst) == 0L ) { stop("no positive MSE values", call. = FALSE) } x[!tst] <- NA opt_h <- which.min(x) if( length(opt_h) > 1L ) { warning("Multiple minimums. Smallest bandwidth used.", call. = FALSE) opt_h <- opt_h[1] } return(opt_h) } opt_h <- apply(X = MSE, MARGIN = 2L, FUN = mseFunc) if( any(opt_h == 1L) || any(opt_h == lbd) ) { warning("At least 1 minimum is at bandwidth boundary.", call. = FALSE) } tminMSE <- array(data = 0.0, dim = nCov) for( i in 1L:nCov ) { tminMSE[i] <- MSE[opt_h[i],i] } optH <- bw[opt_h] minMSE <- tminMSE bHat <- betaHat(data.y = data.y, data.x = data.x, bandwidth = bw[opt_h], kType = kType, lType = lType, tt = time, guess = guess0, xIs = xIs, yIs = yIs, nPatients = nPatients, distanceFunction = distanceFunction) sdVec <- SD(data.y = data.y, data.x = data.x, bandwidth = bw[opt_h], kType = kType, lType = lType, bHat = bHat, tt = time, xIs = xIs, yIs = yIs, nPatients = nPatients, distanceFunction = distanceFunction) results <- matrix(data = 0.0, nrow = nCov, ncol = 6L, dimnames = list(paste("beta",0L:{nCov-1L},sep=""), c("estimate","stdErr","z-value", "p-value", "optBW", "minMSE"))) results[,1L] <- bHat results[,2L] <- sdVec results[,3L] <- bHat/sdVec results[,4L] <- 2.0*pnorm(-abs(results[,3L])) results[,5L] <- bw[opt_h] results[,6L] <- tminMSE if (verbose) { print(results) cat("\n") } return( list( "betaHat" = results[,1L], "stdErr" = results[,2L], "zValue" = results[,3L], "pValue" = results[,4L], "optBW" = results[,5L], "minMSE" = results[,6L] ) ) }
/scratch/gouwar.j/cran-all/cranData/AsynchLong/R/kernelAuto.R
#----------------------------------------------------------------------# # kernelFixed : fixed bandwidths for all methods # #----------------------------------------------------------------------# # # # data.x : Matrix of covariates. It is assumed that the first column# # contains integer patient IDs, the second column contains # # the time of measurement, and the remaining columns # # contain the values of the covariates. # # # # data.y : Matrix of responses. It is assumed that the first column # # contains integer patient IDs, the second column contains # # the time of measurement, and the third column contains # # the value of the measurement. # # # # bandwidth : vector of bandwidth values # # # # kType : a character. One of "epan", "uniform", or "gauss". # # Specifies the form of the kernel function. # # # # lType : a character. One of "identity", "log", "logistic". # # Specifies the form of the link function. # # # # time : a numeric or vector object containing time points # # # # distanceFunction : a character object giving the distance function # # to be used. # # # #----------------------------------------------------------------------# # # # Returns a list. Values are for optimal bandwidth # # # # betaHat : matrix, row k contains parameter estimates for kth time # # point # # sd : matrix, row k contains standard deviations for kth time # # point # # zValue : matrix, row k contains z-values for kth time point # # pValue : matrix, row k contains p-values for kth time point # # # #----------------------------------------------------------------------# kernelFixed <- function(data.x, data.y, bandwidth, kType, lType, time, distanceFunction, verbose, ...){ #------------------------------------------------------------------# # bandwidths must be positive. # #------------------------------------------------------------------# if( any(bandwidth < 1.5e-8) ) { stop("All bandwidths must be > 0", call. = FALSE) } #------------------------------------------------------------------# # nCov assumes a column for patient ids and measurement times # #------------------------------------------------------------------# nCov <- ncol(data.x) - 2L patientIDs <- sort(unique(data.y[,1L])) nPatients <- length(patientIDs) #------------------------------------------------------------------# # For each response, determine which covariates are for the same # # sample and the number of measurements. # #------------------------------------------------------------------# xIs <- list() for( i in 1L:nrow(data.y) ) { xIs[[i]] <- list() xIs[[i]]$v <- which( data.x[,1L] == data.y[i,1L] ) xIs[[i]]$n <- length(xIs[[i]]$v) } #------------------------------------------------------------------# # For each response, determine which response measurements are for # # the same sample and the number of measurements. # #------------------------------------------------------------------# yIs <- list() for( i in 1L:nPatients ) { yIs[[i]] <- list() yIs[[i]]$v <- which( data.y[,1L] == patientIDs[i] ) yIs[[i]]$n <- length(yIs[[i]]$v) } lbd <- length(bandwidth) bHat <- matrix(data = 0.0, nrow = lbd, ncol = nCov, dimnames = list(NULL,colnames(data.x)[3L:(nCov+2L)])) sdVec <- bHat results <- matrix(data = 0.0, nrow = nCov, ncol = 4L, dimnames = list(paste("beta",0L:{nCov-1L},sep=""), c("estimate","stdErr","z-value", "p-value"))) guess <- NULL for( bd in 1L:lbd ) { if(distanceFunction != "distanceLV" && verbose) { cat("Bandwidth: ", bandwidth[bd], "\n") } bHat[bd,] <- betaHat(data.y = data.y, data.x = data.x, bandwidth = bandwidth[bd], kType = kType, lType = lType, tt = time, xIs = xIs, yIs = yIs, nPatients = nPatients, guess = guess, distanceFunction = distanceFunction) results[,1L] <- bHat[bd,] guess <- bHat[bd,] sdVec[bd,] <- SD(data.y = data.y, data.x = data.x, bandwidth = bandwidth[bd], kType = kType, lType = lType, bHat = bHat[bd,], tt = time, xIs = xIs, yIs = yIs, nPatients = nPatients, distanceFunction = distanceFunction) results[,2L] <- sdVec[bd,] results[,3L] <- bHat[bd,]/sdVec[bd,] results[,4L] <- 2.0*stats::pnorm(-abs(results[,3L])) if (verbose) { print(results) cat("\n") } } zv <- bHat/sdVec pv <- 2.0*pnorm(-abs(results[,3L])) return( list( "betaHat" = bHat, "stdErr" = sdVec, "zValue" = zv, "pValue" = pv ) ) }
/scratch/gouwar.j/cran-all/cranData/AsynchLong/R/kernelFixed.R
local_kernel <- function(t, h, kType){ if( kType == "epan" ) { kt <- epanechnikov(t/h) } else if( kType == "uniform" ) { kt <- uniform(t/h) } else if( kType == "gauss" ) { kt <- gauss(t/h) } else { stop("unsupported kernel") } return(kt/h) } epanechnikov <- function(t){ tst <- (-1.0 <= t) & (t <= 1.0 ) kt <- 0.75*( 1.0 - t*t ) kt[ !tst ] <- 0.0 return(kt) } uniform <- function(t){ tst <- (-1.0 <= t) & (t <= 1.0 ) kt <- t kt[ tst ] <- 0.5 kt[ !tst ] <- 0.0 return(kt) } gauss <- function(t){ kt <- exp(-t*t*0.5)/sqrt(2.0*pi) return(kt) }
/scratch/gouwar.j/cran-all/cranData/AsynchLong/R/local_kernel.R
#----------------------------------------------------------------------# # optFunc : Function that R's optim is minimizing. Taken to be U^2 # #----------------------------------------------------------------------# # # # pars : Current parameter estimates # # # # data.y : Matrix of responses. It is assumed that the first column # # contains integer patient IDs, the second column contains # # the time of measurement, and the third column contains # # the value of the measurement. # # # # data.x : Matrix of covariates. The columns contain only the values# # of the covariates. # # # # kernel : a character. One of "TD" = time dependent, # # "TI" = time-invariant or "LV" = last value. # # This specifies how the kernel is used # # # # lType : a character. One of "identity", "log", "logistic". # # Specifies the form of the link function. # # # # tt : If provided, a vector of times at which to evaluate the # # kernel # # # #----------------------------------------------------------------------# # # # Returns scalar value U^2 # # # #----------------------------------------------------------------------# optFunc <- function(pars, data.y, data.x, kernel, lType, xIs, yIs, nPatients) { res <- cmp_uFunc(pars = pars, data.y = data.y, data.x = data.x, kernel = kernel, lType = lType, xIs = xIs, yIs = yIs, nPatients = nPatients) return(res %*% res) } #----------------------------------------------------------------------# # doptFunc : Derivative of function that R's optim is minimizing. # #----------------------------------------------------------------------# # # # pars : Current parameter estimates # # # # data.y : Matrix of responses. It is assumed that the first column # # contains integer patient IDs, the second column contains # # the time of measurement, and the third column contains # # the value of the measurement. # # # # data.x : Matrix of covariates. The columns contain only the values# # of the covariates. # # # # kernel : a character. One of "TD" = time dependent, # # "TI" = time-invariant or "LV" = last value. # # This specifies how the kernel is used # # # # lType : a character. One of "identity", "log", "logistic". # # Specifies the form of the link function. # # # # tt : If provided, a vector of times at which to evaluate the # # kernel # # # #----------------------------------------------------------------------# # # # Returns scalar value 2.0 * dU %*% U # # # #----------------------------------------------------------------------# doptFunc <- function(pars, data.y, data.x, kernel, lType, xIs, yIs, nPatients) { res <- cmp_duFunc(pars = pars, data.y = data.y, data.x = data.x, kernel = kernel, lType = lType, xIs = xIs, yIs = yIs, nPatients = nPatients) return(2.0*(res$du %*% res$u)) }
/scratch/gouwar.j/cran-all/cranData/AsynchLong/R/optFunc.R
plotTD <- function(bHat, sdVec, times) { nTimes <- length(times) intv <- 1.96*sdVec maxy <- max(bHat + intv) miny <- min(bHat - intv) col <- 2L graphics::plot(x = times, y = bHat[,1L], col = col, lty = 1, lwd = 2, xlim = c(times[1]*0.9, times[nTimes]*1.1), ylim = c(miny*0.9,maxy*1.1), xlab = "time", ylab = "beta(t)", main = "Parameter Estimates", graphics::arrows(times, y0 = bHat[,1L]-intv[,1L], times, y1 = bHat[,1L]+intv[,1L], code = 3, angle = 90, length= 0.1, col = col)) graphics::lines(times, bHat[,1L], type = "l", col = col) j <- 2L col <- col + 1L while( j <= ncol(bHat) ) { graphics::points(x = times, y = bHat[,j], col = col, graphics::arrows(times, y0 = bHat[,j]-intv[,j], times, y1 = bHat[,j]+intv[,j], code = 3, angle = 90, length= 0.1, col=col)) graphics::lines(times, bHat[,j], type = "l", col = col) j <- j + 1L col <- col + 1L } graphics::legend('topright', legend = paste("beta",0L:(ncol(bHat)-1L),sep=""), lty = 1, col = 2L:(col-1L), bty = 'n', cex = 0.75) return() }
/scratch/gouwar.j/cran-all/cranData/AsynchLong/R/plotTD.R
preprocessX <- function(data.x) { #------------------------------------------------------------------# # Verify sufficient number of columns in datasets # #------------------------------------------------------------------# nc <- ncol(data.x) if( nc < 3L ) { stop("data.x must include {ID, time, measurement(s)}.", call. = FALSE) } #------------------------------------------------------------------# # ensure that patient ids are integers # #------------------------------------------------------------------# if( !is.integer(data.x[,1L]) ) { data.x[,1L] <- as.integer(round(data.x[,1L],0)) message("patient IDs in data.x were coerced to integer.\n") } intPresent <- FALSE if( nc > 2L ) { for( i in 3L:nc ) { if( isTRUE(all.equal(data.x[,i], 1.0)) ) { intPresent <- TRUE break } } } #------------------------------------------------------------------# # Remove any cases for which all covariates are NA # #------------------------------------------------------------------# rmRow <- apply(data.x, 1, function(x){all(is.na(x))}) data.x <- data.x[!rmRow,] #------------------------------------------------------------------# # Determine total number of covariates. # # Note this includes an intercept # #------------------------------------------------------------------# if( intPresent ){ nCov <- ncol(data.x) - 2L } else { nCov <- ncol(data.x) - 2L + 1L #----------------------------------------------------------------# # Add intercept to data.x # #----------------------------------------------------------------# nms <- colnames(data.x) if( nc > 2L ) { data.x <- cbind(data.x[,1L:2L], 1.0, data.x[,3L:nc]) colnames(data.x) <- c(nms[1L:2L], "(Intercept)", nms[3L:nc]) } else { data.x <- cbind(data.x[,1L:2L], 1.0) colnames(data.x) <- c(nms[1L:2L], "(Intercept)") } } #------------------------------------------------------------------# # Set missing cases to 0.0 # #------------------------------------------------------------------# tst <- is.na(data.x) data.x[tst] <- 0.0 #------------------------------------------------------------------# # Determine if any times in data.x are < 0 # #------------------------------------------------------------------# if( any(data.x[,2L] < {-1.5e-8}) ) { stop("Time is negative in data.x.", call. = FALSE) } return(data.x) }
/scratch/gouwar.j/cran-all/cranData/AsynchLong/R/preprocessX.R
preprocessY <- function(data.y) { #------------------------------------------------------------------# # Verify sufficient number of columns in datasets # #------------------------------------------------------------------# ncy <- ncol(data.y) if( ncy < 3L ) { stop("data.y must include {ID, time, measurement}.", call. = FALSE) } #------------------------------------------------------------------# # ensure that patient ids are integers # #------------------------------------------------------------------# if( !is.integer(data.y[,1L]) ) { data.y[,1L] <- as.integer(round(data.y[,1L],0)) message("patient IDs in data.y were coerced to integer.\n") } #------------------------------------------------------------------# # Remove any cases for which response is NA # #------------------------------------------------------------------# tst <- is.na(data.y[,3L]) data.y <- data.y[!tst,] #------------------------------------------------------------------# # Determine if any times in data.y are < 0 # #------------------------------------------------------------------# if( any(data.y[,2L] < {-1.5e-8}) ) { stop("Time is negative in data.y.", call. = FALSE) } return(data.y) }
/scratch/gouwar.j/cran-all/cranData/AsynchLong/R/preprocessY.R
#----------------------------------------------------------------------# # uFunc : Estimating equation # #----------------------------------------------------------------------# # # # pars : Current parameter estimates # # # # data.y : Matrix of responses. It is assumed that the first column # # contains integer patient IDs, the second column contains # # the time of measurement, and the third column contains # # the value of the measurement. # # # # data.x : Matrix of covariates. The columns contain only the values# # of the covariates. # # # # kernel : a list, ith element containing a matrix of the yIs # # distances # # # # lType : a character. One of "identity", "log", "logistic". # # Specifies the form of the link function. # # # # xIs : list of length nrow(data.y), the elements of which list # # the rows of data.x corresponding the patient in the ith # # row of data.y # # # #----------------------------------------------------------------------# # # # Returns the value of the estimating equations. # # # #----------------------------------------------------------------------# uFunc <- function(pars, data.y, data.x, kernel, lType, xIs, yIs, nPatients) { xbeta <- data.x %*% pars if( lType == "logistic" ) { mu <- 1.0/(1.0 + exp(-xbeta)) } else { mu <- exp(xbeta) } y3 <- data.y[, 3L] zeroVec <- numeric(length=length(pars)) tempFunc <- function(x){ if( xIs[[ x ]]$n < 0.5 ) return( zeroVec ) xI <- xIs[[ x ]]$v res <- colSums( data.x[xI,,drop=FALSE] * kernel[[ x ]] * {y3[x] - mu[xI]} ) return(res) } tempFunc2 <- function(x){ if( yIs[[x]]$n < 0.5 ) return( zeroVec ) temp <- rowSums(sapply(yIs[[x]]$v, tempFunc)) return(temp) } estEq <- rowSums(sapply(1L:nPatients, tempFunc2)) return(estEq) } cmp_uFunc <- compiler::cmpfun(uFunc)
/scratch/gouwar.j/cran-all/cranData/AsynchLong/R/uFunc.R
#----------------------------------------------------------------------# # uFunc : Estimating equation # #----------------------------------------------------------------------# # # # pars : Current parameter estimates # # # # data.y : Matrix of responses. It is assumed that the first column # # contains integer patient IDs, the second column contains # # the time of measurement, and the third column contains # # the value of the measurement. # # # # data.x : Matrix of covariates. The columns contain only the values# # of the covariates. # # # # kernel : a list, ith element containing a matrix of the yIs # # distances # # # # xIs : list of length nrow(data.y), the elements of which list # # the rows of data.x corresponding the patient in the ith # # row of data.y # # # #----------------------------------------------------------------------# # # # Returns the value of the estimating equations. # # # #----------------------------------------------------------------------# uFuncIden <- function(data.y, data.x, kernel, xIs, yIs, nPatients) { nCov <- ncol(data.x) aMat <- matrix(data = 0.0, nrow = nCov, ncol = nCov) bVec <- matrix(data = 0.0, nrow = nrow(data.x), ncol = nCov) ones <- matrix(data = 1.0, nrow = 1L, ncol = nrow(data.x)) for( i in 1L:nPatients ) { ly <- yIs[[i]]$n if( ly < 0.5 ) next for( j in 1L:ly ) { k <- yIs[[i]]$v[j] lx <- xIs[[ k ]]$n if( lx < 0.5 ) next xI <- xIs[[ k ]]$v tx <- data.x[xI,,drop=FALSE] * kernel[[ k ]] bVec[xI,] <- bVec[xI,] + tx * data.y[k,3L] aMat <- aMat + t(tx) %*% data.x[xI,,drop=FALSE] } } bVec <- as.vector(ones %*% bVec) pars <- solve(aMat, bVec) return(pars) }
/scratch/gouwar.j/cran-all/cranData/AsynchLong/R/uFuncIden.R
#################################### ### Generation of simulated data ### #################################### DG = function(X,Z,gamma_X,gamma_Z,Sigma_e,outcome="continuous") { #library(MASS) n = dim(X)[1] px = length(gamma_X) pz = length(gamma_Z) ## treatment g_link = X%*%gamma_X + Z%*%gamma_Z e = 1/(1+exp(-g_link)) # pass through an inv-logit function #e = 1 - exp(-exp(g_link)) # complement log-log model form T = rbinom(n,1,e) ## outcome #### M1 if(outcome=="continuous") { Y = T + X%*%gamma_X + Z%*%gamma_Z + rnorm(n,0,1) } ####### #### M2 if(outcome=="binary") { #T = rbinom(n,1,e) pi = 1/(1+exp(-(T+g_link))) Y = rbinom(n,1,pi) } ####### ## error-prone mu_X = rep(0,px) err = mvrnorm(n, mu_X, Sigma_e , tol = 1e-6, empirical = FALSE, EISPACK = FALSE) W = X + err ## dataset data = cbind(Y,T,W,Z) return(data) }
/scratch/gouwar.j/cran-all/cranData/AteMeVs/R/DG.R
################################################# #### SIMEX Algorithm: estimation for ATE #### ################################################# EST_ATE = function(data, PS="logistic", Psi=seq(0,1,length=10), K=200, gamma,p_x=p, extrapolate="quadratic", Sigma_e, replicate = "FALSE", RM = 0, bootstrap = 100) { n = dim(data)[1] p = dim(data)[2]-2 tau_S1 = function(data, psi, gamma,Sigma_e) { # Step 1 in the SIMEX algorithm ## Algorithm settings Y = data[,1] T = data[,2] if(p_x < p && p_x > 0) { if(replicate == "FALSE") { W = data[,3:(p_x+2)] Z = data[,(p_x+3):(p+2)] #set.seed(k) mu_X = rep(0,p_x) e = mvrnorm(n, mu_X, Sigma_e, tol = 1e-6, empirical = FALSE, EISPACK = FALSE) W_S = W + sqrt(psi) * e x = matrix(unlist(cbind(W_S,Z)),n,p) } ################################## if(replicate == "TRUE") { a = 0 b = RM[1] W_S = NULL for(l in 1:length(RM)) { reme = c(RM,0) W = data[,(3+a):(b+2)] dij = matrix(rnorm(n*RM[l],0,1),n,RM[l]) dibar = rowMeans(dij) cij = (dij - dibar) / sqrt( rowSums((dij - dibar)^2)) work = rowMeans(W) + sqrt(psi/RM[l]) * rowSums(cij * W) W_S = cbind(W_S,work) a = a + reme[l] b = b + reme[l+1] } x = matrix(unlist(cbind(W_S,Z)),n,p) } } if(p_x == p) { if(replicate == "FALSE") { W = data[,3:(p+2)] #set.seed(k) mu_X = rep(0,p_x) e = mvrnorm(n, mu_X, Sigma_e, tol = 1e-6, empirical = FALSE, EISPACK = FALSE) W_S = W + sqrt(psi) * e x = matrix(unlist(W_S),n,p) } ################################## if(replicate == "TRUE") { a = 0 b = RM[1] W_S = NULL for(l in 1:length(RM)) { reme = c(RM,0) W = data[,(3+a):(b+2)] dij = matrix(rnorm(n*RM[l],0,1),n,RM[l]) dibar = rowMeans(dij) cij = (dij - dibar) / sqrt( rowSums((dij - dibar)^2)) work = rowMeans(W) + sqrt(psi/RM[l]) * rowSums(cij * W) W_S = cbind(W_S,work) a = a + reme[l] b = b + reme[l+1] } x = matrix(unlist(W_S),n,p) } } if(p_x == 0) { W = data[,3:(p+2)] x = matrix(unlist(W),n,p) } ## End of settings g_link = x%*%gamma if(PS == "logistic") { ps = 1/(1+exp(-g_link)) } if(PS == "probit") { ps = pnorm(g_link) ps[which(ps==1)] = 0.999 } if(PS == "cloglog") { ps = 1 - exp(-exp(g_link)) ps[which(ps==1)] = 0.999 } output = (sum(T*Y/ps) / sum(T/ps)) - (sum((1-T)*Y/(1-ps)) / sum((1-T)/(1-ps)) ) return(output) } tau_S2 = function(data,Psi,K, gamma,Sigma_e) { # Step 2 in SIMEX algorithm GAMMA_Psi = NULL for(psi in 1 : length(Psi)) { G_coll = NULL # collection for all k in the following loop for(k in 1 : length(K)) { GAMMA_psi_k = tau_S1(data,Psi[psi], gamma,Sigma_e) G_coll = rbind(G_coll, GAMMA_psi_k) } GAMMA_Psi[[psi]] = G_coll } return(GAMMA_Psi) } Output = NULL for(boot in 1:bootstrap) { result = tau_S2(data,Psi,K, gamma,Sigma_e) vt = NULL for(psi in 1:length(Psi)) { vt = rbind(vt,colMeans(result[[psi]])) } if(extrapolate=="cubic") { B = cbind(1,Psi,Psi^2,Psi^3) beta = solve(t(B)%*%B) %*% (t(B)%*%vt) ext = c(1,-1,1,-1) output = ext %*%beta #return(output) } if(extrapolate=="quadratic") { B = cbind(1,Psi,Psi^2) beta = solve(t(B)%*%B) %*% (t(B)%*%vt) ext = c(1,-1,1) output = ext %*%beta #return(output) } if(extrapolate=="linear") { B = cbind(1,Psi) beta = solve(t(B)%*%B) %*% (t(B)%*%vt) ext = c(1,-1) output = ext %*%beta #return(output) } if(extrapolate=="RL") { RL = function(beta) { B1 = beta[1] B2 = beta[2] B3 = beta[3] Q = -mean((vt - B1 - (B2 / (B3 + Psi)) )^2 ) return (Q) } betahat = optim(c(2,2,2),RL,gr = NULL, method = "Nelder-Mead",control = list(fnscale = -1))$par output = betahat[1] + (betahat[2] / (betahat[3] -1)) #return(output) } Output = c(Output,output) } if(bootstrap > 1) { EST = mean(Output) VAR = var(Output)/bootstrap pvalue = 2*pnorm(-abs(EST/sqrt(VAR))) result = t(as.matrix(c(EST,VAR,pvalue))) colnames(result) = c("estimate","variance","p-value") return(result) } if(bootstrap == 1) { return(Output) } }
/scratch/gouwar.j/cran-all/cranData/AteMeVs/R/EST_ATE.R
SIMEX_EST = function(data, PS="logistic", Psi=seq(0,1,length=10),p_x=p, K=200, extrapolate="quadratic", Sigma_e, replicate = "FALSE", RM = 0) { # Step 3 in SIMEX algorithm n = dim(data)[1] p = dim(data)[2]-2 ####### inside function ####### SIMEX_S1 = function(data, PS, psi,p_x, Sigma_e, replicate,RM) { # Step 1 in the SIMEX algorithm ## Algorithm settings Y = data[,1] T = data[,2] if(p_x < p && p_x > 0) { if(replicate == "FALSE") { W = data[,3:(p_x+2)] Z = data[,(p_x+3):(p+2)] #set.seed(k) mu_X = rep(0,p_x) e = mvrnorm(n, mu_X, Sigma_e, tol = 1e-6, empirical = FALSE, EISPACK = FALSE) W_S = W + sqrt(psi) * e x = cbind(W_S,Z) } ################################## if(replicate == "TRUE") { a = 0 b = RM[1] W_S = NULL for(l in 1:length(RM)) { reme = c(RM,0) W = data[,(3+a):(b+2)] dij = matrix(rnorm(n*RM[l],0,1),n,RM[l]) dibar = rowMeans(dij) cij = (dij - dibar) / sqrt( rowSums((dij - dibar)^2)) work = rowMeans(W) + sqrt(psi/RM[l]) * rowSums(cij * W) W_S = cbind(W_S,work) a = a + reme[l] b = b + reme[l+1] } x = cbind(W_S,Z) } } if(p_x == p) { if(replicate == "FALSE") { W = data[,3:(p+2)] #set.seed(k) mu_X = rep(0,p_x) e = mvrnorm(n, mu_X, Sigma_e, tol = 1e-6, empirical = FALSE, EISPACK = FALSE) W_S = W + sqrt(psi) * e x = W_S } ################################## if(replicate == "TRUE") { a = 0 b = RM[1] W_S = NULL for(l in 1:length(RM)) { reme = c(RM,0) W = data[,(3+a):(b+2)] dij = matrix(rnorm(n*RM[l],0,1),n,RM[l]) dibar = rowMeans(dij) cij = (dij - dibar) / sqrt( rowSums((dij - dibar)^2)) work = rowMeans(W) + sqrt(psi/RM[l]) * rowSums(cij * W) W_S = cbind(W_S,work) a = a + reme[l] b = b + reme[l+1] } x = cbind(W_S,Z) } } if(p_x == 0) { W = data[,3:(p+2)] x = W } ## End of settings t = T Da = cbind(t,x) Da = data.frame(Da) if(PS == "logistic") { output = glm(t~., data = Da,family = "binomial")$coef[-1] } if(PS == "probit") { output = glm(t~.,data = Da, family=binomial(link="probit"))$coef[-1] } if(PS == "cloglog") { output = glm(t~.,data = Da, family=binomial(link="cloglog"))$coef[-1] } return(output) } SIMEX_S2 = function(data,PS,Psi,p_x, K, Sigma_e, replicate,RM) { # Step 2 in SIMEX algorithm GAMMA_Psi = NULL for(psi in 1 : length(Psi)) { G_coll = NULL # collection for all k in the following loop for(k in 1 : K) { GAMMA_psi_k = SIMEX_S1(data, PS, Psi[psi],p_x, Sigma_e, replicate,RM) G_coll = rbind(G_coll, GAMMA_psi_k) } GAMMA_Psi[[psi]] = G_coll } return(GAMMA_Psi) } ###################################### result = SIMEX_S2(data,PS,Psi,p_x,K, Sigma_e, replicate,RM) vt = NULL for(psi in 1:length(Psi)) { vt = rbind(vt,colMeans(result[[psi]])) } if(extrapolate=="cubic") { B = cbind(1,Psi,Psi^2,Psi^3) beta = solve(t(B)%*%B) %*% (t(B)%*%vt) ext = c(1,-1,1,-1) output = ext %*%beta } if(extrapolate=="quadratic") { B = cbind(1,Psi,Psi^2) beta = solve(t(B)%*%B) %*% (t(B)%*%vt) ext = c(1,-1,1) output = ext %*%beta } if(extrapolate=="linear") { B = cbind(1,Psi) beta = solve(t(B)%*%B) %*% (t(B)%*%vt) ext = c(1,-1) output = ext %*%beta } if(extrapolate=="RL") { output = NULL for(i in 1:p) { Yresponse = vt[,i] RL = function(beta) { B1 = beta[1] B2 = beta[2] B3 = beta[3] Q = -mean((Yresponse - B1 - (B2 / (B3 + Psi)) )^2 ) return (Q) } betahat = optim(c(1,1,1),RL,gr = NULL, method = "Nelder-Mead",control = list(fnscale = -1))$par output = c(output, ( betahat[1] + (betahat[2] / (betahat[3] -1)) ) ) } } return(output) }
/scratch/gouwar.j/cran-all/cranData/AteMeVs/R/SIMEX_EST.R
VSE_PS = function(V,y,method="lasso",cv="TRUE",alpha=1) { # y is SIMEX estimator and V is weighted matrix #library(ncvreg) #### glmnet package #var_sel = glmnet(V, y , family = "gaussian", alpha = 1) #lambda = which.max(obj2) # search max #lambda = which.max(obj2[7:length(obj2)])+6 # search max #coef = coef[, lambda] #obj2 = -dev2 + log(n) * reg.df2 # - 2*logL + 2*log(n) x df in Step 4 by Yi and Chen (201x) ######### if(cv=="TRUE") { if(method =="lasso"){ opt = cv.ncvreg(V, y , family = "gaussian",penalty="lasso" ,alpha )$lambda lambda = which(opt == min(opt)) var_sel = ncvreg(V, y , family = "gaussian",penalty="lasso" ,alpha ) } if(method =="scad"){ opt = cv.ncvreg(V, y , family = "gaussian",penalty="SCAD" ,alpha, gamma=3.7 )$lambda lambda = which(opt == min(opt)) var_sel = ncvreg(V, y , family = "gaussian",penalty="SCAD" ,alpha, gamma=3.7 ) } if(method =="mcp"){ opt = cv.ncvreg(V, y , family = "gaussian",penalty="MCP" ,alpha, gamma=3 )$lambda lambda = which(opt == min(opt)) var_sel = ncvreg(V, y , family = "gaussian",penalty="MCP" ,alpha, gamma=3 ) } coef = rbind(var_sel$a0,as.matrix(var_sel$beta)) coef = coef[ , lambda] } if(cv=="FALSE") { #### ncvreg package # for lasso, both results are similar. if(method =="lasso"){ var_sel = ncvreg(V, y , family = "gaussian",penalty="lasso" ,alpha ) } if(method =="scad"){ var_sel = ncvreg(V, y , family = "gaussian",penalty="SCAD" ,alpha, gamma=3.7 )} if(method =="mcp"){ var_sel = ncvreg(V, y , family = "gaussian",penalty="MCP" ,alpha, gamma=3 )} coef = rbind(var_sel$a0,as.matrix(var_sel$beta)) # extract coefficients at all values of lambda, including the intercept dev2 = deviance(var_sel) reg.df2 = var_sel$df obj2 = BIC(var_sel) lambda = which.min(obj2) # search max coef = coef[ , lambda] } output = coef[-1] output[which(abs(output)<0.5)]=0 return(output) }
/scratch/gouwar.j/cran-all/cranData/AteMeVs/R/VSE_PS.R
#' @keywords internal "_PACKAGE" #' points_campgrounds #' #' Data on campgrounds in and outside of the Adirondacks in New York. #' For this package demo two data files were combined and only three columns were retained. #' #' @format A data frame with 116 rows and 3 variables: #' \describe{ #' \item{label}{name of the campground} #' \item{long}{longitude value} #' \item{lat}{latitude value} #' ... #' } #' @source \url{https://data.ny.gov/Recreation/Campgrounds-by-County-Within-Adirondack-Catskill-F/tnqf-vydw} #' @source \url{https://data.ny.gov/Recreation/Campgrounds-by-County-Outside-Adirondack-Catskill-/5zxz-z3ci} #' @docType data #' @name points_campgrounds NA #' points #' #' Takes user defined data for points in demo1 #' Default is NULL or empty #' #' @format A function with arguments x, ...: #' \describe{ #' \item{x}{user data} #' ... #' } #' @docType data #' @name points NA #' points_parks #' #' Data on state parks in New York. For this package demo only three columns were retained. #' #' @format A data frame with 254 rows and 3 variables: #' \describe{ #' \item{label}{name of state park} #' \item{long}{longitude value} #' \item{lat}{latitude value} #' ... #' } #' @source \url{https://data.ny.gov/Recreation/Watchable-Wildlife-Sites/hg7a-5ssi} #' @docType data #' @name points_parks NA #' points_watchsites #' #' Data originally from data.ny.gov, for this package demo only three columns were retained. #' #' @format A data frame with 76 rows and 3 variables: #' \describe{ #' \item{label}{name of watchsite location} #' \item{long}{longitude value} #' \item{lat}{latitude value} #' ... #' } #' @source \url{https://data.ny.gov/Recreation/Watchable-Wildlife-Sites/hg7a-5ssi} #' @docType data #' @name points_watchsites NA #' counties_NY #' #' US Census polygon data for New York state counties accessed through the `tigris` R Package. #' #' @format A spatial data frame with 62 rows and 7 variables: #' \describe{ #' \item{STATEP}{state's code} #' \item{NAME}{county name} #' \item{INTPLAT}{latitude} #' \item{INTPTLON}{longitude} #' \item{ALAND}{area of land, in square meters} #' \item{AWATER}{area of water, in square meters} #' \item{geometry}{polygon information} #' ... #' } #' @source \url{https://www.census.gov/geographies/mapping-files/time-series/geo/tiger-line-file.html} #' @docType data #' @name counties_NY NA #' roads_ny_interstate #' #' US Census polyline data for New York state interstates accessed through the `tigris` R Package. #' #' @format A data frame with 245 rows and 5 variables: #' \describe{ #' \item{LINEARID}{unique identifier} #' \item{FULLNAME}{interstate name} #' \item{RTTYP}{route type} #' \item{MTFCC}{US Census feature class code} #' \item{geometry}{polyline information} #' ... #' } #' @docType data #' @name roads_ny_interstate NA #' amphibians #' #' Derived from data.ny.gov biodiversity data by county, filtered for amphibians #' only and combined with counties_NY Census-sourced data. #' #' @format A spatial data frame with 62 county entries: #' \describe{ #' \item{STATEP}{state's code} #' \item{NAME}{county name} #' \item{INTPLAT}{latitude} #' \item{INTPTLON}{longitude} #' \item{ALAND}{area of land, in square meters} #' \item{AWATER}{area of water, in square meters} #' \item{Taxonomic.Group}{For animals and plants, the taxonomic phylum, class, or order to which the species belongs.} #' \item{fill_value}{count of species from amphibians taxonomic grouped by county} #' ... #' } #' @source \url{https://data.ny.gov/Energy-Environment/Biodiversity-by-County-Distribution-of-Animals-Pla/tk82-7km5} #' @docType data #' @name amphibians NA #' reptiles #' #' Derived from data.ny.gov biodiversity data by county, filtered for reptiles only. #' #' #' @format A spatial data frame with 62 county entries: #' \describe{ #' \item{STATEP}{state's code} #' \item{NAME}{county name} #' \item{INTPLAT}{latitude} #' \item{INTPTLON}{longitude} #' \item{ALAND}{area of land, in square meters} #' \item{AWATER}{area of water, in square meters} #' \item{Taxonomic.Group}{For animals and plants, the taxonomic phylum, class, or order to which the species belongs.} #' \item{fill_value}{count of species from reptiles taxonomic group by county} #' ... #' } #' @source \url{https://data.ny.gov/Energy-Environment/Biodiversity-by-County-Distribution-of-Animals-Pla/tk82-7km5} #' @docType data #' @name reptiles NA #' flowering_plants #' #' Derived from data.ny.gov biodiversity data by county, filtered for flowering plants only. #' #' #' @format A spatial data frame with 62 county entries: #' \describe{ #' \item{STATEP}{state's code} #' \item{NAME}{county name} #' \item{INTPLAT}{latitude} #' \item{INTPTLON}{longitude} #' \item{ALAND}{area of land, in square meters} #' \item{AWATER}{area of water, in square meters} #' \item{Taxonomic.Group}{For animals and plants, the taxonomic phylum, class, or order to which the species belongs.} #' \item{fill_value}{count of species from flowering plants taxonomic group by county} #' ... #' } #' @source \url{https://data.ny.gov/Energy-Environment/Biodiversity-by-County-Distribution-of-Animals-Pla/tk82-7km5} #' @docType data #' @name flowering_plants NA #' birds #' #' Derived from data.ny.gov biodiversity data by county, filtered for birds only. #' #' #' @format A spatial data frame with 62 county entries: #' \describe{ #' \item{STATEP}{state's code} #' \item{NAME}{county name} #' \item{INTPLAT}{latitude} #' \item{INTPTLON}{longitude} #' \item{ALAND}{area of land, in square meters} #' \item{AWATER}{area of water, in square meters} #' \item{Taxonomic.Group}{For animals and plants, the taxonomic phylum, class, or order to which the species belongs.} #' \item{fill_value}{count of species from birds taxonomic group by county} #' ... #' } #' @source \url{https://data.ny.gov/Energy-Environment/Biodiversity-by-County-Distribution-of-Animals-Pla/tk82-7km5} #' @docType data #' @name birds NA ## usethis namespace: start ## usethis namespace: end NULL
/scratch/gouwar.j/cran-all/cranData/AtlasMaker/R/AtlasMaker-package.R
#' The user interface for AtlasMaker. #' #' This is the core ui function for AtlasMaker. #' #' @export #' @importFrom leaflet leafletOutput #' #' @param id identifier for the map. This must match the id used in [map_server()]. #' #' @return a [leaflet::leafletOutput()] object. #' @examples #' map_UI('flowering_plants') #' map_UI('map1') #' map_UI('map2') #' map_UI <- function(id) { ns <- NS(id) leaflet::leafletOutput(ns("mymap"), height = 700) }
/scratch/gouwar.j/cran-all/cranData/AtlasMaker/R/map_UI.R
#' The Shiny server module for AtlasMaker. #' #' This is the core ui and server function for AtlasMaker where users pass in the spatial-data #' based lists and aesthetic choices for each map tab. #' #' @param id identifier for the map. This must match the id used in [map_UI()]. #' @param polygons polygon data in geospatial format. #' @param polygon_legend_title title to display on legend for polygon shading #' @param points point data with label, lat, and long variables. #' @param polylines polyline data in geospatial format. #' @param center lat/long of where to center the default map. #' @param min_zoom minimum zoom level users can see, default 7. #' @param map_base_theme Leaflet-compatible theme for base map. #' @param poly_palette Leaflet-compatible color palette for polygon shading. #' @param point_color Leaflet-compatible single color for point colors. #' @param polyline_color Leaflet-compatible single color for polyline colors. #' #' @export #' @import shiny #' @import leaflet #' #' @returns a list of parameters, including spatial data, that are passed into the AtlasMaker module that builds a single map tab. #' @examples #' server <- function(input, output) { #' map_server(id = map2, #' polygons = watersheds, #' polygon_legend_title = "Watershed", #' points = farms, #' polylines = rivers, #' point_color = 'red', #' polyline_color = 'black') #' } #' #' #' #' map_server <- function(id, polygons = NULL, polygon_legend_title = NULL, points = NULL, polylines = NULL, center = NULL, min_zoom = 7, map_base_theme = 'Stamen.Terrain', poly_palette = 'BuPu', point_color = 'black', polyline_color = 'gray') { moduleServer(id, function(input, output, session){ ####base Leaflet map construction------------- output$mymap <- renderLeaflet({ map <- leaflet(options = leafletOptions(minZoom = min_zoom)) %>% addTiles(group = polygons[[1]]) %>% addProviderTiles(provider = map_base_theme) #zoom and centering if(!is.null(center)) { map <- map %>% leaflet::setView(lng = center[1], lat = center[2], min_zoom = min_zoom) } ####polygons------------- # create list of names polygon_names <- list() if(length(polygons) > 0) { if(!is.list(polygons[[1]])) { polygons <- list(polygons) } for(i in 1:length(polygons)){ output <- polygons[[i]]$name polygon_names[[i]] <- output} # add one set of polygons with fill data per number of # polygon lists passed through to this module for(i in 1:length(polygons)) { #fantastic way to get reactive color palette per polygon group mn <- as.numeric(min(polygons[[i]]$data$fill_value)) mx <-as.numeric(max(polygons[[i]]$data$fill_value)) pal_x <- colorNumeric(c(poly_palette), mn:mx) map <- map %>% addPolygons(data = polygons[[i]]$data, layerId = ~polygons, weight = 1, fillOpacity = 0.7, color = ~pal_x(polygons[[i]]$data$fill_value), label = ~paste(polygons[[i]]$data$NAME, polygons[[i]]$data$fill_value), highlightOptions = highlightOptions(weight = 1, color = "black"), group = polygon_names[[i]]) %>% # add legend (this won't trigger if there are no polygons in the module) addLegend(position = "bottomright", pal = pal_x, values = polygons[[i]]$data$fill_value, title = polygon_legend_title) } } ####points------------- # create list of names point_names <- list() if(length(points) > 0) { if(!is.list(points[[1]])) { points <- list(points) } for(i in 1:length(points)){ output <- points[[i]]$name point_names[[i]] <- output} # add one set of points per number of # points lists passed through to this module for(i in 1:length(points)) { map <- map %>% addCircleMarkers(data = points[[i]]$data, lng = points[[i]]$data$long, lat = points[[i]]$data$lat, popup = points[[i]]$data$label, color = point_color, radius = 2, group = point_names) } } ####polylines------ # create list of names polyline_names <- list() if(length(polylines) > 0) { if(!is.list(polylines[[1]])) { polylines <- list(polylines) } for(i in length(polylines)){ output <- polylines[[i]]$name polyline_names[[i]] <- output} # add one set of polylines per number of polyline lists passed through to this module for(i in 1:length(polylines)) { map <- map %>% addPolylines(data = polylines[[i]]$data, color = polyline_color, group = polyline_names) } } ####interactivity------------- # references the above group = calls in the above 3 sections, # polygons are toggle buttons and polylines/points are checkboxes map <- map %>% addLayersControl(baseGroups = polygon_names, overlayGroups = c(point_names, polyline_names), options = layersControlOptions(collapsed = F), data = getMapData(map)) return(map) })} )}
/scratch/gouwar.j/cran-all/cranData/AtlasMaker/R/map_server.R
#' Run a the AtlasMaker Shiny Demo #' #' @param app defaults to demo1 #' @return Demo of AtlasMaker, a Shiny app that displays 4 tabs of Leaflet maps. See package vignette for code. #' @export #' @importFrom shiny runApp shiny_AtlasMaker <- function( app = c('demo1') ) { pkg_dir <- find.package('AtlasMaker') if(!app %in% list.dirs(pkg_dir, full.names = FALSE)) { stop('Invalid application name.') } app_dir <- paste0(pkg_dir, '/', app[1]) shiny::runApp(appDir = app_dir) }
/scratch/gouwar.j/cran-all/cranData/AtlasMaker/R/shiny_AtlasMaker.R
library(AtlasMaker) library(leaflet) library(shiny) ###HOW TO DO LOAD CALL SO IT ISN"T MY PC? data(vignette_data_prepped) # Creating Lists for Map Tab Creation ## Tab 1 - Flowering Plants ## polygons list for tab 1: flowering plants------------- polys_flowering_plants <- list( list( name = 'flowering_plants', data = flowering_plants, label = 'name', fill = 'fill_value' ) ) ## points list for tab 1: flowering plants------------- points_flowering_plants <- list( list( name = 'points_parks', data = points_parks, long = 'long', lat = 'lat', label = 'label' ) ) ## Tab 2 - Birds ## polygon list for tab 2: birds------------- polys_birds <- list( list( name = 'birds', data = birds, label = 'name', fill = 'fill_value' ) ) ## polyline list for tab 2: birds------------- lines_birds <- list( list( name = 'ny_interstates', data = roads_ny_interstate ) ) ## points list for tab 2: birds------------- points_birds <- list( list( name = 'points_watchsites', data = points_watchsites, long = 'long', lat = 'lat', label = 'label' ), list( name = 'points_campgrounds', data = points_campgrounds, long = 'long', lat = 'lat', label = 'label' ) ) ## Tab 3 & 4 ## polygon list for tab 3: amph & rept ------------- polys_amph_rept <- list( list( name = 'amphibians', data = amphibians, label = 'name', fill = 'fill_value' ), list( name = 'reptiles', data = reptiles, label = 'label', fill = 'fill_value' ) ) ## point list for tab 3: amph & rept------------- points_amp_rept <- list( list( name = 'points_parks', data = points_parks, long = 'long', lat = 'lat', label = 'label' ), list( name = 'points_campgrounds', data = points_campgrounds, long = 'long', lat = 'lat', label = 'label' ) ) ## for tab 4------------- ## polygons list for tab 4: all------------- polys_all <- list( list( name = 'flowering_plants', data = flowering_plants, label = 'name', fill = 'fill_value' ), list( name = 'birds', data = birds, label = 'name', fill = 'fill_value' ), list( name = 'amphibians', data = amphibians, label = 'name', fill = 'fill_value' ), list( name = 'reptiles', data = reptiles, label = 'label', fill = 'fill_value' ) ) ## points list for tab 4: all------------- points_all <- list( list( name = 'points_parks', data = points_parks, long = 'long', lat = 'lat', label = 'label' ), list( name = 'points_campgrounds', data = points_campgrounds, long = 'long', lat = 'lat', label = 'label' ) ) ui <- fluidPage( titlePanel("AtlasMaker Demo Map (v0.9)"), mainPanel( tabsetPanel( tabPanel('Flowering Plants', map_UI('flowering_plants')), tabPanel('Birds', map_UI('birds')), tabPanel('Amphibians & Reptiles', map_UI('amph_rept')), tabPanel("All", map_UI("allthegoods")) ) ) ) server <- function(input, output) { map_server("flowering_plants", polygons = polys_flowering_plants, polygon_legend_title = "Biodiversity Count", polylines = NULL, points = points_flowering_plants, poly_palette = 'RdPu', point_color = 'brown' ) map_server("birds", polygons = polys_birds, polylines = lines_birds, points = points_birds, map_base_theme = 'Stamen.Watercolor', poly_palette = 'YlGn', point_color = '#ffa500', polyline_color = "#964b00" ) map_server("amph_rept", polygons = polys_amph_rept, polylines = NULL, points = points_amp_rept, map_base_theme = 'Esri.WorldImagery', poly_palette = 'Greens', point_color = "black" ) map_server("allthegoods", polygons = polys_all, polylines = NULL, points = points_all ) } # Run the application shinyApp(ui = ui, server = server)
/scratch/gouwar.j/cran-all/cranData/AtlasMaker/inst/demo1/app.R
## ---- include = FALSE--------------------------------------------------------- knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ## ----setup-------------------------------------------------------------------- library(AtlasMaker) library(shiny) ## ----------------------------------------------------------------------------- data(atlas_data) ## ----------------------------------------------------------------------------- class(birds) ## ----------------------------------------------------------------------------- head(points_campgrounds) ## ----------------------------------------------------------------------------- class(roads_ny_interstate) ## ----------------------------------------------------------------------------- ## polygons list for tab 1: flowering plants------------- polys_flowering_plants <- list( list( name = 'flowering_plants', data = flowering_plants, label = 'name', fill = 'fill_value' ) ) ## ----------------------------------------------------------------------------- ## points list for tab 1: flowering plants------------- points_flowering_plants <- list( list( name = 'points_parks', data = points_parks, long = 'long', lat = 'lat', label = 'label' ) ) ## ----------------------------------------------------------------------------- ## polygon list for tab 2: birds------------- polys_birds <- list( list( name = 'birds', data = birds, label = 'name', fill = 'fill_value' ) ) ## polyline list for tab 2: birds------------- lines_birds <- list( list( name = 'ny_interstates', data = roads_ny_interstate ) ) ## points list for tab 2: birds------------- points_birds <- list( list( name = 'points_watchsites', data = points_watchsites, long = 'long', lat = 'lat', label = 'label' ), list( name = 'points_campgrounds', data = points_campgrounds, long = 'long', lat = 'lat', label = 'label' ) ) ## ----------------------------------------------------------------------------- ## polygon list for tab 3: amph & rept ------------- polys_amph_rept <- list( list( name = 'amphibians', data = amphibians, label = 'name', fill = 'fill_value' ), list( name = 'reptiles', data = reptiles, label = 'label', fill = 'fill_value' ) ) ## point list for tab 3: amph & rept------------- points_amp_rept <- list( list( name = 'points_parks', data = points_parks, long = 'long', lat = 'lat', label = 'label' ), list( name = 'points_campgrounds', data = points_campgrounds, long = 'long', lat = 'lat', label = 'label' ) ) ## for tab 4------------- ## polygons list for tab 4: all------------- polys_all <- list( list( name = 'flowering_plants', data = flowering_plants, label = 'name', fill = 'fill_value' ), list( name = 'birds', data = birds, label = 'name', fill = 'fill_value' ), list( name = 'amphibians', data = amphibians, label = 'name', fill = 'fill_value' ), list( name = 'reptiles', data = reptiles, label = 'label', fill = 'fill_value' ) ) ## points list for tab 4: all------------- points_all <- list( list( name = 'points_parks', data = points_parks, long = 'long', lat = 'lat', label = 'label' ), list( name = 'points_campgrounds', data = points_campgrounds, long = 'long', lat = 'lat', label = 'label' ) ) ## ----------------------------------------------------------------------------- # 3. Set ui/layout -------- ui <- fluidPage( titlePanel("AtlasMaker Demo Map (v0.9)"), mainPanel( tabsetPanel( tabPanel('Flowering Plants', map_UI('flowering_plants')), tabPanel('Birds', map_UI('birds')), tabPanel('Amphibians & Reptiles', map_UI('amph_rept')), tabPanel("All", map_UI("allthegoods")) ) ) ) ## ----------------------------------------------------------------------------- server <- function(input, output) { map_server("flowering_plants", polygons = polys_flowering_plants, polygons_legend_title = "Biodiversity Count", polylines = NULL, points = points_flowering_plants, poly_palette = 'RdPu', point_color = 'brown' ) map_server("birds", polygons = polys_birds, polylines = lines_birds, points = points_birds, map_base_theme = 'Stamen.Watercolor', poly_palette = 'YlGn', point_color = '#ffa500', polyline_color = "#964b00" ) map_server("amph_rept", polygons = polys_amph_rept, polylines = NULL, points = points_amp_rept, map_base_theme = 'Esri.WorldImagery', poly_palette = 'Greens', point_color = "black" ) map_server("allthegoods", polygons = polys_all, polylines = NULL, points = points_all ) } ## ----------------------------------------------------------------------------- # Run the application shinyApp(ui = ui, server = server)
/scratch/gouwar.j/cran-all/cranData/AtlasMaker/inst/doc/AtlasMaker.R
--- title: "Getting Started with AtlasMaker" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{AtlasMaker} %\VignetteEncoding{UTF-8} %\VignetteEngine{knitr::rmarkdown} runtime: shiny --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` This vignette will walk through creating a 4 tab leaflet-based Shiny App of New York state biodiversity for an outdoor enthusiast. Point, polyline, and polygon data should be in a leaflet-compatible format prior to proceeding with the following steps for your own project. ```{r setup} library(AtlasMaker) library(shiny) ``` ```{r} data(atlas_data) ``` Provided datasets for this vignette come from https://data.ny.gov/, with the exception of counties_NY which was accessed through the `tigris` package and then combines with the biodiversity data. Preprocssed datasets include: Polygons: counties_NY (via tigris package) amphibians birds flowering_plants reptiles Points: points_campgrounds points_parks points_watchsites Polylines: roads_ny_interstate Taking a look at a few of the datasets: ```{r} class(birds) ``` ```{r} head(points_campgrounds) ``` ```{r} class(roads_ny_interstate) ``` # Creating Lists for Map Tab Creation First, we create one list per type of spatial data for each tab we need in the final AtlasMaker Shiny App. We'll make four for this vignette: Flowering Plants, Birds, Amphibians & Reptiles, and All. ## Tab 1 - Flowering Plants For our first Flowering Plants tab, we create one list for the needed polygons and provide the name to be referenced, the datafile which is already in a spatial dataframe format, and then provide which variable should be used for the label ('name') and which variable should be used for the polygon fill ('fill_value'). In this example, the fill_value is the biodiversity of flowering plants in the given New York state county. ```{r} ## polygons list for tab 1: flowering plants------------- polys_flowering_plants <- list( list( name = 'flowering_plants', data = flowering_plants, label = 'name', fill = 'fill_value' ) ) ``` With just the list above, the Flowering Plant tab would display New York state with shaded counties based on the biodiversity fill_value. Let's add some points to the map as well. With the list below, we name and choose the spatial dataframe with point data of where parks are in New York. Next, we map which variables in the spatial dataframe correspond with the long, lat, and label. ```{r} ## points list for tab 1: flowering plants------------- points_flowering_plants <- list( list( name = 'points_parks', data = points_parks, long = 'long', lat = 'lat', label = 'label' ) ) ``` ## Tab 2 - Birds Our next tab for Birds is quite similar, but we add a polylines list to show where New York interstates run with the `lines_birds` list. We also need two sets of points to display both campgrounds and wildlife watchsites, and these are nested into the larger `points_birds` list. ```{r} ## polygon list for tab 2: birds------------- polys_birds <- list( list( name = 'birds', data = birds, label = 'name', fill = 'fill_value' ) ) ## polyline list for tab 2: birds------------- lines_birds <- list( list( name = 'ny_interstates', data = roads_ny_interstate ) ) ## points list for tab 2: birds------------- points_birds <- list( list( name = 'points_watchsites', data = points_watchsites, long = 'long', lat = 'lat', label = 'label' ), list( name = 'points_campgrounds', data = points_campgrounds, long = 'long', lat = 'lat', label = 'label' ) ) ``` ## Tab 3 & 4 For Tab 3 we decide to show both our amphibian and reptiles data, so `polys_amp_rep` is a nested list. Tab 4 will display all the biodiversity data, so has an even larger nested list for it's polygon list. ```{r} ## polygon list for tab 3: amph & rept ------------- polys_amph_rept <- list( list( name = 'amphibians', data = amphibians, label = 'name', fill = 'fill_value' ), list( name = 'reptiles', data = reptiles, label = 'label', fill = 'fill_value' ) ) ## point list for tab 3: amph & rept------------- points_amp_rept <- list( list( name = 'points_parks', data = points_parks, long = 'long', lat = 'lat', label = 'label' ), list( name = 'points_campgrounds', data = points_campgrounds, long = 'long', lat = 'lat', label = 'label' ) ) ## for tab 4------------- ## polygons list for tab 4: all------------- polys_all <- list( list( name = 'flowering_plants', data = flowering_plants, label = 'name', fill = 'fill_value' ), list( name = 'birds', data = birds, label = 'name', fill = 'fill_value' ), list( name = 'amphibians', data = amphibians, label = 'name', fill = 'fill_value' ), list( name = 'reptiles', data = reptiles, label = 'label', fill = 'fill_value' ) ) ## points list for tab 4: all------------- points_all <- list( list( name = 'points_parks', data = points_parks, long = 'long', lat = 'lat', label = 'label' ), list( name = 'points_campgrounds', data = points_campgrounds, long = 'long', lat = 'lat', label = 'label' ) ) ``` # Plug into Shiny UI/Server ## Set Standard Shiny UI As usual with Shiny, we set up a basic `ui` for the app. For each `tabPanel()` the title to display goes in quotes first, followed by the function `map_UI()` with an id you create for each map. ```{r} # 3. Set ui/layout -------- ui <- fluidPage( titlePanel("AtlasMaker Demo Map (v0.9)"), mainPanel( tabsetPanel( tabPanel('Flowering Plants', map_UI('flowering_plants')), tabPanel('Birds', map_UI('birds')), tabPanel('Amphibians & Reptiles', map_UI('amph_rept')), tabPanel("All", map_UI("allthegoods")) ) ) ) ``` ## Set Standard Shiny Server, with AtlasMaker::map_server The `server` is where AtlasMaker uses the `map_server()` function to quickly fill in the lists we've created above. Using one map_server call per tab and starting with the 'flowering_plants', we start with the id created in the UI, followed by setting the polygons and points arguments to the lists we created above. Set a leaflet supported poly_palette, point_color, polyline_color, and map_base_theme if desired. ```{r} server <- function(input, output) { map_server("flowering_plants", polygons = polys_flowering_plants, polygons_legend_title = "Biodiversity Count", polylines = NULL, points = points_flowering_plants, poly_palette = 'RdPu', point_color = 'brown' ) map_server("birds", polygons = polys_birds, polylines = lines_birds, points = points_birds, map_base_theme = 'Stamen.Watercolor', poly_palette = 'YlGn', point_color = '#ffa500', polyline_color = "#964b00" ) map_server("amph_rept", polygons = polys_amph_rept, polylines = NULL, points = points_amp_rept, map_base_theme = 'Esri.WorldImagery', poly_palette = 'Greens', point_color = "black" ) map_server("allthegoods", polygons = polys_all, polylines = NULL, points = points_all ) } ``` *See the 'colors' section of Leaflet guide for options to pass in for colors/palettes: http://rstudio.github.io/leaflet/colors.html* *Pass in any base layer from the link into 'map_base_theme': http://leaflet-extras.github.io/leaflet-providers/preview/index.html* # Run the App **Please note:** knitting this Markdown file will only display a static image of the app, run the following code chunk in your R session to see the fully interactive demo app. The demo app is admittedly a little messy style wise, but with the purpose to show how easily the aesthetics of the maps can be changed using the `map_server()` arguments. ```{r} # Run the application shinyApp(ui = ui, server = server) ```
/scratch/gouwar.j/cran-all/cranData/AtlasMaker/inst/doc/AtlasMaker.Rmd
--- title: "Getting Started with AtlasMaker" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{AtlasMaker} %\VignetteEncoding{UTF-8} %\VignetteEngine{knitr::rmarkdown} runtime: shiny --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` This vignette will walk through creating a 4 tab leaflet-based Shiny App of New York state biodiversity for an outdoor enthusiast. Point, polyline, and polygon data should be in a leaflet-compatible format prior to proceeding with the following steps for your own project. ```{r setup} library(AtlasMaker) library(shiny) ``` ```{r} data(atlas_data) ``` Provided datasets for this vignette come from https://data.ny.gov/, with the exception of counties_NY which was accessed through the `tigris` package and then combines with the biodiversity data. Preprocssed datasets include: Polygons: counties_NY (via tigris package) amphibians birds flowering_plants reptiles Points: points_campgrounds points_parks points_watchsites Polylines: roads_ny_interstate Taking a look at a few of the datasets: ```{r} class(birds) ``` ```{r} head(points_campgrounds) ``` ```{r} class(roads_ny_interstate) ``` # Creating Lists for Map Tab Creation First, we create one list per type of spatial data for each tab we need in the final AtlasMaker Shiny App. We'll make four for this vignette: Flowering Plants, Birds, Amphibians & Reptiles, and All. ## Tab 1 - Flowering Plants For our first Flowering Plants tab, we create one list for the needed polygons and provide the name to be referenced, the datafile which is already in a spatial dataframe format, and then provide which variable should be used for the label ('name') and which variable should be used for the polygon fill ('fill_value'). In this example, the fill_value is the biodiversity of flowering plants in the given New York state county. ```{r} ## polygons list for tab 1: flowering plants------------- polys_flowering_plants <- list( list( name = 'flowering_plants', data = flowering_plants, label = 'name', fill = 'fill_value' ) ) ``` With just the list above, the Flowering Plant tab would display New York state with shaded counties based on the biodiversity fill_value. Let's add some points to the map as well. With the list below, we name and choose the spatial dataframe with point data of where parks are in New York. Next, we map which variables in the spatial dataframe correspond with the long, lat, and label. ```{r} ## points list for tab 1: flowering plants------------- points_flowering_plants <- list( list( name = 'points_parks', data = points_parks, long = 'long', lat = 'lat', label = 'label' ) ) ``` ## Tab 2 - Birds Our next tab for Birds is quite similar, but we add a polylines list to show where New York interstates run with the `lines_birds` list. We also need two sets of points to display both campgrounds and wildlife watchsites, and these are nested into the larger `points_birds` list. ```{r} ## polygon list for tab 2: birds------------- polys_birds <- list( list( name = 'birds', data = birds, label = 'name', fill = 'fill_value' ) ) ## polyline list for tab 2: birds------------- lines_birds <- list( list( name = 'ny_interstates', data = roads_ny_interstate ) ) ## points list for tab 2: birds------------- points_birds <- list( list( name = 'points_watchsites', data = points_watchsites, long = 'long', lat = 'lat', label = 'label' ), list( name = 'points_campgrounds', data = points_campgrounds, long = 'long', lat = 'lat', label = 'label' ) ) ``` ## Tab 3 & 4 For Tab 3 we decide to show both our amphibian and reptiles data, so `polys_amp_rep` is a nested list. Tab 4 will display all the biodiversity data, so has an even larger nested list for it's polygon list. ```{r} ## polygon list for tab 3: amph & rept ------------- polys_amph_rept <- list( list( name = 'amphibians', data = amphibians, label = 'name', fill = 'fill_value' ), list( name = 'reptiles', data = reptiles, label = 'label', fill = 'fill_value' ) ) ## point list for tab 3: amph & rept------------- points_amp_rept <- list( list( name = 'points_parks', data = points_parks, long = 'long', lat = 'lat', label = 'label' ), list( name = 'points_campgrounds', data = points_campgrounds, long = 'long', lat = 'lat', label = 'label' ) ) ## for tab 4------------- ## polygons list for tab 4: all------------- polys_all <- list( list( name = 'flowering_plants', data = flowering_plants, label = 'name', fill = 'fill_value' ), list( name = 'birds', data = birds, label = 'name', fill = 'fill_value' ), list( name = 'amphibians', data = amphibians, label = 'name', fill = 'fill_value' ), list( name = 'reptiles', data = reptiles, label = 'label', fill = 'fill_value' ) ) ## points list for tab 4: all------------- points_all <- list( list( name = 'points_parks', data = points_parks, long = 'long', lat = 'lat', label = 'label' ), list( name = 'points_campgrounds', data = points_campgrounds, long = 'long', lat = 'lat', label = 'label' ) ) ``` # Plug into Shiny UI/Server ## Set Standard Shiny UI As usual with Shiny, we set up a basic `ui` for the app. For each `tabPanel()` the title to display goes in quotes first, followed by the function `map_UI()` with an id you create for each map. ```{r} # 3. Set ui/layout -------- ui <- fluidPage( titlePanel("AtlasMaker Demo Map (v0.9)"), mainPanel( tabsetPanel( tabPanel('Flowering Plants', map_UI('flowering_plants')), tabPanel('Birds', map_UI('birds')), tabPanel('Amphibians & Reptiles', map_UI('amph_rept')), tabPanel("All", map_UI("allthegoods")) ) ) ) ``` ## Set Standard Shiny Server, with AtlasMaker::map_server The `server` is where AtlasMaker uses the `map_server()` function to quickly fill in the lists we've created above. Using one map_server call per tab and starting with the 'flowering_plants', we start with the id created in the UI, followed by setting the polygons and points arguments to the lists we created above. Set a leaflet supported poly_palette, point_color, polyline_color, and map_base_theme if desired. ```{r} server <- function(input, output) { map_server("flowering_plants", polygons = polys_flowering_plants, polygons_legend_title = "Biodiversity Count", polylines = NULL, points = points_flowering_plants, poly_palette = 'RdPu', point_color = 'brown' ) map_server("birds", polygons = polys_birds, polylines = lines_birds, points = points_birds, map_base_theme = 'Stamen.Watercolor', poly_palette = 'YlGn', point_color = '#ffa500', polyline_color = "#964b00" ) map_server("amph_rept", polygons = polys_amph_rept, polylines = NULL, points = points_amp_rept, map_base_theme = 'Esri.WorldImagery', poly_palette = 'Greens', point_color = "black" ) map_server("allthegoods", polygons = polys_all, polylines = NULL, points = points_all ) } ``` *See the 'colors' section of Leaflet guide for options to pass in for colors/palettes: http://rstudio.github.io/leaflet/colors.html* *Pass in any base layer from the link into 'map_base_theme': http://leaflet-extras.github.io/leaflet-providers/preview/index.html* # Run the App **Please note:** knitting this Markdown file will only display a static image of the app, run the following code chunk in your R session to see the fully interactive demo app. The demo app is admittedly a little messy style wise, but with the purpose to show how easily the aesthetics of the maps can be changed using the `map_server()` arguments. ```{r} # Run the application shinyApp(ui = ui, server = server) ```
/scratch/gouwar.j/cran-all/cranData/AtlasMaker/vignettes/AtlasMaker.Rmd
#' @title ChileAirQuality #' @description function that compiles air quality data from the National Air Quality System (S.I.N.C.A.) #' @param Comunas data vector containing the names or codes of the monitoring #' stations. Available stations: "P. O'Higgins","Cerrillos 1","Cerrillos","Cerro Navia", #' "El Bosque","Independecia","La Florida","Las Condes","Pudahuel","Puente Alto","Quilicura", #' "Quilicura 1","Alto Hospicio","Arica","Las Encinas Temuco","Nielol Temuco", #' "Museo Ferroviario Temuco","Padre Las Casas I","Padre Las Casas II","La Union", #' "CESFAM Lago Ranco","Mafil","Fundo La Ribera","Vivero Los Castanos","Valdivia I", #' "Valdivia II","Osorno","Entre Lagos","Alerce","Mirasol","Trapen Norte","Trapen Sur", #' "Puerto Varas","Coyhaique I","Coyhaique II","Punta Arenas". #' To see the full list of stations use ChileAirQuality() #' @param Parametros data vector containing the names of the air quality parameters. #' Available parameters: "PM10", "PM25", "CO","SO2", "NOX", "NO2", "NO", "O3", #' "temp" (temperature), "RH" (relative humidity), "ws" ( wind speed), #' "wd" (wind direction). #' @param fechadeInicio text string containing the start date of the data request #' @param fechadeTermino text string containing the end date of the data request #' @param Curar logical value that activates data curation for particulate matter, #' nitrogen oxides, relative humidity and wind direction. #' @param st logical value that includes validation reports from S.I.N.C.A. "NV": No validated, "PV": Pre-validated, "V": Validated. #' @param Site logical value that allows entering the code of the monitoring #' station in the variable "Comunas" #' @return A data frame with air quality data. #' @source <https://sinca.mma.gob.cl/> #' @export #' @import utils #' @examples #' #' try({ #' stations <- ChileAirQuality() #' }, silent =TRUE) #' #' try({ #' data <- ChileAirQuality(Comunas = "El Bosque", #' Parametros = c("PM10", "PM25"), fechadeInicio = "01/01/2020", #' fechadeTermino = "02/01/2020") #' }, silent =TRUE) #' #' try({ #' head(ChileAirQuality(Comunas = c("EB", "SA"), #' Parametros = "PM10", fechadeInicio = "01/01/2020", #' fechadeTermino = "01/03/2020", Site = TRUE)) #' }, silent = TRUE) #' ChileAirQuality <- function(Comunas = "INFO", Parametros, fechadeInicio, fechadeTermino, Site = FALSE, Curar = TRUE, st = FALSE){ #Find csv file location with list of monitoring stations sysEstaciones <- system.file("extdata", "SINCA.CSV", package = "AtmChile") #Data frame with monitoring stations estationMatrix <- read.csv(sysEstaciones, sep = ",", dec =".", encoding = "UTF-8") # input "INFO" to request information from monitoring stations if(Comunas[1] == "INFO"){ #Return data frame of stations return((estationMatrix)) }else{ ## Format of input values #include start time in start date fi <- paste(fechadeInicio,"1:00") # include end time in end date ft <- paste(fechadeTermino,"23:00") #Start date format Fecha_inicio <- as.POSIXct(strptime(fi, format = "%d/%m/%Y %H:%M")) #End date format Fecha_termino<- as.POSIXct(strptime(ft, format = "%d/%m/%Y %H:%M")) #Auxiliary start date format Fecha_inicio_para_arana <- as.character(Fecha_inicio, format("%y%m%d")) #Auxiliary end date format Fecha_termino_para_arana <- as.character(Fecha_termino, format("%y%m%d")) #date range code for url id_fecha <- gsub(" ","",paste("from=", Fecha_inicio_para_arana, "&to=", Fecha_termino_para_arana)) #time interval in hours horas <- (as.numeric(Fecha_termino)/3600-as.numeric(Fecha_inicio)/3600) #url part 1: Protocol, subdomain, domain and directory urlSinca <- "https://sinca.mma.gob.cl/cgi-bin/APUB-MMA/apub.tsindico2.cgi?outtype=xcl&macro=./" #url part 2: query generals parameters urlSinca2 <- "&path=/usr/airviro/data/CONAMA/&lang=esp&rsrc=&macropath=" # Cleaning variable date date = NULL #Date column date <- seq(Fecha_inicio, Fecha_termino, by = "hour") #Date column format date <- format(date, format = "%d/%m/%Y %H:%M") #Patch that avoids an ERROR data <- data.frame(date) #Empty data frame data_total <- data.frame() ##Selector #loop input variable "Comunas" for (i in 1:length(Comunas)) { try({ ## Assign inputs in "Comunas"to variable inEstation <- Comunas[i] for(j in 1:nrow(estationMatrix)){ mSite <- estationMatrix[j, 1] #Assign site to variable mCod <- estationMatrix[j, 2] #Assign code to variable mLon <- estationMatrix[j, 3] #Assign latitude to variable mLat <- estationMatrix[j, 4] #Assign longitude to variable mEstation <- estationMatrix[j, 5] #Assign station to variable #Verify "Site" control parameter if(Site){ #Compare "Comunas" with the Sites column aux <- mSite }else{ #Compare "Comunas" with the Full Names column aux <- mEstation } ##If the comparison is fulfilled, do: if(inEstation == aux){ try({ #Generate site column site <- rep(mSite, horas + 1) #Generate longitude and latitude column longitude <- rep(mLat, horas + 1) latitude <- rep(mLon, horas + 1) # Join the columns dates, longitude and latitude data <- data.frame(date, site, longitude, latitude) { #Loop input variable "Parametros" for(p in 1:length(Parametros)) { #Assign "Parametros" to variable inParametro <- Parametros[p] # If input parameter is PM10, do: if(inParametro == "PM10" |inParametro == "pm10" | inParametro == "pM10" |inParametro == "Pm10") { #sub query for the parameter PM10 codParametro <- "/Cal/PM10//PM10.horario.horario.ic&" #Concatenate URL url <- gsub(" ", "",paste(urlSinca, mCod, codParametro, id_fecha, urlSinca2)) try( { #Download csv file PM10_Bruto <- read.csv(url,dec =",", sep= ";",na.strings= "") #Join file columns PM10_col1 <- PM10_Bruto$Registros.validados PM10_col2 <- PM10_Bruto$Registros.preliminares PM10_col3 <- PM10_Bruto$Registros.no.validados PM10 <- gsub("NA","",gsub(" ", "",paste(PM10_col1,PM10_col2,PM10_col3))) if(st){ s.PM10 <- NULL for(q in 1:length(PM10)){ if(!is.na(PM10_col1[q])){ s.PM10 <- c(s.PM10, "V") }else if(!is.na(PM10_col2[q])){ s.PM10 <- c(s.PM10, "PV") }else{ if(!is.na(PM10_col3[q])){ s.PM10 <- c(s.PM10, "NV") }else{ s.PM10 <- c(s.PM10, "") } } } if(length(PM10) == 0 & st){s.PM10 <- rep("", horas + 1)} data <- data.frame(data,s.PM10) } # Control mechanism: if the file is not found, it generates an empty column if(length(PM10) == 0){PM10 <- rep("", horas + 1)} # Incorporate the column into the station data frame data <- data.frame(data, PM10) # Print success message print(paste(inParametro, inEstation)) } ,silent = T) } # If input parameter is PM25, do: else if(inParametro == "PM25" |inParametro == "pm25" | inParametro == "pM25" |inParametro == "Pm25") { #sub query for the parameter codParametro <- "/Cal/PM25//PM25.horario.horario.ic&" # Concatenate URL url <- gsub(" ", "",paste(urlSinca, mCod, codParametro, id_fecha, urlSinca2)) try( { #Download csv file PM25_Bruto <- read.csv(url,dec =",", sep= ";",na.strings= "") # Join columns of files PM25_col1 <- PM25_Bruto$Registros.validados PM25_col2 <- PM25_Bruto$Registros.preliminares PM25_col3 <- PM25_Bruto$Registros.no.validados PM25 <- gsub("NA","",gsub(" ", "",paste(PM25_col1,PM25_col2,PM25_col3))) if(st){ s.PM25 <- NULL for(q in 1:length(PM25)){ if(!is.na(PM25_col1[q])){ s.PM25 <- c(s.PM25, "V") }else if(!is.na(PM25_col2[q])){ s.PM25 <- c(s.PM25, "PV") }else{ if(!is.na(PM25_col3[q])){ s.PM25 <- c(s.PM25, "NV") } else{ s.PM25 <- c(s.PM25, "") } } } if(length(PM25) == 0 & st){s.PM25 <- rep("", horas + 1)} data <- data.frame(data,s.PM25) } # Control mechanism: if the file is not found, it generates an empty column if(length(PM25) == 0){PM25 <- rep("",horas + 1)} # Incorporate the column into the station data frame data <- data.frame(data,PM25) # Print success message print(paste(inParametro, inEstation)) } , silent = TRUE) } # If input parameter is Ozone, do: else if(inParametro == "O3"|inParametro == "o3") { #sub query for the parameter codParametro <- "/Cal/0008//0008.horario.horario.ic&" # Concatenate URL url <- gsub(" ", "",paste(urlSinca, mCod, codParametro, id_fecha, urlSinca2)) try( { #Download csv file O3_Bruto <- read.csv(url,dec =",", sep= ";",na.strings= "") # Join columns of files O3_col1 <- O3_Bruto$Registros.validados O3_col2 <- O3_Bruto$Registros.preliminares O3_col3 <- O3_Bruto$Registros.no.validados O3 <- gsub("NA","",gsub(" ", "",paste(O3_col1, O3_col2, O3_col3))) if(st){ s.O3 <- NULL for(q in 1:length(O3)){ if(!is.na(O3_col1[q])){ s.O3 <- c(s.O3, "V") }else if(!is.na(O3_col2[q])){ s.O3 <- c(s.O3, "PV") }else{ if(!is.na(O3_col3[q])){ s.O3 <- c(s.O3, "NV") }else{ s.O3 <- c(s.O3, "") } } } if(length(O3) == 0 & st){s.O3 <- rep("", horas + 1)} data <- data.frame(data,s.O3) } # Control mechanism: if the file is not found, it generates an empty column if(length(O3) == 0){O3 <- rep("",horas + 1)} # Incorporate the column into the station data frame data <- data.frame(data, O3) # Print success message print(paste(inParametro,inEstation)) } , silent = TRUE) } # If input parameter is carbon monoxide, do: else if(inParametro == "CO"| inParametro == "co"| inParametro == "Co"| inParametro == "cO") { # sub query for the parameter codParametro <- "/Cal/0004//0004.horario.horario.ic&" # Concatenate URL url <- gsub(" ", "",paste(urlSinca, mCod, codParametro, id_fecha, urlSinca2)) try( { #Download CSV file CO_Bruto <- read.csv(url, dec =",", sep= ";",na.strings = "") # Join columns of files CO_col1 <- CO_Bruto$Registros.validados CO_col2 <- CO_Bruto$Registros.preliminares CO_col3 <- CO_Bruto$Registros.no.validados CO <- gsub("NA","",gsub(" ", "",paste(CO_col1,CO_col2,CO_col3))) if(st){ s.CO <- NULL for(q in 1:length(CO)){ if(!is.na(CO_col1[q])){ s.CO <- c(s.CO, "V") }else if(!is.na(CO_col2[q])){ s.CO <- c(s.CO, "PV") }else{ if(!is.na(CO_col3[q])){ s.CO <- c(s.CO, "NV") }else{ s.CO <- c(s.CO, "") } } } if(length(CO) == 0 & st){s.CO <- rep("", horas + 1)} data <- data.frame(data,s.CO) } # Control mechanism: if the file is not found, it generates an empty column if(length(O3) == 0){O3 <- rep("",horas + 1)} # Incorporate the column into the station data frame data <- data.frame(data,CO) # Print success message print(paste(inParametro, inEstation)) } , silent = TRUE) } # If input parameter is nitrogen monoxide, do: else if(inParametro == "NO"| inParametro == "no"| inParametro == "No"| inParametro == "nO") { # sub query for the parameter codParametro <- "/Cal/0002//0002.horario.horario.ic&" # Concatenate URL url <- gsub(" ", "",paste(urlSinca, mCod, codParametro, id_fecha, urlSinca2)) try( { #Download CSV file NO_Bruto <- read.csv(url, dec = ",", sep = ";",na.strings = "") # Join columns of files NO_col1 <- NO_Bruto$Registros.validados NO_col2 <- NO_Bruto$Registros.preliminares NO_col3 <- NO_Bruto$Registros.no.validados NO <- gsub("NA", "", gsub(" ", "", paste(NO_col1, NO_col2, NO_col3))) if(st){ s.NO <- NULL for(q in 1:length(NO)){ if(!is.na(NO_col1[q])){ s.NO <- c(s.NO, "V") }else if(!is.na(NO_col2[q])){ s.NO <- c(s.NO, "PV") }else if(!is.na(NO_col3[q])){ s.NO <- c(s.NO, "NV") }else{ s.NO <- c(s.NO, "") } } if(length(NO) == 0 & st){s.NO <- rep("", horas + 1)} data <- data.frame(data,s.NO) } # Control mechanism: if the file is not found, it generates an empty column if(length(NO) == 0){NO <- rep("", horas + 1)} # Incorporate the column into the station data frame data <- data.frame(data, NO) # Print success message print(paste(inParametro, inEstation)) } ,silent = T) } # If input parameter is nitrogen dioxide, do: else if(inParametro == "NO2"| inParametro == "no2"| inParametro == "No2"| inParametro == "nO2") { # sub query for the parameter codParametro <- "/Cal/0003//0003.horario.horario.ic&" # Concatenate URL url <- gsub(" ", "",paste(urlSinca, mCod, codParametro, id_fecha, urlSinca2)) try( { #Download CSV file NO2_Bruto <- read.csv(url, dec =",", sep= ";", na.strings= "") # Join columns of files NO2_col1 <- NO2_Bruto$Registros.validados NO2_col2 <- NO2_Bruto$Registros.preliminares NO2_col3 <- NO2_Bruto$Registros.no.validados NO2 <- gsub("NA","",gsub(" ", "",paste(NO2_col1,NO2_col2,NO2_col3))) if(st){ s.NO2 <- NULL for(q in 1:length(NO2)){ if(!is.na(NO2_col1[q])){ s.NO2 <- c(s.NO2, "V") }else if(!is.na(NO2_col2[q])){ s.NO2 <- c(s.NO2, "PV") }else if(!is.na(NO2_col3[q])){ s.NO2 <- c(s.NO2, "NV") }else{ s.NO2 <- c(s.NO2, "") } } if(length(NO2) == 0 & st){s.NO2 <- rep("", horas + 1)} data <- data.frame(data,s.NO2) } # Control mechanism: if the file is not found, it generates an empty column if(length(NO2) == 0){NO2 <- rep("",horas + 1)} # Incorporate the column into the station data frame data <- data.frame(data, NO2) # Print success message print(paste(inParametro,inEstation)) } , silent = TRUE) } # If input parameter is nitrogen oxide, do: else if(inParametro == "NOX"|inParametro == "NOx"| inParametro == "nOX"|inParametro == "NoX"| inParametro == "Nox"|inParametro == "nOx"| inParametro == "nox"|inParametro == "noX") { # sub query for the parameter codParametro <- "/Cal/0NOX//0NOX.horario.horario.ic&" # Concatenate URL url <- gsub(" ", "",paste(urlSinca, mCod, codParametro, id_fecha, urlSinca2)) try( { #Download CSV file NOX_Bruto <- read.csv(url,dec =",", sep= ";",na.strings= "") # Join columns of files NOX_col1 <- NOX_Bruto$Registros.validados NOX_col2 <- NOX_Bruto$Registros.preliminares NOX_col3 <- NOX_Bruto$Registros.no.validados NOX <- gsub("NA", "", gsub(" ", "", paste(NOX_col1, NOX_col2, NOX_col3))) if(st){ s.NOX <- NULL for(q in 1:length(NOX)){ if(!is.na(NOX_col1[q])){ s.NOX <- c(s.NOX, "V") }else if(!is.na(NOX_col2[q])){ s.NOX <- c(s.NOX, "PV") }else{ if(!is.na(NOX_col3[q])){ s.NOX <- c(s.NOX, "NV") }else{ s.NOX <- c(s.NOX, "") } } } if(length(NOX) == 0 & st){s.NOX <- rep("", horas + 1)} data <- data.frame(data,s.NOX) } # Control mechanism: if the file is not found, it generates an empty column if(length(NOX) == 0){NOX <- rep("", horas + 1)} # Incorporate the column into the station data frame data <- data.frame(data, NOX) # Print success message print(paste(inParametro, inEstation)) } , silent = TRUE) } # If input parameter is sulfur dioxide, do: else if(inParametro == "SO2"| inParametro == "so2"| inParametro == "sO2"| inParametro == "So2") { # sub query for the parameter codParametro <- "/Cal/0001//0001.horario.horario.ic&" # Concatenate URL url <- gsub(" ", "",paste(urlSinca, mCod, codParametro, id_fecha, urlSinca2)) try( { #Download CSV file SO2_Bruto <- read.csv(url, dec =",", sep= ";", na.strings= "") # Join columns of files SO2_col1 <- SO2_Bruto$Registros.validados SO2_col2 <- SO2_Bruto$Registros.preliminares SO2_col3 <- SO2_Bruto$Registros.no.validados SO2 <- gsub("NA","",gsub(" ", "",paste(SO2_col1,SO2_col2,SO2_col3))) if(st){ s.SO2 <- NULL for(q in 1:length(SO2)){ if(!is.na(SO2_col1[q])){ s.SO2 <- c(s.SO2, "V") }else if(!is.na(SO2_col2[q])){ s.SO2 <- c(s.SO2, "PV") }else{ if(!is.na(SO2_col3[q])){ s.SO2 <- c(s.SO2, "NV") }else{ s.SO2 <- c(s.SO2, "") } } } if(length(SO2) == 0 & st){s.SO2 <- rep("", horas + 1)} data <- data.frame(data,s.SO2) } # Control mechanism: if the file is not found, it generates an empty column if(length(SO2) == 0){SO2 <- rep("",horas + 1)} # Incorporate the column into the station data frame data <- data.frame(data, SO2) # Print success message print(paste(inParametro,inEstation)) } , silent = TRUE) } # If input parameter is temperature, do: else if(inParametro == "tEMP" |inParametro == "temperatura"|inParametro == "TeMP" |inParametro == "TEMp"| inParametro == "Temperatura"|inParametro == "TEmP" |inParametro == "TEmp"|inParametro == "TeMp"|inParametro == "TemP"|inParametro == "tEMp" |inParametro == "tEmP"|inParametro == "teMP"|inParametro == "temp"|inParametro == "TEMP" |inParametro == "temP"|inParametro == "teMp"|inParametro == "tEmp"|inParametro == "Temp") { # sub query for the parameter codParametro <- "/Met/TEMP//horario_000.ic&" # Concatenate URL url <- gsub(" ", "", paste(urlSinca, mCod, codParametro, id_fecha, urlSinca2)) try( { #Download CSV file temp_bruto <- read.csv(url,dec =",", sep= ";",na.strings= "") # Join columns of files temp_col1 <- temp_bruto$X temp <- gsub("NA","",gsub(" ", "",temp_col1)) # Control mechanism: if the file is not found, it generates an empty column if(length(temp) == 0){temp <- rep("",horas + 1)} # Incorporate the column into the station data frame data <- data.frame(data, temp) # Print success message print(paste(inParametro, inEstation)) } , silent = TRUE) } #If input parameter is RH, do: else if(inParametro == "HR"| inParametro == "hr"| inParametro == "hR"| inParametro == "Hr") { # sub query for the parameter codParametro <- "/Met/RHUM//horario_000.ic&" # Concatenate URL url <- gsub(" ", "",paste(urlSinca, mCod, codParametro, id_fecha, urlSinca2)) try( { #Download CSV file HR_bruto <- read.csv(url,dec =",", sep= ";",na.strings= "") # Join columns of files HR_col1 <- HR_bruto$X HR <- gsub("NA","",gsub(" ", "",HR_col1)) # Control mechanism: if the file is not found, it generates an empty column if(length(HR) == 0){HR <- rep("",horas + 1)} # Incorporate the column into the station data frame data <- data.frame(data,HR) # Print success message print(paste(inParametro,inEstation)) } , silent = TRUE) } #If input parameter is wind direction, do: else if(inParametro == "wd"| inParametro == "WD"| inParametro == "Wd"| inParametro == "wD") { # sub query for the parameter codParametro <- "/Met/WDIR//horario_000_spec.ic&" # Concatenate URL url <- gsub(" ", "",paste(urlSinca, mCod, codParametro, id_fecha, urlSinca2)) try( { #Download CSV file wd_bruto <- read.csv(url,dec =",", sep= ";",na.strings= "") # Join columns of files wd_col1 <- wd_bruto$X wd <- gsub("NA","",gsub(" ", "",wd_col1)) # Control mechanism: if the file is not found, it generates an empty column if(length(wd) == 0 ){wd <- rep("",horas + 1)} # Incorporate the column into the station data frame data <- data.frame(data,wd) # Print success message print(paste(inParametro,inEstation)) } , silent = TRUE) } #If input parameter is wind speed, do: else if(inParametro == "ws"| inParametro == "WS"| inParametro == "Ws"| inParametro == "wS") { # sub query for the parameter codParametro <- "/Met/WSPD//horario_000.ic&" # Concatenate URL url <- gsub(" ", "",paste(urlSinca, mCod, codParametro, id_fecha, urlSinca2)) try( { #Download CSV file ws_bruto <- read.csv(url,dec =",", sep= ";",na.strings= "") # Join columns of files ws_col1 <- ws_bruto$X ws <- gsub("NA","",gsub(" ", "",ws_col1)) # Control mechanism: if the file is not found, it generates an empty column if(length(ws) == 0){ws <- rep("",horas + 1)} # Incorporate the column into the station data frame data <- data.frame(data,ws) # Print success message print(paste(inParametro,inEstation)) } , silent = TRUE) } #If the input parameter is not one of the list, do: else { # Print failure message print(paste("Contaminante",inParametro,"no soportado en el Software")) #Generar mensaje de fracaso } } try( { # Join the df of each station to the global dataframe data_total <- rbind(data_total, data) } , silent = T) } } , silent = T) } } }, silent = T) } #Control mechanism: If "Curar" is true, do: if(Curar){ #Variable that stores the number of rows in the dataframe len = nrow(data_total) ## First data curation tool: nitrogen oxides ## As long as the nitrogen oxides are not empty columns, do: if((length(data_total$NO) != 0) & (length(data_total$NO2) != 0) & (length(data_total$NOX) != 0)){ try({ for (i in 1:len) { try( { #If the sum of NO and NO2 is greater than NOX Eliminate the data of NO, NO2 and NOX considering an error of 0.1% if((as.numeric(data_total$NO[i]) + as.numeric(data_total$NO2[i])) > as.numeric(data_total$NOX[i]) * 1.001){ data_total$NO[i] = "" data_total$NO2[i] = "" data_total$NOX[i] = "" } } , silent = T) } }, silent = T) } #Second data curation tool: particulate matter if((length(data_total$PM25) != 0) & (length(data_total$PM10) != 0)){ try({ for (i in 1:len) { try( { # If PM25 is greater than PM10, delete PM10 and PM25, considering an error of 0.1% if(as.numeric(data_total$PM25[i]) > as.numeric(data_total$PM10[i])*1.001){ data_total$PM10[i] = "" data_total$PM25[i] = "" } } ,silent = T) } }, silent = T) } try({ #Third control mechanism: wind direction for (i in 1:len) { try({ #If the wind direction is less than 0 or greater than 360, delete the data if(as.numeric(data_total$wd[i]) > 360||as.numeric(data_total$wd[i]) < 0){ data_total$wd[i] = "" } }, silent = T) } }, silent = T) try({ i =NULL #Fourth control mechanism: Relative humidity for (i in 1:len) { try( { ##If the relative humidity is greater than 100% delete the data if(as.numeric(data_total$HR[i]) > 100||as.numeric(data_total$HR[i]) <0){ data_total$HR[i] = "" } }, silent = T) } }, silent = T) } #transform columns into numeric variables if(!st){ for(i in 3:ncol(data_total)){ data_total[[i]] <- as.numeric(data_total[[i]]) } }else{ for(i in 3:ncol(data_total)){ val <- TRUE j <- 1 while(val){ if(data_total[j, i] == ""| is.na(data_total[j, i])){ j <- j + 1 if(j > nrow(data_total)){ val <- FALSE } } if(data_total[j, i] != "NV" & data_total[j, i] != "PV" & data_total[j, i] != "V"){ data_total[[i]] <- as.numeric(data_total[[i]]) val <- FALSE }else{ val <- FALSE } } } } #print final success message print("Datos Capturados!") #return df global return(data_total) } }
/scratch/gouwar.j/cran-all/cranData/AtmChile/R/ChileAirQuality.R
#' Title ChileAirQualityApp #' @description This tool is a dashboard that allows you to use the data download #' functions of this package enhanced with analysis, visualization and #' descriptive statistics tools. #' @return A shiny dashboard to work with the package #' @export #' @seealso <https://chileairquality.shinyapps.io/chileairquality/> #' @examples \dontrun{ChileAirQualityApp()} #' @import shiny #' @import shiny #' @import shinycssloaders # @importFrom plotly plot_ly # @importFrom data.table setDT data.table # @importFrom DT dataTableOutput datatable renderDataTable # @importFrom lubridate year # @importFrom openair timeVariation corPlot timePlot polarPlot calendarPlot scatterPlot smoothTrend ChileAirQualityApp <- function() { Directory <- system.file("shiny", package = "AtmChile") if (Directory == "") { stop("Try reinstalling the package 'AtmChile'.", call. = FALSE) } shiny::runApp(Directory, display.mode = "normal") }
/scratch/gouwar.j/cran-all/cranData/AtmChile/R/ChileAirQualityApp.R
#' Title ChileClimateData #' @description function that compiles climate data from Climate direction of Chile (D.M.C.) #' @param Estaciones data vector containing the codes of the monitoring #' stations. To see the table with the monitoring stations use ChileClimateData() #' @param Parametros data vector containing the names of the climate parameters. #' Available parameters: "Temperatura", "PuntoRocio", "Humedad","Viento", "PresionQFE", "PresionQFF". #' #' @param inicio text string containing the start year of the data request. #' @param fin text string containing the end year of the data request. #' @param Region logical parameter. If region is true it allows to enter the administrative region in which the station is located instead of the station code. #' @return A data frame with climate data of Chile. #' #' @source <http://www.meteochile.gob.cl/> #' @export #' @import data.table #' @import utils #' #' #' @examples #' #' try({ChileClimateData()}, silent = TRUE) #' #' try({ #' data <- ChileClimateData(Estaciones = "180005", #' Parametros = c("Temperatura", "Humedad"), #' inicio = "2020", fin = "2020") #' }, silent = TRUE) #' #' try({ #' head(ChileClimateData(Estaciones = "II", #' Parametros = "Temperatura", inicio = "2020", #' fin = "2020", Region = TRUE)) #' }, silent = TRUE) ChileClimateData <- function(Estaciones = "INFO", Parametros, inicio, fin, Region = FALSE){ #Find csv file location with list of monitoring stations sysEstaciones <- system.file("extdata", "Estaciones.csv", package = "AtmChile") #Data frame with monitoring stations tablaEstaciones <- read.csv(sysEstaciones, sep = "," , dec =".", encoding = "UTF-8") # input "INFO" to request information from monitoring station if(Estaciones[1] == "INFO"){ #Return data frame of stations return(tablaEstaciones) } # error message if end year is greater than start year if(fin < inicio){ stop("Verificar fechas de inicio y fin") } #url part 1: Protocol, subdomain, domain and directory url1 <- "https://climatologia.meteochile.gob.cl/application/datos/getDatosSaclim/" #list of parameters to compare: parametros_list <- c("Temperatura", "PuntoRocio", "Humedad", "Viento", "PresionQFE", "PresionQFF") ##Temporarily out of use #temporal <- c("TMinima", "TMaxima", "Agua6Horas", "Agua24Horas") #parametros_list <- c(parametros_list, temporal) #date ranges intervalo <- inicio:fin #store input length of Stations: lenInEstaciones <- length(Estaciones) #store input length of parameters: lenInParametros <- length(Parametros) #store internal length of Stations: lenEstaciones <- nrow(tablaEstaciones) #store internal length of Parameters: lenParametros <- length(parametros_list) #store internal length of date range: lendate <- length(intervalo) #input date format: start <- as.POSIXct(strptime(paste("01-01-", inicio, "00:00:00", sep =""), format = "%d-%m-%Y %H:%M:%S")) end <- as.POSIXct(strptime(paste("31-12-", fin, "23:00:00", sep =""), format = "%d-%m-%Y %H:%M:%S")) #Temporarily out of use #horas<-(as.numeric(end)/3600-as.numeric(start)/3600) date = NULL #generate date column date <- seq(start, end, by = "hour") #format date column date <- format(date, format = "%d-%m-%Y %H:%M:%S") df <- NULL df2 <- NULL #generate empty global data frame data_total <- data.frame() ## Control mechanism: If "Region" is true, ##the input parameters will be verified with column 7 ##of the matrix (administrative divisions), if false, it will be ##compared with column 1 (Station codes) if(Region == TRUE){ r <- 7 }else{ r <- 1 } # Loop input variable "Estacion" for(i in 1:lenInEstaciones){ # Loop Station Matrix (station code or ad division) for(j in 1:lenEstaciones){ if(Estaciones[i] == tablaEstaciones[j, r]){ estacion_var <- tablaEstaciones[j, 1] #Assign station code to variable Latitud <- tablaEstaciones[j, 5] #Assign latitude to variable Longitud <- tablaEstaciones[j, 6] #Assign longitude to variable Nombre <- rep(tablaEstaciones[j, 4], length(date)) #Generate station name column Latitud <- rep(tablaEstaciones[j, 5], length(date)) #Generate latitude column Longitud <- rep(tablaEstaciones[j, 6], length(date)) #Generate longitude column data <- data.frame(date, Nombre, Latitud, Longitud) #Join data, station name, longitude and latitude in station df setDT(data) #Set station data frame as data table #Loop input variable "Parametros" for(k in 1:lenInParametros){ #Loop internal variable "parametros_list" for(l in 1:lenParametros){ #Compare input with the internal list if(Parametros[k] == parametros_list[l]){ #iterate for each year for(m in 1:lendate){ temp <- tempfile() temp1 <- tempfile() #concatenate url for query url3 <- paste(url1, estacion_var,"_",intervalo[m], "_", parametros_list[l], "_", sep = "") print(url3) #concatenate required zip file name filename <- paste(estacion_var,"_",intervalo[m],"_", parametros_list[l], ".zip", sep = "") #concatenate required csv file name csvname <- paste(estacion_var,"_",intervalo[m],"_", parametros_list[l], "_.csv", sep = "") #clear CSV variable CSV <- NULL try({ #Download zip file download.file(url3, temp, method = "curl") #suppress warnings messages suppressWarnings({ #unzip downloaded file and assing name for the csv file try({ #read csv file #CSV<- read.csv(unzip(temp, csvname), sep = ";", dec = ".", encoding = "UTF-8") CSV<- data.table::fread(unzip(temp, csvname), sep = ";", dec = ".", encoding = "UTF-8") if(parametros_list[l] == "Viento"){ names(CSV) <- unlist(strsplit(names(CSV), ","))[1:5] }else{ names(CSV) <- unlist(strsplit(names(CSV), ","))[-1] } }, silent = T) }) }, silent = TRUE) #In the event of an error or absence of data if(is.null(CSV)| length(CSV) == 0){ #auxliar date variables momento1 <- as.POSIXct(strptime(paste("01-01-", intervalo[m], "00:00:00", sep =""), format = "%d-%m-%Y %H:%M:%S")) momento2 <- as.POSIXct(strptime(paste("31-12-", intervalo[m], "23:00:00", sep =""), format = "%d-%m-%Y %H:%M:%S")) #Generate date column momento <- seq(momento1, momento2, by = "hour") #Generate cod column CodigoNacional <-rep("", length(momento)) #Format data column momento <- format(momento, format = "%d-%m-%Y %H:%M:%S") #generate empty column if(parametros_list[l] == "Temperatura"){ Ts_Valor<- rep("", length(momento)) CSV <- data.frame(CodigoNacional, momento, Ts_Valor) }else if(parametros_list[l] == "PuntoRocio"){ Td_Valor<- rep("", length(momento)) CSV <- data.frame(CodigoNacional, momento, Td_Valor) }else if(parametros_list[l] == "Humedad"){ HR_Valor<- rep("", length(momento)) CSV <- data.frame(CodigoNacional, momento, HR_Valor) }else if(parametros_list[l] == "Viento"){ dd_Valor<- rep("", length(momento)) ff_Valor<- rep("", length(momento)) VRB_Valor<- rep("", length(momento)) CSV <- data.frame(CodigoNacional, momento, dd_Valor,ff_Valor, VRB_Valor) }else if(parametros_list[l] == "PresionQFE"){ QFE_Valor<- rep("", length(momento)) CSV <- data.frame(CodigoNacional, momento, QFE_Valor) }else if(parametros_list[l] == "PresionQFF"){ QFF_Valor<- rep("", length(momento)) CSV <- data.frame(CodigoNacional, momento, QFF_Valor) } } #join data column to station dataframe df<- rbind(df, CSV) #If the files exist delete them suppressWarnings({ file.remove(csvname) }) unlink(temp) } if(parametros_list[l] == "Viento"){ #If the parameter is wind, keep only columns 2, 3, 4 and 5 (with data) df2 <- data.frame(df[2], df[3], df[4], df[5]) }else{ #If the parameter isn't wind, keep only columns 2 and 3(with data) df2 <- data.frame(df[2], df[3]) } #set auxiliary dataframe (df2) as data table setDT(df2) #Generate match between the donwloaded data and the partial dataframe data <- data[df2, on = c("date" = "momento")] #Clean df and df2 df <- NULL df2 <- NULL } } } #Join dataframes into a global dataframe if(is.null(data_total)){ data_total<-data }else{ data_total<-rbind(data_total, data) } } } } #format date column data_total$date <- format(as.POSIXct(strptime(data_total$date, format = "%d-%m-%Y %H:%M:%S")), format = "%d/%m/%Y %H:%M") #clean data without date records data_total <- data_total[!(is.na(data_total$date)),] #clean data without names station records data_total <- data_total[!(is.na(data_total$Nombre)),] #transform columns into numeric variables for(i in 3:ncol(data_total)){ data_total[[i]] <- as.numeric(data_total[[i]]) } #transform data table into a dataframe data_total <- as.data.frame(data_total) #Return dataframe return(data_total) }
/scratch/gouwar.j/cran-all/cranData/AtmChile/R/ChileClimateData.R
--- title: 'AtmChile: A R package to explore open-source air pollution and meteorological data and implementation through Shiny web platform.' authors: - affiliation: '1' name: Francisco Catalán Meyer orcid: 0000-0003-3506-5376 - affiliation: '1' name: Manuel Leiva Guzmán orcid: 0000-0001-8891-0399 - affiliation: '1' name: Richard Toro Araya date: "`r Sys.Date()`" affiliations: - index: '1' name: Department of Chemistry, Faculty of Sciences, University of Chile, Chile tags: - R - open-source - air quality - shiny --- # Summary The study of air quality has taken an increasingly important role in the generation of public policies, this due to the effects that air pollution causes on the health of people and animals, affecting vegetation, soil and materials. , limiting visibility and the potential to contribute significantly to climate change. One of the main difficulties faced by the study of air quality is the enormous volume and disintegration of data collected daily, so the development of data analysis techniques plays an essential role in this. countryside. In the case of Chile, the main open source data are reported by the National Air Quality Information System [(SINCA)](https://sinca.mma.gob.cl/) under the [(Ministry of the Environment of Chile)](https://mma.gob.cl/), which collects air quality data from X stations throughout the country; and the National Meteorological Directorate [(DMC)](https://climatologia.meteochile.gob.cl/) dependent on the General [Directorate of Civil Aeronautics of Chile](https://www.dgac.gob.cl/), which stores meteorological data from 47 stations throughout the country. `AtmChile` is an R package that allows downloading and managing data from SINCA and DMC for multiple parameters of air quality and meteorology, offering quick and easy access for researchers. This package includes `ChileAirQualityApp` a dashboard that integrates the download tools of this package with visualization tools and descriptive statistics analysis in a user-friendly way. The `ChileAirQualityApp` dashboard is displayed in five tabs. Different packages used for building `ChileAirQuality` include `data.table`, `plotly`, `shiny`, `openair`, `lubridate`, `shinycssloaders` and `DT`. # Statement of need The air quality data offered by the SINCA and the DMC are offered with high levels of disaggregation: separated by monitoring station, parameter and by year, in In the case of the DMC, this makes it difficult for researchers trying to compile large data sets. `AtmChile` offers a simple solution to this problem by: 1. Access and management of the open source databases of SINCA and DMC 2. Application of data quality control options This package was implemented in a web platform designed with Shiny offering to generate visualizations and summaries of the main statistical parameters. To our knowledge, there is currently no application that can generate usable summary statistics and graphs using data from the contamination databases from SINCA and/or DMC. However, there are some Shiny apps that deal with data cleansing and visualization of pollution data collected from single/multiple air quality instruments. # Package Overview The package contains 3 functions: `ChileAirQuality` to download air quality data from SINCA open source servers; `ChileClimateData` to download meteorological data from open source DMC servers and `ChileAirQualityApp` a Shiny Dashboard for the data download functions of this package enhanced with analysis, visualization and descriptive statistics tools. `ChileAirQuality` is a function that compiles in a data frame air quality data from the National Air Quality System (SINCA). The input variables are: a) `Comunas`: string vector that can contain the monitoring stations listed in ***Annex I***; b) `Parametros`: string vector that can contain the parameters listed in ***Annex II***; c) `fechadeInicio`: string containing the start date of the data request in format (dd / mm / yyyy); d) `fechadeTermino`: string containing the end date of the data request in in format; e) `Curar`: allows to replace as `NA`, the values that do not meet the conditions: i) *PM25 < PM10*; ii) *(NO2 + NO) < NOX*; iii) *0 < HR < 100* and iv) *0 < wd < 360* if they exist; f) `Site`: logical value that allows entering the code of the monitoring station, listed in ***Annex I***, in the variable `Comunas`; and g) `st`: logical value that includes validation reports from SINCA *"NV"*: No validated, *"PV"*: Pre-validated and *"V"*: Validated. *Example:* df <- ChileAirQuality(Comunas = "Cerrillos", Parametros = c("PM10, PM25"), fechadeInicio = "01/01/2020,", fechadeTermino = "01/01/2021", Curar = TRUE, Site = FALSE, st = FALSE) `ChileClimateData` is a function that compiles meteorological data from the Chilean Meteorological Directorate (DMC). The input variables are: a) `Estaciones`: string vector with the codes of the monitoring stations listed in ***Annex III***; b) `Parametros`: string vector that may contain the parameters listed in ***Annex IV*** c) `inicio`: initial year of the data request; d) `fin`: final year of the data request and e) `Region`: logical parameter, when region is `TRUE`, it allows entering the administrative region in which the station is located instead of the station code and listed in ***Annex III***. *Example:* df2 <- ChileClimateData(Estaciones = "II", Parametros = "Temperatura", inicio = "2020", fin = "2021", Region = TRUE) `ChileAirQualityApp` is a dashboard that allows you to use the data download functions of this package enhanced with analysis, visualization and descriptive statistics tools. `ChileAirQualityApp` is hosted online on [*shinyapp.io*](https://chileairquality.shinyapps.io/chileairquality/) and can be used to serve locally with the AtmChile package. Run `ChileAirQualityApp` as follows: AtmChile::ChileAirQualityApp() # App Display The ***Data Calidad del Aire*** tab allows the user to use the `ChileAirQuality` function to download, within the application, information from the SINCA servers for the parameters listed in ***Annex II*** for the monitoring stations of the Metropolitan Region (RM) and the Region of Aysen (XXI). The option `Curar` of `ChileAirQuality` is found as a checkbox working as previously described.The tab includes the *"Download"* button to download the dataset in case you want to use it locally. The ***Data Climatica*** tab allows the user to use the `ChileClimateData` function to download, within the application, information from the DMC servers for the parameters listed in ***Annex IV*** according to the administrative division of the country. The tab includes the *"Download"* button to download the dataset in case you want to use it locally. The ***Graficas*** tab allows the user to generate visualizations of the downloaded data integrating various options of the `OpenAir` package. Some of the main options are summarized in **Table 1**: **Table 1**: *Summary of the main display options offered in the "Graficas" tab* Option | Plot type | Air Quality | Met. Data | Ungroup stations| Adjust time scale| Adjust variables| --------------|-------------|-------------|-----------|-----------------|------------------|------------------| timePlot | Temporal | **X** | **X** | **X** | **X** | timeVariation | Temporal | **X** | **X** | **X** | | CorPlot | Correlation | **X** | **X** | **X** | | polarPlot | Polar | **X** | | **X** | | scatterPlot | Correlation | **X** | | **X** | | **X** calendarPlot | Temporal | **X** | **X** | | **X** | smoothTrend | Temporal | **X** | **X** | **X** | | | The ***Resumen*** tab offers to generate summaries of descriptive statistics such as: mean, median, standard deviation and coefficient of variation. The tab includes the "Download" button to download the statistical summary in case you want to use it locally. The ***Información*** tab contains summary tables with the parameters considered in the *“Data Calidad del Aire”* and *"Data Climatica”* tab, along with a map with the geographical locations of the stations considered in the *“Data Calidad del Aire”* tab. # Limitations a) Limited meteorological and air quality variables. b) Limited availability of monitoring stations with the application. c) Multiple datasets cannot be downloaded and compared at the same time. d) No interactive or statics plots. e) The user requires precautions on the interpretation of the visualizations and the statistical parameters. # Installation The `AtmChile` package can be installed and load from CRAN repository as follows: install.packages("AtmChile") library(AtmChile) # Case study For a better understanding of the functionality of `ChileAirQualityApp`, we present a case study based on 5 years of pollution data set from SINCA and 5 years of meteorological data set from DMC. ## Air Pollution The pollution data was downloaded from SINCA using `ChileAirQualityApp` for the monitoring stations “Parque O’Higgins” and “La Florida” between 2015 and 2020 using the parameters “PM10”, “PM25”, “ws”(wind speed) and “wd”(wind direction). The data was downloaded from SINCA for the monitoring stations located at Parque O’Higgins and La Florida between the years 2015 and 2020. **Figure 1** show a time series plot generated with the option “timePlot” for PM10 with a month average time resolution. ![Figure 1](Figure1.png) **Figure 1:** *PM10 Monthly time series for the monitoring stations La Florida (LF) and Parque O’Higgins (SA) between 2015 and 2020.* **Figure 2** show the time series plot generated with the “timeVariation” option for PM10 and PM25 for combined monitoring stations. This option generates four graphs: hourly variation according to the average day of the week, hourly variation in the average day, monthly variation in an average year and daily variation in the average week with a confidence interval of 95%. ![Figure 2](Figure2.png) **Figure 2:** *PM10 and PM25 times series for combined monitoring stations between 2015 and 2020 generated with the timeVariation option.* Correlations between PM10, PM25 and the meteorological variables wind speed and wind direction are shown in **Figure 3** by means of a plot generated with the corPlot option separated according to the monitoring station. The coded correlation is observed in three ways: by shape (ellipses), color and numerical value. ![Figure 3](Figure3.png) **Figure 3:** *PM10, PM25, wind speed and wind direction correlation plot for the monitoring stations La Florida (LF) and Parque O’Higgins (SA).* The calendarPlot option generates a calendar with the daily averages of a certain parameter with a scrollbar to filter the time interval. In this case, it was applied for PM25 during the year 2019 as shown in **Figure 4**. ![Figure 4](Figure4.png) **Figure 4:** *PM25 Calendar Plot for combined monitoring stations in 2019.* The polarPlot function plots a bivariate polar graph of how concentrations vary with wind speed and direction. **Figure 5** represents the polar graph for the monitoring stations La Florida (LF) and Parque O'Higgins (SA). ![Figure 5](Figure5.png) **Figure 5:** *PM25 Polar Plot for the monitoring stations La Florida (LF) and Parque O’Higgins (SA).* ## Meteorological data The data was downloaded from DMC for the monitoring stations located at the Antofagasta Region considering the meteorological stations of Cerro Moreno Antofagasta Ap. And El Loa Calama Ad. between the years 2015 and 2020 for the parameters “Ts”(dry air temperature) “dd”(wind direction) and “ff”(wind speed). **Figure 6** show a time series plot generated with the option “smoothTrend” for Temperature(“Ts_Valor”) showing the monthly averages and the linear trend of the temperatures in that period of time. ![Figure 6](Figure6.png) **Figure 6:** *Temperature time series plot for the meteorological stations of Cerro Moreno Antofagasta Ap. And El Loa Calama Ad. between the years 2015 and 2020. Generated with the option “smootTrend”.* The timeVariation option can also be used on the parameters of the DMC meteorological stations. **Figure 7** shows the time series generated with this option for the combined meteorological stations of the Antofagasta Region between 2015 and 2020. ![Figure 7](Figure7.png) **Figure 7:** *Temperature times series for combined meteorological stations between 2015 and 2020 generated with the timeVariation option.* # Acknowledgments # References # Anexo I: ChileAirQuality monitoring stations N° |Code |Latitude |Longitude |Station | Ad. division | ---|----------|------------|-------------|--------------------------|--------------| 1 | SA | -33.4508 | -70.6604 | P. O'Higgins | RM | 2 | CE1 | -33.4795 | -70.7190 | Cerrillos 1 | RM | 3 | CE | -33.4824 | -70.7039 | Cerrillos | RM | 4 | CN | -33.4197 | -70.7317 | Cerro Navia | RM | 5 | EB | -33.5336 | -70.6659 | El Bosque | RM | 6 | IN | -33.4089 | -70.6508 | Independecia | RM | 7 | LF | -33.5032 | -70.5879 | La Florida | RM | 8 | LC | -33.3634 | -70.5230 | Las Condes | RM | 9 | PU | -33.4244 | -70.7498 | Pudahuel | RM | 10 | PA | -33.5779 | -70.5941 | Puente Alto | RM | 11 | QU | -33.336 | -70.7235 | Quilicura | RM | 12 | QU1 | -33.3525 | -70.7479 | Quilicura 1 | RM | 15 | AH | -20.2904 | -70.1001 | Alto Hospicio | I | 16 | AR | -18.4768 | -70.2879 | Arica | XV | 17 | TE | -38.7486 | -72.6207 | Las Encinas Temuco | IX | 18 | TEII | -38.7270 | -72.5800 | Nielol Temuco | IX | 19 | TEIII | -38.7253 | -72.5711 | Museo Ferroviario Temuco | IX | 20 | PLCI | -38.7724 | -72.5950 | Padre Las Casas I | IX | 21 | PLCII | -38.7647 | -72.5987 | Padre Las Casas II | IX | 22 | LU | -40.2868 | -73.0767 | La Union | XIV | 23 | LR | -40.3212 | -72.4718 | CESFAM Lago Ranco | XIV | 24 | MAI | -39.6656 | -72.9537 | Mafil | XIV | 25 | MAII | -39.5423 | -72.9252 | Fundo La Ribera | XIV | 26 | MAIII | -39.7192 | -73.1286 | Vivero Los Castanos | XIV | 27 | VA | -39.8313 | -73.2285 | Valdivia I | XIV | 28 | VAII | -39.8054 | -73.2587 | Valdivia II | XIV | 29 | OS | -40.5844 | -73.1187 | Osorno | X | 30 | OSII | -40.6837 | -72.5963 | Entre Lagos | X | 31 | PMI | -41.3991 | -72.8995 | Alerce | X | 32 | PMII | -41.4795 | -72.9687 | Mirasol | X | 33 | PMIII | -41.5103 | -73.0652 | Trapen Norte | X | 34 | PMIV | -41.5187 | -73.0880 | Trapen Sur | X | 35 | PV | -41.3289 | -72.9682 | Puerto Varas | X | 36 | COI | -45.5799 | -72.0610 | Coyhaique I | XI | 37 | COII | -45.5790 | -72.0499 | Coyhaique II | XI | 38 | PAR | -53.1582 | -70.9214 | Punta Arenas | XII | # Anexo II: ChileAirQuality parameters Parameter| Description | Units ---------|--------------------------------------------------|---------- PM10 |Particulate material minor to 10 micron | ug/m^{3}N PM25 |Particulate material minor to 2,5 micron | ug/m^{3}N SO2 |Sulfur dioxide | ug/m^{3}N NOX |Nitrogen oxides | ppb NO |Nitrogen monoxide | ppb NO2 |Nitrogen dioxide | ppb O3 |tropospheric ozone | ppb CO |Carbon monoxide | ppb temp |Temperature | °C ws |Wind speed | m/s wd |Wind direction | ° HR |Relative humidity | % # Anexo III: meteorological stations N. | National Code | Name | Latitude |Longitude | Ad. division | ---|---------------|----------------------------------------|------------|-----------|--------------| 1 | 180005 | Chacalluta, Arica Ap. | -18.35555 |-70.33889 | XV 2 | 200006 | Diego Aracena Iquique Ap. |-20.54917 |-70.16944 | I 3 | 220002 | El Loa, Calama Ad. |-22.49806 |-68.89805 | II 4 | 230001 | Cerro Moreno Antofagasta Ap. |-23.45361 |-70.44056 | II 5 | 270001 | Mataveri Isla de Pascua Ap. |-27.15889 |-109.42361 | V 6 | 270008 | Desierto de Atacama, Caldera Ad. |-27.25444 |-70.77944 | III 7 | 290004 | La Florida, La Serena Ad. |-29.91444 |-71.20333 | IV 8 | 320041 | Viña del Mar Ad. (Torquemada) |-32.94944 |-71.47444 | V 9 | 320051 | Los Libertadores |-32.84555 |-70.11861 | V 10 | 330007 | Rodelillo, Ad. | -33.06528 |-71.55917 | V 11 | 330019 | Eulogio Sánchez, Tobalaba Ad. | -33.45528 |-70.54222 | RM 12 | 330020 | Quinta Normal, Santiago | -33.44500 |-70.67778 | RM 13 | 330021 | Pudahuel Santiago | -33.37833 |-70.79639 | RM 14 | 330030 | Santo Domingo, Ad. | -33.65611 |-71.61000 | V 15 | 330031 |Juan Fernández, Estación Meteorológica. | -33.63583 |-78.83028 | V 16 | 330066 | La Punta, Juan Fernández Ad. |-33.66639 |-78.93194 | V 17 | 330077 | El Colorado |-33.35000 |-70.28805 | RM 18 | 330111 | Lo Prado Cerro San Francisco |-33.45806 |-70.94889 | RM 19 | 330112 | San José Guayacán |-33.61528 |-70.35583 | RM 20 | 330113 | El Paico |-33.70639 |-71.00000 | RM 21 | 340031 | General Freire, Curicó Ad. |-34.96944 |-71.22028 | VII 22 | 360011 | General Bernardo O'Higgins, Chillán Ad.| -36.58583 |-72.03389 | XVI 23 | 360019 | Carriel Sur, Concepción Ap. |-36.78055 |-73.05083 | VIII 24 | 360042 | Termas de Chillán |-36.90361 |-71.40667 | XVI 25 | 370033 | María Dolores, Los Angeles Ad. |-37.39694 |-72.42361 | VIII 26 | 380013 | Maquehue, Temuco Ad. |-38.76778 |-72.62694 | IX 27 | 380029 | La Araucanía Ad. |-38.93444 |-72.66083 | IX 28 | 390006 | Pichoy, Valdivia Ad. |-39.65667 |-73.08472 | XIV 29 | 400009 | Cañal Bajo, Osorno Ad. |-40.61444 |-73.05083 | X 30 | 410005 | El Tepual Puerto Montt Ap. |-41.44750 |-73.08472 | X 31 | 420004 | Chaitén, Ad. |-42.93028 |-72.71167 | X 32 | 420014 | Mocopulli Ad. |-42.34667 |-73.71167 | X 33 | 430002 | Futaleufú Ad. |-43.18889 |-71.86417 | X 34 | 430004 | Alto Palena Ad. |-43.61167 |-71.81333 | X 35 | 430009 | Melinka Ad. |-43.89778 |-73.74555 | X 36 | 450001 | Puerto Aysén Ad. |-45.39944 |-72.67778 | XI 37 | 450004 | Teniente Vidal, Coyhaique Ad. |-45.59083 |-72.10167 | XI 38 | 450005 | Balmaceda Ad. |-45.91833 |-71.67778 | XI 39 | 460001 | Chile Chico Ad. |-46.58500 |-71.69472 | XI 40 | 470001 | Lord Cochrane Ad. |-47.24389 |-72.57611 | XI 41 | 510005 | Teniente Gallardo, Puerto Natales Ad. | -51.66722 |-72.52528 | XII 42 | 520006 | Carlos Ibañez, Punta Arenas Ap. |-53.00167 |-70.84722 | XII 43 | 530005 | Fuentes Martínez, Porvenir Ad. |-53.25361 |-70.32194 | XII 44 | 550001 |Guardiamarina Zañartu, Pto Williams Ad. |-54.93167 |-67.61000 | XII 45 | 50001 |C.M.A. Eduardo Frei Montalva, Antártica |-62.19194 |-58.98278 | XII 46 | 50002 | Arturo Prat, Base Antártica |-62.47861 |-59.66083 | XII 47 | 950003 | Bernardo O`Higgins, Base Antártica |-63.32083 |-57.89805 | XII # Anexo IV: meteorological parameters Parameter | Description | Output | Units ------------|-------------------------------------|-------------------------|---------- Temperatura |Temperature | Ts_Valor | °C PuntoRocio |Dew point temperature | Td_Valor | °C Humedad |Relative humidity | HR_Valor | % Viento |Wind speed and wind direction | ff_Valor and dd_Valor | m/s and ° PresionQFF |Pressure at sea level | QFF_Valor | Pa PresionQFE |Pressure at monitoring station level | QFE_Valor | Pa
/scratch/gouwar.j/cran-all/cranData/AtmChile/inst/paper/paper.Rmd
#' @keywords internal "_PACKAGE" # The following block is used by usethis to automatically manage # roxygen namespace tags. Modify with care! ## usethis namespace: start ## usethis namespace: end NULL
/scratch/gouwar.j/cran-all/cranData/AtmChile/inst/shiny/AtmChile-package.R
library(shiny) library(shinycssloaders) e <- new.env() source("complementaryFunctions.R",local=e) attach(e) ui <-fluidPage( ################################### HEAD ##################################### HTML("<head> <title>ChileAirQuality Proyect</title> <link rel='shortcut icon' href='ico.png'> <meta name='robots' content='ChileAirQuality Web App' /> <meta name='description' content='Aplicación web para facilitar el estudio de la calidad del aire en Chile' /> </head> "), ################################# CALIDAD DEL AIRE TAB###################### tabsetPanel(tabPanel("Data Calidad del Aire", { titlePanel("Captura de Datos") sidebarLayout( sidebarPanel( #Input start date dateInput("Fecha_inicio", label ="Fecha de inicio", value = Sys.Date()-1, min = "1997-01-01", max= Sys.Date(), format= "dd/mm/yyyy"), #Input end date dateInput("Fecha_Termino", label ="Fecha de Termino", value = Sys.Date()-1, min = ("1997-01-01"), max= Sys.Date(), format= "dd/mm/yyyy"), #Control option: Curate data checkboxInput("validacion", label = "Curar datos", value = TRUE), #Air quality climate factors buttons splitLayout(checkboxGroupInput("F_Climaticos", label ="F. Climaticos", choices =c("temp", "HR", "wd","ws"), selected = c("temp", "HR", "wd","ws") ), #Air quality pollutants buttons checkboxGroupInput("Contaminantes", label ="Contaminantes", choices =c( "PM10", "PM25", "NO","NO2", "NOX","O3","CO", "SO2") ) ), #Air quality stations buttons splitLayout(checkboxGroupInput("Comunas1", label ="Estaciones", choices =c("P. O'Higgins","Cerrillos 1", "Cerrillos", "Cerro Navia", "El Bosque","Independecia") ), checkboxGroupInput("Comunas2", label ="", choices = c("Las Condes","La Florida", "Pudahuel","Puente Alto","Quilicura", "Quilicura 1", "Coyhaique I", "Coyhaique II") ) ), #Action button submitButton("Aplicar Cambios") ), mainPanel( #Deploy air quality data table withSpinner(DT::dataTableOutput("table")), #Download air quality data downloadButton("descargar", label ="Descargar"), #Hide error tags$style(type="text/css", ".shiny-output-error { visibility: hidden; }", ".shiny-output-error:before { visibility: hidden; }" ) ) ) } ), ############################### DATA CLIMATE TAB ########################### tabPanel("Data Climatica", { sidebarLayout( sidebarPanel( #Years range for the data collection sliderInput("rango", "Rango:", min = 1940, max = lubridate::year(Sys.Date()), value = c(2000,(lubridate::year(Sys.Date()) - 1))), #Climate data parameters checkboxGroupInput("parametros", label ="Parametros", choices =c("Temperatura", "PuntoRocio", "Humedad", "Viento", "PresionQFE", "PresionQFF"), selected = c("Temperatura", "PuntoRocio", "Humedad", "Viento", "PresionQFE", "PresionQFF")), #Ad regions button splitLayout( checkboxGroupInput("region1", label ="Regiones", choices =c("I","II", "III", "IV", "V","VI", "VII", "VIII") ), checkboxGroupInput("region2", label ="", choices =c("IX","X", "XI","XII","XIV", "XV", "XVI", "RM")) ), #Action button submitButton("Aplicar Cambios") ), #Deploy climate data table mainPanel( withSpinner( DT::dataTableOutput("table1")), #Download button downloadButton("descargar1",label ="Descargar"), #Hide error tags$style(type="text/css", ".shiny-output-error { visibility: hidden; }", ".shiny-output-error:before { visibility: hidden; }") ) ) } ), ############################## GRAFICAS TAB ################################ tabPanel("Gráficas", { sidebarLayout( sidebarPanel( uiOutput("sData2"), uiOutput("selectorGraficos"),##In development!!! #Deploy graphic selection bar option #Deploy complementary options uiOutput("moreControls"), #Action button submitButton("Actualizar") ), mainPanel( withSpinner(uiOutput("mainGraphics")) , #Hide errors tags$style(type="text/css", ".shiny-output-error { visibility: hidden; }", ".shiny-output-error:before { visibility: hidden; }" ) ) ) } ), ############################# RESUMEN TAB ################################## tabPanel("Resumen", { sidebarLayout( sidebarPanel( uiOutput("sData"), #Select statistic summary option selectInput("statsummary","Resumen Estadistico", choices = c("--Seleccionar--","Promedio", "Mediana","Desviacion Estandar", "coeficiente de variacion") ), #Action bottom submitButton("Aplicar Cambios") ), mainPanel( # Stats table withSpinner(DT::dataTableOutput("statstable")), #Download stats table downloadButton("descargarstats", label ="Descargar" ), #Hide errors tags$style(type="text/css", ".shiny-output-error { visibility: hidden; }", ".shiny-output-error:before { visibility: hidden; }" ) ) ) } ), ############################ INFORMACION TAB ############################### tabPanel("Información", { #Table of variables verticalLayout( tags$body(HTML(" <h1><strong>Calidad del aire</strong></h1> <h2><strong>Variables de Calidad del aire</strong></h2> <p>Esta aplicación tiene disponible los siguientes parámetros para el análisis de la calidad del aire disponibles del Sistema de Información Nacional de Calidad del Aire. </p> ")), withSpinner(tableOutput("info_2")), tags$body(HTML(" <a href = 'https://sinca.mma.gob.cl/'> sinca.mma.gob.cl</a> <h2><strong>Estaciones de monitoreo</strong></h2> <p>Los datos recopilados por esta aplicación son reportados por el sistema de información nacional de calidad del aire a partir de la red de estaciones de monitoreo MACAM distribuidas en las comunas de la región metropolitana. </p>" )), withSpinner(plotly::plotlyOutput("sitemap", width = "500px", height = "500px" )), tags$body(HTML(" <br> <br> <h1><strong>Meteorología</strong></h1> <h2><strong>Variables meteorológicas</strong></h2> <p>Esta aplicación tiene disponible los siguientes parámetros para el análisis meteorológicos disponibles en la Dirección meteorológica de Chile.</p> ")), withSpinner(tableOutput("info_3")), tags$body(HTML(" <a href = 'http://www.meteochile.gob.cl/'> www.meteochile.gob.cl</a> <br> <br> <br> <br>")) ) } ) )) #################################SERVER######################################### server <- function(input, output) { ######################################CALIDAD DEL AIRE TAB#################### #Reactive function for download air quality information from SINCA data_totalAQ<-reactive( ChileAirQuality( Comunas = c(c(input$Comunas1, input$Comunas2)), Parametros = c(input$Contaminantes, input$F_Climaticos), fechadeInicio = as.character( input$Fecha_inicio, format("%d/%m/%Y") ), fechadeTermino = as.character( input$Fecha_Termino, format("%d/%m/%Y") ), Curar = input$validacion )) #Data Table for air quality information output$table <- DT::renderDataTable( DT::datatable({data_totalAQ()}, filter = "top", selection = 'multiple', style = 'bootstrap' ) ) #Download Botton for air quality data output$descargar<-downloadHandler( filename = "data.csv", content = function(file){ write.csv(data_totalAQ(), file) } ) ############################### DATA CLIMATE TAB ############################# #reactive function for download climate data from DMC data_totalDC <- reactive( ChileClimateData( Estaciones = c(input$region1, input$region2), Parametros = input$parametros, inicio = input$rango[1], fin = input$rango[2], Region = TRUE )) #Deploy data table for climate data output$table1 <- DT::renderDataTable( DT::datatable({data_totalDC()}, filter = "top", selection = 'multiple', style = 'bootstrap' ) ) #Download Button for climate data output$descargar1<-downloadHandler( filename = "data.csv", content = function(file){ write.csv(data_totalDC(), file) } ) ############################## GRAFICAS TAB ################################## output$sData2 <- renderUI({ selectInput("selectData2","Seleccionar dataset", choices = c("--Seleccionar--","Data Climatica", "Calidad del aire") ) }) output$selectorGraficos <- renderUI({ if(input$selectData2 == "Calidad del aire"){ selectInput("Select","Tipo de Grafico", choices = c("--Seleccionar--","timeVariation","corPlot","timePlot", "calendarPlot","polarPlot","scatterPlot","smoothTrend") ) } else if(input$selectData2 == "Data Climatica"){ selectInput("Select","Tipo de Grafico", choices = c("--Seleccionar--","timeVariation","corPlot","timePlot", "calendarPlot","smoothTrend") ) } }) #Deploy reactive controls option for air quality graphics output$moreControls <- renderUI({ parClimatico <- comparFunction(input$parametros) if(input$selectData2 == "Calidad del aire"){ ##Options for calendarPlot if(input$Select == "calendarPlot"){ flowLayout( sliderInput("rango_calendar", "Rango:", step = 1, min = lubridate::year(as.Date(input$Fecha_inicio, format = "%d/%m/%Y")), max = lubridate::year(as.Date(input$Fecha_Termino, format = "%d/%m/%Y")), value = c(lubridate::year(as.Date(input$Fecha_inicio, format = "%d/%m/%Y")), lubridate::year(as.Date(input$Fecha_Termino, format = "%d/%m/%Y")))), radioButtons(inputId = "choices", label = "Contaminantes", choices = input$Contaminantes) ) } else if(input$Select == "scatterPlot"){ ##Options for scatterPlot flowLayout( splitLayout(radioButtons(inputId = "x", label = "Contaminantes", choices = input$Contaminantes), radioButtons(inputId = "y", label = "Contaminantes", choices = input$Contaminantes) ), splitLayout( #Logaritm options in the X axis checkboxInput(inputId = "logx",label = "log(x)"), #Logaritm options in the Y axis checkboxInput(inputId ="logy",label = "log(y)"), #Trace lineal correlation checkboxInput(inputId ="lineal",label = "Lineal") ) ) } else if(input$Select == "smoothTrend"){ flowLayout(checkboxInput("checkSites","Desagrupar por Ciudad"), radioButtons(inputId = "choices", label = "Contaminantes", choices = input$Contaminantes) ) } else if(input$Select == "timePlot"){ #Deploy un-group for station option flowLayout(checkboxInput("checkSites","Desagrupar por Ciudad"), selectInput("avgtime","Promedio de tiempo", choices = c("hour","year","month","week", "day")), checkboxGroupInput(inputId = "choices", label = "Contaminantes", choices = input$Contaminantes, selected = input$Contaminantes) ) } else{ #Deploy un-group for station option flowLayout(checkboxInput("checkSites","Desagrupar por Ciudad"), checkboxGroupInput(inputId = "choices", label = "Contaminantes", choices = input$Contaminantes, selected = input$Contaminantes) ) } } else if(input$selectData2 == "Data Climatica"){ if(input$Select == "calendarPlot"){ flowLayout( sliderInput("rango_calendar", "Rango:", step = 1, min = input$rango[1], max =input$rango[2], value = c(input$rango[1], input$rango[2])), radioButtons(inputId = "choices", label = "Parametros", choices = parClimatico) ) } else if(input$Select == "smoothTrend"){ flowLayout(checkboxInput("checkSites","Desagrupar por Ciudad"), radioButtons(inputId = "choices", label = "Parametros", choices = parClimatico) ) } else if(input$Select == "timePlot"){ #Deploy un-group for station option flowLayout(checkboxInput("checkSites","Desagrupar por Ciudad"), selectInput("avgtime","Promedio de tiempo", choices = c("hour","year","month","week", "day")), checkboxGroupInput(inputId = "choices", label = "Parametros", choices = parClimatico, selected = parClimatico) ) } else{ #Deploy un-group for station option flowLayout(checkboxInput("checkSites","Desagrupar por Ciudad"), checkboxGroupInput(inputId = "choices", label = "Parametros", choices = parClimatico, selected = parClimatico) ) } } }) #Transform controls for meteorological parameters output$grafico<-renderPlot({ try({ if(input$selectData2 == "Calidad del aire"){ if(input$checkSites){ if(input$Select =="timeVariation") { #deploy timeVariation of air quality data un-group by site openair::timeVariation(data_totalAQ(), pollutant = input$choices, type = "site") } else if(input$Select=="corPlot"){ #deploy corPlot of air quality data un-group by site openair::corPlot(data_totalAQ(), pollutant = c(input$choices,input$F_Climaticos), type = "site") } else if(input$Select=="timePlot"){ #deploy timePlot of air quality data un-group by site openair::timePlot(data_totalAQ(), pollutant = input$choices, type = "site", avg.time = input$avgtime) } else if(input$Select=="polarPlot"){ #deploy polarPlot of air quality data un-group by site openair::polarPlot(data_totalAQ(), pollutant = input$choices, type = "site") } else if(input$Select=="calendarPlot"){ #deploy timePlot of air quality data un-group by site openair::calendarPlot(data_totalAQ(), pollutant = input$choices, type = "site", year = as.numeric(input$rango_calendar[1]):as.numeric(input$rango_calendar[2])) } else if(input$Select=="scatterPlot"){ #deploy scatterPlot of air quality data openair::scatterPlot(data_totalAQ(), x = input$x, y= input$y, x.log = input$logx, y.log = input$logy, linear = input$lineal) } else if(input$Select=="smoothTrend"){ openair::smoothTrend(data_totalAQ(), pollutant = input$choices, type = "site") } }else{ if(input$Select=="timeVariation"){ #deploy timeVariation of air quality data openair::timeVariation(data_totalAQ(), pollutant = input$choices) } else if(input$Select=="corPlot"){ #deploy corPlot of air quality data openair::corPlot(data_totalAQ(), pollutant = c(input$choices,input$F_Climaticos)) } else if(input$Select=="timePlot"){ #deploy timePlot of air quality data un-group by site openair::timePlot(data_totalAQ(), pollutant = input$choices, avg.time = input$avgtime) } else if(input$Select=="polarPlot"){ #deploy polarPlot of air quality data un-group by site openair::polarPlot(data_totalAQ(), pollutant = input$choices) } else if(input$Select=="calendarPlot"){ #deploy calendarPlot of air quality data un-group by site openair::calendarPlot(data_totalAQ(), pollutant = input$choices, year = as.numeric(input$rango_calendar[1]):as.numeric(input$rango_calendar[2])) } else if(input$Select=="scatterPlot"){ #deploy scatterPlot of air quality data un-group by site openair::scatterPlot(data_totalAQ(), x = input$x, y= input$y, log.x = input$logx, log.y = input$logy, linear = input$lineal) } else if(input$Select=="smoothTrend"){ openair::smoothTrend(data_totalAQ(), pollutant = input$choices) } } } else if (input$selectData2 == "Data Climatica"){ if(input$checkSites){ if(input$Select=="timeVariation"){ #deploy timeVariation of air quality data un-group by site openair::timeVariation(data_totalDC(), pollutant = input$choices, type = "Nombre") } else if(input$Select=="corPlot"){ #deploy corPlot of air quality data un-group by site openair::corPlot(data_totalDC(), pollutant = input$choices ,type = "Nombre") } else if(input$Select=="timePlot"){ #deploy timePlot of air quality data un-group by site openair::timePlot(data_totalDC(), pollutant = input$choices ,type = "Nombre", avg.time = input$avgtime) } else if(input$Select=="calendarPlot"){ #deploy timePlot of air quality data un-group by site openair::calendarPlot(data_totalDC(), pollutant = input$choices ,type = "Nombre", year = as.numeric(input$rango_calendar[1]):as.numeric(input$rango_calendar[2])) } else if(input$Select=="smoothTrend"){ openair::smoothTrend(data_totalDC(), pollutant = input$choices ,type = "Nombre") } }else{ if(input$Select=="timeVariation"){ #deploy timeVariation of air quality data openair::timeVariation(data_totalDC(), pollutant = input$choices) } else if(input$Select=="corPlot"){ #deploy corPlot of air quality data openair::corPlot(data_totalDC(), pollutant = input$choices) } else if(input$Select=="timePlot"){ #deploy timePlot of air quality data un-group by site openair::timePlot(data_totalDC(), pollutant = input$choices, avg.time = input$avgtime) } else if(input$Select=="calendarPlot"){ #deploy calendarPlot of air quality data un-group by site openair::calendarPlot(data_totalDC(), pollutant = input$choices, year = as.numeric(input$rango_calendar[1]):as.numeric(input$rango_calendar[2])) } else if(input$Select=="smoothTrend"){ openair::smoothTrend(data_totalDC(), pollutant = input$choices) } } } }, silent = TRUE) }) #Graphics options descriptions output$text<-renderUI({ #Time Variation description suppressWarnings({ if(input$Select=="timeVariation"){ tags$body( tags$h2("timeVariation"), tags$p("La función timeVariation produce cuatro gráficos: variación del día de la semana, variación de la hora media del día y un gráfico combinado de hora del día - día de la semana y un gráfico mensual. También se muestra en los gráficos el intervalo de confianza del 95% en la media.") ) } else if(input$Select=="corPlot"){ #Corplot description tags$body( tags$h2("corPlot"), tags$p("El corPlot muestra la correlación codificada de tres formas: por forma (elipses), color y valor numérico. Las elipses se pueden considerar como representaciones visuales de un diagrama de dispersión. Con una correlación positiva perfecta se traza una línea a 45 grados de pendiente positiva. Para una correlación cero, la forma se convierte en un círculo.") ) } else if(input$Select=="timePlot"){ #timePlot description tags$body( tags$h2("timePlot"), tags$p("La función timePlot permite trazar rápidamente series de tiempo de datos para varios contaminantes o variables. Trazara series de tiempo de datos de alta resolución por hora.") ) } else if(input$Select=="polarPlot"){ #polarPlot description tags$body( tags$h2("polarPlot"), tags$p("La función polarPlot traza una gráfica polar bivariada de concentraciones. Se muestra como las concentraciones varían según la velocidad y la dirección del viento.") ) } else if(input$Select=="calendarPlot"){ #Calendarplot tags$body( tags$h2("calendarPlot"), tags$p("La función calendarPlot proporciona una forma eficaz de visualizar los datos de esta manera al mostrar las concentraciones diarias en formato de calendario. La concentración de una especie se muestra por su color.") ) } else if(input$Select=="scatterPlot"){ #scatterPlot description tags$body( tags$h2("scatterPlot"), tags$p("Los gráficos de dispersión son extremadamente útiles y una técnica de análisis muy utilizada para considerar como las variables se relacionan entre sí." ) ) } else if(input$Select=="smoothTrend"){ #Corplot description tags$body( tags$h2("smoothTrend"), tags$p("La función smoothTrend proporciona una forma flexible de estimar la tendencia en la concentración de un contaminante u otra variable. Los valores medios mensuales se calculan a partir de una serie de tiempo horaria (o de mayor resolución) o diaria. ") ) } }) }) output$mainGraphics<-renderUI({ verticalLayout( #Deploy air quality graphics withSpinner(plotOutput("grafico")), uiOutput("text") ) }) ###################################### RESUMEN TAB ########################### # Select dataset output$sData <- renderUI({ selectInput("selectData","Seleccionar dataset", choices = c("--Seleccionar--","Data Climatica", "Calidad del aire") ) }) #Calculate the statistical summary stats<-reactive( if(input$selectData == "Data Climatica"){ if(input$statsummary == "Promedio"){ datamean2(data_totalDC()) } else if(input$statsummary == "Mediana"){ datamedian2(data_totalDC()) } else if(input$statsummary == "Desviacion Estandar"){ datasd2(data_totalDC()) } else if(input$statsummary == "coeficiente de variacion"){ datacv2(data_totalDC()) } } else if(input$selectData == "Calidad del aire"){ if(input$statsummary == "Promedio"){ datamean(data_totalAQ()) } else if(input$statsummary == "Mediana"){ datamedian(data_totalAQ()) } else if(input$statsummary == "Desviacion Estandar"){ datasd(data_totalAQ()) } else if(input$statsummary == "coeficiente de variacion"){ datacv(data_totalAQ()) } } ) #Build the statistical summary table output$statstable <- DT::renderDataTable( DT::datatable({stats()}, filter = "top", selection = 'multiple', style = 'bootstrap' ) ) #Download the statistical summary output$descargarstats<-downloadHandler( filename = "stats.csv", content = function(file){ write.csv(stats(), file) } ) #################################INFORMACION TAB############################## #Map plot of air quality stations output$sitemap<-plotly::renderPlotly({ siteplot(ChileAirQuality()) }) #air quality variables descriptions output$info_2 <- renderTable({ read.csv("varAQ.csv", encoding = "UTF-8") }) #data climate variables descriptions output$info_3 <- renderTable({ read.csv("varDC.csv", encoding = "UTF-8") }) } #############################################RUN################################ shinyApp(ui = ui, server = server)
/scratch/gouwar.j/cran-all/cranData/AtmChile/inst/shiny/app.R
CV<- function(x, dec = 3){ cv = (sd(x, na.rm = TRUE)/mean(x, na.rm = TRUE))*100 cv = round(cv, dec) if(!is.na(cv)){ cv = paste(cv, "%") } return(cv) } meant<-function(x, dec = 3){ meant = round(mean(x, na.rm = TRUE), dec) return(meant) } mediant<-function(x, dec = 3){ mediant = round(median(x, na.rm = TRUE), dec) return(mediant) } sdt<-function(x, dec = 3){ sd = round(sd(x, na.rm = TRUE), dec) return(sd) } datamean<- function(data, inicio = 5){ len = length(data) data<- data.table::data.table(data) datamean <- data[, lapply(.SD, meant), by = .(site, longitude, latitude), .SDcols = inicio:len] datamean <- as.data.frame(datamean) return(datamean) } datasd<- function(data, inicio = 5){ len = length(data) data<- data.table::data.table(data) datasd <- data[, lapply(.SD, sdt), by = .(site, longitude, latitude), .SDcols = inicio:len] datasd <- as.data.frame(datasd) return(datasd) } datamedian<- function(data, inicio = 5){ len = length(data) data<- data.table::data.table(data) datamedian <- data[, lapply(.SD, mediant), by = .(site, longitude, latitude), .SDcols = inicio:len] datamedian <- as.data.frame(datamedian) return(datamedian) } datacv<- function(data, inicio = 5){ len = length(data) data<- data.table::data.table(data) datacv <- data[, lapply(.SD, CV), by = .(site, longitude, latitude), .SDcols = inicio:len] datacv <- as.data.frame(datacv) return(datacv) } datamean2<- function(data, inicio = 5){ len = length(data) data<- data.table::data.table(data) datamean <- data[, lapply(.SD, meant), by = .(Nombre, Latitud, Longitud), .SDcols = inicio:len] datamean <- as.data.frame(datamean) return(datamean) } datasd2<- function(data, inicio = 5){ len = length(data) data<- data.table::data.table(data) datasd <- data[, lapply(.SD, sdt), by = .(Nombre, Latitud, Longitud), .SDcols = inicio:len] datasd <- as.data.frame(datasd) return(datasd) } datamedian2<- function(data, inicio = 5){ len = length(data) data<- data.table::data.table(data) datamedian <- data[, lapply(.SD, mediant), by = .(Nombre, Latitud, Longitud), .SDcols = inicio:len] datamedian <- as.data.frame(datamedian) return(datamedian) } datacv2<- function(data, inicio = 5){ len = length(data) data<- data.table::data.table(data) datacv <- data[, lapply(.SD, CV), by = .(Nombre, Latitud, Longitud), .SDcols = inicio:len] datacv <- as.data.frame(datacv) return(datacv) } comparFunction<- function(data){ obs <- data comparar <- data.frame( par<- c("Temperatura", "PuntoRocio", "Humedad", "PresionQFE", "PresionQFF", "dd_Valor", "ff_Valor"), nom <- c("Ts_Valor", "Td_Valor", "HR_Valor", "QFE_Valor", "QFF_Valor", "dd_Valor", "ff_Valor") ) a <- NULL for(i in 1:length(obs)){ aux <- obs[i] if(aux == "Viento"){ a <- c(a, "dd_Valor", "ff_Valor") }else{ for(j in 1:nrow(comparar)){ aux1 <- comparar[j, 1] aux2 <- comparar[j, 2] if(aux == aux1){ a <- c(a, aux2) } } } } print(a) return(a) } siteplot<-function(data, latitud = data$Longitud, longitud = data$Latitud, centro = c(-70.6, -33.4)){ fig<-plotly::plot_ly(data, lat = latitud, lon = longitud, marker = list(color = "red"), hovertext = ~paste("Estacion:", data$Estacion,"<br />", "Site:", data$Ciudad), type = 'scattermapbox' ) fig<- plotly::layout( p = fig, mapbox = list( style = 'open-street-map', zoom =9, center = list(lon = centro[1], lat = centro[2]) ) ) return(fig) } ChileClimateData <- function(Estaciones = "INFO", Parametros, inicio, fin, Region = FALSE){ tablaEstaciones <- data.frame( "Codigo Nacional" = c("180005","200006","220002","230001","270001","270008","290004","320041", "320051","330007","330019","330020","330021","330030","330031","330066", "330077","330111","330112","330113","340031","360011","360019","360042", "370033","380013","380029","390006","400009","410005","420004","420014", "430002","430004","430009","450001","450004","450005","460001","470001", "510005","520006","530005","550001","950001","950002","950003"), "Codigo OMM" = c("85406","85418","85432","85442","85469","85467","85488","85556","85539", "85560","85580","85577","85574","85586","85585","85584","85594","85571", "85593","85569","85629","85672","85682","85671","85703","85743","85744", "85766","85782","85799","85830","85824","85832","85836","85837","85862", "85864","85874","85886","85892","85920","85934","85940","85968","89056", "89057","89059"), "Codigo OACI" = c("SCAR","SCDA","SCCF","SCFA","SCIP","SCAT","SCSE","SCVM","","SCRD","SCTB", "SCQN","SCEL","SCSN","","SCIR","","","","","SCIC","SCCH","SCIE","","SCGE", "SCTC","SCQP","SCVD","SCJO","SCTE","SCTN","SCPQ","SCFT","SCAP","SCMK","SCAS", "SCCY","SCBA","SCCC","SCHR","SCNT","SCCI","SCFM","SCGZ","SCRM","SCBP","SCBO"), "Nombre" = c("Chacalluta Arica Ap.","Diego Aracena Iquique Ap.","El Loa Calama Ad.", "Cerro Moreno Antofagasta Ap.","Mataveri Isla de Pascua Ap.", "Desierto de Atacama Caldera Ad.","La Florida La Serena Ad.", "Vina del Mar Ad. (Torquemada)","Los Libertadores","Rodelillo Ad.", "Eulogio Sanchez Tobalaba Ad.","Quinta Normal Santiago","Pudahuel Santiago", "Santo Domingo Ad.","Juan Fernandez Estacion Meteorologica.", "La Punta Juan Fernandez Ad.","El Colorado","Lo Prado Cerro San Francisco", "San Jose Guayacan","El Paico","General Freire Curico Ad.", "General Bernardo O'Higgins Chillan Ad.","Carriel Sur Concepcion Ap.", "Termas de Chillan","Maria Dolores Los Angeles Ad.","Maquehue Temuco Ad.", "La Araucania Ad.","Pichoy Valdivia Ad.","Canal Bajo Osorno Ad.", "El Tepual Puerto Montt Ap.","Chaiten Ad.","Mocopulli Ad.","Futaleufu Ad.", "Alto Palena Ad.","Melinka Ad.","Puerto Aysen Ad.","Teniente Vidal Coyhaique Ad.", "Balmaceda Ad.","Chile Chico Ad.","Lord Cochrane Ad.", "Teniente Gallardo Puerto Natales Ad.","Carlos Ibanez Punta Arenas Ap.", "Fuentes Martinez Porvenir Ad.","Guardiamarina Zanartu Pto Williams Ad.", "C.M.A. Eduardo Frei Montalva Antartica","Base Antartica Arturo Prat", "Base Antartica Bernardo O`Higgins"), "Latitud" = c("-18.35555","-20.54917","-22.49806","-23.45361","-27.15889","-27.25444", "-29.91444","-32.94944","-32.84555","-33.06528","-33.45528","-33.44500", "-33.37833","-33.65611","-33.63583","-33.66639","-33.35000","-33.45806", "-33.61528","-33.70639","-34.96944","-36.58583","-36.78055","-36.90361", "-37.39694","-38.76778","-38.93444","-39.65667","-40.61444","-41.44750", "-42.93028","-42.34667","-43.18889","-43.61167","-43.89778","-45.39944", "-45.59083","-45.91833","-46.58500","-47.24389","-51.66722","-53.00167", "-53.25361","-54.93167","-62.19194","-62.47861","-63.32083"), "Longitud" = c("-70.33889","-70.16944","-68.89805","-70.44056","-109.42361","-70.77944", "-71.20333","-71.47444","-70.11861","-71.55917","-70.54222","-70.67778", "-70.79639","-71.61000","-78.83028","-78.93194","-70.28805","-70.94889", "-70.35583","-71.00000","-71.22028","-72.03389","-73.05083","-71.40667", "-72.42361","-72.62694","-72.66083","-73.08472","-73.05083","-73.08472", "-72.71167","-73.71167","-71.86417","-71.81333","-73.74555","-72.67778", "-72.10167","-71.67778","-71.69472","-72.57611","-72.52528","-70.84722", "-70.32194","-67.61000","-58.98278","-59.66083","-57.89805"), "Region" = c("XV","I","II","II","V","III","VI","V","V","V","RM","RM","RM","V","V","V", "RM","RM","RM","RM","VII","XVI","VII","XVI","VIII","IX","IX","XIV","X","X", "X","X","X","X","XI","XI","XI","XI","XI","XI","XII","XII","XII","XII","XII", "XII","XII") ) if(Estaciones[1] == "INFO"){ return(tablaEstaciones) } if(fin < inicio){ print() stop("Verificar fechas de inicio y fin") } url1 <- "https://climatologia.meteochile.gob.cl/application/datos/getDatosSaclim/" parametros_list <- c("Temperatura", "PuntoRocio", "Humedad", "Viento", "PresionQFE", "PresionQFF") #temporal <- c("TMinima", "TMaxima", "Agua6Horas", "Agua24Horas") #parametros_list <- c(parametros_list, temporal) intervalo <- inicio:fin lenInEstaciones <- length(Estaciones) lenInParametros <- length(Parametros) lenEstaciones <- nrow(tablaEstaciones) lenParametros <- length(parametros_list) lendate <- length(intervalo) start <- as.POSIXct(strptime(paste("01-01-", inicio, "00:00:00", sep =""), format = "%d-%m-%Y %H:%M:%S")) end <- as.POSIXct(strptime(paste("31-12-", fin, "23:00:00", sep =""), format = "%d-%m-%Y %H:%M:%S")) #horas<-(as.numeric(end)/3600-as.numeric(start)/3600) date = NULL date <- seq(start, end, by = "hour") date <- format(date, format = "%d-%m-%Y %H:%M:%S") df <- NULL df2 <- NULL data_total <- data.frame() if(Region == TRUE){ r <- 7 }else{ r <- 1 } for(i in 1:lenInEstaciones){ for(j in 1:lenEstaciones){ if(Estaciones[i] == tablaEstaciones[j, r]){ estacion_var <- tablaEstaciones[j, 1] Latitud <- tablaEstaciones[j, 5] Longitud <- tablaEstaciones[j, 6] Nombre <- rep(tablaEstaciones[j, 4], length(date)) Latitud <- rep(tablaEstaciones[j, 5], length(date)) Longitud <- rep(tablaEstaciones[j, 6], length(date)) data <- data.frame(date, Nombre, Latitud, Longitud) data.table::setDT(data) for(k in 1:lenInParametros){ for(l in 1:lenParametros){ if(Parametros[k] == parametros_list[l]){ for(m in 1:lendate){ url3 <- paste(url1, estacion_var,"_",intervalo[m], "_", parametros_list[l], "_", sep = "") print(url3) filename <- paste(estacion_var,"_",intervalo[m],"_", parametros_list[l], ".zip", sep = "") csvname <- paste(estacion_var,"_",intervalo[m],"_", parametros_list[l], "_.csv", sep = "") CSV <- NULL try({ download.file(url3, destfile = filename, method = "curl") suppressWarnings({ unzip(zipfile = filename) try({ #CSV <- read.csv(csvname, sep = ";", dec = ".", encoding = "UTF-8") CSV <- data.table::fread(csvname, sep = ";", dec = ".", encoding = "UTF-8") if(parametros_list[l] == "Viento"){ names(CSV) <- unlist(strsplit(names(CSV), ","))[1:5] }else{ names(CSV) <- unlist(strsplit(names(CSV), ","))[-1] } CSV<-as.data.frame(CSV) }, silent = T) }) }, silent = TRUE) print(head(CSV)) if(is.null(CSV)| length(CSV) == 0){ momento1 <- as.POSIXct(strptime(paste("01-01-", intervalo[m], "00:00:00", sep =""), format = "%d-%m-%Y %H:%M:%S")) momento2 <- as.POSIXct(strptime(paste("31-12-", intervalo[m], "23:00:00", sep =""), format = "%d-%m-%Y %H:%M:%S")) momento <- seq(momento1, momento2, by = "hour") CodigoNacional <-rep("", length(momento)) momento <- format(momento, format = "%d-%m-%Y %H:%M:%S") if(parametros_list[l] == "Temperatura"){ Ts_Valor<- rep("", length(momento)) CSV <- data.frame(CodigoNacional, momento, Ts_Valor) }else if(parametros_list[l] == "PuntoRocio"){ Td_Valor<- rep("", length(momento)) CSV <- data.frame(CodigoNacional, momento, Td_Valor) }else if(parametros_list[l] == "Humedad"){ HR_Valor<- rep("", length(momento)) CSV <- data.frame(CodigoNacional, momento, HR_Valor) }else if(parametros_list[l] == "Viento"){ dd_Valor<- rep("", length(momento)) ff_Valor<- rep("", length(momento)) VRB_Valor<- rep("", length(momento)) CSV <- data.frame(CodigoNacional, momento, dd_Valor,ff_Valor, VRB_Valor) }else if(parametros_list[l] == "PresionQFE"){ QFE_Valor<- rep("", length(momento)) CSV <- data.frame(CodigoNacional, momento, QFE_Valor) }else if(parametros_list[l] == "PresionQFF"){ QFF_Valor<- rep("", length(momento)) CSV <- data.frame(CodigoNacional, momento, QFF_Valor) } } df<- rbind(df, CSV) suppressWarnings({ file.remove(filename) file.remove(csvname) }) } if(parametros_list[l] == "Viento"){ df2 <- data.frame(df[2], df[3], df[4], df[5]) }else{ df2 <- data.frame(df[2], df[3]) } data.table::setDT(df2) data <- data[df2, on = c("date" = "momento")] df <- NULL df2 <- NULL } } } if(is.null(data_total)){ data_total<-data }else{ data_total<-rbind(data_total, data) } } } } data_total$date <- format(as.POSIXct(strptime(data_total$date, format = "%d-%m-%Y %H:%M:%S")), format = "%d/%m/%Y %H:%M") data_total <- data_total[!(is.na(data_total$date)),] data_total <- data_total[!(is.na(data_total$Nombre)),] data_total <- as.data.frame(data_total) for(i in 3:ncol(data_total)){ data_total[[i]] <- as.numeric(data_total[[i]]) #transformar columnas en variables numericas } return(data_total) } ChileAirQuality <- function(Comunas = "INFO", Parametros, fechadeInicio, fechadeTermino, Site = FALSE, Curar = TRUE){ estationMatrix <- data.frame( "Ciudad" = c("SA","CE1","CE","CN","EB","IN","LF","LC","PU","PA","QU","QU1","AH","AR","TE","TEII", "TEIII","PLCI","PLCII","LU","LR","MAI","MAII","MAIII","VA","VAII","OS","OSII","PMI", "PMII","PMIII","PMIV","PV","COI","COII","PAR"), "cod" = c("RM/D14","RM/D16","RM/D31","RM/D18","RM/D17","RM/D11","RM/D12","RM/D13","RM/D15", "RM/D27","RM/D30","RM/D19","RI/117","RXV/F01","RIX/901","RIX/905","RIX/904","RIX/903", "RIX/902","RXIV/E04","RXIV/E06","RXIV/E01","RXIV/E05","RXIV/E02","RXIV/E03","RXIV/E08", "RX/A01","RX/A04","RX/A08","RX/A07","RX/A02","RX/A03","RX/A09","RXI/B03","RXI/B04","RXII/C05"), "Longitud" = c("-33.450819","-33.479515","-33.482411","-33.419725","-33.533626","-33.40892","-33.503288", "-33.363453","-33.424439","-33.577948","-33.33632","-33.352539","-20.290467","-18.476839", "-38.748699","-38.727003","-38.725302","-38.772463","-38.764767","-40.286857","-40.321282", "-39.665626","-39.542346","-39.719218","-39.831316","-39.805429","-40.584479","-40.683736", "-41.39917","-41.479507","-41.510342","-41.18765","-41.328935","-45.57993636","-45.57904645", "-53.158295"), "Latitud" = c("-70.6604476","-70.719064","-70.703947","-70.73179","-70.665906","-70.650886","-70.587916", "-70.523024","-70.749876","-70.594184","-70.723583","-70.747952","-70.100192","-70.287911", "-72.620788","-72.580002","-72.571193","-72.595024","-72.598796","-73.07671","-72.471895", "-72.953729","-72.925205","-73.128677","-73.228513","-73.25873","-73.11872","-72.596399", "-72.899523","-72.968756","-73.065294","-73.08804","-72.968209","-72.0610848","-72.04996681", "-70.921497"), "Estacion" = c("P. O'Higgins","Cerrillos 1","Cerrillos","Cerro Navia","El Bosque","Independecia","La Florida", "Las Condes","Pudahuel","Puente Alto","Quilicura","Quilicura 1","Alto Hospicio","Arica", "Las Encinas Temuco","Nielol Temuco","Museo Ferroviario Temuco","Padre Las Casas I", "Padre Las Casas II","La Union","CESFAM Lago Ranco","Mafil","Fundo La Ribera", "Vivero Los Castanos","Valdivia I","Valdivia II","Osorno","Entre Lagos","Alerce","Mirasol", "Trapen Norte","Trapen Sur","Puerto Varas","Coyhaique I","Coyhaique II","Punta Arenas"), "Region" = c("RM","RM","RM","RM","RM","RM","RM","RM","RM","RM","RM","RM","I","XV","IX","IX","IX","IX", "IX","XIV","XIV","XIV","XIV","XIV","XIV","XIV","X","X","X","X","X","X","X","XI","XI","XII") ) if(Comunas[1] == "INFO"){ #"INFO" para solicitar informacion de estaciones de monitoreo return((estationMatrix)) #Retorna matriz de estaciones }else{ fi <- paste(fechadeInicio,"1:00") #incluir hora en fecha de inicio ft <- paste(fechadeTermino,"23:00") # incluir hora en fecha de termino Fecha_inicio <- as.POSIXct(strptime(fi, format = "%d/%m/%Y %H:%M")) #Asignar formato de fecha de termino Fecha_termino<- as.POSIXct(strptime(ft, format = "%d/%m/%Y %H:%M")) #Asignar formato de fecha de termino #Fechas para arana# Fecha_inicio_para_arana <- as.character(Fecha_inicio, format("%y%m%d")) #formato fecha inicio para el enrutador Fecha_termino_para_arana <- as.character(Fecha_termino, format("%y%m%d")) #formato fecha termino para el enrutador id_fecha <- gsub(" ","",paste("from=", Fecha_inicio_para_arana, "&to=", Fecha_termino_para_arana)) #codigo de intervalo de fechas para enrutador horas <- (as.numeric(Fecha_termino)/3600-as.numeric(Fecha_inicio)/3600) #horas entre fechas urlSinca <- "https://sinca.mma.gob.cl/cgi-bin/APUB-MMA/apub.tsindico2.cgi?outtype=xcl&macro=./" #parte inicial url de extraccion urlSinca2 <- "&path=/usr/airviro/data/CONAMA/&lang=esp&rsrc=&macropath=" #parte final de ur de extraccion #Data frame vacio# date = NULL date <- seq(Fecha_inicio, Fecha_termino, by = "hour") date <- format(date, format = "%d/%m/%Y %H:%M") data <- data.frame(date)#Parche que evita un ERROR data_total <- data.frame() #Data frame Vacio for (i in 1:length(Comunas)) { try({ inEstation <- Comunas[i] # Asignar Comunas a variable for(j in 1:nrow(estationMatrix)){ mSite <- estationMatrix[j, 1] #Asignar site a variable mCod <- estationMatrix[j, 2] #Asignar code a variable mLon <- estationMatrix[j, 3] #Asignar latitud a variable mLat <- estationMatrix[j, 4] #Asignar longitud a variable mEstation <- estationMatrix[j, 5] #Asignar estacion a variable if(Site){ # Si Site es verdadero aux <- mSite #aux, la variable de comparacion }else{ #Se comparara con Site aux <- mEstation #Si es falso se comparara con El nombre de la estacion } if(inEstation == aux){ try({ site <- rep(mSite, horas + 1) #Generar columna site longitude <- rep(mLat, horas + 1) #Generar columna longitud latitude <- rep(mLon, horas + 1) # Generar columna latitud data <- data.frame(date, site, longitude, latitude) #Unir columnas { for(p in 1:length(Parametros)) { inParametro <- Parametros[p] #Asignar contaminante a variable if(inParametro == "PM10" |inParametro == "pm10" | inParametro == "pM10" |inParametro == "Pm10") { codParametro <- "/Cal/PM10//PM10.horario.horario.ic&" #Codigo especifico para PM10 url <- gsub(" ", "",paste(urlSinca, mCod, codParametro, id_fecha, urlSinca2)) #Generar URL try( { PM10_Bruto <- read.csv(url,dec =",", sep= ";",na.strings= "") #Descargar csv PM10_col1 <- PM10_Bruto$Registros.validados PM10_col2 <- PM10_Bruto$Registros.preliminares PM10_col3 <- PM10_Bruto$Registros.no.validados PM10 <- gsub("NA","",gsub(" ", "",paste(PM10_col1,PM10_col2,PM10_col3))) #unir columnas del csv if(length(PM10) == 0){PM10 <- rep("", horas + 1)}# Generar columna vacia en caso de que no exista informacion data <- data.frame(data,PM10) #Incorporar al df de la comuna print(paste(inParametro,inEstation)) #Imprimir mnsje de exito } ,silent = T) } else if(inParametro == "PM25" |inParametro == "pm25" | inParametro == "pM25" |inParametro == "Pm25") { codParametro <- "/Cal/PM25//PM25.horario.horario.ic&" #Codigo especifico PM25 url <- gsub(" ", "",paste(urlSinca, mCod, codParametro, id_fecha, urlSinca2)) #Generar URL try( { PM25_Bruto <- read.csv(url,dec =",", sep= ";",na.strings= "") PM25_col1 <- PM25_Bruto$Registros.validados PM25_col2 <- PM25_Bruto$Registros.preliminares PM25_col3 <- PM25_Bruto$Registros.no.validados PM25 <- gsub("NA","",gsub(" ", "",paste(PM25_col1,PM25_col2,PM25_col3))) if(length(PM25) == 0){PM25 <- rep("",horas + 1)} data <- data.frame(data,PM25) #Crear columna print(paste(inParametro, inEstation)) #Mensaje de exito } , silent = TRUE) } else if(inParametro == "O3") { codParametro <- "/Cal/0008//0008.horario.horario.ic&" #Codigo url Ozono url <- gsub(" ", "",paste(urlSinca, mCod, codParametro, id_fecha, urlSinca2)) #Generarurl try( { O3_Bruto <- read.csv(url,dec =",", sep= ";",na.strings= "") O3_col1 <- O3_Bruto$Registros.validados O3_col2 <- O3_Bruto$Registros.preliminares O3_col3 <- O3_Bruto$Registros.no.validados O3 <- gsub("NA","",gsub(" ", "",paste(O3_col1, O3_col2, O3_col3))) if(length(O3) == 0){O3 <- rep("",horas + 1)} data <- data.frame(data, O3) print(paste(inParametro,inEstation)) } , silent = TRUE) } else if(inParametro == "CO"| inParametro == "co"| inParametro == "Co"| inParametro == "cO") { codParametro <- "/Cal/0004//0004.horario.horario.ic&" #Codigo CO url <- gsub(" ", "",paste(urlSinca, mCod, codParametro, id_fecha, urlSinca2)) #Generar url try( { CO_Bruto <- read.csv(url, dec =",", sep= ";",na.strings = "") CO_col1 <- CO_Bruto$Registros.validados CO_col2 <- CO_Bruto$Registros.preliminares CO_col3 <- CO_Bruto$Registros.no.validados CO <- gsub("NA","",gsub(" ", "",paste(CO_col1,CO_col2,CO_col3))) if(length(O3) == 0){O3 <- rep("",horas + 1)} data <- data.frame(data,CO) print(paste(inParametro, inEstation)) #mensaje de exito } , silent = TRUE) } else if(inParametro == "NO"| inParametro == "no"| inParametro == "No"| inParametro == "nO") { codParametro <- "/Cal/0002//0002.horario.horario.ic&" #codigo monoxido de carbono url <- gsub(" ", "",paste(urlSinca, mCod, codParametro, id_fecha, urlSinca2)) #generar url try( { NO_Bruto <- read.csv(url, dec = ",", sep = ";",na.strings = "") NO_col1 <- NO_Bruto$Registros.validados NO_col2 <- NO_Bruto$Registros.preliminares NO_col3 <- NO_Bruto$Registros.no.validados NO <- gsub("NA", "", gsub(" ", "", paste(NO_col1, NO_col2, NO_col3))) if(length(NO) == 0){NO <- rep("", horas + 1)} data <- data.frame(data, NO) print(paste(inParametro, inEstation)) #mensaje de exito } ,silent = T) }else if(inParametro == "NO2"| inParametro == "no2"| inParametro == "No2"| inParametro == "nO2") { codParametro <- "/Cal/0003//0003.horario.horario.ic&" #codigo dioxido de nitrogeno url <- gsub(" ", "",paste(urlSinca, mCod, codParametro, id_fecha, urlSinca2)) try( { NO2_Bruto <- read.csv(url, dec =",", sep= ";", na.strings= "") NO2_col1 <- NO2_Bruto$Registros.validados NO2_col2 <- NO2_Bruto$Registros.preliminares NO2_col3 <- NO2_Bruto$Registros.no.validados NO2 <- gsub("NA","",gsub(" ", "",paste(NO2_col1,NO2_col2,NO2_col3))) if(length(NO2) == 0){NO2 <- rep("",horas + 1)} data <- data.frame(data, NO2) print(paste(inParametro,inEstation)) } , silent = TRUE) }else if(inParametro == "NOX"|inParametro == "NOx"| inParametro == "nOX"|inParametro == "NoX"| inParametro == "Nox"|inParametro == "nOx"| inParametro == "nox"|inParametro == "noX") { codParametro <- "/Cal/0NOX//0NOX.horario.horario.ic&" url <- gsub(" ", "",paste(urlSinca, mCod, codParametro, id_fecha, urlSinca2)) try( { NOX_Bruto <- read.csv(url,dec =",", sep= ";",na.strings= "") NOX_col1 <- NOX_Bruto$Registros.validados NOX_col2 <- NOX_Bruto$Registros.preliminares NOX_col3 <- NOX_Bruto$Registros.no.validados NOX <- gsub("NA", "", gsub(" ", "", paste(NOX_col1, NOX_col2, NOX_col3))) if(length(NOX) == 0){NOX <- rep("", horas + 1)} data <- data.frame(data, NOX) print(paste(inParametro, inEstation)) } , silent = TRUE) }else if(inParametro == "SO2"| inParametro == "so2"| inParametro == "sO2"| inParametro == "So2") { codParametro <- "/Cal/0001//0001.horario.horario.ic&" url <- gsub(" ", "",paste(urlSinca, mCod, codParametro, id_fecha, urlSinca2)) try( { SO2_Bruto <- read.csv(url, dec =",", sep= ";", na.strings= "") SO2_col1 <- SO2_Bruto$Registros.validados SO2_col2 <- SO2_Bruto$Registros.preliminares SO2_col3 <- SO2_Bruto$Registros.no.validados SO2 <- gsub("NA","",gsub(" ", "",paste(SO2_col1, SO2_col2, SO2_col3))) if(length(SO2) == 0){SO2 <- rep("",horas + 1)} data <- data.frame(data, SO2) print(paste(inParametro, inEstation)) } , silent = TRUE) }else if(inParametro == "tEMP" |inParametro == "TeMP"|inParametro == "TEmP" |inParametro == "TEMp" |inParametro == "TEmp"|inParametro == "TeMp"|inParametro == "TemP"|inParametro == "tEMp" |inParametro == "tEmP"|inParametro == "teMP"|inParametro == "temp"|inParametro == "TEMP" |inParametro == "temP"|inParametro == "teMp"|inParametro == "tEmp"|inParametro == "Temp") { codParametro <- "/Met/TEMP//horario_000.ic&" url <- gsub(" ", "", paste(urlSinca, mCod, codParametro, id_fecha, urlSinca2)) try( { temp_bruto <- read.csv(url,dec =",", sep= ";",na.strings= "") temp_col1 <- temp_bruto$X temp <- gsub("NA","",gsub(" ", "",temp_col1)) if(length(temp) == 0){temp <- rep("",horas + 1)} data <- data.frame(data, temp) print(paste(inParametro, inEstation)) } , silent = TRUE) } else if(inParametro == "HR"| inParametro == "hr"| inParametro == "hR"| inParametro == "Hr") { codParametro <- "/Met/RHUM//horario_000.ic&" url <- gsub(" ", "",paste(urlSinca, mCod, codParametro, id_fecha, urlSinca2)) try( { HR_bruto <- read.csv(url,dec =",", sep= ";",na.strings= "") HR_col1 <- HR_bruto$X HR <- gsub("NA","",gsub(" ", "",HR_col1)) if(length(HR) == 0){HR <- rep("",horas + 1)} data <- data.frame(data,HR) print(paste(inParametro,inEstation)) } , silent = TRUE) } else if(inParametro == "wd"| inParametro == "WD"| inParametro == "Wd"| inParametro == "wD") { codParametro <- "/Met/WDIR//horario_000_spec.ic&" url <- gsub(" ", "",paste(urlSinca, mCod, codParametro, id_fecha, urlSinca2)) try( { wd_bruto <- read.csv(url,dec =",", sep= ";",na.strings= "") wd_col1 <- wd_bruto$X wd <- gsub("NA","",gsub(" ", "",wd_col1)) if(length(wd) == 0 ){wd <- rep("",horas + 1)} data <- data.frame(data,wd) print(paste(inParametro,inEstation)) } , silent = TRUE) } else if(inParametro == "ws"| inParametro == "WS"| inParametro == "Ws"| inParametro == "wS") { codParametro <- "/Met/WSPD//horario_000.ic&" url <- gsub(" ", "",paste(urlSinca, mCod, codParametro, id_fecha, urlSinca2)) try( { ws_bruto <- read.csv(url,dec =",", sep= ";",na.strings= "") ws_col1 <- ws_bruto$X ws <- gsub("NA","",gsub(" ", "",ws_col1)) if(length(ws) == 0){ws <- rep("",horas + 1)} data <- data.frame(data,ws) print(paste(inParametro,inEstation)) } , silent = TRUE) } else { print(paste("Contaminante",inParametro,"no soportado en el Software")) #Generar mensaje de fracaso } } try( { data_total <- rbind(data_total, data) #Unir el df de cada comuna al df total } , silent = T) } } , silent = T) } } }, silent = T) } if(Curar){ len = nrow(data_total) #Variable que almacena el numero de filas del dataframe try({ for (i in 1:len) { try( { if((as.numeric(data_total$NO[i]) + as.numeric(data_total$NO2[i])) > as.numeric(data_total$NOX[i]) * 1.001){ data_total$NO[i] = "" #Si la suma de NO y NO2 es mayor a NOX data_total$NO2[i] = "" #Eliminar el dato de NO, NO2 y NOX data_total$NOX[i] = "" #Conciderando error del 0.1% } } , silent = T) } }, silent = T) try({ for (i in 1:len) { try( { if(as.numeric(data_total$PM25[i]) > as.numeric(data_total$PM10[i])*1.001){ data_total$PM10[i] = "" #Si PM25 es mayor a PM10 borrar PM10 data_total$PM25[i] = "" #Y PM25 conciderando error del 0.1% } } ,silent = T) } }, silent = T) try({ for (i in 1:len) { try({ if(as.numeric(data_total$wd[i]) > 360||as.numeric(data_total$wd[i]) < 0){ data_total$wd[i] = "" #Si la tireccion del viento es menor a 0 o mayor a 360 eliminar el dato } }, silent = T) } }, silent = T) try({ i =NULL for (i in 1:len) { try( { if(as.numeric(data_total$HR[i]) > 100||as.numeric(data_total$HR[i]) <0){ data_total$HR[i] = "" #Si la humedad relativa es mayor al 100% borrar el dato } }, silent = T) } }, silent = T) } for(i in 3:ncol(data_total)){ data_total[[i]] <- as.numeric(data_total[[i]]) #transformar columnas en variables numericas } print("Datos Capturados!") return(data_total) #retornar df total } }
/scratch/gouwar.j/cran-all/cranData/AtmChile/inst/shiny/complementaryFunctions.R
#' @title Creates a Neighbourhood Using Locality Sensitive Hashing for Gaussian Projections #' #' @description This package uses Locality Sensitive Hashing and creates a Neighbourhood Graph for a datset and calculates the ARI value for the same. It uses Gaussian Random planes to decide the nature of a given point. #' #' @param #' mydata A data frame consisting of the data set without the class column #' #' @param #' result9 A column which consists of the class column #' #' @return NULL #' #' @examples LSH_Gaussian(iris[,-5],iris$Species) #' #' @export #' LSH_Gaussian LSH_Gaussian <- function(mydata,result9) { #Store the dataset without the class column mydata1 = mydata #Store only the class column of the dataset result8 = result9 result1 <- t(mydata1) mode(result1) <- "numeric" cols <- c(1:nrow(mydata1)) rows <- ncol(mydata1) set.seed(100) x43 <- NULL l9 <-list() list3 <- list() notables <- 10 list4 <- list() l4 <- list() hc1<- NULL i <- 1 l5 <- list() #------------------------------------------------------------------# #LSH Fit Module for(x5 in 1:notables) { d <- floor(runif(1,min = 10, max = 31)) norm.random.projection <- function(d, mydata1, scaling=TRUE) { d.original <- nrow(result1) # Projection matrix P <- rnorm(d*d.original,mean =0,sd = 1); P <- matrix(P, nrow=d,ncol = d.original); # random data projection if (scaling == TRUE) reduced.m <- sqrt(1/d) * (P%*%result1) else reduced.m <- P%*%result1; reduced.m } m2 <- norm.random.projection(d,result1) result2 <- sign(m2) result2 <- (result2+1)/2 M2 <- as.matrix(result2) M3 <- t(M2) hc1<- NULL i <- 1 l5 <- list() l4 <- (lapply(seq_len(nrow(M3)), function(i) M3[i,])) for(i in 1:nrow(mydata1)) { hc1 <- paste0(l4[[i]],collapse = "") l5[[hc1]] = c(l5[[hc1]],i) #generating buckets } list4 <- append(list4,(list(l5))) } #-----------------------------------------------------------# #LSH Query Module for(n in 1:nrow(mydata1)) { for(x5 in 1:notables) { hc2 <- paste0(l4[[n]],collapse = "") len3 <- length(names(list4[[x5]])) for(j in 1:len3) { if(hc2 == names(list4[[x5]][j])) { break() } } #matching bucket Id len4 <- NULL len4 <- length(list4[[x5]][[j]]) disteu <- NULL disteu1 <- NULL distham <- NULL x41 <- NULL x42 <- NULL k <- 1 k1 <- 1 k2 <- 1 k3 <- 1 #declaring variables if(len4 > notables) { for(k in 1:len4) { #disteu[k] <- dist2(mydata1[n,],mydata1[list4[[x5]][[j]][k],],method = "euclidean") disteu[k] <- lsa::cosine(result1[,n],result1[,list4[[x5]][[j]][k]]) } x41 <- order(disteu,na.last = TRUE,decreasing = FALSE) x41 <- x41[2:(notables+1)] for(k1 in 1:notables) { x42[k1] <- list4[[x5]][[j]][x41[k1]] } disteu1 <- sort(disteu,decreasing = FALSE) disteu1 <- disteu1[2:(notables+1)] } else { for(k2 in 1:len3) { distham[k2] <- stringdist::stringdist(names(list4[[x5]][j]), names(list4[[x5]][k2]), method = c("hamming")) } disthamor <- order(distham,decreasing = FALSE) disthamor <- disthamor[2:len3] for(k3 in 1:(len3-1)) { d1 <- disthamor[k3] len5 <- length(list4[[x5]][[d1]]) if(len5 > (notables-1)) { for(k in 1:len5) { #disteu[k] <- dist2(mydata1[n,],mydata1[list4[[x5]][[d1]][k],],method = "euclidean") disteu[k] <- lsa::cosine(result1[,n],result1[,list4[[x5]][[d1]][k]]) } x41 <- order(disteu,na.last = TRUE,decreasing = FALSE) for(k1 in 1:notables) { x42[k1] <- list4[[x5]][[d1]][x41[k1]] } disteu1 <- sort(disteu,decreasing = FALSE) disteu1 <- disteu1[1:notables] break() } } } x43[[x5]] <- x42 x54 <- unique(unlist(x43)) #calculating unique neighbours len6 <- length(x54) if(len6 >= notables) break() } disteu23 <- NULL for(k in 1:len6) { #disteu23[k] <- dist2(mydata1[n,],mydata1[x54[k],],method = "euclidean") disteu23[k] <- lsa::cosine(result1[,n],result1[,x54[k]]) } x45 <- NULL x45 <- order(disteu23,na.last = TRUE,decreasing = FALSE) x55 <- NULL for(k in 1:notables) { x55[k] <- x54[x45[k]] } disteu24 <- NULL disteu24 <- disteu23[1:notables] l9 <- append(l9,list(c(x55))) } m4 <- NULL m4 <- do.call(rbind, l9) #generating the neighbourhood matrix print("Neighbourhood Matrix") print(m4) #--------------------------------------------------------# #Creating the clusters and drawing neighbourhood graph m7 <- melt(m4) m7 <- m7[,-2] m8 <- as.matrix(m7) g1 <- graph_from_edgelist(m8,directed = FALSE) plot(g1,vertex.size = 5) clstur <- cluster_louvain(g1) pred <- rep(0,nrow(mydata1)) for(y2 in 1:length(clstur)) { pred[clstur[[y2]]] = y2 } randIndex(pred, result8,correct = T,original = F) }
/scratch/gouwar.j/cran-all/cranData/AurieLSHGaussian/R/AurieLSHGaussian.R
#' Retrieve a csv dataset from the australian_politicians repository. #' #' @description #' `get_auspol()` downloads a requested Australian politicians .csv dataset using an associated argument. #' #' @param df A character string used to request an Australian politicians dataset. *See Request Codes* below. #' #' @details #' #' There are four request codes: `all`, `allbyparty`, `mps` and `senators`. #' #' The specifics of these are: #' #' - `all` requests the australian_politicians-all.csv dataset. #' - `allbyparty` requests the australian_politicians-all-by_party.csv dataset. #' - `mps` requests the australian_politicians-mps-by_division.csv dataset. #' - `senators` requests the australian_politicians-senators-by_state.csv dataset. #' #' An incorrect request (an argument not associated with a dataset or non-character #' string argument) will stop function processes and return an error message. #' #' @return The requested dataset using \code{df} to a user assigned name. #' #' @examples #' \dontrun{ #' # Request the Senators by State dataset. #' senators_df <- get_auspol("senators") #' #' # Preview first 10 observations of the dataset. #' head(senators_df, 10) #' } #' @seealso `show_datacodes()` function help. #' #' @export # Function to access Australian politicians datasets. # Takes one argument as a character string to download and assign dataset to given variable name. # assign function name `getdata` # takes one argument `df` as a character string get_auspol <- function(df){ # set request codes for datasets in vector datacodes <- c("all", "allbyparty", "mps", "senators") # check if provided argument is a character string if(!purrr::is_character(df)){ # if not a character string produce error message stop("Provided request code must be a character string.") } # else if provided character string is in vector else if(df %in% datacodes){ # assign to temporary file tmpdir <- tempfile(fileext = ".csv") # if `df` is equal to "all" if(df == "all"){ # assign GitHub download URL for `all` dataset dwnld <- "https://raw.github.com/RohanAlexander/australian_politicians/master/data/australian_politicians-all.csv" # download from the assigned URL to the temporary directory, showing download progress utils::download.file(dwnld, tmpdir, quiet = F) # read in CSV using `read_csv` from `readr`, do not show column types readr::read_csv(tmpdir, show_col_types = F) } else if(df == "allbyparty"){ dwnld <- "https://raw.github.com/RohanAlexander/australian_politicians/master/data/australian_politicians-all-by_party.csv" utils::download.file(dwnld, tmpdir, quiet = F) readr::read_csv(tmpdir, show_col_types = F) } else if(df == "mps"){ dwnld <- "https://raw.github.com/RohanAlexander/australian_politicians/master/data/australian_politicians-mps-by_division.csv" utils::download.file(dwnld, tmpdir, quiet = F) readr::read_csv(tmpdir, show_col_types = F) } else if(df == "senators"){ dwnld <- "https://raw.github.com/RohanAlexander/australian_politicians/master/data/australian_politicians-senators-by_state.csv" utils::download.file(dwnld, tmpdir, quiet = F) readr::read_csv(tmpdir, show_col_types = F) } } else{ # else if character string is not in vector stop function and return error stop("Provided request code is not associated with a dataset.") } }
/scratch/gouwar.j/cran-all/cranData/AustralianPoliticians/R/get_auspol.R
#' Generate datasets for House of Representative and Senate members service dates. #' #' @description `get_reps_senate()` generates a dataset for members' service time for #' the Australian House of Representatives, the Australian Senate, or a joined dataset #' containing values for both the HoR and Senate. Additionally, will produce a set of #' arguments that can be used as request codes for the individual datasets. #' #' @param x A character string used to request a printout of the request code arguments, #' *see Request Codes* below, or one of three prepared datasets. #' #' @details #' There are four request codes: `reps_senate`, `reps`, `senate` and `codes`. #' #' The specifics of these are: #' #' - `reps_senate` - generates a dataset of HoRs and Senate members; #' - `reps` - generates a dataset of HoRs members; #' - `senate` - generates a dataset of Senate members; and #' - `codes` - returns a tibble of codes used to request data. #' #' An incorrect request code (an argument not associated with a dataset or non-character string argument) #' will stop function processes and return an error message. #' #' @return A console printout of a tibble containing arguments to be used with the function, #' or the requested dataset using \code{x} assigned to a user created variable. #' #' @examples #' \dontrun{ #' # Generate a printout of the arguments. #' get_reps_senate("codes") #' #' # Generate combined HoR and Senate dataset. #' reps_senate <- get_reps_senate("reps_senate") #' #' # Preview dataset. #' head(reps_senate) #' #' # Generate only HoR dataset. #' reps <- get_reps_senate("reps") #' #' # Preview dataset. #' head(reps) #' } #' #' @export # Function to produce manipulated datasets for HoRs and Senate members. # Takes one parameter as a character string to produce datasets. # assign function name get_reps_senate <- function(x){ # assign vector to store download URLS dwnlds <- c("https://raw.github.com/RohanAlexander/australian_politicians/master/data/australian_politicians-all.csv", "https://raw.github.com/RohanAlexander/australian_politicians/master/data/australian_politicians-mps-by_division.csv", "https://raw.github.com/RohanAlexander/australian_politicians/master/data/australian_politicians-senators-by_state.csv" ) # assign tibble object using tibble function from tibble package codetibble <- tibble::tibble( # store the data request codes as values request_code = c("reps_senate", "reps", "senate", "codes"), # store the corresponding dataset as values dataset = c("Generates a dataset of HoRs and Senate members", "Generates a dataset of HoRs members", "Generates a dataset of Senate members", "Returns a tibble of codes used to request data") ) if(!purrr::is_character(x)){ # if not a character string produce error message stop("Provided request code must be a character string.") } else if(!(x %in% codetibble$request_code)){ stop('Provided code does not match any request code. Use get_reps_senate("codes") for valid request codes.') } else if(x == "codes"){ # print out data request codes stored in tibble utils::head(codetibble, 3) } else if(x == "reps_senate"){ # assign 3 temporary files with file type .csv tmpfls <- sapply(paste0("tmpfl", 1:3), tempfile, fileext = ".csv") # download required csv files utils::download.file(dwnlds, tmpfls, quiet = F, method = "libcurl") # read csv files into list dflist <- lapply(tmpfls, readr::read_csv, show_col_types = F) # assign first item in the list to new variable australian_mps <- dflist[[1]] # filter for where member is 1 australian_mps <- dplyr::filter(australian_mps, member == 1) # join with second item in list by uniqueID australian_mps <- dplyr::left_join(australian_mps, dflist[[2]], by = "uniqueID") # select uniqueID, mpFrom, and mpTo australian_mps <- dplyr::select(australian_mps, uniqueID, mpFrom, mpTo) # mutate house column to hold "reps" australian_mps <- dplyr::mutate(australian_mps, house = "reps") # rename mpFrom to from and mpTo to to australian_mps <- dplyr::rename(australian_mps, from = mpFrom, to = mpTo) # assign new variable from first item in list australian_senators <- dflist[[1]] # filter for where senator is 1 australian_senators <- dplyr::filter(australian_senators, senator == 1) # join with third item in list by uniqueID australian_senators <- dplyr::left_join(australian_senators, dflist[[3]], by = "uniqueID") # select uniqueID, senatorFrom, and senatorTo australian_senators <- dplyr::select(australian_senators, uniqueID, senatorFrom, senatorTo) # mutate house column to hold "senate" australian_senators <- dplyr::mutate(australian_senators, house = "senate") # rename seantorFrom to from and senatorTo to to australian_senators <- dplyr::rename(australian_senators, from = senatorFrom, to = senatorTo) # assign new variable through row binding two created variables australian_politicians <- rbind(australian_mps, australian_senators) # mutate house values so where house is senate it is Senate # and where house is reps it is HoR dplyr::mutate(australian_politicians, house = dplyr::case_when( house == "senate" ~ "Senate", house == "reps" ~ "HoR", TRUE ~ "OH NO") ) } else if(x == "reps"){ # assign 3 temporary files with file type .csv tmpfls <- sapply(paste0("tmpfl", 1:2), tempfile, fileext = ".csv") # download required csv files utils::download.file(dwnlds[c(1,2)], tmpfls, quiet = F, method = "libcurl") # read csv files into list dflist <- lapply(tmpfls, readr::read_csv, show_col_types = F) # assign first item in the list to new variable australian_mps <- dflist[[1]] # filter for where member is 1 australian_mps <- dplyr::filter(australian_mps, member == 1) # join with second item in list by uniqueID australian_mps <- dplyr::left_join(australian_mps, dflist[[2]], by = "uniqueID") # select uniqueID, mpFrom, and mpTo australian_mps <- dplyr::select(australian_mps, uniqueID, mpFrom, mpTo) # mutate house column to hold "reps" australian_mps <- dplyr::mutate(australian_mps, house = "HoR") # rename mpFrom to from and mpTo to to australian_mps <- dplyr::rename(australian_mps, from = mpFrom, to = mpTo) } else if(x == "senate"){ # assign 3 temporary files with file type .csv tmpfls <- sapply(paste0("tmpfl", 1:2), tempfile, fileext = ".csv") # download required csv files utils::download.file(dwnlds[c(1,3)], tmpfls, quiet = F, method = "libcurl") # read csv files into list dflist <- lapply(tmpfls, readr::read_csv, show_col_types = F) # assign new variable from first item in list australian_senators <- dflist[[1]] # filter for where senator is 1 australian_senators <- dplyr::filter(australian_senators, senator == 1) # join with third item in list by uniqueID australian_senators <-dplyr::left_join(australian_senators, dflist[[2]], by = "uniqueID") # select uniqueID, senatorFrom, and senatorTo australian_senators <- dplyr::select(australian_senators, uniqueID, senatorFrom, senatorTo) # mutate house column to hold "senate" australian_senators <- dplyr::mutate(australian_senators, house = "Senate") # rename seantorFrom to from and senatorTo to to australian_senators <- dplyr::rename(australian_senators, from = senatorFrom, to = senatorTo) } }
/scratch/gouwar.j/cran-all/cranData/AustralianPoliticians/R/get_repsandsenate.R
utils::globalVariables(c("member", "uniqueID", "mpFrom", "mpTo", "senator", "senatorFrom", "senatorTo"))
/scratch/gouwar.j/cran-all/cranData/AustralianPoliticians/R/globals.R
#' Produce and send to console a tibble of the data request codes and associated datasets. #' #' @description #' `show_datacodes()` produces a tibble of the arguments used with the `get_ausdata()` function #' and the associated datasets. #' #' @param limit A numeric value used to determine the number of values returned. #' Default is set to four (4) values, which returns all tibble values. #' #' @details #' Items under *Request Codes* can be used to request and download the associated #' Australian Politicians dataset. #' #' The specifics of these are: #' #' - `"all"` australian_politicians-all.csv. #' - `"allbyparty"` australian_politicians-all-by_party.csv. #' - `"mps"` australian_politicians-mps-by_division.csv. #' - `"senators"` australian_politicians-senators-by_state.csv. #' #' @return A console printout of a tibble with a designated number of values set by \code{limit}. #' #' @examples #' \dontrun{ #' # Print out dataset request codes. #' show_datacodes() #' #' # Request "All" Australian Politicians dataset. #' get_auspol("all") #' } #' #' @seealso `get_auspol()` function help. #' #' @export # Function to produce the codes used to access Australian politicians datasets. # Creates two vectors then assigns these to a tibble, which is then printed to the console using the head function. # assign function name `show_datacodes` taking one numeric argument show_datacodes <- function(limit = 4){ # assign tibble object using tibble function from tibble package codetibble <- tibble::tibble( # store the data request codes as values request_code = c("all", "allbyparty", "mps", "senators"), # store the corresponding dataset as values dataset = c("australian_politicians-all.csv", "australian_politicians-all-by_party.csv", "australian_politicians-mps-by_division.csv", "australian_politicians-senators-by_state.csv") ) # print out tibble using head function and numeric limit utils::head(codetibble, limit) }
/scratch/gouwar.j/cran-all/cranData/AustralianPoliticians/R/show_datacodes.R
## ---- include = FALSE--------------------------------------------------------- knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ## ----setup-------------------------------------------------------------------- library(AustralianPoliticians) ## ----eval = F----------------------------------------------------------------- # show_datacodes() # # A tibble: 4 x 2 # request_code dataset # <chr> <chr> # 1 all australian_politicians-all.csv # 2 allbyparty australian_politicians-all-by_party.csv # 3 mps australian_politicians-mps-by_division.csv # 4 senators australian_politicians-senators-by_state.csv ## ---- eval = F---------------------------------------------------------------- # get_auspol("all") # # A tibble: 1,781 x 20 # uniqueID surname allOtherNames firstName commonName # <chr> <chr> <chr> <chr> <chr> # 1 Abbott18~ Abbott Richard Hart~ Richard NA # 2 Abbott18~ Abbott Percy Phipps Percy NA # 3 Abbott18~ Abbott Macartney Macartney Mac # 4 Abbott18~ Abbott Charles Lydi~ Charles Aubrey # 5 Abbott18~ Abbott Joseph Palmer Joseph NA # 6 Abbott19~ Abbott Anthony John Anthony Tony # 7 Abel1939 Abel John Arthur John NA # 8 Abetz1958 Abetz Eric Eric NA # 9 Adams1943 Adams Judith Anne Judith NA # 10 Adams1951 Adams Dick Godfrey~ Dick NA # # ... with 1,771 more rows, and 15 more variables: # # displayName <chr>, earlierOrLaterNames <chr>, # # title <chr>, gender <chr>, birthDate <date>, # # birthYear <dbl>, birthPlace <chr>, # # deathDate <date>, member <dbl>, senator <dbl>, # # wasPrimeMinister <dbl>, wikidataID <chr>, # # wikipedia <chr>, adb <chr>, comments <chr> # # all_auspol <- get_auspol("all") ## ----eval = F----------------------------------------------------------------- # # Return codes used to call datasets # get_reps_senate("codes") # # A tibble: 3 x 2 # request_code dataset # <chr> <chr> # 1 reps_senate Generates a dataset of HoRs and Senate ~ # 2 reps Generates a dataset of HoRs members # 3 senate Generates a dataset of Senate members # # # Request HoR and Senate dataset # reps_senate <- get_reps_senate("reps_senate") # # # Preview dataset # head(reps_senate) # # A tibble: 6 x 4 # uniqueID from to house # <chr> <date> <date> <chr> # 1 Abbott1869 1913-05-31 1919-11-03 HoR # 2 Abbott1886 1925-11-14 1929-10-12 HoR # 3 Abbott1886 1931-12-19 1937-03-28 HoR # 4 Abbott1891 1940-09-21 1949-10-31 HoR # 5 Abbott1957 1994-03-26 2019-05-18 HoR # 6 Abel1939 1975-12-13 1977-11-10 HoR # # # # Request HoR dataset # reps <- get_reps_senate("reps") # # # Preview dataset # head(reps) # # A tibble: 6 x 4 # uniqueID from to house # <chr> <date> <date> <chr> # 1 Abbott1869 1913-05-31 1919-11-03 HoR # 2 Abbott1886 1925-11-14 1929-10-12 HoR # 3 Abbott1886 1931-12-19 1937-03-28 HoR # 4 Abbott1891 1940-09-21 1949-10-31 HoR # 5 Abbott1957 1994-03-26 2019-05-18 HoR # 6 Abel1939 1975-12-13 1977-11-10 HoR # # # # Request Senate dataset # senate <- get_reps_senate("senate") # # #Preview dataset # head(senate) # # A tibble: 6 x 4 # uniqueID from to house # <chr> <date> <date> <chr> # 1 Abbott1859 1928-12-18 1929-06-30 Senate # 2 Abbott1869 1925-11-14 1929-06-30 Senate # 3 Abbott1877 1935-07-01 1941-06-30 Senate # 4 Abetz1958 1994-02-22 NA Senate # 5 Adams1943 2005-07-01 2012-03-31 Senate # 6 Adamson1857 1920-07-01 1922-05-02 Senate
/scratch/gouwar.j/cran-all/cranData/AustralianPoliticians/inst/doc/australianpoliticians.R
--- title: "Introduction to AustralianPoliticians" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{australianpoliticians} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` ## Default usage Load the package with: ```{r setup} library(AustralianPoliticians) ``` The purpose of `AustralianPoliticians` is to make it easier to access biographical and political data about Australian federal politicians. This is done through the use of functions that get and manipulate publicly accessible datasets that were constructed for this purpose. These datasets have every politician in the House of Representatives and the Senate between 1901 and 2021. To get started with the package: ## Show data request codes Request codes are used to access the specific datasets in `AustralianPoliticians`. These codes used in conjunction with the `get_auspol()` function allow for a dataset to be downloaded and assigned a variable name. The `show_datacodes()` function prints these codes to the console as a tibble. ```{r eval = F} show_datacodes() # A tibble: 4 x 2 request_code dataset <chr> <chr> 1 all australian_politicians-all.csv 2 allbyparty australian_politicians-all-by_party.csv 3 mps australian_politicians-mps-by_division.csv 4 senators australian_politicians-senators-by_state.csv ``` ## Download Australian Politician data Each of the shown codes is associated with a .csv dataset. The `get_auspol()` function is used to download these datasets, allowing them to be assigned to a variable. To function correctly, the argument passed to `get_auspol()` must be a character string. If `get_auspol()` is called without being assigned to a variable it will print out a preview to the requested dataset to the console, as seen below. ```{r, eval = F} get_auspol("all") # A tibble: 1,781 x 20 uniqueID surname allOtherNames firstName commonName <chr> <chr> <chr> <chr> <chr> 1 Abbott18~ Abbott Richard Hart~ Richard NA 2 Abbott18~ Abbott Percy Phipps Percy NA 3 Abbott18~ Abbott Macartney Macartney Mac 4 Abbott18~ Abbott Charles Lydi~ Charles Aubrey 5 Abbott18~ Abbott Joseph Palmer Joseph NA 6 Abbott19~ Abbott Anthony John Anthony Tony 7 Abel1939 Abel John Arthur John NA 8 Abetz1958 Abetz Eric Eric NA 9 Adams1943 Adams Judith Anne Judith NA 10 Adams1951 Adams Dick Godfrey~ Dick NA # ... with 1,771 more rows, and 15 more variables: # displayName <chr>, earlierOrLaterNames <chr>, # title <chr>, gender <chr>, birthDate <date>, # birthYear <dbl>, birthPlace <chr>, # deathDate <date>, member <dbl>, senator <dbl>, # wasPrimeMinister <dbl>, wikidataID <chr>, # wikipedia <chr>, adb <chr>, comments <chr> all_auspol <- get_auspol("all") ``` ## House of Representatives and Senate In some cases, it may be necessary to join datasets to gain more information than is contained in just one dataset. The `get_reps_senate()` function does this in downloading the `house of representatives` data or `senate` data and joins these with the `all` dataset to show the dates served by a politician in either political sector. It can do this for both datasets, joining `house of representatives` and `senate` to `all`, or for just one of `house of representative` or `senate` depending on what is required. This function also includes an argument that allows for the associated request codes to be printed to the console. ```{r eval = F} # Return codes used to call datasets get_reps_senate("codes") # A tibble: 3 x 2 request_code dataset <chr> <chr> 1 reps_senate Generates a dataset of HoRs and Senate ~ 2 reps Generates a dataset of HoRs members 3 senate Generates a dataset of Senate members # Request HoR and Senate dataset reps_senate <- get_reps_senate("reps_senate") # Preview dataset head(reps_senate) # A tibble: 6 x 4 uniqueID from to house <chr> <date> <date> <chr> 1 Abbott1869 1913-05-31 1919-11-03 HoR 2 Abbott1886 1925-11-14 1929-10-12 HoR 3 Abbott1886 1931-12-19 1937-03-28 HoR 4 Abbott1891 1940-09-21 1949-10-31 HoR 5 Abbott1957 1994-03-26 2019-05-18 HoR 6 Abel1939 1975-12-13 1977-11-10 HoR # Request HoR dataset reps <- get_reps_senate("reps") # Preview dataset head(reps) # A tibble: 6 x 4 uniqueID from to house <chr> <date> <date> <chr> 1 Abbott1869 1913-05-31 1919-11-03 HoR 2 Abbott1886 1925-11-14 1929-10-12 HoR 3 Abbott1886 1931-12-19 1937-03-28 HoR 4 Abbott1891 1940-09-21 1949-10-31 HoR 5 Abbott1957 1994-03-26 2019-05-18 HoR 6 Abel1939 1975-12-13 1977-11-10 HoR # Request Senate dataset senate <- get_reps_senate("senate") #Preview dataset head(senate) # A tibble: 6 x 4 uniqueID from to house <chr> <date> <date> <chr> 1 Abbott1859 1928-12-18 1929-06-30 Senate 2 Abbott1869 1925-11-14 1929-06-30 Senate 3 Abbott1877 1935-07-01 1941-06-30 Senate 4 Abetz1958 1994-02-22 NA Senate 5 Adams1943 2005-07-01 2012-03-31 Senate 6 Adamson1857 1920-07-01 1922-05-02 Senate ```
/scratch/gouwar.j/cran-all/cranData/AustralianPoliticians/inst/doc/australianpoliticians.Rmd
--- title: "Introduction to AustralianPoliticians" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{australianpoliticians} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` ## Default usage Load the package with: ```{r setup} library(AustralianPoliticians) ``` The purpose of `AustralianPoliticians` is to make it easier to access biographical and political data about Australian federal politicians. This is done through the use of functions that get and manipulate publicly accessible datasets that were constructed for this purpose. These datasets have every politician in the House of Representatives and the Senate between 1901 and 2021. To get started with the package: ## Show data request codes Request codes are used to access the specific datasets in `AustralianPoliticians`. These codes used in conjunction with the `get_auspol()` function allow for a dataset to be downloaded and assigned a variable name. The `show_datacodes()` function prints these codes to the console as a tibble. ```{r eval = F} show_datacodes() # A tibble: 4 x 2 request_code dataset <chr> <chr> 1 all australian_politicians-all.csv 2 allbyparty australian_politicians-all-by_party.csv 3 mps australian_politicians-mps-by_division.csv 4 senators australian_politicians-senators-by_state.csv ``` ## Download Australian Politician data Each of the shown codes is associated with a .csv dataset. The `get_auspol()` function is used to download these datasets, allowing them to be assigned to a variable. To function correctly, the argument passed to `get_auspol()` must be a character string. If `get_auspol()` is called without being assigned to a variable it will print out a preview to the requested dataset to the console, as seen below. ```{r, eval = F} get_auspol("all") # A tibble: 1,781 x 20 uniqueID surname allOtherNames firstName commonName <chr> <chr> <chr> <chr> <chr> 1 Abbott18~ Abbott Richard Hart~ Richard NA 2 Abbott18~ Abbott Percy Phipps Percy NA 3 Abbott18~ Abbott Macartney Macartney Mac 4 Abbott18~ Abbott Charles Lydi~ Charles Aubrey 5 Abbott18~ Abbott Joseph Palmer Joseph NA 6 Abbott19~ Abbott Anthony John Anthony Tony 7 Abel1939 Abel John Arthur John NA 8 Abetz1958 Abetz Eric Eric NA 9 Adams1943 Adams Judith Anne Judith NA 10 Adams1951 Adams Dick Godfrey~ Dick NA # ... with 1,771 more rows, and 15 more variables: # displayName <chr>, earlierOrLaterNames <chr>, # title <chr>, gender <chr>, birthDate <date>, # birthYear <dbl>, birthPlace <chr>, # deathDate <date>, member <dbl>, senator <dbl>, # wasPrimeMinister <dbl>, wikidataID <chr>, # wikipedia <chr>, adb <chr>, comments <chr> all_auspol <- get_auspol("all") ``` ## House of Representatives and Senate In some cases, it may be necessary to join datasets to gain more information than is contained in just one dataset. The `get_reps_senate()` function does this in downloading the `house of representatives` data or `senate` data and joins these with the `all` dataset to show the dates served by a politician in either political sector. It can do this for both datasets, joining `house of representatives` and `senate` to `all`, or for just one of `house of representative` or `senate` depending on what is required. This function also includes an argument that allows for the associated request codes to be printed to the console. ```{r eval = F} # Return codes used to call datasets get_reps_senate("codes") # A tibble: 3 x 2 request_code dataset <chr> <chr> 1 reps_senate Generates a dataset of HoRs and Senate ~ 2 reps Generates a dataset of HoRs members 3 senate Generates a dataset of Senate members # Request HoR and Senate dataset reps_senate <- get_reps_senate("reps_senate") # Preview dataset head(reps_senate) # A tibble: 6 x 4 uniqueID from to house <chr> <date> <date> <chr> 1 Abbott1869 1913-05-31 1919-11-03 HoR 2 Abbott1886 1925-11-14 1929-10-12 HoR 3 Abbott1886 1931-12-19 1937-03-28 HoR 4 Abbott1891 1940-09-21 1949-10-31 HoR 5 Abbott1957 1994-03-26 2019-05-18 HoR 6 Abel1939 1975-12-13 1977-11-10 HoR # Request HoR dataset reps <- get_reps_senate("reps") # Preview dataset head(reps) # A tibble: 6 x 4 uniqueID from to house <chr> <date> <date> <chr> 1 Abbott1869 1913-05-31 1919-11-03 HoR 2 Abbott1886 1925-11-14 1929-10-12 HoR 3 Abbott1886 1931-12-19 1937-03-28 HoR 4 Abbott1891 1940-09-21 1949-10-31 HoR 5 Abbott1957 1994-03-26 2019-05-18 HoR 6 Abel1939 1975-12-13 1977-11-10 HoR # Request Senate dataset senate <- get_reps_senate("senate") #Preview dataset head(senate) # A tibble: 6 x 4 uniqueID from to house <chr> <date> <date> <chr> 1 Abbott1859 1928-12-18 1929-06-30 Senate 2 Abbott1869 1925-11-14 1929-06-30 Senate 3 Abbott1877 1935-07-01 1941-06-30 Senate 4 Abetz1958 1994-02-22 NA Senate 5 Adams1943 2005-07-01 2012-03-31 Senate 6 Adamson1857 1920-07-01 1922-05-02 Senate ```
/scratch/gouwar.j/cran-all/cranData/AustralianPoliticians/vignettes/australianpoliticians.Rmd
### Creating functions for calculating statistics of automated advertisement view_percent <- function(data){ x <- data$Impressions y <- data$Viewable round( y/x*100, digits=2) } eCPM <- function(data){ x <- data$Impressions y <- data$Revenue round( y/x*1000, digits=2) } CPMv <- function(data){ x <- data$Viewable y <- data$Revenue round( y/x*1000, digits=2) } CTR <- function(data){ x <- data$Impressions y <- data$Clicks round( y/x, digits=2) } CPC <- function(data){ x <- data$Clicks y <- data$Revenue round( y/x, digits=2) } fill_rate <- function(data){ x <- data$Requests y <- data$Impressions round( y/x*100, digits=2) } ### Downloading a sample (Also possible as excel or other file) data <- data.frame( Date = c("2022-07-01", "2022-07-02", "2022-07-03", "2022-07-04", "2022-07-05", "2022-07-06", "2022-07-07", "2022-07-08", "2022-07-09", "2022-07-10", "2022-07-11", "2022-07-12", "2022-07-13", "2022-07-14", "2022-07-15", "2022-07-16", "2022-07-17", "2022-07-18", "2022-07-19", "2022-07-20", "2022-07-21", "2022-07-22", "2022-07-23", "2022-07-24", "2022-07-25", "2022-07-26", "2022-07-27", "2022-07-28", "2022-07-29", "2022-07-30", "2022-07-31", "2022-07-01", "2022-07-02", "2022-07-03", "2022-07-04", "2022-07-05", "2022-07-06", "2022-07-07", "2022-07-08", "2022-07-09", "2022-07-10", "2022-07-11", "2022-07-12", "2022-07-13", "2022-07-14", "2022-07-15", "2022-07-16", "2022-07-17", "2022-07-18", "2022-07-19", "2022-07-20", "2022-07-21", "2022-07-22", "2022-07-23", "2022-07-24", "2022-07-25", "2022-07-26", "2022-07-27", "2022-07-28", "2022-07-29", "2022-07-30", "2022-07-31"), Block = c("1_234", "1_234", "1_234", "1_234", "1_234", "1_234", "1_234", "1_234", "1_234", "1_234", "1_234", "1_234", "1_234", "1_234", "1_234", "1_234", "1_234", "1_234", "1_234", "1_234", "1_234", "1_234", "1_234", "1_234", "1_234", "1_234", "1_234", "1_234", "1_234", "1_234", "1_234", "1_235", "1_235", "1_235", "1_235", "1_235", "1_235", "1_235", "1_235", "1_235", "1_235", "1_235", "1_235", "1_235", "1_235", "1_235", "1_235", "1_235", "1_235", "1_235", "1_235", "1_235", "1_235", "1_235", "1_235", "1_235", "1_235", "1_235", "1_235", "1_235", "1_235", "1_235"), Requests = c(372234, 268816, 291224, 399109, 383962, 382214, 389865, 365455, 281391, 291740, 388472, 381215, 372994, 375715, 372318, 280157, 290029, 398011, 382938, 386224, 376212, 355127, 274288, 282119, 374851, 378399, 379820, 372036, 354963, 278810, 304971, 1108755, 1848347, 1790694, 1784609, 1682512, 1068344, 1093918, 1881346, 1868104, 1784772, 1757443, 1647247, 1033891, 1092752, 1862124, 1844850, 1765838, 1760493, 1650159, 1067656, 1166593, 1931007, 1822504, 1824652, 1818503, 1656483, 1086639, 1100089, 1928854, 1928290, 786539), Impressions = c(18537, 12432, 13764, 12987, 14541, 11544, 23088, 24753, 20091, 18759, 22422, 27861, 36741, 44733, 37185, 20091, 16317, 31191, 38184, 54279, 48507, 18648, 8325, 11433, 14652, 17982, 90909, 146631, 130647, 34521, 9990, 65268, 471195, 357309, 289155, 328671, 249750, 301476, 2901096, 3299364, 2271726, 1615383, 2631366, 951936, 736263, 2611608, 2984235, 1724829, 1955931, 1957818, 1286712, 1813074, 4187253, 5306910, 5449212, 2508822, 1784436, 761571, 825507, 2839269, 2682648, 1114773), Revenue = c(13.5, 9.13, 8.85, 8.42, 9.35, 7.29, 16.3, 16.7, 14.3, 12.4, 14.5, 17.6, 24.4, 26.0, 26.6, 16.4, 14.5, 20.8, 24.2, 31.7, 27.8, 16.1, 6.08, 7.98, 11.3, 12.3, 48.1, 73.6, 65.7, 19.1, 5.4, 53.1, 538.0, 397.0, 285.0, 294.0, 187.0, 231.0, 1868.0, 1971.0, 1374.0, 1231.0, 2418.0, 815.0, 849.0, 2567.0, 2195.0, 1192.0, 1306.0, 1247.0, 814.0, 1106.0, 3909.0, 5836.0, 4530.0, 1390.0, 1051.0, 467.0, 487.0, 1669.0, 1654.0, 739.0), Clicks = c(1167, 720, 856, 817, 1031, 749, 1566, 1527, 1128, 1128, 1518, 2004, 2588, 3171, 2452, 1274, 1167, 2072, 2773, 3668, 3541, 1128, 545, 759, 895, 1265, 6868, 11061, 9709, 2481, 710, 4816, 35294, 26860, 22288, 23328, 18542, 22550, 227428, 252819, 174866, 125359, 202524, 72262, 56191, 198243, 229296, 130349, 145457, 145934, 94403, 133005, 327065, 409989, 416926, 191151, 134727, 58088, 63137, 214451, 196657, 93178), Viewable = c(13320, 8214, 9768, 9324, 11766, 8547, 17871, 17427, 12876, 12876, 17316, 22866, 29526, 36186, 27972, 14541, 13320, 23643, 31635, 41847, 40404, 12876, 6216, 8658, 10212, 14430, 78366, 126207, 110778, 28305, 8103, 54945, 402708, 306471, 254301, 266178, 211566, 257298, 2594958, 2884668, 1995225, 1430346, 2310798, 824508, 641136, 2261958, 2616270, 1487289, 1659672, 1665111, 1077144, 1517592, 3731820, 4677984, 4757127, 2181039, 1537239, 662781, 720390, 2446884, 2243865, 1063158) ) ### Adding results of calculations to the sample data$ViewablePercent <- view_percent(data) data$eCPM <- eCPM(data) data$CPMv <- CPMv(data) data$CTR <- CTR(data) data$CPC <- CPC(data) data$FillRate <- fill_rate(data) ### Creating a function that will use all the metrics together adstats <- function(data){ data$ViewablePercent <- view_percent(data) data$eCPM <- eCPM(data) data$CPMv <- CPMv(data) data$CTR <- CTR(data) data$CPC <- CPC(data) data$FillRate <- fill_rate(data) data } data <- adstats(data) ### Plotting globalVariables(c("Date", "Forecast")) plot_trend_and_forecast <- function(data, x_col, y_col, group_col) { data$Date <- as.Date(data$Date) data_groups <- split(data, data[[group_col]]) for (group in names(data_groups)) { group_data <- data_groups[[group]] time_series <- ts(group_data[[y_col]], frequency = 1, start = min(group_data[[x_col]])) arima_model <- auto.arima(time_series) forecast <- forecast(arima_model, h = 6) forecast_dates <- seq(max(group_data[[x_col]]) + 1, to = max(group_data[[x_col]]) + length(forecast$mean), by = "day") forecast_data <- data.frame(Date = forecast_dates, Forecast = forecast$mean) print(ggplot() + geom_line(data = group_data, aes(x = !!rlang::sym(x_col), y = !!rlang::sym(y_col))) + geom_line(data = forecast_data, aes(x = Date, y = Forecast), color = "blue") + geom_ribbon(data = forecast_data, aes(x = Date, ymin = forecast$lower[, 2], ymax = forecast$upper[, 2]), fill = "blue", alpha = 0.2) + labs(x = x_col, y = y_col, title = group) + theme_minimal()) } } plot_trend_and_forecast(data, "Date", "eCPM", "Block") #Any value instead of Impressions can be here
/scratch/gouwar.j/cran-all/cranData/AutoAds/R/AutoAds.R
#' Get a 2-Legged Token for Authentication. #' #' Get a 2-legged token for OAuth-based authentication to the AutoDesk Forge #' Platform. #' @param id A string. Client ID for the app generated from the AutoDesk Dev #' Portal. #' @param secret A string. Client Secret for the app generated from the AutoDesk #' Dev Portal. #' @param scope A string. Space-separated list of required scopes. May be #' \code{user-profile:read}, \code{data:read}, \code{data:write}, #' \code{data:create}, \code{data:search}, \code{bucket:create}, #' \code{bucket:read}, \code{bucket:update}, \code{bucket:delete}, #' \code{code:all}, \code{account:read}, \code{account:write}, or a #' combination of these. #' @return An object containing the \code{access_token}, \code{code_type}, and #' \code{expires_in} milliseconds. #' @seealso \url{https://developer.autodesk.com/en/docs/oauth/v2/overview/} #' @examples #' \dontrun{ #' # Get a 2-legged token with the "data:read" and "data:write" scopes #' resp <- getToken(id = Sys.getenv("client_id"), secret = Sys.getenv("client_secret"), #' scope = "data:write data:read") #' myToken <- resp$content$access_token #' } #' @import httr #' @import jsonlite #' @export getToken <- function(id = NULL, secret = NULL, scope = "data:write data:read") { if (is.null(id)) stop("id is null") if (is.null(secret)) stop("secret is null") if (is.null(scope)) stop("scope is null") url <- 'https://developer.api.autodesk.com/authentication/v1/authenticate' dat = list(client_id = id, client_secret = secret, grant_type = "client_credentials", scope = scope) resp <- POST(url, user_agent("https://github.com/paulgovan/AutoDeskR"), body = dat, encode = "form") if (http_type(resp) != "application/json") { stop("AutoDesk API did not return json", call. = FALSE) } warn_for_status(resp) parsed <- jsonlite::fromJSON(content(resp, "text"), simplifyVector = FALSE) structure( list( content = parsed, path = url, response = resp ), class = "getToken" ) }
/scratch/gouwar.j/cran-all/cranData/AutoDeskR/R/authentication.R
#' Make a Bucket for an App. #' #' Make an app-based bucket for storage of design files using the Data Management API. #' @param token A string. Token generated with \code{\link{getToken}} function #' with \code{bucket:create}, \code{bucket:read}, and \code{data:write} #' scopes. #' @param bucket A string. Unique bucket name. Defaults to \code{mybucket}. #' @param policy A string. May be \code{transient}, \code{temporary}, or #' \code{persistent}. #' @return An object containing the \code{bucketKey}, \code{bucketOwner}, and #' \code{createdDate}. #' @seealso \url{https://developer.autodesk.com/en/docs/data/v2/overview/} #' @examples #' \dontrun{ #' # Make a transient bucket with the name "mybucket" #' resp <- makeBucket(token = myToken, bucket = "mybucket", policy = "transient") #' } #' @import httr #' @import jsonlite #' @export makeBucket <- function(token = NULL, bucket = "mybucket", policy = "transient") { if (is.null(token)) stop("token is null") if (is.null(bucket)) stop("bucket is null") if (is.null(policy)) stop("policy is null") # if (policy != "transient" | policy != "temporary" | policy != "persistent") # stop("Please select a bucket policy of 'transient', 'temporary', or 'persistent'") url <- 'https://developer.api.autodesk.com/oss/v2/buckets' dat <- list(bucketKey = bucket, policyKey = policy) resp <- POST(url, user_agent("https://github.com/paulgovan/AutoDeskR"), add_headers(Authorization = paste0("Bearer ", token)), body = dat, encode = "json") if (http_type(resp) != "application/json") { stop("AutoDesk API did not return json", call. = FALSE) } warn_for_status(resp) parsed <- jsonlite::fromJSON(content(resp, "text"), simplifyVector = FALSE) structure( list( content = parsed, path = url, response = resp ), class = "makeBucket" ) } #' Check the Status of an App-Managed Bucket. #' #' Check the status of a recently created app-managed bucket using the Data Management API. #' @param token A string. Token generated with \code{\link{getToken}} function with \code{bucket:create}, \code{bucket:read}, and \code{data:write} scopes. #' @param bucket A string. Name of the bucket. Defaults to \code{mybucket}. #' @return An object containing the \code{bucketKey}, \code{bucketOwner}, and #' \code{createdDate}. #' @seealso \url{https://developer.autodesk.com/en/docs/data/v2/overview/} #' @examples #' \dontrun{ #' # Check the status of a bucket with the name "mybucket" #' resp <- checkBucket(token = myToken, bucket = "mybucket") #' resp #' } #' @import httr #' @import jsonlite #' @export checkBucket <- function(token = NULL, bucket = "mybucket") { if (is.null(token)) stop("token is null") if (is.null(bucket)) stop("bucket is null") url <- paste0('https://developer.api.autodesk.com/oss/v2/buckets/', bucket, '/details') resp <- GET(url, user_agent("https://github.com/paulgovan/AutoDeskR"), add_headers(Authorization = paste0("Bearer ", token))) if (http_type(resp) != "application/json") { stop("AutoDesk API did not return json", call. = FALSE) } warn_for_status(resp) parsed <- jsonlite::fromJSON(content(resp, "text"), simplifyVector = FALSE) structure( list( content = parsed, path = url, response = resp ), class = "checkBucket" ) } #' Upload a File to an App-Managed Bucket. #' #' Upload a design file to an app-managed bucket using the Data Management API. #' @param file A string. File path. #' @param token A string. Token generated with \code{\link{getToken}} function #' with \code{bucket:create}, \code{bucket:read}, and \code{data:write} #' scopes. #' @param bucket A string. Unique bucket name. Defaults to \code{mybucket}. #' @return An object containing the \code{bucketKey}, \code{objectId} (i.e. #' urn), \code{objectKey} (i.e. file name), \code{size}, \code{contentType} #' (i.e. "application/octet-stream"), \code{location}. and other content #' information. #' @seealso \url{https://developer.autodesk.com/en/docs/data/v2/overview/} #' @examples #' \dontrun{ #' # Upload the "aerial.dwg" file to "mybucket" #' resp <- uploadFile(file = system.file("inst/samples/aerial.dwg", package = "AutoDeskR"), #' token = myToken, bucket = "mybucket") #' myUrn <- resp$content$objectId #' } #' @import httr #' @import jsonlite #' @export uploadFile <- function(file = NULL, token = NULL, bucket = "mybucket") { if (is.null(file)) stop("file is null") if (is.null(token)) stop("token is null") if (is.null(bucket)) stop("bucket is null") url <- paste0("https://developer.api.autodesk.com/oss/v2/buckets/", bucket, "/objects/", basename(file)) resp <- PUT(url, user_agent("https://github.com/paulgovan/AutoDeskR"), add_headers(Authorization = paste0("Bearer ", token)), body = upload_file(file)) if (http_type(resp) != "application/json") { stop("AutoDesk API did not return json", call. = FALSE) } warn_for_status(resp) parsed <- jsonlite::fromJSON(content(resp, "text"), simplifyVector = FALSE) structure( list( content = parsed, path = url, response = resp ), class = "uploadFile" ) }
/scratch/gouwar.j/cran-all/cranData/AutoDeskR/R/dataManagement.R
#' Convert a DWG to a PDF. #' #' Convert a publicly accessible DWG file to a publicly accessible PDF using the Design Automation API. #' @param source A string. Publicly accessible web address of the input dwg #' file. #' @param destination A string. Publicly accessible web address for the output #' pdf file. #' @param token A string. Token generated with \code{\link{getToken}} function #' with \code{code:all} scope. #' @seealso #' \url{https://developer.autodesk.com/en/docs/design-automation/v2/overview/} #' @examples #' \dontrun{ #' mySource <- "http://download.autodesk.com/us/samplefiles/acad/visualization_-_aerial.dwg" #' myDestination <- "https://drive.google.com/folderview?id=0BygncDVHf60mTDZVNDltLThLNmM&usp=sharing" #' resp <- makePdf(mySource, myDestination, token = myToken) #' } #' @import httr #' @import jsonlite #' @export makePdf <- function(source = NULL, destination = NULL, token = NULL) { if (is.null(source)) stop("source is null") if (is.null(destination)) stop("destination is null") if (is.null(token)) stop("token is null") url <- 'https://developer.api.autodesk.com/autocad.io/us-east/v2/WorkItems' dat <- list( "@odata.type" = "#ACES.Models.WorkItem", Arguments = list( InputArguments = list( structure( list( Resource = source, Name = "HostDwg", StorageProvider = "Generic" ) ) ), OutputArguments = list( structure( list( Name = "Result", StorageProvider = "Generic", HttpVerb = "POST", Resource = destination ) ) ) ), ActivityId = "PlotToPDF", Id = "" ) resp <- POST(url, add_headers(Authorization = paste0("Bearer ", token)), body = dat, encode = "json") if (http_type(resp) != "application/json") { stop("AutoDesk API did not return json", call. = FALSE) } warn_for_status(resp) parsed <- jsonlite::fromJSON(content(resp, "text"), simplifyVector = FALSE) structure( list( content = parsed, path = url, response = resp ), class = "makePdf" ) } #' Check the status of a PDF. #' #' Check the status of a recently created PDF file using the Design Automation #' API. #' @param source A string. Publicly accessible web address of the input dwg #' file. #' @param destination A string. Publicly accessible web address for the output #' pdf file. #' @param token A string. Token generated with \code{\link{getToken}} function #' with \code{code:all} scope. #' @seealso #' \url{https://developer.autodesk.com/en/docs/design-automation/v2/overview/} #' @examples #' \dontrun{ #' mySource <- "http://download.autodesk.com/us/samplefiles/acad/visualization_-_aerial.dwg" #' myDestination <- "https://drive.google.com/folderview?id=0BygncDVHf60mTDZVNDltLThLNmM&usp=sharing" #' resp <- checkPdf(mySource, myDestination, token = myToken) #' resp #' } #' @import httr #' @import jsonlite #' @export checkPdf <- function(source = NULL, destination = NULL, token = NULL) { if (is.null(source)) stop("source is null") if (is.null(destination)) stop("destination is null") if (is.null(token)) stop("token is null") url <- 'https://developer.api.autodesk.com/autocad.io/us-east/v2/WorkItems' dat <- list( "@odata.type" = "#ACES.Models.WorkItem", Arguments = list( InputArguments = list( structure( list( Resource = source, Name = "HostDwg", StorageProvider = "Generic" ) ) ), OutputArguments = list( structure( list( Name = "Result", StorageProvider = "Generic", HttpVerb = "POST", Resource = destination ) ) ) ), ActivityId = "PlotToPDF", Id = "" ) resp <- GET(url, add_headers(Authorization = paste0("Bearer ", token)), body = dat, encode = "json") if (http_type(resp) != "application/json") { stop("AutoDesk API did not return json", call. = FALSE) } warn_for_status(resp) parsed <- jsonlite::fromJSON(content(resp, "text"), simplifyVector = FALSE) structure( list( content = parsed, path = url, response = resp ), class = "checkPdf" ) }
/scratch/gouwar.j/cran-all/cranData/AutoDeskR/R/designAutomation.R
#' Translate a File into SVF Format. #' #' Translate an uploaded file into SVF format using the Model Derivative API. #' @param urn A string. Source URN (objectId) for the file. Note the URN must be #' Base64 encoded. To encode the URN, see, for example, the #' \code{jsonlite::base64_enc} function. #' @param token A string. Token generated with \code{\link{getToken}} function #' with \code{data:read} and \code{data:write} scopes. #' @return An object containing the \code{result}, \code{urn}, and additional #' activity information. #' @seealso #' \url{https://developer.autodesk.com/en/docs/model-derivative/v2/overview/} #' @examples #' \dontrun{ #' # Translate the "aerial.dwg" file into a svf file #' myEncodedUrn <- jsonlite::base64_enc(myUrn) #' resp <- translateSvf(urn = myEncodedUrn, token = myToken) #' } #' @import httr #' @import jsonlite #' @export translateSvf <- function(urn = NULL, token = NULL) { if (is.null(urn)) stop("urn is null") if (is.null(token)) stop("token is null") url <- 'https://developer.api.autodesk.com/modelderivative/v2/designdata/job' dat <- list( input = list( urn = urn ), output = list( formats = list( structure( list( type = "svf", views = list( "2d", "3d" ) ) ) ) ) ) resp <- POST(url, add_headers(Authorization = paste0("Bearer ", token)), body = dat, encode = "json") if (http_type(resp) != "application/json") { stop("AutoDesk API did not return json", call. = FALSE) } warn_for_status(resp) parsed <- jsonlite::fromJSON(content(resp, "text"), simplifyVector = FALSE) structure( list( content = parsed, path = url, response = resp ), class = "translateSvf" ) } #' Check the Status of a Translated File. #' #' Check the status of a recently translated file using the Model Derivative API. #' @param urn A string. Source URN (objectId) for the file. Note the URN must be #' Base64 encoded. To encode the URN, see, for example, the #' \code{jsonlite::base64_enc} function. #' @param token A string. Token generated with \code{\link{getToken}} function #' with \code{data:read} and \code{data:write} scopes. #' @seealso #' \url{https://developer.autodesk.com/en/docs/model-derivative/v2/overview/} #' @examples #' \dontrun{ #' # Check the status of the translated "aerial.dwg" svf file #' resp <- checkFile(urn = myEncodedUrn, token = myToken) #' resp #' } #' @import httr #' @import jsonlite #' @export checkFile <- function(urn = NULL, token = NULL) { if (is.null(urn)) stop("urn is null") if (is.null(token)) stop("token is null") url <- paste0('https://developer.api.autodesk.com/modelderivative/v2/designdata/', urn, '/manifest') resp <- GET(url, add_headers(Authorization = paste0("Bearer ", token))) if (http_type(resp) != "application/json") { stop("AutoDesk API did not return json", call. = FALSE) } warn_for_status(resp) parsed <- jsonlite::fromJSON(content(resp, "text"), simplifyVector = FALSE) structure( list( content = parsed, path = url, response = resp ), class = "checkFile" ) } #' Get the Metadata for a File. #' #' Get the metadata of an uploaded file using the Model Derivative API. #' @param urn A string. Source URN (objectId) for the file. Note the URN must be #' Base64 encoded. To encode the URN, see, for example, the #' \code{jsonlite::base64_enc} function. #' @param token A string. Token generated with \code{\link{getToken}} function #' with \code{data:read} and \code{data:write} scopes. #' @return An object containing the \code{type}, \code{name}, and \code{guid} of #' the file. #' @seealso #' \url{https://developer.autodesk.com/en/docs/model-derivative/v2/overview/} #' @examples #' \dontrun{ #' # Get the metadata for the "aerial.dwg" svf file #' resp <- getMetadata(urn <- myEncodedUrn, token = myToken) #' myGuid <- resp$content$data$metadata[[1]]$guid #' } #' @import httr #' @import jsonlite #' @export getMetadata <- function(urn = NULL, token = NULL) { if (is.null(urn)) stop("urn is null") if (is.null(token)) stop("token is null") url <- paste0('https://developer.api.autodesk.com/modelderivative/v2/designdata/', urn, '/metadata') resp <- GET(url, add_headers(Authorization = paste0("Bearer ", token))) if (http_type(resp) != "application/json") { stop("AutoDesk API did not return json", call. = FALSE) } warn_for_status(resp) parsed <- jsonlite::fromJSON(content(resp, "text"), simplifyVector = FALSE) structure( list( content = parsed, path = url, response = resp ), class = "getMetadata" ) } #' Get the Geometry Data for a File. #' #' Get the geometry of an uploaded file using the Model Derivative API. #' @param guid A string. GUID retrieved via the \code{\link{getMetadata}} #' function. #' @param urn A string. Source URN (objectId) for the file. Note the URN must be #' Base64 encoded. To encode the URN, see, for example, the #' \code{jsonlite::base64_enc} function. #' @param token A string. Token generated with \code{\link{getToken}} function #' with \code{data:read} and \code{data:write} scopes. #' @return An object containing the geometry data for the selected file. #' @seealso #' \url{https://developer.autodesk.com/en/docs/model-derivative/v2/overview/} #' @examples #' \dontrun{ #' # Get the geometry data for the "aerial.dwg" svf file #' resp <- getData(guid <- myGuid, urn <- myEncodedUrn, token = myToken) #' } #' @import httr #' @import jsonlite #' @export getData <- function(guid = NULL, urn = NULL, token = NULL) { if (is.null(guid)) stop("guid is null") if (is.null(urn)) stop("urn is null") if (is.null(token)) stop("token is null") url <- paste0('https://developer.api.autodesk.com/modelderivative/v2/designdata/', urn, '/metadata/', guid, '/properties') resp <- GET(url, add_headers(Authorization = paste0("Bearer ", token))) if (http_type(resp) != "application/json") { stop("AutoDesk API did not return json", call. = FALSE) } warn_for_status(resp) parsed <- jsonlite::fromJSON(content(resp, "text"), simplifyVector = FALSE) structure( list( content = parsed, path = url, response = resp ), class = "getData" ) } #' Get the Object Tree of a File. #' #' Get the object tree of an uploaded file using the Model Derivative API. #' @param guid A string. GUID retrieved via the \code{\link{getMetadata}} #' function. #' @param urn A string. Source URN (objectId) for the file. Note the URN must be #' Base64 encoded. To encode the URN, see, for example, the #' \code{jsonlite::base64_enc} function. #' @param token A string. Token generated with \code{\link{getToken}} function #' with \code{data:read} and \code{data:write} scopes. #' @return An object containing the object tree for the selected file. the file. #' @seealso #' \url{https://developer.autodesk.com/en/docs/model-derivative/v2/overview/} #' @examples #' \dontrun{ #' # Get the object tree for the "aerial.dwg" svf file #' resp <- getObjectTree(guid <- myGuid, urn <- myEncodedUrn, token = myToken) #' resp #' } #' @import httr #' @import jsonlite #' @export getObjectTree <- function(guid = NULL, urn = NULL, token = NULL){ if (is.null(guid)) stop("guid is null") if (is.null(urn)) stop("urn is null") if (is.null(token)) stop("token is null") url <- paste0('https://developer.api.autodesk.com/modelderivative/v2/designdata/', urn, '/metadata/', guid) resp <- GET(url, add_headers(Authorization = paste0("Bearer ", token))) if (http_type(resp) != "application/json") { stop("AutoDesk API did not return json", call. = FALSE) } warn_for_status(resp) parsed <- jsonlite::fromJSON(content(resp, "text"), simplifyVector = FALSE) structure( list( content = parsed, path = url, response = resp ), class = "getObjectTree" ) } #' Translate a File into OBJ Format. #' #' Translate an uploaded file into OBJ format using the Model Derivative API. #' @param urn A string. Source URN (objectId) for the file. Note the URN must be #' Base64 encoded. To encode the URN, see, for example, the #' \code{jsonlite::base64_enc} function. #' @param token A string. Token generated with \code{\link{getToken}} function #' with \code{data:read} and \code{data:write} scopes. #' @return An object containing the \code{result}, \code{urn}, and additional #' activity information. #' @seealso #' \url{https://developer.autodesk.com/en/docs/model-derivative/v2/overview/} #' @examples #' \dontrun{ #' # Translate the "aerial.dwg" file into a obj file #' resp <- translateObj(urn <- myEncodedUrn, token = myToken) #' } #' @import httr #' @import jsonlite #' @export translateObj <- function(urn = NULL, token = NULL) { if (is.null(urn)) stop("urn is null") if (is.null(token)) stop("token is null") url <- 'https://developer.api.autodesk.com/modelderivative/v2/designdata/job' dat <- list( input = list( urn = urn ), output = list( formats = list( structure( list( type = "obj" ) ) ) ) ) resp <- POST(url, add_headers(Authorization = paste0("Bearer ", token)), body = dat, encode = "json") if (http_type(resp) != "application/json") { stop("AutoDesk API did not return json", call. = FALSE) } warn_for_status(resp) parsed <- jsonlite::fromJSON(content(resp, "text"), simplifyVector = FALSE) structure( list( content = parsed, path = url, response = resp ), class = "translateObj" ) } #' Get the Output URN for a File. #' #' Get the output urn of a translated file using the Model Derivative API. #' @param urn A string. Source URN (objectId) for the file. Note the URN must be #' Base64 encoded. To encode the URN, see, for example, the #' \code{jsonlite::base64_enc} function. #' @param token A string. Token generated with \code{\link{getToken}} function #' with \code{data:read} and \code{data:write} scopes. #' @return An object containing the \code{result}, \code{urn}, and additional #' activity information. #' @seealso #' \url{https://developer.autodesk.com/en/docs/model-derivative/v2/overview/} #' @examples #' \dontrun{ #' # Get the output urn for the "aerial.dwg" obj file #' resp <- getOutputUrn(urn <- myUrn, token = Sys.getenv("token")) #' resp #' } #' @import httr #' @import jsonlite #' @export getOutputUrn <- function(urn, token) { if (is.null(urn)) stop("urn is null") if (is.null(token)) stop("token is null") url <- paste0('https://developer.api.autodesk.com/modelderivative/v2/designdata/', urn, '/manifest') resp <- GET(url, add_headers(Authorization = paste0("Bearer ", token))) if (http_type(resp) != "application/json") { stop("AutoDesk API did not return json", call. = FALSE) } warn_for_status(resp) parsed <- jsonlite::fromJSON(content(resp, "text"), simplifyVector = FALSE) structure( list( content = parsed, path = url, response = resp ), class = "getOutputUrn" ) } #' Download a file locally. #' #' Download a file from the Forge Platform using the Model Derivative API. #' @param urn A string. Source URN (objectId) for the file. Note the URN must be #' Base64 encoded. To encode the URN, see, for example, the #' \code{jsonlite::base64_enc} function. #' @param output_urn A string. Output_urn retrieved via #' \code{\link{getOutputUrn}} #' @param token A string. Token generated with \code{\link{getToken}} function #' with \code{data:read} and \code{data:write} scopes. #' @return An object containing the \code{result}, \code{urn}, and additional #' activity information. #' @seealso #' \url{https://developer.autodesk.com/en/docs/model-derivative/v2/overview/} #' @examples #' \dontrun{ #' # Download the "aerial.dwg" png file #' myEncodedOutputUrn <- jsonlite::base64_enc(myOutputUrn) #' resp <- downloadFile(urn <- myEncodedUrn, output_urn <- myEncodedOutputUrn, token = myToken) #' } #' @import httr #' @import jsonlite #' @export downloadFile <- function(urn = NULL, output_urn = NULL, token = NULL) { if (is.null(urn)) stop("urn is null") if (is.null(output_urn)) stop("output_urn is null") if (is.null(token)) stop("token is null") url <- paste0('https://developer.api.autodesk.com/modelderivative/v2/designdata/', urn, '/manifest/', output_urn) resp <- GET(url, add_headers(Authorization = paste0("Bearer ", token))) warn_for_status(resp) parsed <- jsonlite::fromJSON(content(resp, "text"), simplifyVector = FALSE) structure( list( content = parsed, path = url, response = resp ), class = "downloadFile" ) }
/scratch/gouwar.j/cran-all/cranData/AutoDeskR/R/modelDerivative.R
#' Launch the Viewer. #' #' @param urn A string. Source URN (objectId) for the file. Note the URN must be #' Base64 encoded. To encode the URN, see, for example, the #' \code{jsonlite::base64_enc} function. #' @param token A string. Token generated with \code{\link{getToken}} function #' with \code{data:read} scope. #' @param viewerType A string. The type of viewer to instantiate. Either #' "header" for the default viewer, "headless" for a viewer without toolbar #' or panels, or "vr" to enter WebVR mode on a mobile device. #' @seealso #' \url{https://developer.autodesk.com/en/docs/viewer/v2/overview/} #' @examples #' \dontrun{ #' # View the "aerial.dwg" file in the AutoDesk viewer #' myEncodedUrn <- jsonlite::base64_enc(myUrn) #' viewer3D(urn <- myEncodedUrn, token = myToken) #' } #' @importFrom shiny shinyApp htmlTemplate #' @export viewer3D <- function(urn = NULL, token = NULL, viewerType = "header") { if (is.null(urn)) stop("urn is null") if (is.null(token)) stop("token is null") if (is.null(viewerType)) stop("viewerType is null") # Paste strings to be passed to html documentID <- paste0("'urn:", urn, "'") accessToken <- paste0("'", token, "'") # Choose an html template if (viewerType == "header") { template <- "template.html" } else if (viewerType == "vr"){ template <- "vr.html" } else { template <- "headless.html" } # Run app shiny::shinyApp( ui = shiny::htmlTemplate(system.file("viewer3D", template, package = "AutoDeskR"), documentID = documentID, accessToken = accessToken ), server = function(input, output) { } ) } #' UI Module Function. #' #' @param id A string. A namespace for the module. #' @param urn A string. Source URN (objectId) for the file. Note the URN must be #' Base64 encoded. To encode the URN, see, for example, the #' \code{jsonlite::base64_enc} function. #' @param token A string. Token generated with \code{\link{getToken}} function #' with \code{data:read} scope. #' @param viewerType A string. The type of viewer to instantiate. Either #' "header" for the default viewer or "headless" for a viewer without toolbar #' or panels. #' @seealso #' \url{https://developer.autodesk.com/en/docs/viewer/v2/overview/} #' @examples #' \dontrun{ #' ui <- function(request) { #' shiny::fluidPage( #' viewerUI("pg", myEncodedUrn, myToken) #' ) #' } #' server <- function(input, output, session) { #' } #' shiny::shinyApp(ui, server) #' } #' @importFrom shiny htmlTemplate NS fluidPage shinyApp #' @export viewerUI <- function(id, urn = NULL, token = NULL, viewerType = "header") { if (is.null(urn)) stop("urn is null") if (is.null(token)) stop("token is null") if (viewerType != "header" || "headless") stop("Please choose a viewerType of 'header' or 'headless'") # Paste strings to be passed to html documentID <- paste0("'urn:", urn, "'") accessToken <- paste0("'", token, "'") # Choose an html template if (viewerType == "header") { template <- "template.html" } else if (viewerType == "vr"){ template <- "vr.html" } else { template <- "headless.html" } # Send the htmlTemplate to Shiny ns <- shiny::NS(id) shiny::htmlTemplate(system.file("viewer3D", template, package = "AutoDeskR"), documentID = documentID, accessToken = accessToken ) }
/scratch/gouwar.j/cran-all/cranData/AutoDeskR/R/viewer.R
--- title: "AutoDeskR: An R Interface to the AutoDesk APIs" author: "Paul Govan" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{AutoDeskR} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- <img src="https://github.com/paulgovan/AutoDeskR/blob/master/inst/images/basicSample.png?raw=true" height="500px" /> # The AutoDeskR Package AutoDeskR is an R package that provides an interface to the: Authentication API for obtaining authentication to the AutoDesk Forge Platfrom, Data Management API for managing data across the platform's cloud services, Design Automation API for performing automated tasks on model files in the cloud, Model Derivative API for translating design files into different formats, sending them to the viewer app, and extracting model data, Viewer for rendering 2D and 3D models. # Quick Start To install AutoDeskR in [R](https://www.r-project.org): ```c install.packages("AutoDeskR") ``` Or to install the development version: ```c devtools::install_github('paulgovan/autodeskr') ``` # Authentication AutoDesk uses OAuth-based authentication for access to their services. To get started with this package, first visit the [Create an App](https://developer.autodesk.com/en/docs/oauth/v2/tutorials/create-app/) tutorial for instructions on creating an app and getting a Client ID and Secret. We highly recommend that the Client ID, Secret, and access tokens be stored in a file called `.Renviron` and accessing these keys with the `Sys.getenv()` function. This step is a possible solution for preventing authentication information from being in a publicly accessible location (e.g. GitHub repo). For more information on storing keys in the `.Renviron` file and accessing them with `Sys.getenv()`, see the appendix in this [API Best Practices](https://CRAN.R-project.org/package=httr/vignettes/api-packages.html) vignette. To get an access token, use the `getToken()` function, which returns an object with the `access_token`, `type`, and `expires_in` variables.: ```c resp <- getToken(id = Sys.getenv("client_id"), secret = Sys.getenv("client_secret")) myToken <- resp$content$access_token ``` # Data Management The Data Management API provides users a way to store and access data across the Forge Platform. ## Create a Bucket and Upload a File To create a bucket, first get a token with the `bucket:create`, `bucket:read`, and `data:write` scopes. ```c resp <- getToken(id = Sys.getenv("client_id"), secret = Sys.getenv("client_secret"), scope = "bucket:create bucket:read data:write") myToken <- resp$content$access_token ``` Then use the `makeBucket()` function to create a bucket, where `bucket` is a name for the bucket. ```c resp <- makeBucket(token = myToken, bucket = "mybucket") ``` To check the status of a bucket: ```c resp <- checkBucket(token = myToken, bucket = "mybucket") resp ``` Finally, to upload a file to the bucket, use the `uploadFile()` function, which returns an object containing the `bucketKey`, `objectId` (i.e. urn), `objectKey` (i.e. file name), `size`, `contentType` (i.e. "application/octet-stream"), `location` and other content information. Note the unique urn of the file and store it in `.Renviron` for future use. ```c resp <- uploadFile(file = system.file("samples/aerial.dwg", package = "AutoDeskR"), token = myToken, bucket = "mybucket") myUrn <- resp$content$objectId ``` # Design Automation The Design Automation API provides users the ability to perform automated tasks on design files in the cloud. ## Convert a DWG File to a PDF File To convert a DWG file to a PDF file, use the `makePdf` function, where `source` and `destination` are the publicly accessible source of the DWG file and destination for the PDF file, respectively. ```c mySource <- "http://download.autodesk.com/us/samplefiles/acad/visualization_-_aerial.dwg" myDestination <- "https://drive.google.com/folderview?id=0BygncDVHf60mTDZVNDltLThLNmM&usp=sharing" resp <- makePdf(source = mySource, destination = myDestination, token = myToken) ``` Note that in this example, the `token` must be generated with the `code:all` scope. To check the status of the conversion process: ```c resp <- checkPdf(source = mySource, destination = myDestination, token = myToken) resp ``` # Model Derivative The Model Derivative API enables users to translate their designs into different formats and extract valuable data. ## Translate a File into OBJ Format To translate a supported file into OBJ format, first get an access token with the `data:read` and `data:write` scopes. Note that only certain types of files can be translated into OBJ format. To find out which types of files can be translated into what format, see the [Supported Translation Formats Table](https://developer.autodesk.com/en/docs/model-derivative/v2/overview/supported-translations/). ```c resp <- getToken(id = Sys.getenv("client_id"), secret = Sys.getenv("client_secret"), scope = "data:read data:write") myToken <- resp$content$access_token ``` The platform requires that the urn of the file be Base-64 encoded. Fortunately, the `jsonlite` package has a nifty function for encoding the urn. ```c # Here myUrn was generated from the 'uploadFile()' function myEncodedUrn <- jsonlite::base64_enc(myUrn) ``` Then, translate the file into OBJ format: ```c resp <- translateObj(urn = myEncodedUrn, token = myToken) ``` To check the status of the translation process: ```c resp <- checkFile(urn = myEncodedUrn, token = myToken) resp ``` To download an OBJ file locally, we need the output `urn` of the translated file, which is different than the `urn` of the source file. In this case, use the `getOutputUrn()` function, which returns an object containing the `result`, output `urn` and other activity information. ```c resp <- getOutputUrn(urn = myUrn, token = Sys.getenv("token")) resp ``` Depending on the type of file and translation process, the response may contain multiple output `urn`s for different file types (e.g. obj, svf, png). In order to find the correct OBJ file, look through the `resp` object for a `urn` than ends in ".obj" and assign this `urn` to `myOutputUrn`, which should look similar to the following: ```c myOutputUrn < "urn:adsk.viewing:fs.file:dXJuOmFkc2sub2JqZWN0czpvcy5vYmplY3Q6bW9kZWxkZXJpdmF0aXZlL0E1LmlhbQ/output/geometry/bc3339b2-73cd-4fba-9cb3-15363703a354.obj" ``` Finally, to download the OBJ file locally: ```c myEncodedOutputUrn = jsonlite::base64_enc(myOutputUrn) resp <- downloadFile(urn = myEncodedUrn, output_urn <- myEncodedOutputUrn, token = myToken) ``` ## Prepare a File for the Viewer To prepare a file for the online viewer, first get an access token with the `data:read` and `data:write` scopes. ```c resp <- getToken(id = Sys.getenv("client_id"), secret = Sys.getenv("client_secret"), scope = "data:read data:write") myToken <- resp$content$access_token ``` Nex, encode the urn using the `jsonlite::base64_enc()` function. ```c myEncodedUrn <- jsonlite::base64_enc(myUrn) ``` Then, translate the file into SVF format: ```c resp <- translateSvf(urn = myEncodedUrn, token = myToken) ``` To check the status of the translation process: ```c resp <- checkFile(urn = myEncodedUrn, token = myToken) resp ``` Finally, embed the urn of the file in the viewer, which is described in the **Viewer** section. ## Extract Data from a File To extract data from a file, follow the steps in the previous section for getting a token with the `data:read` and `data:write` scopes, encoding the `urn` of the file using the `jsonlite::base64_enc()` function, and translating the file into SVF format using the `translateSvf()` function. Next, retrieve metadata for a file using the `getMetadata()` function, which returns an object with the `type`, `name`, and `guid` of the file. Note the `guid` and store it in `.Renviron`. ```c resp <- getMetadata(urn = myEncodedUrn, token = myToken) myGuid <- resp$content$data$metadata[[1]]$guid ``` To get the object tree of a model, use the `getObjectTree()` function. ```c resp <- getObjectTree(guid = myGuid, urn = myEncodedUrn, token = myToken) resp ``` To extract data from the model, use the `getData()` function. ```c resp <- getData(guid = myGuid, urn = myEncodedUrn, token = myToken) ``` # Viewer AutoDesk provides a WebGL-based viewer for rendering 2D and 3D models. To use the viewer, make sure to first follow the instructions in **Prepare a File for the Viewer** above. Then simply pass the `urn` of the file and the `token` to the `viewer3D()` function: ```c viewer3D(urn = myEncodedUrn, token = myToken) ``` <img src="https://github.com/paulgovan/AutoDeskR/blob/master/inst/images/aerial.png?raw=true" height="500px" /> The viewer can also be embedded in Shiny applications, interactive R markdown documents, and other web pages thanks to the Shiny Modules framework. Here is a simple example of a Shiny app and the `viewerUI()` function: ```c ui <- function(request) { shiny::fluidPage( viewerUI("pg", myEncodedUrn, myToken) ) } server <- function(input, output, session) { } shiny::shinyApp(ui, server) ``` # Acknowledgements Many thanks to the developers at [AutoDesk](https://github.com/Developer-Autodesk) for providing this great set of tools and for the support needed to learn and implement these APIs.
/scratch/gouwar.j/cran-all/cranData/AutoDeskR/inst/doc/AutoDeskR.Rmd
--- title: "AutoDeskR: An R Interface to the AutoDesk APIs" author: "Paul Govan" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{AutoDeskR} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- <img src="https://github.com/paulgovan/AutoDeskR/blob/master/inst/images/basicSample.png?raw=true" height="500px" /> # The AutoDeskR Package AutoDeskR is an R package that provides an interface to the: Authentication API for obtaining authentication to the AutoDesk Forge Platfrom, Data Management API for managing data across the platform's cloud services, Design Automation API for performing automated tasks on model files in the cloud, Model Derivative API for translating design files into different formats, sending them to the viewer app, and extracting model data, Viewer for rendering 2D and 3D models. # Quick Start To install AutoDeskR in [R](https://www.r-project.org): ```c install.packages("AutoDeskR") ``` Or to install the development version: ```c devtools::install_github('paulgovan/autodeskr') ``` # Authentication AutoDesk uses OAuth-based authentication for access to their services. To get started with this package, first visit the [Create an App](https://developer.autodesk.com/en/docs/oauth/v2/tutorials/create-app/) tutorial for instructions on creating an app and getting a Client ID and Secret. We highly recommend that the Client ID, Secret, and access tokens be stored in a file called `.Renviron` and accessing these keys with the `Sys.getenv()` function. This step is a possible solution for preventing authentication information from being in a publicly accessible location (e.g. GitHub repo). For more information on storing keys in the `.Renviron` file and accessing them with `Sys.getenv()`, see the appendix in this [API Best Practices](https://CRAN.R-project.org/package=httr/vignettes/api-packages.html) vignette. To get an access token, use the `getToken()` function, which returns an object with the `access_token`, `type`, and `expires_in` variables.: ```c resp <- getToken(id = Sys.getenv("client_id"), secret = Sys.getenv("client_secret")) myToken <- resp$content$access_token ``` # Data Management The Data Management API provides users a way to store and access data across the Forge Platform. ## Create a Bucket and Upload a File To create a bucket, first get a token with the `bucket:create`, `bucket:read`, and `data:write` scopes. ```c resp <- getToken(id = Sys.getenv("client_id"), secret = Sys.getenv("client_secret"), scope = "bucket:create bucket:read data:write") myToken <- resp$content$access_token ``` Then use the `makeBucket()` function to create a bucket, where `bucket` is a name for the bucket. ```c resp <- makeBucket(token = myToken, bucket = "mybucket") ``` To check the status of a bucket: ```c resp <- checkBucket(token = myToken, bucket = "mybucket") resp ``` Finally, to upload a file to the bucket, use the `uploadFile()` function, which returns an object containing the `bucketKey`, `objectId` (i.e. urn), `objectKey` (i.e. file name), `size`, `contentType` (i.e. "application/octet-stream"), `location` and other content information. Note the unique urn of the file and store it in `.Renviron` for future use. ```c resp <- uploadFile(file = system.file("samples/aerial.dwg", package = "AutoDeskR"), token = myToken, bucket = "mybucket") myUrn <- resp$content$objectId ``` # Design Automation The Design Automation API provides users the ability to perform automated tasks on design files in the cloud. ## Convert a DWG File to a PDF File To convert a DWG file to a PDF file, use the `makePdf` function, where `source` and `destination` are the publicly accessible source of the DWG file and destination for the PDF file, respectively. ```c mySource <- "http://download.autodesk.com/us/samplefiles/acad/visualization_-_aerial.dwg" myDestination <- "https://drive.google.com/folderview?id=0BygncDVHf60mTDZVNDltLThLNmM&usp=sharing" resp <- makePdf(source = mySource, destination = myDestination, token = myToken) ``` Note that in this example, the `token` must be generated with the `code:all` scope. To check the status of the conversion process: ```c resp <- checkPdf(source = mySource, destination = myDestination, token = myToken) resp ``` # Model Derivative The Model Derivative API enables users to translate their designs into different formats and extract valuable data. ## Translate a File into OBJ Format To translate a supported file into OBJ format, first get an access token with the `data:read` and `data:write` scopes. Note that only certain types of files can be translated into OBJ format. To find out which types of files can be translated into what format, see the [Supported Translation Formats Table](https://developer.autodesk.com/en/docs/model-derivative/v2/overview/supported-translations/). ```c resp <- getToken(id = Sys.getenv("client_id"), secret = Sys.getenv("client_secret"), scope = "data:read data:write") myToken <- resp$content$access_token ``` The platform requires that the urn of the file be Base-64 encoded. Fortunately, the `jsonlite` package has a nifty function for encoding the urn. ```c # Here myUrn was generated from the 'uploadFile()' function myEncodedUrn <- jsonlite::base64_enc(myUrn) ``` Then, translate the file into OBJ format: ```c resp <- translateObj(urn = myEncodedUrn, token = myToken) ``` To check the status of the translation process: ```c resp <- checkFile(urn = myEncodedUrn, token = myToken) resp ``` To download an OBJ file locally, we need the output `urn` of the translated file, which is different than the `urn` of the source file. In this case, use the `getOutputUrn()` function, which returns an object containing the `result`, output `urn` and other activity information. ```c resp <- getOutputUrn(urn = myUrn, token = Sys.getenv("token")) resp ``` Depending on the type of file and translation process, the response may contain multiple output `urn`s for different file types (e.g. obj, svf, png). In order to find the correct OBJ file, look through the `resp` object for a `urn` than ends in ".obj" and assign this `urn` to `myOutputUrn`, which should look similar to the following: ```c myOutputUrn < "urn:adsk.viewing:fs.file:dXJuOmFkc2sub2JqZWN0czpvcy5vYmplY3Q6bW9kZWxkZXJpdmF0aXZlL0E1LmlhbQ/output/geometry/bc3339b2-73cd-4fba-9cb3-15363703a354.obj" ``` Finally, to download the OBJ file locally: ```c myEncodedOutputUrn = jsonlite::base64_enc(myOutputUrn) resp <- downloadFile(urn = myEncodedUrn, output_urn <- myEncodedOutputUrn, token = myToken) ``` ## Prepare a File for the Viewer To prepare a file for the online viewer, first get an access token with the `data:read` and `data:write` scopes. ```c resp <- getToken(id = Sys.getenv("client_id"), secret = Sys.getenv("client_secret"), scope = "data:read data:write") myToken <- resp$content$access_token ``` Nex, encode the urn using the `jsonlite::base64_enc()` function. ```c myEncodedUrn <- jsonlite::base64_enc(myUrn) ``` Then, translate the file into SVF format: ```c resp <- translateSvf(urn = myEncodedUrn, token = myToken) ``` To check the status of the translation process: ```c resp <- checkFile(urn = myEncodedUrn, token = myToken) resp ``` Finally, embed the urn of the file in the viewer, which is described in the **Viewer** section. ## Extract Data from a File To extract data from a file, follow the steps in the previous section for getting a token with the `data:read` and `data:write` scopes, encoding the `urn` of the file using the `jsonlite::base64_enc()` function, and translating the file into SVF format using the `translateSvf()` function. Next, retrieve metadata for a file using the `getMetadata()` function, which returns an object with the `type`, `name`, and `guid` of the file. Note the `guid` and store it in `.Renviron`. ```c resp <- getMetadata(urn = myEncodedUrn, token = myToken) myGuid <- resp$content$data$metadata[[1]]$guid ``` To get the object tree of a model, use the `getObjectTree()` function. ```c resp <- getObjectTree(guid = myGuid, urn = myEncodedUrn, token = myToken) resp ``` To extract data from the model, use the `getData()` function. ```c resp <- getData(guid = myGuid, urn = myEncodedUrn, token = myToken) ``` # Viewer AutoDesk provides a WebGL-based viewer for rendering 2D and 3D models. To use the viewer, make sure to first follow the instructions in **Prepare a File for the Viewer** above. Then simply pass the `urn` of the file and the `token` to the `viewer3D()` function: ```c viewer3D(urn = myEncodedUrn, token = myToken) ``` <img src="https://github.com/paulgovan/AutoDeskR/blob/master/inst/images/aerial.png?raw=true" height="500px" /> The viewer can also be embedded in Shiny applications, interactive R markdown documents, and other web pages thanks to the Shiny Modules framework. Here is a simple example of a Shiny app and the `viewerUI()` function: ```c ui <- function(request) { shiny::fluidPage( viewerUI("pg", myEncodedUrn, myToken) ) } server <- function(input, output, session) { } shiny::shinyApp(ui, server) ``` # Acknowledgements Many thanks to the developers at [AutoDesk](https://github.com/Developer-Autodesk) for providing this great set of tools and for the support needed to learn and implement these APIs.
/scratch/gouwar.j/cran-all/cranData/AutoDeskR/vignettes/AutoDeskR.Rmd
#' Implemented t-distributed stochastic neighbor embedding #' #' This function is used to upload a table into R for further use in the AutoPipe #' #' #' @usage AutoPipe_tSNE(me,perplexity=30,max_iter=500,groups_men) #' #' @param me The path of the expression table #' @param perplexity numeric; Perplexity parameter #' @param max_iter integer; Number of iterations (default: 1000) #' @param groups_men the data frame with the group clustering that the function Groups_Sup or top_supervised (2. place on the list) returns with #' the data about each sample and its coressponding cluster. #' @export AutoPipe_tSNE AutoPipe_tSNE=function(me,perplexity=30,max_iter=500,groups_men){ set.seed(5000) ana=Rtsne::Rtsne(t(me), check_duplicates = F, dim=3, perplexity=perplexity, max_iter=max_iter) ana=data.frame(ana$Y) rownames(ana)=colnames(me) ana$cluster=groups_men[rownames(ana), ]$cluster max=max(groups_men[rownames(ana), ]$cluster) ana$col="red" col<-RColorBrewer::brewer.pal(n=max,name = "Paired") for(i in 1:max){ color=col[i] ana[ana$cluster==i, ]$col=color } plot(ana[,1:2], col=ana$col, pch=19, bty="n", main="t-distributed stochastic neighbor embedding") }
/scratch/gouwar.j/cran-all/cranData/AutoPipe/R/AutoPipe_tSNE.R
#' cluster the samples #' #' This function clusters the samples into x clusters. #' @usage Groups_Sup(me_TOP, me, number_of_k,TRw) #' #' @param me_TOP the matrix with the n top genes, usually the from #' output of the function TopPAM #' @param me the original expression matrix. (with genes in rows and samples in columns). #' @param number_of_k the number of clusters #' @param TRw threshold for the elemenation of the samples with a Silhouette width lower than TRw. #' Default value is -1. #' #' @examples #' #' ## load data #' library(org.Hs.eg.db) #' data(rna) #' me_x=rna #' res<-AutoPipe::TopPAM(me_x,max_clusters = 8, TOP=100) #' me_TOP=res[[1]] #' number_of_k=res[[3]] #' File_genes=Groups_Sup(me_TOP, me=me_x, number_of_k,TRw=-1) #' groups_men=File_genes[[2]] #' me_x=File_genes[[1]] #' #' @export Groups_Sup Groups_Sup=function(me_TOP, me, number_of_k,TRw=-1){ number_of_k=number_of_k pamx <- cluster::pam(t(me_TOP), k=number_of_k) si <- cluster::silhouette(pamx) graphics::barplot(si[,3]) me_TOP_s=me_TOP[,rownames(si[si[,3]>TRw, ])] dim(me_TOP_s) groups_men=as.data.frame(si[si[,3]>TRw, ]) graphics::barplot(groups_men$sil_width) (rownames(groups_men) %in% colnames(me) ) Exp=(me[, rownames(groups_men)]) dim(Exp) return(list(Exp, groups_men)) }
/scratch/gouwar.j/cran-all/cranData/AutoPipe/R/Groups_Sup.R
#' Produce a Heatmap using a Supervised clustering Algorithm #' #' This function produces a plot with a Heatmap using #' a supervised clustering algorithm which the user choses. #' with a the mean Silhouette width plotted on the right top corner #' and the Silhouette width for each sample on top. #' On the right side of the plot the n highest and lowest scoring #' genes for each cluster will added. And next to them the coressponding pathways #' (see Details) #' #' #' @usage Supervised_Cluster_Heatmap(groups_men, gene_matrix, #' method="PAMR",TOP=1000,TOP_Cluster=150, #' show_sil=FALSE,show_clin=FALSE,genes_to_print=5, #' print_genes=FALSE,samples_data=NULL,colors="RdBu", #' GSE=FALSE,topPaths=5,db="c2",plot_mean_sil=FALSE,stats_clust =NULL,threshold=2) #' @param groups_men the data frame with the group clustering that the function Groups_Sup or top_supervised (2. place on the list) returns with #' the data about each sample and its coressponding cluster. #' @param gene_matrix the matrix of n selected genes that the function Groups_Sup returns #' @param method the method to cluster of Clustering. The default is "PAMR" which uses the pamr library. #' other methods are SAM and our own "EXReg" (see details) #' @param TOP the number of the top genes to take. the default value is 1000. #' @param show_sil a logical value that indicates if the function should show #' the Silhouette width for each sample. Default is FALSE. #' @param show_clin a logical value if TRUE the function will plot the clinical data provided #' by the user. Default value is FALSE. #' @param genes_to_print the number of genes to print for each cluster. this function #' adds on the right side. #' of the heatmap the n highest expressed genes and the n lowest expressed genes for each #' cluster. Default value is 5. #' @param print_genes a logical value indicating if or not to plot the TOP genes for each #' cluster.Default value is FALSE. #' @param samples_data the clinical data provided by the user to plot under the heatmap. it will be #' plotted only if show_clin is TRUE. Default value is NULL. see details for format. #' @param colors the colors for the Heatmap. The function RColorBrewer palletes. #' @param GSE a logical variable that indicates wether to plot thr Gene Set Enrichment Analysis #' next to the heatmap. Default value is FALSE. #' @param topPaths a numerical value that says how many pathways the Gene Set Enrichment #' plots should contain fo each cluster. Default value is 5. #' @param db a value for the database for the GSE to be used. Default value is "c1". #' the paramater can one of the values: "c1","c2","c3",c4","c5","c6","c7","h". See the #' broad institue GSE \href{http://software.broadinstitute.org/gsea/index.jsp}{GSE webpage} for further information in each dataset. #' @param plot_mean_sil A logical value. if TRUE the function plots the mean of the #' Silhouette width for each cluster number or gap statistic. #' @param stats_clust A vector with the mean Silhouette widths or gap statistic for the number of clusters. The first #' value should be for 2 Clusters. 2nd is for 3 clusters and so on. #' @param threshold the threshhold for the pam analysis default is 2. #' @param TOP_Cluster a numeric variable for the number of genes to include in the clusters. Default is 150. #' @details sample data should be a data.frame with the sample names #' as rownames and the clinical triats as columns. #' each trait must be a numeric variable. #' #' #' @examples #' #' ##load the org.Hs.eg Library #' library(org.Hs.eg.db) #' ## load data #' data(rna) #' me_x=rna #' ## calculate best number of clusters and #' res<-AutoPipe::TopPAM(me_x,max_clusters = 6, TOP=100) #' me_TOP=res[[1]] #' number_of_k=res[[3]] #' File_genes=Groups_Sup(me_TOP, me=me_x, number_of_k,TRw=-1) #' groups_men=File_genes[[2]] #' me_x=File_genes[[1]] #' o_g<-Supervised_Cluster_Heatmap(groups_men = groups_men, gene_matrix=me_x, #' method="PAMR",show_sil=TRUE,print_genes=TRUE,threshold=0, #' TOP = 100,GSE=FALSE,plot_mean_sil=TRUE,stats_clust=res[[2]]) #' #' @import graphics #' @export Supervised_Cluster_Heatmap Supervised_Cluster_Heatmap=function(groups_men, gene_matrix, method="PAMR",TOP=1000,TOP_Cluster=150, show_sil=FALSE,show_clin=FALSE,genes_to_print=5, print_genes=FALSE,samples_data=NULL,colors="RdBu", GSE=FALSE,topPaths=5,db="c2",plot_mean_sil=FALSE,stats_clust =NULL,threshold=2){ cluster_files=supVisGenes(groups_men,gene_matrix=gene_matrix,method=method,TOP = TOP,threshold = threshold,TOP_Cluster=TOP_Cluster) ordert_genes<-cluster_files[[1]] genes_print_list<-cluster_files[[2]] sil_w <-if(show_sil){as.data.frame(groups_men[,c("cluster","sil_width"),drop=FALSE])}else{NULL} new_nchheatmap(ordert_genes, sil_width =sil_w ,samples_data = samples_data,print_genes = print_genes,list_of_genes = genes_print_list ,plot_mean_sil=plot_mean_sil,sil_mean =stats_clust, genes_to_print=genes_to_print,col=colors,GSE=GSE,db=db,topPaths=topPaths) return(cluster_files) }
/scratch/gouwar.j/cran-all/cranData/AutoPipe/R/Supervised_Cluster_Heatmap.R
#' Compute Top genes #' #' This function computes the n=TOP genes and the the best number of clusters #' #' @export TopPAM #' @usage TopPAM(me, max_clusters=15,TOP=1000,B=100,clusterboot=FALSE) #' @param me a matrix with genes in rows and samples in columns #' @param max_clusters max. number of clusters to check #' @param TOP the number of genes to take. #' @param B integer, number of Monte Carlo (“bootstrap”) samples. #' @param clusterboot A logical value indicating wether or not to calculate the Gap statistic and to bootstrap. #' @details we use the clusGap algorithm from the package cluster to calculate the Gap statistic. #' @return a list of 1. A matrix with the top genes #' 2. A list of means of the Silhouette width for each number of clusters. 3. The optimal number of clusters. 4. gap_st the gap statistic of the clustering #' 5. best number of clusters according to the gap statistic. #' #' @examples #' #' ##load the org.Hs.eg Library #' library(org.Hs.eg.db) #' #' ## load data #' data(rna) #' me_x=rna #' res<-AutoPipe::TopPAM(me_x,max_clusters = 8, TOP=100,clusterboot=FALSE) #' me_TOP=res[[1]] #' number_of_k=res[[3]] #' #' @import graphics #' @import cluster TopPAM=function(me, max_clusters=15,TOP=1000,B=100,clusterboot=FALSE){ #Top 1000 dim(me) sd=as.data.frame(apply(me,1, function(x){sd(x)})) sd=as.data.frame(sd[order(sd[,1], decreasing = T), ,drop = FALSE]) me_TOP=me[rownames(sd)[1:TOP], ] dim(me_TOP) #Do Cluster PAM #How many clusters sil_mean=as.numeric(do.call(cbind, lapply(2:max_clusters, function(i){ pamx <- cluster::pam(t(me_TOP), k=i) print(paste("Cluster with k=",i, sep="")) si <- cluster::silhouette(pamx) mean_s=mean(as.numeric(si[,3])) return(mean_s) }))) gap_st=NULL best_nc_gp=NULL if(clusterboot==TRUE){ gap_st<-cluster::clusGap(t(me_TOP),FUNcluster = cluster::pam,K.max = max_clusters,B=100) graphics::plot(gap_st,main = "Gap Statistics", bty="n",xaxt="n") graphics::axis(side = 1,at = c(1:19),labels= c(2:20)) best_nc_gp<-cluster::maxSE(gap_st$Tab[,3],gap_st$Tab[,4],method = "Tibs2001SEmax",.25) } return(list(me_TOP,sil_mean,which.max(sil_mean)+1,gap_st,best_nc_gp)) }
/scratch/gouwar.j/cran-all/cranData/AutoPipe/R/TopPAM.R
#' Unsupervised Clustering #' #' A function for unsupervised Clustering of the data #' #' @usage UnSuperClassifier(data,clinical_data=NULL,thr=2,TOP_Cluster=150,TOP=100) #' @export UnSuperClassifier #' #' @param data the data for the clustering. Data should be in the following format: samples in columns and #' the genes in the rows (colnames and rownames accordingly). The rownames should be Entrez ID in order to #' plot a gene set enrichment analysis. #' @param clinical_data the clinical data provided by the user to plot under the heatmap. it will be #' plotted only if show_clin is TRUE. Default value is NULL. see details for format. #' @param TOP_Cluster numeric; Number of genes in each cluster. #' @param TOP numeric; the number of the TOP genes to take from the gene exoression matrix see TopPAM TOP. #' @param thr The threshold for the PAMR algorithm default is 2. #' @details sample data should be a data.frame with the sample names #' as rownames and the clinical triats as columns. #' each trait must be a numeric variable. #' @return the function is an autated Pipeline for clustering it plot cluster analysis for the geneset #' @import graphics UnSuperClassifier<-function(data,clinical_data=NULL,thr=2,TOP_Cluster=150,TOP=100){ res<-AutoPipe::TopPAM(data,max_clusters = 8, TOP=TOP) me_TOP=res[[1]] dim(me_TOP) #-> Wähle Nr of Cluster number_of_k=res[[3]] File_genes=Groups_Sup(me_TOP, me=data, number_of_k,TRw=-1) groups_men=File_genes[[2]] if(is.null(clinical_data)){ o_g<-Supervised_Cluster_Heatmap(groups_men = groups_men, gene_matrix=File_genes[[1]],TOP_Cluster=TOP_Cluster, method="PAMR",show_sil=TRUE,threshold = thr ,print_genes=T,TOP = TOP,GSE=T,plot_mean_sil=T,stats_clust=res[[2]]) } else{ o_g<-Supervised_Cluster_Heatmap(groups_men = groups_men, gene_matrix=File_genes[[1]],threshold=thr,TOP_Cluster=TOP_Cluster, method="PAMR",show_clin =TRUE,show_sil=TRUE,samples_data = clinical_data ,print_genes=T,TOP = 1000,GSE=T,plot_mean_sil=T,stats_clust=res[[2]]) } }
/scratch/gouwar.j/cran-all/cranData/AutoPipe/R/UnSuperClassifier.R
#' A function to plot do a Consensus clustering to validate the results #' #' this function calls the ConsensusClusterPlus function with thedaraset and plots a plot #' with the heatmaps of the clustering for each number of clusters from 2 to max_clust #' #' @usage cons_clust(data,max_clust,TOPgenes) #' @param data this is the data for the ConsensusClusterPlus #' @param max_clust the max number of clusters that should be evaluated. #' @param TOPgenes the number of the top genes to choose for the clustering #' @return plots a plot with all the heatmaps from the ConsensusClusterPlus for the number ofd clusters 2 to max_clust #' the same return value as the COnsensusClusterPlus #' @export cons_clust #' @examples #' #' data(rna) #' cons_clust(rna,5,TOPgenes=50) #' ########Consensus Clustering cons_clust<-function(data,max_clust=5,TOPgenes=150){ geneset<-data dim(geneset) mads=apply(geneset,1,stats::mad) geneset=geneset[rev(order(mads))[1:TOPgenes],] geneset= sweep(geneset,1, apply(geneset,1,stats::median,na.rm=T)) title=tempdir() results = ConsensusClusterPlus::ConsensusClusterPlus(as.matrix(geneset),maxK=max_clust,reps=50,pItem=0.8,pFeature=1, title=title,clusterAlg="hc",distance="euclidean") aa=seq(1,max_clust, by=1) length(aa)=suppressWarnings(prod(dim(matrix(aa,ncol = 3)))) aa[is.na(aa)]=0 lm=matrix(aa, ncol=3, byrow = T) graphics::layout(lm, c(1),c(1)) for(i in 2:max_clust){ xx=as.matrix(results[[i]][["consensusMatrix"]]) nc=ncol(xx) nr=nrow(xx) xx <- sweep(xx, 1L, rowMeans(xx, na.rm = T), check.margin = FALSE) sx <- apply(xx, 1L, stats::sd, na.rm = T) xx <- sweep(xx, 1L, sx, "/", check.margin = FALSE) xx<-t(xx) graphics::par(mar = c(3, 3, 3, 3)) graphics::image(1L:nc, 1L:nr, xx, xlim = 0.5 + c(0, nc), ylim = 0.5 + c(0, nr), axes = FALSE, xlab = "", ylab = "", col=RColorBrewer::brewer.pal(n = 4, "Blues"),useRaster=T) graphics::title(main=paste("ConsensusCluster",i), line = 2) } return(results) }
/scratch/gouwar.j/cran-all/cranData/AutoPipe/R/cons_clust.R
#' rna egene expression of 48 meningiomas #' #' A dataset containing the gene expression data od 48 meningioma tumors #' #' #' @format A data frame with 200 rows and 48 variables: #' \describe{ #' \item{BT_1008}{sample BT_1008, } #' \item{BT_1017}{sample BT_1017, } #' \item{BT_1025}{sample BT_1025, } #' \item{BT_1042}{sample BT_1042, } #' \item{BT_1050}{sample BT_1050, } #' \item{BT_1056}{sample BT_1056, } #' \item{BT_1065}{sample BT_1065, } #' \item{BT_1067}{sample BT_1067, } #' \item{BT_1072}{sample BT_1072, } #' \item{BT_1078}{sample BT_1078, } #' \item{BT_1082}{sample BT_1082, } #' \item{BT_1091}{sample BT_1091, } #' \item{BT_1094}{sample BT_1094, } #' \item{BT_1097}{sample BT_1097, } #' \item{BT_1115}{sample BT_1115, } #' \item{BT_605}{sample BT_605, } #' \item{BT_617}{sample BT_617, } #' \item{BT_619}{sample BT_619, } #' \item{BT_633}{sample BT_633, } #' \item{BT_634}{sample BT_634, } #' \item{BT_644}{sample BT_644, } #' \item{BT_654}{sample BT_654, } #' \item{BT_659}{sample BT_659, } #' \item{BT_690}{sample BT_690, } #' \item{BT_695}{sample BT_695, } #' \item{BT_700}{sample BT_700, } #' \item{BT_738}{sample BT_738, } #' \item{BT_751}{sample BT_751, } #' \item{BT_771}{sample BT_771, } #' \item{BT_797}{sample BT_797, } #' \item{BT_803}{sample BT_803, } #' \item{BT_808}{sample BT_808, } #' \item{BT_820}{sample BT_820, } #' \item{BT_837}{sample BT_837, } #' \item{BT_855}{sample BT_855, } #' \item{BT_862}{sample BT_862, } #' \item{BT_873}{sample BT_873, } #' \item{BT_882}{sample BT_882, } #' \item{BT_887}{sample BT_887, } #' \item{BT_900}{sample BT_900, } #' \item{BT_905}{sample BT_905, } #' \item{BT_907}{sample BT_907, } #' \item{BT_920}{sample BT_920, } #' \item{BT_944}{sample BT_944, } #' \item{BT_962}{sample BT_962, } #' \item{BT_963}{sample BT_963, } #' \item{BT_982}{sample BT_982, } #' \item{BT_990}{sample BT_990, } #' ... #' } "rna"
/scratch/gouwar.j/cran-all/cranData/AutoPipe/R/data.R
#' @import org.Hs.eg.db entrez_to_name<-function(list_of_ent){ ln<-length(list_of_ent[[1]]) list_of_ent<-list_of_ent[[1]] out<-unlist(lapply(1:ln, function(i){ return(annotate::lookUp(list_of_ent[i],'org.Hs.eg', 'SYMBOL')) })) return(out) }
/scratch/gouwar.j/cran-all/cranData/AutoPipe/R/entrez_to_name.R
new_nchheatmap<-function(ordert_genes,col="RdBu",labRow = NULL,cexRoww = NULL, cexColl = NULL, labCol = NULL, main = NULL, xlab = NULL, ylab = NULL,sil_width=NULL, samples_data=NULL,genes_to_print=5,print_genes=FALSE, list_of_genes=NULL,plot_mean_sil=FALSE, sil_mean=NULL,GSE=FALSE,topPaths=5,db="c2"){ ################################ formatting the layout cluster_number<-length(ordert_genes) if( (is.null(ordert_genes)) & (cluster_number<2) ){ stop("Not enough clusters") } ####### get the names of the samples sample_names<-colnames(ordert_genes[[1]]) nc<-ncol(ordert_genes[[1]]) ###### layout for heatmap with nothing else lmat<-do.call(rbind,lapply(1:length(ordert_genes), function(i){ return(c(0,i,0)) })) lwid <- c(0.5, 4,0.5) lhei <- c(1) ###### layout for heatmap + sill. width if( (!print_genes) & (is.null(samples_data)) & (!plot_mean_sil) & (!GSE)){ print("Use Layout Format 1") lmat<-do.call(rbind,lapply(1:(cluster_number+1), function(i){ return(c(0,i,0)) })) lwid <- c(0.5, 4,0.5) lhei <- c(1,rep(1,times=cluster_number)) } ###### layout for heatmap + sill. width + Mean sil if( (!print_genes) & (is.null(samples_data)) & (plot_mean_sil) & (!GSE)){ print("Use Layout Format 2") lmat<-do.call(rbind,lapply(1:(cluster_number+1), function(i){ return(c(0,i,0)) })) lmat[1,3]<-(cluster_number+2) lwid <- c(0.5, 4,2) lhei <- c(1,rep(1,times=cluster_number)) } ###### layout for heatmap + sill. width + clinical data if( (!print_genes) & (!is.null(samples_data)) & (!plot_mean_sil) & (!GSE)){ print("Use Layout Format 3") lmat<-do.call(rbind,lapply(1:(cluster_number+1), function(i){ return(c(0,i,0)) })) num_of_data<-ncol(samples_data) lmat<-rbind(lmat,do.call(rbind,lapply((cluster_number+2):((cluster_number+2)+2*num_of_data), function(i){ return(c(0,i,0)) }))) lwid <- c(0.5, 4,0.5) lhei <- c(1,rep(1,times=cluster_number),rep(0.25,times=num_of_data),rep(0.5,times=num_of_data)) } ###### layout for heatmap + clinical data + Mean sil width if( (!print_genes) & (!is.null(samples_data)) & (plot_mean_sil) & (!GSE)){ print("Use Layout Format 4") lmat<-do.call(rbind,lapply(1:(cluster_number+1), function(i){ return(c(0,i,0)) })) num_of_data<-ncol(samples_data) lmat<-rbind(lmat,do.call(rbind,lapply((cluster_number+2):((cluster_number+1)+2*num_of_data), function(i){ return(c(0,i,0)) }))) lmat[1,3]<-((cluster_number+2)+2*num_of_data) lwid <- c(0.5, 4,2) lhei <- c(1,rep(1,times=cluster_number),rep(0.25,times=num_of_data),rep(0.5,times=num_of_data)) } ###### layout for heatmap + sill. width + clinical data + genes if( (print_genes) & (!is.null(samples_data)) & (!plot_mean_sil) & (!GSE)){ print("Use Layout Format 5") lmat<-do.call(rbind,lapply(1:(cluster_number+1), function(i){ return(c(0,i,0)) })) num_of_data<-ncol(samples_data) lmat<-rbind(lmat,do.call(rbind,lapply((cluster_number+2):((cluster_number+1)+2*num_of_data), function(i){ return(c(0,i,0)) }))) lmat[2:(cluster_number+1),3]<-((cluster_number+2*num_of_data)+2): (((cluster_number+2*num_of_data)+1)+cluster_number) lwid <- c(0.5, 4,2) lhei <- c(1,rep(1,times=cluster_number),rep(0.25,times=num_of_data),rep(0.5,times=num_of_data)) } ###### layout for heatmap + sill. width + clinical data + genes + Mean Sil width if( (print_genes) & (!is.null(samples_data)) & (plot_mean_sil) & (GSE==F)){ print("Use Layout Format 6") lmat<-do.call(rbind,lapply(1:(cluster_number+1), function(i){ return(c(0,i,0)) })) num_of_data<-ncol(samples_data) lmat<-rbind(lmat,do.call(rbind,lapply((cluster_number+2):((cluster_number+1)+2*num_of_data), function(i){ return(c(0,i,0)) }))) lmat[2:(cluster_number+1),3]<-((cluster_number+2*num_of_data)+2): (((cluster_number+2*num_of_data)+1)+cluster_number) lmat[1,3]<-(((cluster_number+2*num_of_data)+1)+cluster_number)+1 lwid <- c(0.5, 4,2) lhei <- c(1,rep(1,times=cluster_number),rep(0.25,times=num_of_data),rep(0.5,times=num_of_data)) } ###### layout for heatmap + sill. width + without clinical data + genes + Mean Sil width if( (print_genes) & (is.null(samples_data)) & (plot_mean_sil) & (GSE==F)){ print("Use Layout Format 7") lmat<-do.call(rbind,lapply(1:(cluster_number+1), function(i){ return(c(0,i,0)) })) lmat[2:(cluster_number+1),3]<-((cluster_number)+2): (((cluster_number)+1)+cluster_number) lmat[1,3]<-(((cluster_number)+1)+cluster_number)+1 lwid <- c(0.5, 4,2) lhei <- c(1,rep(1,times=cluster_number)) } ###### layout for heatmap + sill. width + clinical data + genes + Mean Sil width +GSE if( (print_genes==F) & (!is.null(samples_data))& (plot_mean_sil) & (GSE==T)){ print("Use Layout Format 8") lmat<-do.call(rbind,lapply(1:(cluster_number+1), function(i){ return(c(0,i,0,0,0,0)) })) num_of_data<-ncol(samples_data) lmat<-rbind(lmat,do.call(rbind,lapply((cluster_number+2):((cluster_number+1)+2*num_of_data), function(i){ return(c(0,i,0,0,0,0)) }))) lmat[2:(cluster_number+1),3]<-((cluster_number+2*num_of_data)+2): (((cluster_number+2*num_of_data)+1)+cluster_number) lmat[2:(cluster_number+1),4]<-((cluster_number+2*num_of_data)+2): (((cluster_number+2*num_of_data)+1)+cluster_number) lmat[2:(cluster_number+1),5]<-((cluster_number+2*num_of_data)+2): (((cluster_number+2*num_of_data)+1)+cluster_number) lmat[1,3]<-(((cluster_number+2*num_of_data)+1)+cluster_number)+1 lwid <- c(0.5, 4,2) lhei <- c(1,rep(1,times=cluster_number),rep(0.25,times=num_of_data),rep(0.5,times=num_of_data)) } ###### layout for heatmap clinical data +GSE if( (print_genes==F) & (!is.null(samples_data))& (!plot_mean_sil) & (GSE==T)){ print("Use Layout Format 9") lmat<-do.call(rbind,lapply(1:(cluster_number+1), function(i){ return(c(0,i,0,0,0,0)) })) num_of_data<-ncol(samples_data) lmat<-rbind(lmat,do.call(rbind,lapply((cluster_number+2):((cluster_number+1)+2*num_of_data), function(i){ return(c(0,i,0,0,0,0)) }))) lmat[2:(cluster_number+1),3]<-((cluster_number+2*num_of_data)+2): (((cluster_number+2*num_of_data)+1)+cluster_number) lmat[2:(cluster_number+1),4]<-((cluster_number+2*num_of_data)+2): (((cluster_number+2*num_of_data)+1)+cluster_number) lmat[2:(cluster_number+1),5]<-((cluster_number+2*num_of_data)+2): (((cluster_number+2*num_of_data)+1)+cluster_number) lmat[1,3]<-(((cluster_number+2*num_of_data)+1)+cluster_number)+1 lwid <- c(0.5, 4,2) lhei <- c(1,rep(1,times=cluster_number),rep(0.25,times=num_of_data),rep(0.5,times=num_of_data)) } ###### layout for heatmap + sill. width data + genes + Mean Sil width if( (print_genes==F) & (is.null(samples_data)) & (plot_mean_sil) & (GSE==T)){ print("Use Layout Format 10") lmat<-do.call(rbind,lapply(1:(cluster_number+1), function(i){ return(c(0,i,0,0,0,0)) })) lmat[2:(cluster_number+1),3]<-((cluster_number)+2): (((cluster_number)+1)+cluster_number) lmat[2:(cluster_number+1),4]<-((cluster_number)+2): (((cluster_number)+1)+cluster_number) lmat[2:(cluster_number+1),5]<-((cluster_number)+2): (((cluster_number)+1)+cluster_number) lmat[1,3]<-(((cluster_number)+1)+cluster_number)+1 lwid <- c(0.5, 4,2) lhei <- c(1,rep(1,times=cluster_number)) } ###### layout for heatmap + sill. width + GSE + without Mean Sil width without clinical data if( (print_genes==F) & (is.null(samples_data)) & (plot_mean_sil) & (GSE==T)){ print("Use Layout Format 11") lmat<-do.call(rbind,lapply(1:(cluster_number+1), function(i){ return(c(0,i,0,0,0,0)) })) lmat[2:(cluster_number+1),3]<-((cluster_number)+2): (((cluster_number)+1)+cluster_number) lmat[2:(cluster_number+1),4]<-((cluster_number)+2): (((cluster_number)+1)+cluster_number) lmat[2:(cluster_number+1),5]<-((cluster_number)+2): (((cluster_number)+1)+cluster_number) lmat[1,3]<-(((cluster_number)+1)+cluster_number)+1 lwid <- c(0.5, 4,2) lhei <- c(1,rep(1,times=cluster_number)) } ###### layout for heatmap + sill. width + GSE + Mean Sil width without clinical data if( (print_genes==F) & (is.null(samples_data)) & (!plot_mean_sil) & (GSE==T)){ print("Use Layout Format 12") lmat<-do.call(rbind,lapply(1:(cluster_number+1), function(i){ return(c(0,i,0,0,0,0)) })) lmat[2:(cluster_number+1),3]<-((cluster_number)+2): (((cluster_number)+1)+cluster_number) lmat[2:(cluster_number+1),4]<-((cluster_number)+2): (((cluster_number)+1)+cluster_number) lmat[2:(cluster_number+1),5]<-((cluster_number)+2): (((cluster_number)+1)+cluster_number) lmat[1,3]<-(((cluster_number)+1)+cluster_number)+1 lwid <- c(0.5, 4,2) lhei <- c(1,rep(1,times=cluster_number)) } ###### layout for heatmap + sill. width + clinical data + genes + Mean Sil width + GSE Analysis if( (print_genes) & (!is.null(samples_data)) &(plot_mean_sil) & (GSE)){ print("Use Layout Format 13") lmat<-do.call(rbind,lapply(1:(cluster_number+1), function(i){ return(c(0,i,0,0,0,0,0)) })) #add for sample data num_of_data<-ncol(samples_data) lmat<-rbind(lmat,do.call(rbind,lapply((cluster_number+2):((cluster_number+1)+2*num_of_data), function(i){ return(c(0,i,0,0,0,0,0)) }))) ##Genes lmat[2:(cluster_number+1),3]<-((cluster_number+2*num_of_data)+2): (((cluster_number+2*num_of_data)+1)+cluster_number) ##GSE lmat[2:(cluster_number+1),4]<-(((cluster_number+2*num_of_data)+2)+cluster_number): (((cluster_number+2*num_of_data)+1)+cluster_number*2) lmat[2:(cluster_number+1),5]<-(((cluster_number+2*num_of_data)+2)+cluster_number): (((cluster_number+2*num_of_data)+1)+cluster_number*2) lmat[2:(cluster_number+1),6]<-(((cluster_number+2*num_of_data)+2)+cluster_number): (((cluster_number+2*num_of_data)+1)+cluster_number*2) lmat[1,3]<-(((cluster_number+2*num_of_data)+2)+cluster_number*2) #add legende for sample data #start_nr=(((cluster_number+2*num_of_data)+2)+cluster_number*2) #for(i in 1:2*num_of_data){ # lmat[i+(1+cluster_number),3]=start_nr+i #} lwid <- c(0.5, 4,2) lhei <- c(1,rep(1,times=cluster_number),rep(0.25,times=num_of_data),rep(0.5,times=num_of_data)) } ###### layout for heatmap + sill. width + clinical data + genes + without Mean Sil width + GSE Analysis if( (print_genes) & (!is.null(samples_data)) &(!plot_mean_sil) & (GSE)){ print("Use Layout Format 14") lmat<-do.call(rbind,lapply(1:(cluster_number+1), function(i){ return(c(0,i,0,0,0,0,0)) })) num_of_data<-ncol(samples_data) lmat<-rbind(lmat,do.call(rbind,lapply((cluster_number+2):((cluster_number+1)+2*num_of_data), function(i){ return(c(0,i,0,0,0,0,0)) }))) ##Genes lmat[2:(cluster_number+1),3]<-((cluster_number+2*num_of_data)+2): (((cluster_number+2*num_of_data)+1)+cluster_number) ## GSE lmat[2:(cluster_number+1),4]<-(((cluster_number+2*num_of_data)+2)+cluster_number): (((cluster_number+2*num_of_data)+1)+cluster_number*2) lmat[2:(cluster_number+1),5]<-(((cluster_number+2*num_of_data)+2)+cluster_number): (((cluster_number+2*num_of_data)+1)+cluster_number*2) lmat[2:(cluster_number+1),6]<-(((cluster_number+2*num_of_data)+2)+cluster_number): (((cluster_number+2*num_of_data)+1)+cluster_number*2) lwid <- c(0.5, 4,2) lhei <- c(1,rep(1,times=cluster_number),rep(0.25,times=num_of_data),rep(0.5,times=num_of_data)) } ###### layout for heatmap + sill. width +without clinical data + genes + without Mean Sil width + GSE Analysis if( (print_genes) & (is.null(samples_data)) &(!plot_mean_sil) & (GSE)){ print("Use Layout Format 15") lmat<-do.call(rbind,lapply(1:(cluster_number+1), function(i){ return(c(0,i,0,0,0,0,0)) })) ##genes lmat[2:(cluster_number+1),3]<-((cluster_number)+2): (((cluster_number)+1)+cluster_number) ## GSE lmat[2:(cluster_number+1),4]<-(((cluster_number)+2)+cluster_number): (((cluster_number)+1)+cluster_number*2) lmat[2:(cluster_number+1),5]<-(((cluster_number)+2)+cluster_number): (((cluster_number)+1)+cluster_number*2) lmat[2:(cluster_number+1),6]<-(((cluster_number)+2)+cluster_number): (((cluster_number)+1)+cluster_number*2) lwid <- c(0.5, 4,2) lhei <- c(1,rep(1,times=cluster_number)) } ####### with sil mean , with sil width without clinical data with genes with GSE if( (print_genes) & (is.null(samples_data)) &(plot_mean_sil) & (GSE)){ # lmat<-do.call(rbind,lapply(1:(cluster_number+1), function(i){ # return(c(0,i,0,0,0)) # })) # lmat[2:(cluster_number+1),3]<-((cluster_number)+2): (((cluster_number)+1)+cluster_number) # lmat[2:(cluster_number+1),4]<-(((cluster_number)+2)+cluster_number): (((cluster_number)+1)+cluster_number*2) # lmat[1,3]<-(((cluster_number)+2)+cluster_number*2) # lwid <- c(0.5, 4,2,6,2) # lhei <- c(1,rep(1,times=cluster_number)) lmat<-do.call(rbind,lapply(1:(cluster_number+1), function(i){ return(c(0,i,0,0,0,0,0)) })) #Text print("Use Layout Format 17") lmat[2:(cluster_number+1),3]<-((cluster_number)+2): (((cluster_number)+1)+cluster_number) #GSEA lmat[2:(cluster_number+1),4]<-((((cluster_number)+1)+cluster_number)+1) : ((((cluster_number)+1)+cluster_number)+cluster_number) lmat[2:(cluster_number+1),5]<-((((cluster_number)+1)+cluster_number)+1) : ((((cluster_number)+1)+cluster_number)+cluster_number) lmat[2:(cluster_number+1),6]<-((((cluster_number)+1)+cluster_number)+1) : ((((cluster_number)+1)+cluster_number)+cluster_number) #Mean Silwi lmat[1,3]<-((((cluster_number)+1)+cluster_number)+cluster_number)+1 lwid <- c(0.5, 4,2) lhei <- c(1,rep(1,times=cluster_number)) } ######### layout without clinical data with genes without GSE with mean sil width if( (print_genes) & (is.null(samples_data)) & (plot_mean_sil) & (!GSE)){ print("Use Layout Format 18") lmat<-do.call(rbind,lapply(1:(cluster_number+1), function(i){ return(c(0,i,0)) })) lmat[2:(cluster_number+1),3]<-((cluster_number)+2): (((cluster_number)+1)+cluster_number) lmat[1,3]<-(((cluster_number)+1)+cluster_number)+1 lwid <- c(0.5, 4,2) lhei <- c(1,rep(1,times=cluster_number)) } ######### layout without clinical data with genes without GSE without mean sil width if( (print_genes) & (is.null(samples_data)) & (!plot_mean_sil) & (!GSE)){ print("Use Layout Format 19") lmat<-do.call(rbind,lapply(1:(cluster_number+1), function(i){ return(c(0,i,0)) })) lmat[2:(cluster_number+1),3]<-((cluster_number)+2): (((cluster_number)+1)+cluster_number) lmat[1,3]<-(((cluster_number)+1)+cluster_number)+1 lwid <- c(0.5, 4,2) lhei <- c(1,rep(1,times=cluster_number)) } ##grDevices::pdf(file="try.pdf",width=10,height=10) if(is.null(sil_width)){ lmat<-lmat-1 lmat[which(lmat<0)]<-0 } print(lmat) graphics::layout(lmat, widths = lwid, heights = lhei, respect = TRUE) ################# #Add Silhouette#################### if(!is.null(sil_width)){ palla<-RColorBrewer::brewer.pal(n =max(length(ordert_genes),3) ,name = "Paired") graphics::par(mar = c(1,3,0,0)) graphics::plot(c(0,nc), c(min(sil_width[,2]),max(sil_width[,2])), bty="n",type="n", xaxs="i",xlab="",ylab="",axes=F) graphics::axis(side = 2,line = 0,cex.axis=0.7) graphics::title(ylab = "Sil. Width",cex.lab=0.7,line=2) if(!is.null(sil_width)){ start=c(0,0) for(i in 1:nc){ clust_col=palla[sil_width[i,1]] a=sample_names[i] width=sil_width[a,2] xx=c(i-0.5,i-0.5) yy=c(0,(width)) graphics::polygon(xx,yy, lwd=1,col=clust_col,border = clust_col) graphics::points(x=i-0.5,y=width,pch=22,col=clust_col,bg=clust_col) } } } for(i in 1:length(ordert_genes)){ xx=as.matrix(ordert_genes[[i]]) nc=ncol(xx) nr=nrow(xx) xx <- sweep(xx, 1L, rowMeans(xx, na.rm = T), check.margin = FALSE) sx <- apply(xx, 1L, stats::sd, na.rm = T) xx <- sweep(xx, 1L, sx, "/", check.margin = FALSE) xx<-t(xx) graphics::par(mar = c(1, 3, 0, 0)) (graphics::image(1L:nc, 1L:nr, xx, xlim = 0.5 + c(0, nc), ylim = 0.5 + c(0, nr), axes = FALSE, xlab = "", ylab = "", col=RColorBrewer::brewer.pal(n = 11,name = col),useRaster=T)) } ######################################### clinical data if(!is.null(samples_data)){ for(j in 1:ncol(samples_data)){ graphics::par(mar = c(0.5, 3,0,0)) graphics::plot(c(0,nc), c(1,10), bty="n",type="n",xaxs="i",xlab="",ylab="",axes=FALSE)# plot_w=nc plot_h=5 diff_at<-unique(samples_data[,j]) num_of_at<-length(diff_at) if(j==1) graphics::text(x=nc/2,y=7,"Clinical Data",cex=1,adj = c(0,0)) graphics::text(x=0.5,y=7,colnames(samples_data)[j],cex=0.7,adj = c(0,0)) #pall<-palette(rainbow(num_of_at,start=((j-1)/ncol(samples_data)),end=(j/ncol(samples_data)))) # pallb<-rainbow(num_of_at, start=rgb2hsv(col2rgb('brown'))[1], # end=rgb2hsv(col2rgb('purple'))[1],alpha = 0.5) # pallb<-RColorBrewer::brewer.pal(n =max(num_of_at,3) ,name = "Paired") rownamesge<-sample_names yy<-c(2,plot_h,plot_h,2) vl<-length(sample_names) for (i in 1:vl) { xx<-c(i-1,i-1,i,i) col_indx<-which(diff_at==samples_data[rownamesge[i],j]) color<-pallb[col_indx] # if(samples_data[rownamesge[i],j]==1) # color="black" # else # color="grey" graphics::polygon(xx,yy,col = color, border = NA ) } } } ######################################### clinical data legende if(!is.null(samples_data)){ for(j in 1:ncol(samples_data)){ graphics::par(mar = c(0.5, 3,1,0)) graphics::plot(c(0,20), c(1,10), bty="n",type="n",xaxs="i",xlab="",ylab="",axes=FALSE)# if(j==1) graphics::text(x=10,y=8,"color legend for the clinical data",cex=1,adj = c(0,0)) plot_w=nc plot_h=5 diff_at<-unique(samples_data[,j]) num_of_at<-length(diff_at) graphics::text(x=0.5,y=7,colnames(samples_data)[j],cex=0.7,adj = c(0,0)) pallb<-RColorBrewer::brewer.pal(n =max(num_of_at,3) ,name = "Paired") for(iii in 1:length(pallb)){ ff=iii/2 xx=c(3.5, 4,4,3.5) yy=c((8-ff),(8-ff),(8-ff+0.5),(8-ff+0.5)) graphics::polygon(xx,yy, col = pallb[iii], border = NA ) graphics::text(x=4.5,y=8-ff,diff_at[iii],cex=0.7,adj = c(0,0)) } } } ##################add genes on the side if( print_genes & (genes_to_print>=1) ){ if(!is.null(list_of_genes)){ up_genes<-as.array(lapply(1:length(list_of_genes), function(i){ current_list<-list_of_genes[[i]] rownames(current_list[1:genes_to_print,]) })) print(up_genes) down_genes<-as.array(lapply(1:length(list_of_genes), function(i){ current_list<-list_of_genes[[i]] rownames(current_list[nrow(current_list):(nrow(current_list)-genes_to_print+1),]) })) for (i in 1:length(up_genes)) { graphics::par(mar = c(1, 0.5,0,0)) graphics::plot(x= c(1,1000),y=c(0,genes_to_print+2), bty="n",type="n",xlab="",ylab="",axes=FALSE,yaxs="i") #space_for_gene_names<-1000/length(up_genes) # yPoints<-seq(from=((i-1)*(space_for_gene_names)) # ,to=(i*space_for_gene_names) # ,by=((space_for_gene_names/(genes_to_print+2)))) ### remove firs and last element so genes wont overlap on plot # last<-length(yPoints) # yPoints<-yPoints[-last]## remove last # yPoints<-yPoints[-1]## remove first # yPoints<-yPoints[-1]## remove first if(i==1){ graphics::text(c("Up Reg.","Down Reg"),x=c(1,300),y=genes_to_print+1,col = "Black",cex = 0.7,adj = c(0,0)) } u_g<-entrez_to_name(up_genes[i]) graphics::text(u_g,x=1,y=1:genes_to_print,col = "chocolate3",cex = 0.7,adj = c(0,0)) d_g<-entrez_to_name(down_genes[i]) graphics::text(d_g,x=300,y=1:genes_to_print,col = "cornflowerblue",cex = 0.7, adj = c(0,0)) } }else{ stop("List of genes is NULL") } } ###########plot GSE if(GSE){ if(!is.null(list_of_genes)){ pall<-RColorBrewer::brewer.pal(n =max(length(ordert_genes),3) ,name = "Paired") paths<-pathway_fgsea(db=db,number_of_k=cluster_number,clusters_data=list_of_genes,topPaths=topPaths) width=1 dif=1 for(i in 1:length(list_of_genes)){ graphics::par(mar = c(1, 0.5,0,0)) graphics::plot(x= c(1,1200),y=c(0,topPaths*(dif+width)+2), bty="n",type="n",xlab="",ylab="" ,axes=FALSE,yaxs="i") graphics::abline(v=1) if(i==length(list_of_genes)){ graphics::axis(side = 1,at = seq(from=100, to=800, by=100),labels = seq(from=0.1,to=0.8,by=0.1),cex.axis=0.7) } paths_c<-paths[[i]] clust_col=pall[i] for (j in 1:nrow(paths_c)) { yy=c(dif+j*(width+dif),2*dif+j*(width+dif),2*dif+j*(width+dif),dif+j*(width+dif)) e<-paths_c[j,"ES"]*1000 xx=c(1,1,e,e) graphics::polygon(x = xx,y = yy,col = clust_col) graphics::text(x=e+50,y = dif+j*(width+dif),paths_c[j,"pathway"],adj=c(0,0),cex=0.5) } } }else{ stop("List of Genes is Empty") } } ################plot mean Sill. width if(plot_mean_sil){ diff_clusters<-length(sil_mean) graphics::par(mar = c(1, 3,0,0)) graphics::plot(sil_mean, type = "l", bty="n", xlab = "",ylab="",xaxt="n",cex.axis=0.6,cex.lab=0.6,col="grey") graphics::axis(3, 1:diff_clusters, seq(2,(diff_clusters+1),by=1),line = 2,cex.lab=0.6,cex.axis=0.6) graphics::points(sil_mean, col="red", pch=20) graphics::abline(v=which.max(sil_mean), lty=3) graphics::title(xlab = "Number of Clusters (n)", line = 0,cex.lab=0.6) graphics::title(ylab = "Mean Sil.Width", line = 2,cex.lab=0.6) } ##grDevices::dev.off() }
/scratch/gouwar.j/cran-all/cranData/AutoPipe/R/new_nchheatmap.R
pathway_fgsea<-function(db="c1",number_of_k,clusters_data,topPaths=5){ ############################# read gene to pathway lists #load("R/sysdata.rda") d<-if(db=="c1") msigdbr::msigdbr(species = "Homo sapiens", category = "C1",subcategory = NULL) else d<-if(db=="c2") msigdbr::msigdbr(species = "Homo sapiens", category = "C2",subcategory = NULL) else d<-if(db=="c3") msigdbr::msigdbr(species = "Homo sapiens", category = "C3",subcategory = NULL) else d<-if(db=="c4") msigdbr::msigdbr(species = "Homo sapiens", category = "C4",subcategory = NULL) else d<-if(db=="c5") msigdbr::msigdbr(species = "Homo sapiens", category = "C5",subcategory = NULL) else d<-if(db=="c6") msigdbr::msigdbr(species = "Homo sapiens", category = "C6",subcategory = NULL) else d<-if(db=="c7") msigdbr::msigdbr(species = "Homo sapiens", category = "C7",subcategory = NULL) else d<-if(db=="h") msigdbr::msigdbr(species = "Homo sapiens", category = "H",subcategory = NULL) ####################################### change format to accepted format by fgsea unq<-unique(d$gs_name) i=1 ds<-lapply(1:length(unq),FUN = function(i){ tt<-as.list(d[d$gs_name==unq[i],"entrez_gene"]) tt<-as.character(tt$entrez_gene) }) names(ds)<-unq d<-ds ####################################### fgsea top_paths<-lapply(1:number_of_k, function(i){ cluster_stats<-as.data.frame(clusters_data[[i]]) stats<-(cluster_stats[,1]) names(stats)<-rownames(cluster_stats) fgseaRes<-fgsea::fgsea(pathways = d,stats = stats, minSize=15, maxSize=500, nperm=1000) topPathwaysUp <- fgseaRes[fgseaRes$ES > 0,] topPathways <-topPathwaysUp[utils::head(order(topPathwaysUp$pval), n=topPaths), c("pathway","ES","pval")] topPathways<-topPathways[order(topPathways$ES),] }) return(top_paths) }
/scratch/gouwar.j/cran-all/cranData/AutoPipe/R/pathway_fgsea.R
#' Input Expression File #' #' This function is used to upload a table into R for further use in the AutoPipe #' #' #' @usage read_expression_file(file, format = "csv", sep=";",gene_name="SYMBOL", Trans=FALSE) #' #' @param file The path of the expression table #' @param format The format of the table "csv" or "txt" #' @param sep The seperator of the input table #' @param gene_name Genes are given in "SYMBOL" or "ENTREZID" #' @param Trans Need Matrix Transpose TRUE or FALSE #' @return A data.frame with a gene expression matrix #' #' @export read_expression_file read_expression_file=function(file, format = "csv", sep=";",gene_name="SYMBOL", Trans=FALSE){ print(paste("----- Start Import --------")) data_out=if(format=="csv"){ data_out=utils::read.csv(file,row.names=1,header=T,sep = sep ) if(Trans==T){data_out=t(data_out)} data_out=if(gene_name=="SYMBOL"){ new=clusterProfiler::bitr(rownames(data_out), fromType="SYMBOL", toType="ENTREZID", OrgDb="org.Hs.eg.db") rownames(new)=new$ENTREZID new=new[!duplicated(new$ENTREZID), ] data_out=data_out[new$SYMBOL, ] rownames(data_out)=new$ENTREZID return(data_out) } return(data_out) } data_out=if(format=="txt"){ data_out=utils::read.table(file,row.names=1,header=T) if(Trans==T){data_out=(t(data_out))} data_out=if(gene_name=="SYMBOL"){ new=clusterProfiler::bitr(rownames(data_out), fromType="SYMBOL", toType="ENTREZID", OrgDb="org.Hs.eg.db") #Remove Duplicated genes new=new[!duplicated(new$ENTREZID), ] rownames(new)=new$ENTREZID data_out=data_out[new$SYMBOL, ] rownames(data_out)=new$ENTREZID return(data_out) } return(data_out) } print(paste("-- Data contained", nrow(data_out), "Genes ------------- Data contained", ncol(data_out), "Samples -----")) return(data_out) }
/scratch/gouwar.j/cran-all/cranData/AutoPipe/R/read_expression_file.R
sil_width<-function(cluster_which,dist_mat){ cluster_which<-as.data.frame(cluster_which) cluster_which[,2]<-as.numeric(cluster_which[,2]) dist_mat-dist_mat i=1 j=2 ai_list<-unlist(lapply(1:nrow(cluster_which), function(i) { xs<-cluster_which[(cluster_which[,2]==cluster_which[i,2] ),] xs<-xs[xs[,1]!=cluster_which[i,1],] ai<-mean(dist_mat[i,xs[,1]]) })) number_of_k<-max(unique(cluster_which[,2])) di_mat<-do.call(cbind,lapply(1:nrow(cluster_which), function(i){ unlist(lapply(1:number_of_k, function(j){ if(cluster_which[i,2]==j){ return(NA) }else{ bs<-cluster_which[(cluster_which[,2]==j ),] return(mean(dist_mat[i,bs[,1]])) } })) })) bi_list<-unlist(lapply(1:nrow(cluster_which), function(i){ min(di_mat[,i],na.rm = T) })) si<-unlist(lapply(1:length(bi_list), function(i){ (bi_list[i]-ai_list[i])/max(ai_list[i],bi_list[i]) })) return(si) } # # cluster_which<-as.data.frame(cluster_which) # cluster_which[,2]<-as.numeric(cluster_which[,2]) # dist_mat<-as.matrix(daisy(t(y))) # i=1 # j=2 # ai_list<-unlist(lapply(1:nrow(cluster_which), function(i) { # xs<-cluster_which[(cluster_which[,2]==cluster_which[i,2] ),] # xs<-xs[xs[,1]!=cluster_which[i,1],] # ai<-mean(dist_mat[i,xs[,1]]) # })) # # number_of_k<-max(unique(cluster_which[,2])) # # di_mat<-do.call(cbind,lapply(1:nrow(cluster_which), function(i){ # unlist(lapply(1:number_of_k, function(j){ # if(cluster_which[i,2]==j){ # return(NA) # }else{ # bs<-cluster_which[(cluster_which[,2]==j ),] # return(mean(dist_mat[i,bs[,1]])) # } # })) # })) # # bi_list<-unlist(lapply(1:nrow(cluster_which), function(i){ # min(di_mat[,i],na.rm = T) # })) # # si<-unlist(lapply(1:length(bi_list), function(i){ # (bi_list[i]-ai_list[i])/max(ai_list[i],bi_list[i]) # })) # #
/scratch/gouwar.j/cran-all/cranData/AutoPipe/R/sil_width.R
#' @import graphics supVisGenes=function(groups_men, gene_matrix, method,TOP=1000,p_val=0.05,OR=3 ,threshold=2, TOP_Cluster=150){ me_x=gene_matrix number_of_k=max(groups_men$cluster) ordert_genes=if(method=="PAMR"){ mydata <- list(x=as.matrix(me_x),y=factor(groups_men$cluster), geneid=rownames(me_x),genenames=rownames(me_x)) #training the data mytrain <-pamr::pamr.train(mydata) #leave 10 out cross validation (LOCV) mycv <- pamr::pamr.cv(mytrain,mydata, nfold=10) #plot to check different thresholds #pamr::pamr.plotcv(mycv) #confusion matrix to check the prediction error #pamr::pamr.confusion(mycv, threshold=threshold) #provides gene list and their scores for each class order_file=pamr::pamr.listgenes(mytrain, mydata, threshold=threshold) gene_lists=as.array(lapply(1:number_of_k, function(i){ list_of_genes=as.data.frame(as.numeric(order_file[,i+1])) rownames(list_of_genes)=order_file[,1] names(list_of_genes)="Sig" list_of_genes$Test=1 list_of_genes=list_of_genes[order(list_of_genes$Sig, decreasing = T), ] # vector_gene=c(rownames(list_of_genes[1:150, ]), #rownames(list_of_genes[(nrow(list_of_genes)-150):nrow(list_of_genes), ])) # # if (length(vector_gene)>1){return(me_x[vector_gene, ])} # else{return(NA)} })) ordert_genes<-as.array(lapply(1:number_of_k, function(i){ list_of_genes<-gene_lists[[i]] if(nrow(list_of_genes)<TOP_Cluster){ stop("Please Choose Another Threshold") } vector_gene=c(rownames(list_of_genes[1:TOP_Cluster, ]),rownames(list_of_genes[(nrow(list_of_genes)-TOP_Cluster):nrow(list_of_genes), ])) if (length(vector_gene)>1){return(me_x[vector_gene, ])} else{return(NA)} })) print("########################## Finish with PAMR ##################################################") return(list(ordert_genes,gene_lists)) } ordert_genes=if(method=="SAM"){ ################################################################### # # SAM_analysis.R -- Performs SAM analysis # This analysis was performed after silhouette based selection of # core 387 samples # ################################################################### sam.out<-siggenes::sam(as.matrix(me_x),cl=groups_men$cluster,gene.names=rownames(me_x),rand=123) graphics::plot(sam.out) sam.out ordert_genes=as.array(lapply(1:1, function(i){ list_of_genes=data.frame([email protected]) list_of_genes$sam.out.p.value=as.numeric(list_of_genes$sam.out.p.value) list_of_genes$Test=1 vector_gene=rownames(list_of_genes[list_of_genes$sam.out.p.value<0.00001, ]) return(me_x[vector_gene, ]) })) } ordert_genes=if(method=="EXReg"){ mx=me_x #Filter genes to 10.000 Tops sd=as.data.frame(apply(mx,1, function(x){stats::var(x)})) sd=as.data.frame(sd[order(sd[,1], decreasing = T), ,drop = FALSE]) #mx_TOP=t(mx_TOP) dim(mx) mx_TOP=as.matrix(mx[rownames(sd)[1:TOP], ]) dim(mx_TOP) ####working order_file=as.data.frame(do.call(rbind,lapply(1:nrow(mx_TOP),function(i){ #seperate gene gene=as.data.frame(mx_TOP[i, ], drop=F) colnames(gene)=rownames(mx_TOP)[i] #look for Cluster out=data.frame(do.call(cbind,lapply(1:number_of_k, function(i1){ if(nrow(groups_men[groups_men$cluster==i1, ])!=0){ #gene<-as.data.frame(gene) gene_x<-(gene) ##### sometimes need to activate DONT KNOW WHY YET group=c(0) gene_x<-cbind(gene_x,group) gene_x[rownames(groups_men[groups_men$cluster==i1, ]),"group"]=1 #pred <- prediction(gene[,1], gene$group) #auc.perf = performance(pred, measure = "auc") #AUC=as.numeric([email protected]) model=stats::glm(gene_x[,"group"]~gene_x[,1], family = stats::binomial(link = "logit")) exp=as.numeric(stats::coef(model))[2] p_value=as.numeric(stats::coef(summary(model))[,4])[2] out1=as.data.frame(cbind(exp,p_value)) names(out1)=c(paste("OR_Cluster",i1,sep=""),paste("P_value_Cluster",i1,sep="")) rownames(out1)=colnames(gene_x)[1] return(out1) }else{ out1=as.data.frame(cbind(NA,NA)) names(out1)=c(paste("OR_Cluster",i1,sep=""),paste("P_value_Cluster",i1,sep="")) rownames(out1)=names(gene)[1] return(out1) } }))) return(out) }))) stats::na.omit(order_file) lists_of_genes<-as.array(lapply(1:number_of_k, function(i){ c=i isna_cluster=is.na(order_file[,((c-1)*2)+2]) if(!(sum(!isna_cluster)==0)){ list_genes<-order_file[,c(((c-1)*2)+1,((c-1)*2)+2)] list_genes<-list_genes[list_genes[,2]<p_val,] #order_file_s=order_file[order_file[,((c-1)*2)+2]<p_val, ] list_genes<-list_genes[(list_genes[,1]>OR)|(list_genes[,1]<(-OR)),] #order_file_s2=order_file_s[order_file_s[,((c-1)*2)+1]>OR|order_file_s[,((c-1)*2)+1]<(-OR), ] #order_file_s2=order_file_s2[order(order_file_s2[,((c-1)*2)+1], decreasing = T), ] list_genes<-list_genes[order(list_genes[,1],decreasing = T),] cluster_genes=rownames(list_genes) if(length(cluster_genes)==0) return(NA) else return(list_genes) }else{ return(NA) } })) ordert_genes=as.array(lapply(1:number_of_k, function(i){ c=i isna_cluster=is.na(order_file[,((c-1)*2)+2]) if(!(sum(!isna_cluster)==0)){ order_file_s=order_file[order_file[,((c-1)*2)+2]<p_val, ] order_file_s2=order_file_s[order_file_s[,((c-1)*2)+1]>OR|order_file_s[,((c-1)*2)+1]<(-OR), ] order_file_s2=order_file_s2[order(order_file_s2[,((c-1)*2)+1], decreasing = T), ] cluster_genes=rownames(order_file_s2) if(length(cluster_genes)==0) return(NA) else return(mx[cluster_genes, ]) }else{ return(NA) } })) remove_from_file<-do.call(rbind,lapply(1:number_of_k, function(i){ if(is.na(ordert_genes[[i]])){ return(F) }else{ return(T) } })) index<-remove_from_file[,1] ordert_genes<-ordert_genes[index] return(list(ordert_genes,lists_of_genes)) print("########################## Finish with EXReg ##################################################") } }
/scratch/gouwar.j/cran-all/cranData/AutoPipe/R/supVisGenes.R
#' A Function for Assisting Supervised Clustering #' #' when perfoming a supervised clustering the user should run this function in order to get the best results. #' @usage top_supervised(me,TOP=1000,cluster_which,TRw=-1) #' @param me the matrix of the gene exporessions, the olums should be the samples and the colnames the sample names #' the rownames should be the genes . at best the ENTEREZID #' @param TOP the top genes to choose, default is 100. #' @param cluster_which a dataframe with the supervised clustering arrangment of the samples. the dataframe should have the #' sample names in the first column and the clustering in the secound column. #' @param TRw the threshhold for excluding samples with silhouette width < TRw #' @return a list. the first place is the expression matrix, the secound is the silhouette for each sample. #' @export top_supervised #' @examples #' #' #' library(org.Hs.eg.db) #' data(rna) #' cluster_which<-cbind(colnames(rna),c(rep(1,times=24),rep(2,times=24))) #' me_x=rna #' ## calculate best number of clusters and #' res<-top_supervised(me_x,TOP = 100,cluster_which) #' me_TOP=res[[1]] #' number_of_k=2 #' groups_men=res[[2]] #' me_x=me_TOP #' colnames(me_x) #' o_g<-Supervised_Cluster_Heatmap(groups_men = groups_men, gene_matrix=me_x, #' method="PAMR",show_sil=TRUE,print_genes=TRUE,threshold = 0, #' TOP = 100,GSE=FALSE,plot_mean_sil=FALSE,stats_clust=res[[2]], #' samples_data = as.data.frame(groups_men[,1,drop=FALSE])) #' top_supervised<-function(me,TOP=1000,cluster_which,TRw=-1){ dim(me) sd=as.data.frame(apply(me,1, function(x){sd(x)})) sd=as.data.frame(sd[order(sd[,1], decreasing = T), ,drop = FALSE]) me_TOP=me[rownames(sd)[1:TOP], ] dim(me_TOP) dist_mat<-as.matrix(cluster::daisy(t(me_TOP))) cluster_which<-as.data.frame(cluster_which) cluster_which[,2]<-as.numeric(cluster_which[,2]) sil<-sil_width(cluster_which,dist_mat) groups_men<-cbind(as.data.frame(cluster_which),sil) groups_men[,2]<-as.numeric(groups_men[,2]) groups_men[,3]<-as.numeric(groups_men[,3]) rownames(groups_men)<-groups_men[,1] colnames(groups_men)<-c("sample","cluster","sil_width") groups_men<-groups_men[order(groups_men$cluster),] groups_men<-groups_men[,-1] groups_men<-groups_men[groups_men[,2]>TRw, ] Exp=(me[, rownames(groups_men)]) return(list(Exp,groups_men)) }
/scratch/gouwar.j/cran-all/cranData/AutoPipe/R/top_supervised.R
library(org.Hs.eg.db) options(shiny.maxRequestSize=1000*1024^2) server <- function(input, output) { output$distPlot <- renderPlot({ # input$file1 will be NULL initially. After the user selects # and uploads a file, head of that data file by default, # or all rows if selected, will be shown. req(input$file1) if(input$show_clin) req(input$file2) # when reading semicolon separated files, # having a comma separator causes `read.csv` to error tryCatch( { if(input$read_expr_file == "FALSE"){ df <-read.csv(input$file1$datapath, sep = input$sep1,row.names = 1) }else{ df <-read_expression_file(file= input$file1$datapath, format = "csv", sep=input$sep1,gene_name="SYMBOL", Trans=input$Trans) } samples_data <- read.csv(input$file2$datapath, sep = input$sep2,row.names = 1) }, error = function(e) { # return a safeError if a parsing error occurs stop(safeError(e)) } ) if(input$read_expr_file == "FALSE") { me_x=df ## calculate best number of clusters and res<-AutoPipe::TopPAM(me_x,max_clusters = input$max_clust, TOP=input$TOP) me_TOP=res[[1]] number_of_k=res[[3]] File_genes=AutoPipe::Groups_Sup(me_TOP, me=me_x, number_of_k,TRw=-1) groups_men=File_genes[[2]] me_x=File_genes[[1]] if(input$show_clin){ print((samples_data)) o_g<-AutoPipe::Supervised_Cluster_Heatmap(groups_men = groups_men, gene_matrix=me_x, method="PAMR",show_sil=input$show_sil,print_genes=input$print_genes,genes_to_print = input$genes_to_print,TOP_Cluster = input$TOP_Cluster, topPaths = input$topPaths,threshold = input$threshold,samples_data = samples_data, TOP = input$TOP,GSE=input$GSE,plot_mean_sil=input$plot_mean_sil,sil_mean=res[[2]],db = input$db) }else{ o_g<-AutoPipe::Supervised_Cluster_Heatmap(groups_men = groups_men, gene_matrix=me_x, method="PAMR",show_sil=input$show_sil,print_genes=input$print_genes,genes_to_print = input$genes_to_print,TOP_Cluster = input$TOP_Cluster, topPaths = input$topPaths,threshold = input$threshold, TOP = input$TOP,GSE=input$GSE,plot_mean_sil=input$plot_mean_sil,sil_mean=res[[2]],db = input$db) } } else { return(df) } }) }
/scratch/gouwar.j/cran-all/cranData/AutoPipe/inst/shiny-examples/myapp/server.R
# Define UI ui <- fluidPage( # Application title titlePanel("AutoPipe"), sidebarLayout( # Sidebar with a slider input sidebarPanel( checkboxInput("show_sil", "Show Silhouette width", FALSE), checkboxInput("show_clin", "Show Clinical Data", FALSE), checkboxInput("print_genes", "Print Genes", FALSE), checkboxInput("GSE", "Show Gene Set Enrichment Analysis", FALSE), checkboxInput("plot_mean_sil", "Show Mean Silhouette width", FALSE), sliderInput("TOP", "Number of genes to Cluster:", min = 1000, max = 10000, step = 1000, value = 1000), sliderInput("max_clust", "Maximum number of clusters to check:", min = 2, max = 20, step = 1, value = 8), sliderInput("TOP_Cluster", "Number of Genes to diplay in each Cluster:", min = 25, max = 1000, value = 150), sliderInput("genes_to_print", "The top genes to print:", min = 5, max = 9, value = 5), sliderInput("topPaths", "The top pathsways to print:", min = 5, max = 9, value = 5), sliderInput("threshold", "Threshold for selecting genes:", min = 0, max = 5, step = 0.1, value = 2), selectInput("db", "Database for GSE:", c("C1" = "c1", "C2" = "c2", "C3" = "c3", "C4" = "c4", "C5" = "c5", "C6" = "c6", "C7" = "c7")), tags$hr(), fileInput("file1", "Choose CSV File for expression data", accept = c( "text/csv", "text/comma-separated-values,text/plain", ".csv") ), radioButtons("sep1", "Separator", choices = c(Comma = ",", Semicolon = ";", Tab = "\t"), selected = ","), checkboxInput("read_expr_file", "Format expression file", FALSE), checkboxInput("Trans", "Rows are Samples", FALSE), tags$hr(), fileInput("file2", "Choose CSV File for sample traits", accept = c( "text/csv", "text/comma-separated-values,text/plain", ".csv") ), radioButtons("sep2", "Separator", choices = c(Comma = ",", Semicolon = ";", Tab = "\t"), selected = ",") ), # Show a plot of the generated distribution mainPanel( plotOutput("distPlot",width = "100%",height = "800px") ) ) ) ##samples_data=NULL,plot_mean_sil=FALSE,threshold=2
/scratch/gouwar.j/cran-all/cranData/AutoPipe/inst/shiny-examples/myapp/ui.R
# AutoPlots is a package for quickly creating high quality visualizations under a common and easy api. # Copyright (C) <year> <name of author> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WAfppRRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <https://www.gnu.org/licenses/>. # @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ---- # :: Helper Functions :: ---- # @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ---- #' @noRd SummaryFunction <- function(AggMethod) { if(AggMethod == "count") { aggFunc <- function(x) .N } else if(AggMethod == "mean") { aggFunc <- function(x) mean(x, na.rm = TRUE) } else if(AggMethod == "log(mean(x))") { aggFunc <- function(x) log(mean(x, na.rm = TRUE)) } else if(AggMethod == "mean(abs(x))") { aggFunc <- function(x) mean(abs(x), na.rm = TRUE) } else if(AggMethod == "sum") { aggFunc <- function(x) sum(x, na.rm = TRUE) } else if(AggMethod == "log(sum(x))") { aggFunc <- function(x) log(sum(x, na.rm = TRUE)) } else if(AggMethod == "sum(abs(x))") { aggFunc <- function(x) sum(abs(x), na.rm = TRUE) } else if(AggMethod == "median") { aggFunc <- function(x) median(x, na.rm = TRUE) } else if(AggMethod == "log(median(x))") { aggFunc <- function(x) log(median(x, na.rm = TRUE)) } else if(AggMethod == "median(abs(x))") { aggFunc <- function(x) median(abs(x), na.rm = TRUE) } else if(AggMethod == "sd") { aggFunc <- function(x) sd(x, na.rm = TRUE) } else if(AggMethod == "log(sd(x))") { aggFunc <- function(x) log(sd(x, na.rm = TRUE)) } else if(AggMethod == "sd(abs(x))") { aggFunc <- function(x) sd(abs(x), na.rm = TRUE) } else if(AggMethod == "skewness") { aggFunc <- function(x) e1071::skewness(x, na.rm = TRUE) } else if(AggMethod == "skewness(abs(x))") { aggFunc <- function(x) e1071::skewness(abs(x), na.rm = TRUE) } else if(AggMethod == "kurtosis") { aggFunc <- function(x) e1071::kurtosis(x, na.rm = TRUE) } else if(AggMethod == "kurtosis(abs(x))") { aggFunc <- function(x) e1071::kurtosis(abs(x), na.rm = TRUE) } else if(AggMethod == "CoeffVar") { aggFunc <- function(x) sd(x, na.rm = TRUE) / mean(x, na.rm = TRUE) } else if(AggMethod == "CoeffVar(abs(x))") { aggFunc <- function(x) sd(abs(x), na.rm = TRUE) / mean(abs(x), na.rm = TRUE) } return(aggFunc) } #' @noRd ColTypes <- function(data) { CT <- c() for(Col in names(data)) CT <- c(CT, class(data[[Col]])[1L]) CT } #' @noRd bold_ <- function(x) paste0('<b>',x,'</b>') #' @noRd font_ <- function(family = "Segoe UI Symbol", size = 12, color = 'white') list(family = family, size = size, color = color) #' @noRd ColNameFilter <- function(data, Types = 'all') { if(Types == 'all') return(names(data)) nam <- c() for(t in Types) { if(tolower(t) == 'numeric') { nam <- NumericColNames(data) } else if(tolower(t) == 'character') { nam <- CharacterColNames(data) } else if(tolower(t) == 'factor') { nam <- FactorColNames(data) } else if(tolower(t) == 'logical') { nam <- LogicalColNames(data) } else if(tolower(t) %chin% c("date","idate","idatetime","posixct","posix")) { nam <- DateColNames(data) } } return(nam) } #' @noRd NumericColNames <- function(data) { x <- as.list(names(data)[which(sapply(data, is.numeric))]) if(!identical(x, character(0))) return(x) else return(NULL) } #' @noRd CharacterColNames <- function(data) { x <- as.list(names(data)[which(sapply(data, is.character))]) if(!identical(x, character(0))) return(x) else return(NULL) } #' @noRd FactorColNames <- function(data) { x <- as.list(names(data)[which(sapply(data, is.factor))]) if(!identical(x, character(0))) return(x) else return(NULL) } #' @noRd LogicalColNames <- function(data) { x <- as.list(names(data)[which(sapply(data, is.logical))]) if(!identical(x, character(0))) return(x) else return(NULL) } #' @noRd DateColNames <- function(data) { x <- list() counter <- 0L for(i in names(data)) { if(class(data[[i]])[1L] %in% c("IDate","Date","date","POSIXct","POSIX")) { counter <- counter + 1L x[[counter]] <- i } } if(length(x) > 0L) return(x) else return(NULL) } #' # text & logical with NULL default #' @noRd CEP <- function(x) if(any(missing(x))) 'NULL' else if(!exists('x')) 'NULL' else if(is.null(x)) "NULL" else if(identical(x, character(0))) "NULL" else if(identical(x, numeric(0))) "NULL" else if(identical(x, integer(0))) "NULL" else if(identical(x, logical(0))) "NULL" else if(any(x == "")) "NULL" else if(any(is.na(x))) "NULL" else if(any(x == 'None')) "NULL" else if(is.numeric(x)) x else if(length(x) > 1) paste0("c(", noquote(paste0("'", x, "'", collapse = ',')), ")") else paste0("'", x, "'") #' # number and logical with FALSE / TRUE default #' @noRd CEPP <- function(x, Default = NULL, Type = 'character') if(missing(x)) 'NULL' else if(!exists('x')) 'NULL' else if(length(x) == 0) 'NULL' else if(any(is.na(x))) 'NULL' else if(all(x == "")) 'NULL' else if(Type == 'numeric') NumNull(x) else if(Type == 'character') CharNull(x) #' @title ExpandText #' #' @description This function is for pasting character vector arguments into their respective parameter slots for code printing (and command line vector argument passing) #' #' #' @noRd ExpandText <- function(x) { if(length(x) > 0L) { if(is.character(x) || is.factor(x) || lubridate::is.Date(x) || lubridate::is.POSIXct(x)) { return(paste0("c('", paste0(x, collapse = "','"), "')")) } else if(is.numeric(x) || is.logical(x)) { return(paste0("c(", paste0(x, collapse = ","), ")")) } } else { return('NULL') } } #' @title CharNull #' #' @param x Value #' #' @noRd CharNull <- function(x, Char = FALSE) { if(missing(x)) { return(NULL) } if(!exists('x')) { return(NULL) } if(length(x) == 0) { return(NULL) } if(all(is.na(suppressWarnings(as.character(x))))) { return(NULL) } else if(any(is.na(suppressWarnings(as.character(x)))) && length(x) > 1) { x <- x[!is.na(x)] x <- suppressWarnings(as.character(x)) return(x) } else if(any(is.na(suppressWarnings(as.character(x)))) && length(x) == 1) { return(NULL) } else { x <- suppressWarnings(as.character(x)) return(x) } if(!Char) { return(NULL) } else { return("NULL") } } #' @title FakeDataGenerator #' #' @description Create fake data for examples #' #' @author Adrian Antico #' @family Data Wrangling #' #' @param Correlation Set the correlation value for simulated data #' @param N Number of records #' @param ID Number of IDcols to include #' @param ZIP Zero Inflation Model target variable creation. Select from 0 to 5 to create that number of distinctly distributed data, stratifed from small to large #' @param FactorCount Number of factor type columns to create #' @param AddDate Set to TRUE to include a date column #' @param AddComment Set to TRUE to add a comment column #' @param AddWeightsColumn Add a weights column for ML #' @param ChainLadderData Set to TRUE to return Chain Ladder Data for using AutoMLChainLadderTrainer #' @param Classification Set to TRUE to build classification data #' @param MultiClass Set to TRUE to build MultiClass data #' #' @return data.table of data #' @export FakeDataGenerator <- function(Correlation = 0.70, N = 1000L, ID = 5L, FactorCount = 2L, AddDate = TRUE, AddComment = FALSE, AddWeightsColumn = FALSE, ZIP = 5L, ChainLadderData = FALSE, Classification = FALSE, MultiClass = FALSE) { # Error checking if(sum(Classification, MultiClass) > 1) stop("Only one of the following can be set to TRUE: Classifcation, and MultiClass") # Create ChainLadderData if(ChainLadderData) { # Overwrite N N <- 1000 # Define constants MaxCohortDays <- 15L # Start date CalendarDateData <- data.table::data.table(CalendarDateColumn = rep(as.Date("2018-01-01"), N), key = "CalendarDateColumn") # Increment date column so it is sequential CalendarDateData[, temp := seq_len(N)] CalendarDateData[, CalendarDateColumn := CalendarDateColumn + lubridate::days(temp) - 1L] CohortDate_temp <- data.table::copy(CalendarDateData) data.table::setnames(x = CohortDate_temp, old = c("CalendarDateColumn"), new = c("CohortDate_temp")) # Cross join the two data sets ChainLadderData <- data.table::setkeyv(data.table::CJ( CalendarDateColumn = CalendarDateData$CalendarDateColumn, CohortDateColumn = CohortDate_temp$CohortDate_temp, sorted = TRUE, unique = TRUE), cols = c("CalendarDateColumn", "CohortDateColumn")) # Remove starter data sets and N rm(CalendarDateData, CohortDate_temp, N) # Remove impossible dates ChainLadderData <- ChainLadderData[CohortDateColumn >= CalendarDateColumn] # Add CohortPeriods ChainLadderData[, CohortDays := as.numeric(difftime(CohortDateColumn, CalendarDateColumn, tz = "MST", units = "day"))] # Limit the number of CohortTime ChainLadderData <- ChainLadderData[CohortDays < MaxCohortDays] # Add measure columns placeholder values ChainLadderData[, ":=" (Leads = 0, Appointments = 0, Rates = 0)] # Sort decending both date columns data.table::setorderv(x = ChainLadderData, cols = c("CalendarDateColumn","CohortDateColumn"), order = c(-1L, 1L)) # Add columns for BaselineMeasure and ConversionMeasure UniqueCalendarDates <- unique(ChainLadderData$CalendarDateColumn) NN <- length(UniqueCalendarDates) LoopSeq <- c(1:15) LoopSeq <- cumsum(LoopSeq) LoopSeq <- c(1, LoopSeq) LoopSeq <- c(LoopSeq, seq(135, 15*993, 15)) for(cal in seq(NN)) { # Generate first element of decay data DecayCurveData <- dgeom(x = 0, prob = runif(n = 1L, min = 0.45, max = 0.55), log = FALSE) # Fill in remain elements in vector if(cal > 1L) { zz <- seq_len(min(15L, cal)) for(i in zz[1:min(cal-1L,15)]) { DecayCurveData <- c(DecayCurveData, c(dgeom(x = i, prob = runif(n = 1L, min = 0.45, max = 0.55), log = FALSE))) } } # Fill ChainLadderData data.table::set(ChainLadderData, i = (LoopSeq[cal]+1L):LoopSeq[cal + 1L], j = "Rates", value = DecayCurveData[seq_len(min(15L, cal))]) } # Fill in Leads and Conversions---- x <- unique(ChainLadderData[, .SD, .SDcols = c("CalendarDateColumn","Leads")]) x[, Leads := runif(n = x[, .N], min = 100, max = 500)] ChainLadderData <- merge(ChainLadderData[, .SD, .SDcols = c("CalendarDateColumn","CohortDateColumn","CohortDays","Appointments","Rates")], x, by = "CalendarDateColumn", all = FALSE) ChainLadderData[, Appointments := Leads * Rates] ChainLadderData[, Sales := Appointments * Rates * (runif(.N))] ChainLadderData[, Rates := NULL] data.table::setcolorder(ChainLadderData, c(1,2,3,5,4)) return(ChainLadderData) } # Modify---- if(MultiClass && FactorCount == 0L) { FactorCount <- 1L temp <- 1L } # Create data---- Correl <- Correlation data <- data.table::data.table(Adrian = runif(N)) data[, x1 := qnorm(Adrian)] data[, x2 := runif(N)] data[, Independent_Variable1 := (pnorm(Correl * x1 + sqrt(1-Correl^2) * qnorm(x2)))] data[, Independent_Variable2 := log(pnorm(Correl * x1 + sqrt(1-Correl^2) * qnorm(x2)))] data[, Independent_Variable3 := exp(pnorm(Correl * x1 + sqrt(1-Correl^2) * qnorm(x2)))] data[, Independent_Variable4 := exp(exp(pnorm(Correl * x1 + sqrt(1-Correl^2) * qnorm(x2))))] data[, Independent_Variable5 := sqrt(pnorm(Correl * x1 + sqrt(1-Correl^2) * qnorm(x2)))] data[, Independent_Variable6 := (pnorm(Correl * x1 + sqrt(1-Correl^2) * qnorm(x2)))^0.10] data[, Independent_Variable7 := (pnorm(Correl * x1 + sqrt(1-Correl^2) * qnorm(x2)))^0.25] data[, Independent_Variable8 := (pnorm(Correl * x1 + sqrt(1-Correl^2) * qnorm(x2)))^0.75] data[, Independent_Variable9 := (pnorm(Correl * x1 + sqrt(1-Correl^2) * qnorm(x2)))^2] data[, Independent_Variable10 := (pnorm(Correl * x1 + sqrt(1-Correl^2) * qnorm(x2)))^4] if(ID > 0L) for(i in seq_len(ID)) data[, paste0("IDcol_", i) := runif(N)] data[, ":=" (x2 = NULL)] # FactorCount---- for(i in seq_len(FactorCount)) { RandomValues <- sort(c(runif(n = 4L, min = 0.01, max = 0.99))) RandomLetters <- sort(c(sample(x = LETTERS, size = 5L, replace = FALSE))) data[, paste0("Factor_", i) := as.factor( data.table::fifelse(Independent_Variable1 < RandomValues[1L], RandomLetters[1L], data.table::fifelse(Independent_Variable1 < RandomValues[2L], RandomLetters[2L], data.table::fifelse(Independent_Variable1 < RandomValues[3L], RandomLetters[3L], data.table::fifelse(Independent_Variable1 < RandomValues[4L], RandomLetters[4L], RandomLetters[5L])))))] } # Add date---- if(AddDate) { if(FactorCount == 0) { data <- data[, DateTime := as.Date(Sys.time())] data[, temp := seq_len(.N)][, DateTime := DateTime - temp][, temp := NULL] data <- data[order(DateTime)] } else { data <- data[, DateTime := as.Date(Sys.time())] CatFeatures <- sort(c(as.numeric(which(sapply(data, is.factor))), as.numeric(which(sapply(data, is.character))))) data[, temp := seq_len(.N), by = c(names(data)[c(CatFeatures)])][, DateTime := DateTime - temp][, temp := NULL] data.table::setorderv(x = data, cols = c("DateTime", c(names(data)[c(CatFeatures)])), order = rep(1, length(c(names(data)[c(CatFeatures)]))+1)) } } # Zero Inflation Setup if(!Classification && !MultiClass) { if(ZIP == 1L) { data[, Adrian := data.table::fifelse(Adrian < 0.5, 0, Independent_Variable8)][, Independent_Variable8 := NULL] } else if(ZIP == 2L) { data[, Adrian := data.table::fifelse(Adrian < 0.33, 0, data.table::fifelse(Adrian < 0.66, log(Adrian * 10), log(Adrian*20)))] } else if(ZIP == 3L) { data[, Adrian := data.table::fifelse(Adrian < 0.25, 0, data.table::fifelse(Adrian < 0.50, log(Adrian * 10), data.table::fifelse(Adrian < 0.75, log(Adrian * 50), log(Adrian * 150))))] } else if(ZIP == 4L) { data[, Adrian := data.table::fifelse(Adrian < 0.20, 0, data.table::fifelse(Adrian < 0.40, log(Adrian * 10), data.table::fifelse(Adrian < 0.60, log(Adrian * 50), data.table::fifelse(Adrian < 0.80, log(Adrian * 150), log(Adrian * 250)))))] } else if(ZIP == 5L) { data[, Adrian := data.table::fifelse(Adrian < 1/6, 0, data.table::fifelse(Adrian < 2/6, log(Adrian * 10), data.table::fifelse(Adrian < 3/6, log(Adrian * 50), data.table::fifelse(Adrian < 4/6, log(Adrian * 250), data.table::fifelse(Adrian < 5/6, log(Adrian * 500), log(Adrian * 1000))))))] } } # Classification if(Classification) data[, Adrian := data.table::fifelse(jitter(x = Adrian, factor = 100) > 0.63, 1, 0)] # Remove---- data[, ":=" (x1 = NULL)] # MultiClass if(MultiClass) { data[, Adrian := NULL] data.table::setnames(data, "Factor_1", "Adrian") } # Comment data if(AddComment) { a <- c('Hello', 'Hi', 'Howdy', 'House', 'Someone', 'Watching', 'You') b <- c('really like', 'absolutely adore', 'mediocre', 'great', 'stochastic') c <- c('noload', 'download', 'upload', 'Burn Notice', 'The Office') N1 <- 1/length(a) N2 <- 1/length(b) N3 <- 1/length(c) N11 <- 1/N1 N22 <- 1/N2 N33 <- 1/N3 RandomText <- function(N1,N11,N2,N22,N3,N33,a,b,c) { paste(sample(x = a, size = 1, replace = TRUE, prob = rep(N1, N11)), sample(x = b, size = 1, replace = TRUE, prob = rep(N2, N22)), sample(x = c, size = 1, replace = TRUE, prob = rep(N3, N33))) } data[, Comment := "a"] for(i in seq_len(data[, .N])) { data.table::set(data, i = i, j = "Comment", value = RandomText(N1,N11,N2,N22,N3,N33,a,b,c)) } } # Add weights column if(AddWeightsColumn) { data[, Weights := runif(.N)] } # Return data return(data) } #' @title Standardize #' #' @description Generate standardized values for multiple variables, by groups if provided, and with a selected granularity #' #' @author Adrian Antico #' @family Feature Engineering #' #' @param data Source data.table #' @param ColNames Character vector of column names #' @param GroupVars Character vector of column names to have percent ranks by the group levels #' @param Center TRUE #' @param Scale TRUE #' @param ScoreTable FALSE. Set to TRUE to return a data.table that can be used to apply or backtransform via StandardizeScoring #' #' @noRd Standardize <- function(data, ColNames, GroupVars = NULL, Center = TRUE, Scale = TRUE, ScoreTable = FALSE) { # Standardize if(length(GroupVars) == 0L) { data[, paste0(ColNames, '_Standardize') := lapply(.SD, FUN = function(x) (x - mean(x, na.rm = TRUE)) / sd(x, na.rm = TRUE)), .SDcols = c(ColNames)] } else { data[, paste0(ColNames, '_Standardize') := lapply(.SD, FUN = function(x) (x - mean(x, na.rm = TRUE)) / sd(x, na.rm = TRUE)), .SDcols = c(ColNames), by = c(eval(GroupVars))] } # ScoreTable creation if(ScoreTable) { x <- data[, lapply(.SD, mean, na.rm = TRUE), .SDcols = c(ColNames), by = c(GroupVars)] data.table::setnames(x = x, old = ColNames, new = paste0(ColNames, "_mean")) y <- data[, lapply(.SD, sd, na.rm = TRUE), .SDcols = c(ColNames), by = c(GroupVars)] data.table::setnames(x = y, old = ColNames, new = paste0(ColNames, "_sd")) xy <- cbind(x,y[, (GroupVars) := NULL]) } # Return if(!ScoreTable) { return(data) } else { return(list( data = data, ScoreTable = xy )) } } #' @title StandardizeScoring #' #' @description Generate standardized values for multiple variables, by groups if provided, and with a selected granularity #' #' @author Adrian Antico #' @family Feature Engineering #' #' @param data Source data.table #' @param Apply 'apply' or 'backtransform' #' @param ColNames Character vector of column names #' @param GroupVars Character vector of column names to have percent ranks by the group levels #' @param Center TRUE #' @param Scale TRUE #' #' @noRd StandardizeScoring <- function(data, ScoreTable, Apply = 'apply', GroupVars = NULL) { # Facts nam <- names(ScoreTable)[which(!names(ScoreTable) %in% GroupVars)] # Apply will apply standardization to new data # Backtransform will undo standardization if(Apply == 'apply') { data.table::setkeyv(x = data, cols = GroupVars) data.table::setkeyv(x = ScoreTable, cols = GroupVars) data[ScoreTable, paste0(nam) := mget(paste0('i.', nam))] nams <- nam[seq_len(length(nam) / 2)] ColNames <- gsub(pattern = "_mean", replacement = "", x = nams) for(i in ColNames) data[, paste0(i, "_Standardize") := (get(i) - get(paste0(i, "_mean"))) / get(paste0(i, "_sd"))] data.table::set(data, j = c(nam), value = NULL) } else { data.table::setkeyv(x = data, cols = GroupVars) data.table::setkeyv(x = ScoreTable, cols = GroupVars) data[ScoreTable, paste0(nam) := mget(paste0('i.', nam))] nams <- nam[seq_len(length(nam) / 2)] ColNames <- gsub(pattern = "_mean", replacement = "", x = nams) for(i in ColNames) data[, eval(i) := get(paste0(i, "_Standardize")) * get(paste0(i, "_sd")) + get(paste0(i, "_mean"))] data.table::set(data, j = c(nam), value = NULL) } # Return return(data) } #' @title PercRank #' #' @description Generate percent ranks for multiple variables, by groups if provided, and with a selected granularity #' #' @author Adrian Antico #' @family Feature Engineering #' #' @param data Source data.table #' @param ColNames Character vector of column names #' @param GroupVars Character vector of column names to have percent ranks by the group levels #' @param Granularity Provide a value such that data.table::frank(Variable) * (1 / Granularity) / .N * Granularity. Default is 0.001 #' @param ScoreTable = FALSE. Set to TRUE to get the reference values for applying to new data. Pass to scoring version of this function #' #' @noRd PercRank <- function(data, ColNames, GroupVars = NULL, Granularity = 0.001, ScoreTable = FALSE) { if(length(GroupVars) == 0L) { data[, paste0(ColNames, '_PercRank') := lapply(.SD, FUN = function(x) data.table::frank(x) * (1 / Granularity) / .N * Granularity), .SDcols = c(ColNames)] } else { data[, paste0(ColNames, '_PercRank') := lapply(.SD, FUN = function(x) data.table::frank(x) * (1 / Granularity) / .N * Granularity), .SDcols = c(ColNames), by = c(eval(GroupVars))] } if(!ScoreTable) { return(data) } else { return(list( data = data, ScoreTable = unique(data[, .SD, .SDcols = c(ColNames, paste0(ColNames, '_PercRank'))]) )) } } #' Test YeoJohnson Transformation #' #' @author Adrian Antico #' @family Feature Engineering #' @noRd #' @param x The data in numerical vector form #' @param eps erorr tolerance #' @param ... Arguments to pass along #' @return YeoJohnson results Test_YeoJohnson <- function(x, eps = 0.001, ...) { stopifnot(is.numeric(x)) lambda <- Estimate_YeoJohnson_Lambda(x, eps = eps, ...) trans_data <- x na_idx <- is.na(x) trans_data[!na_idx] <- Apply_YeoJohnson(x[!na_idx], lambda, eps) mu <- mean(trans_data, na.rm = TRUE) sigma <- sd(trans_data, na.rm = TRUE) trans_data_standardized <- (trans_data - mu) / sigma ptest <- nortest::pearson.test(trans_data_standardized) val <- list(Name = "YeoJohnson", Data = trans_data, Lambda = lambda, Normalized_Statistic = unname(ptest$statistic / ptest$df)) return(val) } #' Estimate YeoJohnson Transformation #' #' @author Adrian Antico #' @family Feature Engineering #' @noRd #' @param x The data in numerical vector form #' @param lower the lower bound for search #' @param upper the upper bound for search #' @param eps erorr tolerance #' @return YeoJohnson results Estimate_YeoJohnson_Lambda <- function(x, lower = -5, upper = 5, eps = 0.001) { n <- length(x) ccID <- !is.na(x) x <- x[ccID] # See references, Yeo & Johnson Biometrika (2000) yj_loglik <- function(lambda) { x_t <- Apply_YeoJohnson(x, lambda, eps) x_t_bar <- mean(x_t) x_t_var <- var(x_t) * (n - 1) / n constant <- sum(sign(x) * log(abs(x) + 1)) - 0.5 * n * log(x_t_var) + (lambda - 1) * constant } results <- optimize( yj_loglik, lower = lower, upper = upper, maximum = TRUE, tol = .0001) return(results$maximum) } #' Apply YeoJohnson Transformation #' #' @author Adrian Antico #' @family Feature Engineering #' @noRd #' @param x The data in numerical vector form #' @param lambda optimal lambda #' @param eps erorr tolerance #' @return YeoJohnson results Apply_YeoJohnson <- function(x, lambda, eps = 0.001) { pos_idx <- x >= 0 neg_idx <- x < 0 # Transform negative values if(any(pos_idx)) { if(abs(lambda) < eps) { x[pos_idx] <- log(x[pos_idx] + 1) } else { x[pos_idx] <- ((x[pos_idx] + 1) ^ lambda - 1) / lambda } } # Transform nonnegative values if(any(neg_idx)) { if(abs(lambda - 2) < eps) { x[neg_idx] <- -log(-x[neg_idx] + 1) } else { x[neg_idx] <- -((-x[neg_idx] + 1) ^ (2 - lambda) - 1) / (2 - lambda) } } return(x) } #' Inverse YeoJohnson Transformation #' #' @author Adrian Antico #' @family Feature Engineering #' @noRd #' @param x The data in numerical vector form #' @param lambda optimal lambda #' @param eps erorr tolerance #' @return YeoJohnson results InvApply_YeoJohnson <- function(x, lambda, eps = 0.001) { val <- x neg_idx <- x < 0 if(any(!neg_idx)) { if(abs(lambda) < eps) { val[!neg_idx] <- exp(x[!neg_idx]) - 1 } else { val[!neg_idx] <- (x[!neg_idx] * lambda + 1) ^ (1 / lambda) - 1 } } if(any(neg_idx)) { if(abs(lambda - 2) < eps) { val[neg_idx] <- -expm1(-x[neg_idx]) } else { val[neg_idx] <- 1 - (-(2 - lambda) * x[neg_idx] + 1) ^ (1 / (2 - lambda)) } } return(val) } #' Test BoxCox Transformation #' #' @author Adrian Antico #' @family Feature Engineering #' @noRd #' @param x The data in numerical vector form #' @param ... Arguments to pass along #' @return BoxCox results Test_BoxCox <- function(x, ...) { stopifnot(is.numeric(x)) lambda <- Estimate_BoxCox_Lambda(x, ...) trans_data <- Apply_BoxCox(x, lambda) mu <- mean(trans_data, na.rm = TRUE) sigma <- sd(trans_data, na.rm = TRUE) trans_data_standardized <- (trans_data - mu) / sigma ptest <- nortest::pearson.test(trans_data_standardized) val <- list(Name = "BoxCox", Data = trans_data, Lambda = lambda, Normalized_Statistic = unname(ptest$statistic / ptest$df)) return(val) } #' Estimate BoxCox Transformation #' #' @author Adrian Antico #' @family Feature Engineering #' @noRd #' @param x The data in numerical vector form #' @param lower the lower bound for search #' @param upper the upper bound for search #' @param eps erorr tolerance #' @return BoxCox results Estimate_BoxCox_Lambda <- function(x, lower = -1, upper = 2, eps = 0.001) { n <- length(x) ccID <- !is.na(x) x <- x[ccID] if (any(x <= 0)) stop("x must be positive") log_x <- log(x) xbar <- exp(mean(log_x)) fit <- lm(x ~ 1, data = data.frame(x = x)) xqr <- fit$qr boxcox_loglik <- function(lambda) { if (abs(lambda) > eps) xt <- (x ^ lambda - 1) / lambda else xt <- log_x * (1 + (lambda * log_x) / 2 * (1 + (lambda * log_x) / 3 * (1 + (lambda * log_x) / 4))) - n / 2 * log(sum(qr.resid(xqr, xt / xbar ^ (lambda - 1)) ^ 2)) } results <- optimize( boxcox_loglik, lower = lower, upper = upper, maximum = TRUE, tol = .0001) return(results$maximum) } #' Apply BoxCox Transformation #' #' @author Adrian Antico #' @family Feature Engineering #' @noRd #' @param x The data in numerical vector form #' @param lambda optimal lambda #' @param eps erorr tolerance #' @return BoxCox results Apply_BoxCox <- function(x, lambda, eps = 0.001) { if(lambda < 0) x[x < 0] <- NA if(abs(lambda) < eps) { val <- log(x) } else { val <- (sign(x) * abs(x) ^ lambda - 1) / lambda } return(val) } #' Inverse BoxCox Transformation #' #' @author Adrian Antico #' @family Feature Engineering #' @noRd #' @param x The data in numerical vector form #' @param lambda optimal lambda #' @param eps erorr tolerance #' @return BoxCox results InvApply_BoxCox <- function(x, lambda, eps = 0.001) { if(lambda < 0) x[x > -1 / lambda] <- NA if(abs(lambda) < eps) { val <- exp(x) } else { x <- x * lambda + 1 val <- sign(x) * abs(x) ^ (1 / lambda) } return(val) } #' Test Asinh Transformation #' #' @author Adrian Antico #' @family Feature Engineering #' @noRd #' @param x The data in numerical vector form #' @return Asinh results Test_Asinh <- function(x) { stopifnot(is.numeric(x)) trans_data <- asinh(x) mu <- mean(trans_data, na.rm = TRUE) sigma <- sd(trans_data, na.rm = TRUE) trans_data_standardized <- (trans_data - mu) / sigma ptest <- nortest::pearson.test(trans_data_standardized) val <- list(Name = "Asinh", Data = trans_data, Lambda = NA, Normalized_Statistic = unname(ptest$statistic / ptest$df)) return(val) } #' Inverse Asinh Transformation #' #' @author Adrian Antico #' @family Feature Engineering #' @noRd #' @param x The data in numerical vector form #' @return Asinh results Apply_Asinh <- function(x) { return(asinh(x)) } #' Inverse Asinh Transformation #' #' @author Adrian Antico #' @family Feature Engineering #' @noRd #' @param x The data in numerical vector form #' @return Asinh results InvApply_Asinh <- function(x) { return(sinh(x)) } #' Test Asin Transformation #' #' @author Adrian Antico #' @family Feature Engineering #' @noRd #' @param x The data in numerical vector form #' @return Asin results Test_Asin <- function(x) { stopifnot(is.numeric(x)) trans_data <- asin(sqrt(x)) mu <- mean(trans_data, na.rm = TRUE) sigma <- sd(trans_data, na.rm = TRUE) trans_data_standardized <- (trans_data - mu) / sigma ptest <- nortest::pearson.test(trans_data_standardized) val <- list(Name = "Asin", Data = trans_data, Lambda = NA, Normalized_Statistic = unname(ptest$statistic / ptest$df)) return(val) } #' Inverse Asin Transformation #' #' @author Adrian Antico #' @family Feature Engineering #' @noRd #' @param x The data in numerical vector form #' @return Asin results Apply_Asin <- function(x) { return(asin(sqrt(x))) } #' Inverse Asin Transformation #' #' @author Adrian Antico #' @family Feature Engineering #' @noRd #' @param x The data in numerical vector form #' @return Asin results InvApply_Asin <- function(x) { return(sin(x) ^ 2) } #' Test Logit Transformation #' #' @author Adrian Antico #' @family Feature Engineering #' @noRd #' @param x The data in numerical vector form #' @return Logit results Test_Logit <- function(x) { stopifnot(is.numeric(x)) trans_data <- log(x / (1 - x)) mu <- mean(trans_data, na.rm = TRUE) sigma <- sd(trans_data, na.rm = TRUE) trans_data_standardized <- (trans_data - mu) / sigma ptest <- nortest::pearson.test(trans_data_standardized) val <- list(Name = "Logit", Data = trans_data, Lambda = NA, Normalized_Statistic = unname(ptest$statistic / ptest$df)) return(val) } #' Apply Logit Transformation #' #' @author Adrian Antico #' @family Feature Engineering #' @noRd #' @param x The data in numerical vector form #' @return Logit results Apply_Logit <- function(x) { return(log(x / (1 - x))) } #' Inverse Logit Transformation #' #' @author Adrian Antico #' @family Feature Engineering #' @noRd #' @param x The data in numerical vector form #' @return Logit results InvApply_Logit <- function(x) { return(1 / (1 + exp(-x))) } #' Test Identity Transformation #' #' @author Adrian Antico #' @family Feature Engineering #' @noRd #' @param x The data in numerical vector form #' @return Identity results Test_Identity <- function(x) { stopifnot(is.numeric(x)) x.t <- x mu <- mean(x.t, na.rm = TRUE) sigma <- sd(x.t, na.rm = TRUE) x.t <- (x.t - mu) / sigma ptest <- nortest::pearson.test(x.t) val <- list(Name = "Identity", Data = x, Lambda = NA, Normalized_Statistic = unname(ptest$statistic / ptest$df)) return(val) } #' Test Log Transformation #' #' @author Adrian Antico #' @family Feature Engineering #' @noRd #' @param x The data in numerical vector form #' @return Log results Test_Log <- function(x) { stopifnot(is.numeric(x)) trans_data <- log(x) mu <- mean(trans_data, na.rm = TRUE) sigma <- sd(trans_data, na.rm = TRUE) trans_data_standardized <- (trans_data - mu) / sigma ptest <- nortest::pearson.test(trans_data_standardized) val <- list(Name = "Log", Data = trans_data, Lambda = NA, Normalized_Statistic = unname(ptest$statistic / ptest$df)) return(val) } #' Apply Log Transformation #' #' @author Adrian Antico #' @family Feature Engineering #' @noRd #' @param x The data in numerical vector form #' @return Log results Apply_Log <- function(x) { return(log(x)) } #' Inverse Log Transformation #' #' @author Adrian Antico #' @family Feature Engineering #' @noRd #' @param x The data in numerical vector form #' @return Log results InvApply_Log <- function(x) { return(exp(x)) } #' Test LogPlus1 Transformation #' #' @author Adrian Antico #' @family Feature Engineering #' @noRd #' @param x The data in numerical vector form #' @return LogPlus1 results Test_LogPlus1 <- function(x) { stopifnot(is.numeric(x)) xx <- min(x, na.rm = TRUE) if(xx <= 0) trans_data <- log(x+abs(xx)+1) else trans_data <- log(x) mu <- mean(trans_data, na.rm = TRUE) sigma <- sd(trans_data, na.rm = TRUE) trans_data_standardized <- (trans_data - mu) / sigma ptest <- nortest::pearson.test(trans_data_standardized) val <- list(Name = "LogPlus1", Data = trans_data, Lambda = NA, Normalized_Statistic = unname(ptest$statistic / ptest$df)) return(val) } #' Apply LogPlus1 Transformation #' #' @author Adrian Antico #' @family Feature Engineering #' @noRd #' @param x The data in numerical vector form #' @return Log results Apply_LogPlus1 <- function(x) { return(log(x+1)) } #' Inverse LogPlus1 Transformation #' #' @author Adrian Antico #' @family Feature Engineering #' @noRd #' @param x The data in numerical vector form #' @return Log results InvApply_LogPlus1 <- function(x) { return(exp(x)-1) } #' Test Sqrt Transformation #' #' @author Adrian Antico #' @family Feature Engineering #' @noRd #' @param x The data in numerical vector form #' @return Sqrt results Test_Sqrt <- function(x) { stopifnot(is.numeric(x)) trans_data <- sqrt(x) mu <- mean(trans_data, na.rm = TRUE) sigma <- sd(trans_data, na.rm = TRUE) trans_data_standardized <- (trans_data - mu) / sigma ptest <- nortest::pearson.test(trans_data_standardized) val <- list(Name = "Sqrt", Data = trans_data, Lambda = NA, Normalized_Statistic = unname(ptest$statistic / ptest$df)) return(val) } #' Apply Sqrt Transformation #' #' @author Adrian Antico #' @family Feature Engineering #' @noRd #' @param x The data in numerical vector form #' @return Log results Apply_Sqrt <- function(x) { return(sqrt(x)) } #' Inverse Sqrt Transformation #' #' @author Adrian Antico #' @family Feature Engineering #' @noRd #' @param x The data in numerical vector form #' @return Log results InvApply_Sqrt <- function(x) { return(x^2) } #' @title AutoTransformationCreate #' #' @description AutoTransformationCreate is a function for automatically identifying the optimal transformations for numeric features and transforming them once identified. This function will loop through your selected transformation options (YeoJohnson, BoxCox, Asinh, Asin, and Logit) and find the one that produces data that is the closest to normally distributed data. It then makes the transformation and collects the metadata information for use in the AutoTransformationScore() function, either by returning the objects (always) or saving them to file (optional). #' #' @author Adrian Antico #' @family Feature Engineering #' @param data This is your source data #' @param ColumnNames List your columns names in a vector, for example, c("Target", "IV1") #' @param Methods Choose from "YeoJohnson", "BoxCox", "Asinh", "Log", "LogPlus1", "Asin", "Logit", and "Identity". Note, LogPlus1 runs #' @param Path Set to the directly where you want to save all of your modeling files #' @param TransID Set to a character value that corresponds with your modeling project #' @param SaveOutput Set to TRUE to save necessary file to run AutoTransformationScore() #' @return data with transformed columns and the transformation object for back-transforming later #' @noRd AutoTransformationCreate <- function(data, ColumnNames = NULL, Methods = c("BoxCox","YeoJohnson","Asinh","Log","LogPlus1","Sqrt","Asin","Logit","Identity"), Path = NULL, TransID = "ModelID", SaveOutput = FALSE) { # Check arguments Methods <- unique(tolower(Methods)) if(!data.table::is.data.table(data)) data.table::setDT(data) if(!any(tolower(Methods) %chin% c("boxcox", "yeojohnson", "asinh", "sqrt", "log", "logplus1", "asin", "logit"))) stop("Methods not supported") # if(!"identity" %chin% Methods) Methods <- c(Methods, "identity") if(is.numeric(ColumnNames) || is.integer(ColumnNames)) ColumnNames <- names(data)[ColumnNames] for(i in ColumnNames) if(!(any(class(data[[eval(i)]]) %chin% c("numeric", "integer")))) stop("ColumnNames must be for numeric or integer columns") # Loop through ColumnNames # colNames = 1 for(colNames in seq_along(ColumnNames)) {# colNames = 1L # Collection Object if(length(Methods) < 5) { EvaluationTable <- data.table::data.table( ColumnName = rep("BLABLA", length(ColumnNames) * (length(Methods)+1)), MethodName = rep("BLABLA", length(ColumnNames) * (length(Methods)+1)), Lambda = rep(1.0, length(ColumnNames) * (length(Methods)+1)), NormalizedStatistics = rep(1.0, length(ColumnNames) * (length(Methods)+1))) } else { EvaluationTable <- data.table::data.table( ColumnName = rep("BLABLA", length(ColumnNames) * (length(Methods) + 1)), MethodName = rep("BLABLA", length(ColumnNames) * (length(Methods) + 1)), Lambda = rep(1.0, length(ColumnNames) * (length(Methods) + 1)), NormalizedStatistics = rep(1.0, length(ColumnNames) * (length(Methods) + 1))) } DataCollection <- list() Counter <- 0L # Check range of data MinVal <- min(data[[eval(ColumnNames[colNames])]], na.rm = TRUE) MaxVal <- max(data[[eval(ColumnNames[colNames])]], na.rm = TRUE) # Create Final Methods Object FinalMethods <- Methods # Update Methods if(MinVal <= 0) FinalMethods <- FinalMethods[!(tolower(FinalMethods) %chin% c("boxcox","log","logit"))] if(MinVal < 0) FinalMethods <- FinalMethods[!(tolower(FinalMethods) %chin% c("sqrt","asin"))] if(MaxVal > 1) FinalMethods <- FinalMethods[!(tolower(FinalMethods) %chin% c("asin"))] if(MaxVal >= 1) FinalMethods <- FinalMethods[!(tolower(FinalMethods) %chin% c("logit"))] # Store column data as vector x <- data[[eval(ColumnNames[colNames])]] # YeoJohnson if(any(tolower(FinalMethods) %chin% "yeojohnson")) { Counter <- Counter + 1L data.table::set(EvaluationTable, i = Counter, j = "ColumnName", value = eval(ColumnNames[colNames])) output <- Test_YeoJohnson(x) DataCollection[["yeojohnson"]] <- output$Data data.table::set(EvaluationTable, i = Counter, j = "MethodName", value = output$Name) data.table::set(EvaluationTable, i = Counter, j = "Lambda", value = output$Lambda) data.table::set(EvaluationTable, i = Counter, j = "NormalizedStatistics", value = output$Normalized_Statistic) } # Log if(any(tolower(FinalMethods) %chin% "log")) { Counter <- Counter + 1L data.table::set(EvaluationTable, i = Counter, j = "ColumnName", value = eval(ColumnNames[colNames])) output <- Test_Log(x) DataCollection[["log"]] <- output$Data data.table::set(EvaluationTable, i = Counter, j = "MethodName", value = output$Name) data.table::set(EvaluationTable, i = Counter, j = "Lambda", value = NA) data.table::set(EvaluationTable, i = Counter, j = "NormalizedStatistics", value = output$Normalized_Statistic) } # LogPlus1 if(any(tolower(FinalMethods) %chin% "logplus1")) { Counter <- Counter + 1L data.table::set(EvaluationTable, i = Counter, j = "ColumnName", value = eval(ColumnNames[colNames])) output <- Test_LogPlus1(x) DataCollection[["logplus1"]] <- output$Data data.table::set(EvaluationTable, i = Counter, j = "MethodName", value = output$Name) data.table::set(EvaluationTable, i = Counter, j = "Lambda", value = NA) data.table::set(EvaluationTable, i = Counter, j = "NormalizedStatistics", value = output$Normalized_Statistic) } # Sqrt if(any(tolower(FinalMethods) %chin% "sqrt")) { Counter <- Counter + 1L data.table::set(EvaluationTable, i = Counter, j = "ColumnName", value = eval(ColumnNames[colNames])) output <- Test_Sqrt(x) DataCollection[["sqrt"]] <- output$Data data.table::set(EvaluationTable, i = Counter, j = "MethodName", value = output$Name) data.table::set(EvaluationTable, i = Counter, j = "Lambda", value = NA) data.table::set(EvaluationTable, i = Counter, j = "NormalizedStatistics", value = output$Normalized_Statistic) } # BoxCox if(any(tolower(FinalMethods) %chin% "boxcox")) { Counter <- Counter + 1L data.table::set(EvaluationTable, i = Counter, j = "ColumnName", value = eval(ColumnNames[colNames])) output <- Test_BoxCox(x) DataCollection[["boxcox"]] <- output$Data data.table::set(EvaluationTable, i = Counter, j = "MethodName", value = output$Name) data.table::set(EvaluationTable, i = Counter, j = "Lambda", value = output$Lambda) data.table::set(EvaluationTable, i = Counter, j = "NormalizedStatistics", value = output$Normalized_Statistic) } # Asinh if(any(tolower(FinalMethods) %chin% "asinh")) { Counter <- Counter + 1L data.table::set(EvaluationTable, i = Counter, j = "ColumnName", value = eval(ColumnNames[colNames])) output <- Test_Asinh(x) DataCollection[["asinh"]] <- output$Data data.table::set(EvaluationTable, i = Counter, j = "MethodName", value = output$Name) data.table::set(EvaluationTable, i = Counter, j = "Lambda", value = output$Lambda) data.table::set(EvaluationTable, i = Counter, j = "NormalizedStatistics", value = output$Normalized_Statistic) } # Asin if(any(tolower(FinalMethods) %chin% "asin")) { Counter <- Counter + 1L data.table::set(EvaluationTable, i = Counter, j = "ColumnName", value = eval(ColumnNames[colNames])) output <- Test_Asin(x) DataCollection[["asin"]] <- output$Data data.table::set(EvaluationTable, i = Counter, j = "MethodName", value = output$Name) data.table::set(EvaluationTable, i = Counter, j = "Lambda", value = output$Lambda) data.table::set(EvaluationTable, i = Counter, j = "NormalizedStatistics", value = output$Normalized_Statistic) } # Logit if(any(tolower(FinalMethods) %chin% "logit")) { Counter <- Counter + 1L data.table::set(EvaluationTable, i = Counter, j = "ColumnName", value = eval(ColumnNames[colNames])) output <- Test_Logit(x) DataCollection[["logit"]] <- output$Data data.table::set(EvaluationTable, i = Counter, j = "MethodName", value = output$Name) data.table::set(EvaluationTable, i = Counter, j = "Lambda", value = output$Lambda) data.table::set(EvaluationTable, i = Counter, j = "NormalizedStatistics", value = output$Normalized_Statistic) } # Identity if(any(tolower(FinalMethods) %chin% "identity")) { Counter <- Counter + 1L data.table::set(EvaluationTable, i = Counter, j = "ColumnName", value = eval(ColumnNames[colNames])) output <- Test_Identity(x) DataCollection[["identity"]] <- output$Data data.table::set(EvaluationTable, i = Counter, j = "MethodName", value = output$Name) data.table::set(EvaluationTable, i = Counter, j = "Lambda", value = output$Lambda) data.table::set(EvaluationTable, i = Counter, j = "NormalizedStatistics", value = output$Normalized_Statistic) } # Pick winner EvaluationTable <- EvaluationTable[MethodName != "BLABLA"] if(colNames == 1L) { Results <- EvaluationTable[order(NormalizedStatistics)][1L] } else { Results <- data.table::rbindlist(list(Results, EvaluationTable[order(NormalizedStatistics)][1L])) } # Apply to data---- data <- tryCatch({data[, ColumnNames[colNames] := DataCollection[[tolower(Results[eval(colNames), MethodName])]]]}, error = function(x) data) } # Save output---- if(SaveOutput && !is.null(Path)) data.table::fwrite(Results, file = file.path(normalizePath(Path), paste0(TransID, "_transformation.csv"))) # Return data---- return(list(Data = data, FinalResults = Results)) } #' @title ClassificationMetrics #' #' @description ClassificationMetrics #' #' @author Adrian Antico #' @family Model Evaluation #' #' @param TestData Test data from your modeling #' @param Thresholds Value #' @param Target Name of your target variable #' @param PredictColumnName Name of your predicted value variable #' @param PositiveOutcome The value of the positive outcome level #' @param NegativeOutcome The value of the negative outcome level #' @param CostMatrix c(True Positive Cost, False Negative Cost, False Positive Cost, True Negative Cost) #' @noRd ClassificationMetrics <- function(TestData, Thresholds, Target, PredictColumnName, PositiveOutcome, NegativeOutcome, CostMatrix = c(0,1,1,0)) { if("Target" %chin% names(TestData)) data.table::set(TestData, j = "Target", value = NULL) ThreshLength <- rep(1, length(Thresholds)) ThresholdOutput <- data.table::data.table( Threshold = ThreshLength, TN = ThreshLength, TP = ThreshLength, FN = ThreshLength, FP = ThreshLength, N = ThreshLength, P = ThreshLength, MCC = ThreshLength, Accuracy = ThreshLength, TPR = ThreshLength, TNR = ThreshLength, FNR = ThreshLength, FPR = ThreshLength, FDR = ThreshLength, FOR = ThreshLength, F1_Score = ThreshLength, F2_Score = ThreshLength, F0.5_Score = ThreshLength, NPV = ThreshLength, PPV = ThreshLength, ThreatScore = ThreshLength, Utility = ThreshLength) counter <- 0L for(Thresh in Thresholds) { counter <- counter + 1L TN <- TestData[, sum(data.table::fifelse(get(PredictColumnName) < Thresh & get(Target) == eval(NegativeOutcome), 1, 0))] TP <- TestData[, sum(data.table::fifelse(get(PredictColumnName) > Thresh & get(Target) == eval(PositiveOutcome), 1, 0))] FN <- TestData[, sum(data.table::fifelse(get(PredictColumnName) < Thresh & get(Target) == eval(PositiveOutcome), 1, 0))] FP <- TestData[, sum(data.table::fifelse(get(PredictColumnName) > Thresh & get(Target) == eval(NegativeOutcome), 1, 0))] N1 <- TestData[, .N] N <- TestData[get(PredictColumnName) < eval(Thresh), .N] P1 <- TestData[get(Target) == 1, .N] P <- TestData[get(Target) == 1 & get(PredictColumnName) > Thresh, .N] # Calculate metrics ---- MCC <- (TP*TN-FP*FN)/sqrt((TP+FP)*(TP+FN)*(TN+FP)*(TN+FN)) Accuracy <- (TP+TN)/N1 TPR <- TP/P1 TNR <- TN/(N1-P1) FNR <- FN / P1 FPR <- FP / N1 FDR <- FP / (FP + TP) FOR <- FN / (FN + TN) F1_Score <- 2 * TP / (2 * TP + FP + FN) F2_Score <- 3 * TP / (2 * TP + FP + FN) F0.5_Score <- 1.5 * TP / (0.5 * TP + FP + FN) NPV <- TN / (TN + FN) PPV <- TP / (TP + FP) ThreatScore <- TP / (TP + FN + FP) Utility <- P1/N1 * (CostMatrix[1L] * TPR + CostMatrix[2L] * (1 - TPR)) + (1 - P1/N1) * (CostMatrix[3L] * FPR + CostMatrix[4L] * (1 - FPR)) # Fill in values ---- data.table::set(ThresholdOutput, i = counter, j = "Threshold", value = Thresh) data.table::set(ThresholdOutput, i = counter, j = "P", value = P) data.table::set(ThresholdOutput, i = counter, j = "N", value = N) data.table::set(ThresholdOutput, i = counter, j = "TN", value = TN) data.table::set(ThresholdOutput, i = counter, j = "TP", value = TP) data.table::set(ThresholdOutput, i = counter, j = "FP", value = FP) data.table::set(ThresholdOutput, i = counter, j = "FN", value = FN) data.table::set(ThresholdOutput, i = counter, j = "Utility", value = Utility) data.table::set(ThresholdOutput, i = counter, j = "MCC", value = MCC) data.table::set(ThresholdOutput, i = counter, j = "Accuracy", value = Accuracy) data.table::set(ThresholdOutput, i = counter, j = "F1_Score", value = F1_Score) data.table::set(ThresholdOutput, i = counter, j = "F0.5_Score", value = F0.5_Score) data.table::set(ThresholdOutput, i = counter, j = "F2_Score", value = F2_Score) data.table::set(ThresholdOutput, i = counter, j = "NPV", value = NPV) data.table::set(ThresholdOutput, i = counter, j = "TPR", value = TPR) data.table::set(ThresholdOutput, i = counter, j = "TNR", value = TNR) data.table::set(ThresholdOutput, i = counter, j = "FNR", value = FNR) data.table::set(ThresholdOutput, i = counter, j = "FPR", value = FPR) data.table::set(ThresholdOutput, i = counter, j = "FDR", value = FDR) data.table::set(ThresholdOutput, i = counter, j = "FOR", value = FOR) data.table::set(ThresholdOutput, i = counter, j = "PPV", value = PPV) data.table::set(ThresholdOutput, i = counter, j = "ThreatScore", value = ThreatScore) } # Remove NA's ThresholdOutput <- ThresholdOutput[, RowSum := rowSums(x = as.matrix(ThresholdOutput))][!is.na(RowSum)][, RowSum := NULL] return(ThresholdOutput) } #' @title RemixClassificationMetrics #' #' @description RemixClassificationMetrics #' #' @author Adrian Antico #' @family Model Evaluation #' #' @param TargetVariable Name of your target variable #' @param Thresholds seq(0.01,0.99,0.01), #' @param CostMatrix c(1,0,0,1) c(TP utility, FN utility, FP utility, TN utility) #' @param ClassLabels c(1,0), #' @param ValidationData. Test data #' @noRd RemixClassificationMetrics <- function(TargetVariable = NULL, Thresholds = seq(0.01,0.99,0.01), CostMatrix = c(1,0,0,1), ClassLabels = c(1,0), ValidationData. = NULL) { # Create metrics if(!"p1" %chin% names(ValidationData.)) data.table::setnames(ValidationData., "Predict", "p1") temp <- ClassificationMetrics( TestData = ValidationData., Target = eval(TargetVariable), PredictColumnName = "p1", Thresholds = Thresholds, PositiveOutcome = ClassLabels[1L], NegativeOutcome = ClassLabels[2L], CostMatrix = CostMatrix) if(temp[,.N] > 95) data.table::setorderv(temp, cols = "MCC", order = -1L, na.last = TRUE) # Return values---- return(temp) } #' @title BinaryMetrics #' #' @description Compute binary metrics and save them to file #' #' @author Adrian Antico #' @family Model Evaluation #' #' @param ClassWeights. = ClassWeights #' @param CostMatrixWeights. = CostMatrixWeights #' @param SaveModelObjects. = SaveModelObjects #' @param ValidationData. = ValidationData #' @param TrainOnFull. = TrainOnFull #' @param TargetColumnName. = TargetColumnName #' @param ModelID. = ModelID #' @param model_path. = model_path #' @param metadata_path. = metadata_path #' @param Method 'threshold' for 0.01 to 0.99 by 0.01 thresholds or 'bins' for 20 equally sized bins #' #' @noRd BinaryMetrics <- function(ClassWeights. = ClassWeights, CostMatrixWeights. = CostMatrixWeights, SaveModelObjects. = SaveModelObjects, ValidationData. = ValidationData, TrainOnFull. = TrainOnFull, TargetColumnName. = TargetColumnName, ModelID. = ModelID, model_path. = model_path, metadata_path. = metadata_path, Method = "threshold") { if(is.null(CostMatrixWeights.)) CostMatrixWeights. <- c(ClassWeights.[1L], 0, 0, ClassWeights.[2L]) if(Method == "threshold") { vals <- seq(0.01,0.99,0.01) } else if(Method == "bins") { temp <- ValidationData.$p1 vals <- quantile(temp, probs = seq(0.05,1,0.05), type = 7) } if(SaveModelObjects. && !TrainOnFull.) { EvalMetrics <- RemixClassificationMetrics(TargetVariable = eval(TargetColumnName.), Thresholds = unique(vals), CostMatrix = CostMatrixWeights., ClassLabels = c(1,0), ValidationData. = ValidationData.) } else { EvalMetrics <- RemixClassificationMetrics(TargetVariable = eval(TargetColumnName.), Thresholds = unique(vals), CostMatrix = CostMatrixWeights., ClassLabels = c(1,0), ValidationData. = ValidationData.) } EvalMetrics[, P_Predicted := TP + FP] data.table::setcolorder(EvalMetrics, c(1,ncol(EvalMetrics),2:(ncol(EvalMetrics)-1))) data.table::setcolorder(EvalMetrics, c(1:8, ncol(EvalMetrics), 9:10, 17:19, 11:16, 20:(ncol(EvalMetrics)-1))) data.table::setcolorder(EvalMetrics, c(1:14, ncol(EvalMetrics), 15:(ncol(EvalMetrics)-1))) data.table::setorderv(EvalMetrics, "Utility", -1) return(EvalMetrics) } #' @title DummifyDT #' #' @description DummifyDT creates dummy variables for the selected columns. Either one-hot encoding, N+1 columns for N levels, or N columns for N levels. #' #' @author Adrian Antico #' @family Feature Engineering #' #' @param data The data set to run the micro auc on #' @param cols A vector with the names of the columns you wish to dichotomize #' @param TopN Default is NULL. Scalar to apply to all categorical columns or a vector to apply to each categorical variable. Only create dummy variables for the TopN number of levels. Will be either TopN or max(levels) #' @param OneHot Set to TRUE to run one hot encoding, FALSE to generate N columns for N levels #' @param KeepFactorCols Set to TRUE to keep the original columns used in the dichotomization process #' @param SaveFactorLevels Set to TRUE to save unique levels of each factor column to file as a csv #' @param SavePath Provide a file path to save your factor levels. Use this for models that you have to create dummy variables for. #' @param ImportFactorLevels Instead of using the data you provide, import the factor levels csv to ensure you build out all of the columns you trained with in modeling. #' @param FactorLevelsList Supply a list of factor variable levels #' @param ClustScore This is for scoring AutoKMeans. It converts the added dummy column names to conform with H2O dummy variable naming convention #' @param ReturnFactorLevels If you want a named list of all the factor levels returned, set this to TRUE. Doing so will cause the function to return a list with the source data.table and the list of factor variables' levels #' @param GroupVar Ignore this #' @return Either a data table with new dummy variables columns and optionally removes base columns (if ReturnFactorLevels is FALSE), otherwise a list with the data.table and a list of the factor levels. #' @noRd DummifyDT <- function(data, cols, TopN = NULL, KeepFactorCols = FALSE, OneHot = FALSE, SaveFactorLevels = FALSE, SavePath = NULL, ImportFactorLevels = FALSE, FactorLevelsList = NULL, ClustScore = FALSE, ReturnFactorLevels = FALSE, GroupVar = FALSE) { # Check data.table ---- if(!data.table::is.data.table(data)) data.table::setDT(data) # Check arguments ---- if(!is.null(TopN)) if(length(TopN) > 1L && length(TopN) != length(cols)) stop("TopN must match the length of cols") if(!is.null(TopN)) if(length(TopN) > 1L) TopN <- rev(TopN) if(!is.character(cols)) stop("cols needs to be a character vector of names") if(!is.logical(KeepFactorCols)) stop("KeepFactorCols needs to be either TRUE or FALSE") if(!is.logical(KeepFactorCols)) stop("KeepFactorCols needs to be either TRUE or FALSE") if(!is.logical(OneHot)) stop("OneHot needs to be either TRUE or FALSE") if(!is.logical(SaveFactorLevels)) stop("SaveFactorLevels needs to be either TRUE or FALSE") if(!is.logical(ImportFactorLevels)) stop("ImportFactorLevels needs to be either TRUE or FALSE") if(!is.logical(ClustScore)) stop("ClustScore needs to be either TRUE or FALSE") if(!is.null(SavePath)) if(!is.character(SavePath)) stop("SavePath needs to be a character value of a folder location") # Ensure correct argument settings ---- if(OneHot && ClustScore) { OneHot <- FALSE KeepFactorCols <- FALSE } # Build dummies start ---- FactorsLevelsList <- list() if(!GroupVar) if(length(cols) > 1L && "GroupVar" %chin% cols) cols <- cols[!cols %chin% "GroupVar"] if(length(TopN) > 1L) Counter <- 1L for(col in cols) { size <- ncol(data) Names <- setdiff(names(data), col) if(ImportFactorLevels) { temp <- data.table::fread(file.path(SavePath, paste0(col, ".csv")), sep = ",") inds <- sort(unique(temp[[eval(col)]])) } else if(!is.null(FactorLevelsList)) { temp <- FactorLevelsList[[eval(col)]] inds <- sort(unique(temp[[eval(col)]])) } else if(!is.null(TopN)) { if(length(TopN) > 1L) { indss <- data[, .N, by = eval(col)][order(-N)] inds <- sort(indss[seq_len(min(TopN[Counter], .N)), get(col)]) if(length(TopN) > 1L) Counter <- Counter + 1L } else { indss <- data[, .N, by = eval(col)][order(-N)] inds <- sort(indss[seq_len(min(TopN, .N)), get(col)]) } } else { indss <- data[, .N, by = eval(col)][order(-N)] inds <- sort(unique(data[[eval(col)]])) } # Allocate columns ---- data.table::alloc.col(data, n = ncol(data) + length(inds)) # Save factor levels for scoring later ---- if(SaveFactorLevels) { if(!is.null(TopN)) { if(length(TopN) > 1L) { temp <- indss[seq_len(min(TopN[Counter-1L], .N))][, N := NULL] data.table::fwrite(x = temp, file = file.path(SavePath, paste0(col, ".csv")), sep = ",") } else { temp <- indss[seq_len(min(TopN, .N))][, N := NULL] data.table::fwrite(x = temp, file = file.path(SavePath, paste0(col, ".csv")), sep = ",") } } else { temp <- indss[, N := NULL] data.table::fwrite(x = temp, file = file.path(SavePath, paste0(col, ".csv")), sep = ",") } } # Collect Factor Levels ---- if(ReturnFactorLevels && SaveFactorLevels) { FactorsLevelsList[[eval(col)]] <- temp } else if(ReturnFactorLevels) { FactorsLevelsList[[eval(col)]] <- data[, get(col), by = eval(col)][, V1 := NULL] } # Convert to character if col is factor ---- if(is.factor(data[[eval(col)]])) data.table::set(data, j = eval(col), value = as.character(data[[eval(col)]])) # If for clustering set up old school way ---- if(!ClustScore) { data.table::set(data, j = paste0(col, "_", inds), value = 0L) } else { data.table::set(data, j = paste0(col, inds), value = 0L) } # Build dummies ---- for(ind in inds) { if(!ClustScore) { data.table::set(data, i = which(data[[col]] %in% ind), j = paste0(col, "_", ind), value = 1L) } else { data.table::set(data, i = which(data[[col]] %in% ind), j = paste0(col, ind),value = 1L) } } # Remove original factor columns ---- if(!KeepFactorCols) data.table::set(data, j = eval(col), value = NULL) if(ClustScore) setcolorder(data, c(setdiff(names(data), Names), Names)) if(OneHot) data.table::set(data, j = paste0(col, "_Base"), value = 0L) } # Clustering section ---- if(ClustScore) data.table::setnames(data, names(data), tolower(gsub('[[:punct:] ]+', replacement = "", names(data)))) # Return data ---- if(ReturnFactorLevels) { return(list(data = data, FactorLevelsList = FactorsLevelsList)) } else { return(data) } } #' @title AutoLagRollStats #' #' @description AutoLagRollStats Builds lags and a large variety of rolling statistics with options to generate them for hierarchical categorical interactions. #' #' @author Adrian Antico #' @family Feature Engineering #' #' @param data A data.table you want to run the function on #' @param Targets A character vector of the column names for the reference column in which you will build your lags and rolling stats #' @param DateColumn The column name of your date column used to sort events over time #' @param IndependentGroups A vector of categorical column names that you want to have run independently of each other. This will mean that no interaction will be done. #' @param HierarchyGroups A vector of categorical column names that you want to have generate all lags and rolling stats done for the individual columns and their full set of interactions. #' @param TimeGroups A vector of TimeUnits indicators to specify any time-aggregated GDL features you want to have returned. E.g. c("raw" (no aggregation is done),"hour", "day","week","month","quarter","year") #' @param TimeBetween Specify a desired name for features created for time between events. Set to NULL if you don't want time between events features created. #' @param TimeUnit List the time aggregation level for the time between events features, such as "hour", "day", "weeks", "months", "quarter", or "year" #' @param TimeUnitAgg List the time aggregation of your data that you want to use as a base time unit for your features. E.g. "raw" or "day" #' @param Lags A numeric vector of the specific lags you want to have generated. You must include 1 if WindowingLag = 1. #' @param MA_RollWindows A numeric vector of the specific rolling statistics window sizes you want to utilize in the calculations. #' @param SD_RollWindows A numeric vector of Standard Deviation rolling statistics window sizes you want to utilize in the calculations. #' @param Skew_RollWindows A numeric vector of Skewness rolling statistics window sizes you want to utilize in the calculations. #' @param Kurt_RollWindows A numeric vector of Kurtosis rolling statistics window sizes you want to utilize in the calculations. #' @param Quantile_RollWindows A numeric vector of Quantile rolling statistics window sizes you want to utilize in the calculations. #' @param Quantiles_Selected Select from the following c("q5", "q10", "q15", "q20", "q25", "q30", "q35", "q40", "q45", "q50", "q55", "q60"," q65", "q70", "q75", "q80", "q85", "q90", "q95") #' @param RollOnLag1 Set to FALSE to build rolling stats off of target columns directly or set to TRUE to build the rolling stats off of the lag-1 target #' @param Type List either "Lag" if you want features built on historical values or "Lead" if you want features built on future values #' @param SimpleImpute Set to TRUE for factor level imputation of "0" and numeric imputation of -1 #' @param ShortName Default TRUE. If FALSE, Group Variable names will be added to the rolling stat and lag names. If you plan on have multiple versions of lags and rollings stats by different group variables then set this to FALSE. #' @param Debug Set to TRUE to get a print of which steps are running #' @return data.table of original data plus created lags, rolling stats, and time between event lags and rolling stats #' @noRd AutoLagRollStats <- function(data, Targets = NULL, HierarchyGroups = NULL, IndependentGroups = NULL, DateColumn = NULL, TimeUnit = NULL, TimeUnitAgg = NULL, TimeGroups = NULL, TimeBetween = NULL, RollOnLag1 = TRUE, Type = "Lag", SimpleImpute = TRUE, Lags = NULL, MA_RollWindows = NULL, SD_RollWindows = NULL, Skew_RollWindows = NULL, Kurt_RollWindows = NULL, Quantile_RollWindows = NULL, Quantiles_Selected = NULL, ShortName = TRUE, Debug = FALSE) { # Define args ---- RollFunctions <- c() if(!is.null(MA_RollWindows)) RollFunctions <- c(RollFunctions,"mean") if(!is.null(SD_RollWindows)) RollFunctions <- c(RollFunctions,"sd") if(!is.null(Skew_RollWindows)) RollFunctions <- c(RollFunctions,"skew") if(!is.null(Kurt_RollWindows)) RollFunctions <- c(RollFunctions,"kurt") if(!is.null(Quantiles_Selected)) RollFunctions <- c(RollFunctions,Quantiles_Selected) if(is.null(TimeBetween)) TimeBetween <- NULL else TimeBetween <- "TimeBetweenRecords" if(RollOnLag1) RollOnLag1 <- 1L else RollOnLag1 <- 0L TimeGroupPlaceHolder <- c() if("raw" %chin% tolower(TimeGroups)) TimeGroupPlaceHolder <- c(TimeGroupPlaceHolder, "raw") if(any(c("hours","hour","hr","hrs","hourly") %chin% tolower(TimeGroups))) { TimeGroupPlaceHolder <- c(TimeGroupPlaceHolder, "hour") if(is.list(Lags)) names(Lags)[which(names(Lags) %chin% c("hours","hour","hr","hrs","hourly"))] <- "hour" if(is.list(MA_RollWindows)) names(MA_RollWindows)[which(names(MA_RollWindows) %chin% c("hours","hour","hr","hrs","hourly"))] <- "hour" if(is.list(SD_RollWindows)) names(SD_RollWindows)[which(names(SD_RollWindows) %chin% c("hours","hour","hr","hrs","hourly"))] <- "hour" if(is.list(Skew_RollWindows)) names(Skew_RollWindows)[which(names(Skew_RollWindows) %chin% c("hours","hour","hr","hrs","hourly"))] <- "hour" if(is.list(Kurt_RollWindows)) names(Kurt_RollWindows)[which(names(Kurt_RollWindows) %chin% c("hours","hour","hr","hrs","hourly"))] <- "hour" if(is.list(Quantile_RollWindows)) names(Quantile_RollWindows)[which(names(Quantile_RollWindows) %chin% c("hours","hour","hr","hrs","hourly"))] <- "hour" } if(any(c("days","day","dy","dd","d") %chin% tolower(TimeGroups))) { TimeGroupPlaceHolder <- c(TimeGroupPlaceHolder, "day") if(is.list(Lags)) names(Lags)[which(names(Lags) %chin% c("days","day","dy","dd","d"))] <- "day" if(is.list(MA_RollWindows)) names(MA_RollWindows)[which(names(MA_RollWindows) %chin% c("days","day","dy","dd","d"))] <- "day" if(is.list(SD_RollWindows)) names(SD_RollWindows)[which(names(SD_RollWindows) %chin% c("days","day","dy","dd","d"))] <- "day" if(is.list(Skew_RollWindows)) names(Skew_RollWindows)[which(names(Skew_RollWindows) %chin% c("days","day","dy","dd","d"))] <- "day" if(is.list(Kurt_RollWindows)) names(Kurt_RollWindows)[which(names(Kurt_RollWindows) %chin% c("days","day","dy","dd","d"))] <- "day" if(is.list(Quantile_RollWindows)) names(Quantile_RollWindows)[which(names(Quantile_RollWindows) %chin% c("days","day","dy","dd","d"))] <- "day" } if(any(c("weeks","week","weaks","weak","wk","wkly","wks") %chin% tolower(TimeGroups))) { TimeGroupPlaceHolder <- c(TimeGroupPlaceHolder, "weeks") if(is.list(Lags)) names(Lags)[which(names(Lags) %chin% c("weeks","week","weaks","weak","wk","wkly","wks"))] <- "weeks" if(is.list(MA_RollWindows)) names(MA_RollWindows)[which(names(MA_RollWindows) %chin% c("weeks","week","weaks","weak","wk","wkly","wks"))] <- "weeks" if(is.list(SD_RollWindows)) names(SD_RollWindows)[which(names(SD_RollWindows) %chin% c("weeks","week","weaks","weak","wk","wkly","wks"))] <- "weeks" if(is.list(Skew_RollWindows)) names(Skew_RollWindows)[which(names(Skew_RollWindows) %chin% c("weeks","week","weaks","weak","wk","wkly","wks"))] <- "weeks" if(is.list(Kurt_RollWindows)) names(Kurt_RollWindows)[which(names(Kurt_RollWindows) %chin% c("weeks","week","weaks","weak","wk","wkly","wks"))] <- "weeks" if(is.list(Quantile_RollWindows)) names(Quantile_RollWindows)[which(names(Quantile_RollWindows) %chin% c("weeks","week","weaks","weak","wk","wkly","wks"))] <- "weeks" } if(any(c("months","month","mth","mnth","monthly","mnthly") %chin% tolower(TimeGroups))) { TimeGroupPlaceHolder <- c(TimeGroupPlaceHolder, "months") if(is.list(Lags)) names(Lags)[which(names(Lags) %chin% c("months","month","mth","mnth","monthly","mnthly"))] <- "months" if(is.list(MA_RollWindows)) names(MA_RollWindows)[which(names(MA_RollWindows) %chin% c("months","month","mth","mnth","monthly","mnthly"))] <- "months" if(is.list(SD_RollWindows)) names(SD_RollWindows)[which(names(SD_RollWindows) %chin% c("months","month","mth","mnth","monthly","mnthly"))] <- "months" if(is.list(Skew_RollWindows)) names(Skew_RollWindows)[which(names(Skew_RollWindows) %chin% c("months","month","mth","mnth","monthly","mnthly"))] <- "months" if(is.list(Kurt_RollWindows)) names(Kurt_RollWindows)[which(names(Kurt_RollWindows) %chin% c("months","month","mth","mnth","monthly","mnthly"))] <- "months" if(is.list(Quantile_RollWindows)) names(Quantile_RollWindows)[which(names(Quantile_RollWindows) %chin% c("months","month","mth","mnth","monthly","mnthly"))] <- "months" } if(any(c("quarter","quarters","qarter","quarterly","q","qtly") %chin% tolower(TimeGroups))) { TimeGroupPlaceHolder <- c(TimeGroupPlaceHolder, "quarter") if(is.list(Lags)) names(Lags)[which(names(Lags) %chin% c("quarter","qarter","quarterly","q","qtly"))] <- "quarter" if(is.list(MA_RollWindows)) names(MA_RollWindows)[which(names(MA_RollWindows) %chin% c("quarter","qarter","quarterly","q","qtly"))] <- "quarter" if(is.list(SD_RollWindows)) names(SD_RollWindows)[which(names(SD_RollWindows) %chin% c("quarter","qarter","quarterly","q","qtly"))] <- "quarter" if(is.list(Skew_RollWindows)) names(Skew_RollWindows)[which(names(Skew_RollWindows) %chin% c("quarter","qarter","quarterly","q","qtly"))] <- "quarter" if(is.list(Kurt_RollWindows)) names(Kurt_RollWindows)[which(names(Kurt_RollWindows) %chin% c("quarter","qarter","quarterly","q","qtly"))] <- "quarter" if(is.list(Quantile_RollWindows)) names(Quantile_RollWindows)[which(names(Quantile_RollWindows) %chin% c("quarter","qarter","quarterly","q","qtly"))] <- "quarter" } if(any(c("year","years","annual","yearly","annually","ann","yr","yrly") %chin% tolower(TimeGroups))) { TimeGroupPlaceHolder <- c(TimeGroupPlaceHolder, "year") if(is.list(Lags)) names(Lags)[which(names(Lags) %chin% c("year","annual","yearly","annually","ann","yr","yrly"))] <- "year" if(is.list(MA_RollWindows)) names(MA_RollWindows)[which(names(MA_RollWindows) %chin% c("year","annual","yearly","annually","ann","yr","yrly"))] <- "year" if(is.list(SD_RollWindows)) names(SD_RollWindows)[which(names(SD_RollWindows) %chin% c("year","annual","yearly","annually","ann","yr","yrly"))] <- "year" if(is.list(Skew_RollWindows)) names(Skew_RollWindows)[which(names(Skew_RollWindows) %chin% c("year","annual","yearly","annually","ann","yr","yrly"))] <- "year" if(is.list(Kurt_RollWindows)) names(Kurt_RollWindows)[which(names(Kurt_RollWindows) %chin% c("year","annual","yearly","annually","ann","yr","yrly"))] <- "year" if(is.list(Quantile_RollWindows)) names(Quantile_RollWindows)[which(names(Quantile_RollWindows) %chin% c("year","annual","yearly","annually","ann","yr","yrly"))] <- "year" } TimeGroups <- TimeGroupPlaceHolder if(is.null(TimeUnitAgg)) TimeUnitAgg <- TimeGroups[1L] #The correct TimeGroups are: c("hour", "day", "weeks", "months", "quarter", "year", "1min", "5min", "10min", "15min", "30min", "45min") # Ensure date column is proper ---- if(Debug) print("Data Wrangling: Convert DateColumnName to Date or POSIXct----") if(!(tolower(TimeUnit) %chin% c("1min","5min","10min","15min","30min","hour"))) { if(is.character(data[[eval(DateColumn)]])) { x <- data[1,get(DateColumn)] x1 <- lubridate::guess_formats(x, orders = c("mdY", "BdY", "Bdy", "bdY", "bdy", "mdy", "dby", "Ymd", "Ydm")) data.table::set(data, j = eval(DateColumn), value = as.Date(data[[eval(DateColumn)]], tryFormats = x1)) } } else { data.table::set(data, j = eval(DateColumn), value = as.POSIXct(data[[eval(DateColumn)]])) } # Debugging---- if(Debug) print("AutoLagRollStats: No Categoricals") # No Categoricals---- if(is.null(IndependentGroups) && is.null(HierarchyGroups)) { # Initialize Counter---- Counter <- 0L # Loop through various time aggs---- for(timeaggs in TimeGroups) { # Increment Counter---- Counter <- Counter + 1L # Copy data---- tempData <- data.table::copy(data) # Check time scale---- if(Counter > 1) { # Floor Date column to timeagg level---- data.table::set(tempData, j = eval(DateColumn), value = lubridate::floor_date(x = tempData[[eval(DateColumn)]], unit = timeaggs)) # Agg by date column---- tempData <- tempData[, lapply(.SD, mean, na.rm = TRUE), .SDcols = c(eval(Targets)), by = c(eval(DateColumn))] # Build features---- tempData <- DT_GDL_Feature_Engineering( tempData, lags = if(is.list(Lags)) Lags[[timeaggs]] else Lags, periods = if(is.list(MA_RollWindows)) MA_RollWindows[[timeaggs]] else MA_RollWindows, SDperiods = if(is.list(SD_RollWindows)) SD_RollWindows[[timeaggs]] else SD_RollWindows, Skewperiods = if(is.list(Skew_RollWindows)) Skew_RollWindows[[timeaggs]] else Skew_RollWindows, Kurtperiods = if(is.list(Kurt_RollWindows)) Kurt_RollWindows[[timeaggs]] else Kurt_RollWindows, Quantileperiods = if(is.list(Quantile_RollWindows)) Quantile_RollWindows[[timeaggs]] else Quantile_RollWindows, statsFUNs = RollFunctions, targets = Targets, groupingVars = NULL, sortDateName = DateColumn, timeDiffTarget = NULL, timeAgg = timeaggs, WindowingLag = RollOnLag1, ShortName = ShortName, Type = Type, SimpleImpute = SimpleImpute) } else { # Build features---- data.table::setkeyv(data <- DT_GDL_Feature_Engineering( data, lags = if(is.list(Lags)) Lags[[timeaggs]] else Lags, periods = if(is.list(MA_RollWindows)) MA_RollWindows[[timeaggs]] else MA_RollWindows, SDperiods = if(is.list(SD_RollWindows)) SD_RollWindows[[timeaggs]] else SD_RollWindows, Skewperiods = if(is.list(Skew_RollWindows)) Skew_RollWindows[[timeaggs]] else Skew_RollWindows, Kurtperiods = if(is.list(Kurt_RollWindows)) Kurt_RollWindows[[timeaggs]] else Kurt_RollWindows, Quantileperiods = if(is.list(Quantile_RollWindows)) Quantile_RollWindows[[timeaggs]] else Quantile_RollWindows, statsFUNs = RollFunctions, targets = Targets, groupingVars = NULL, sortDateName = DateColumn, timeDiffTarget = NULL, timeAgg = timeaggs, WindowingLag = RollOnLag1, ShortName = ShortName, Type = Type, SimpleImpute = SimpleImpute), DateColumn) } # Check if timeaggs is same of TimeUnit---- if(Counter > 1L) { data.table::setkeyv(data[, TEMPDATE := lubridate::floor_date(get(DateColumn), unit = eval(timeaggs))], "TEMPDATE") data[tempData, (setdiff(names(tempData), names(data))) := mget(paste0("i.", setdiff(names(tempData), names(data))))] data.table::set(data, j = "TEMPDATE", value = NULL) } } } # Debugging---- if(Debug) print("AutoLagRollStats: Indep + Hierach") # Hierarchy Categoricals---- if(!is.null(HierarchyGroups)) { # Categorical Names Fully Interacted---- Categoricals <- FullFactorialCatFeatures(GroupVars = HierarchyGroups, BottomsUp = TRUE) # Categorical Names Fully Interacted (Check if there already)---- for(cat in seq_len(length(Categoricals)-length(HierarchyGroups))) { if(!any(names(data) %chin% Categoricals[cat])) data[, eval(Categoricals[cat]) := do.call(paste, c(.SD, sep = " ")), .SDcols = c(unlist(data.table::tstrsplit(Categoricals[cat], "_")))] } # Loop through each feature interaction Counter <- 0L for(Fact in Categoricals) { # Loop through all TimeGroups---- for(timeaggs in TimeGroups) { # Counter incrementing Counter <- Counter + 1L # Check if timeaggs is same of TimeUnitAgg ---- if(Counter > 1L) { # Aggregate tempData and tempRegs to correct dimensional level---- tempData <- data[, .SD, .SDcols = c(eval(Targets), eval(DateColumn), eval(Fact))] # Agg by date column ---- if(timeaggs != "raw") { tempData[, eval(DateColumn) := lubridate::floor_date(x = get(DateColumn), unit = timeaggs)] tempData <- tempData[, lapply(.SD, mean, na.rm = TRUE), .SDcols = c(eval(Targets)), by = c(eval(DateColumn), eval(Fact))] } # Build GDL Features---- data.table::setkeyv(tempData <- DT_GDL_Feature_Engineering( tempData, lags = if(is.list(Lags)) Lags[[timeaggs]] else Lags, periods = if(is.list(MA_RollWindows)) MA_RollWindows[[timeaggs]] else MA_RollWindows, SDperiods = if(is.list(SD_RollWindows)) SD_RollWindows[[timeaggs]] else SD_RollWindows, Skewperiods = if(is.list(Skew_RollWindows)) Skew_RollWindows[[timeaggs]] else Skew_RollWindows, Kurtperiods = if(is.list(Kurt_RollWindows)) Kurt_RollWindows[[timeaggs]] else Kurt_RollWindows, Quantileperiods = if(is.list(Quantile_RollWindows)) Quantile_RollWindows[[timeaggs]] else Quantile_RollWindows, statsFUNs = RollFunctions, targets = Targets, groupingVars = Fact, sortDateName = DateColumn, timeDiffTarget = NULL, timeAgg = timeaggs, WindowingLag = RollOnLag1, ShortName = ShortName, Type = Type, SimpleImpute = SimpleImpute), c(Fact, DateColumn)) } else { # Build GDL Features---- data <- DT_GDL_Feature_Engineering( data, lags = if(is.list(Lags)) Lags[[timeaggs]] else Lags, periods = if(is.list(MA_RollWindows)) MA_RollWindows[[timeaggs]] else MA_RollWindows, SDperiods = if(is.list(SD_RollWindows)) SD_RollWindows[[timeaggs]] else SD_RollWindows, Skewperiods = if(is.list(Skew_RollWindows)) Skew_RollWindows[[timeaggs]] else Skew_RollWindows, Kurtperiods = if(is.list(Kurt_RollWindows)) Kurt_RollWindows[[timeaggs]] else Kurt_RollWindows, Quantileperiods = if(is.list(Quantile_RollWindows)) Quantile_RollWindows[[timeaggs]] else Quantile_RollWindows, statsFUNs = RollFunctions, targets = Targets, groupingVars = Fact, sortDateName = DateColumn, timeDiffTarget = NULL, timeAgg = timeaggs, WindowingLag = RollOnLag1, ShortName = ShortName, Type = Type, SimpleImpute = SimpleImpute) } # Check if timeaggs is same of TimeUnit---- if(Counter > 1L) { data.table::setkeyv(data[, TEMPDATE := lubridate::floor_date(get(DateColumn), unit = eval(timeaggs))], c(Fact,"TEMPDATE")) data[tempData, (setdiff(names(tempData), names(data))) := mget(paste0("i.", setdiff(names(tempData), names(data))))] data.table::set(data, j = "TEMPDATE", value = NULL) } } } } # Debugging---- if(Debug) print("AutoLagRollStats: Indep") # Single categoricals at a time AND no hierarchical: if there are hierarchical the single cats will be handled above---- if(!is.null(IndependentGroups) && is.null(HierarchyGroups)) { # Loop through IndependentGroups---- Counter <- 0L # Fact = IndependentGroups[1] # timeaggs = TimeGroups[1] for(Fact in IndependentGroups) { # Loop through all TimeGroups---- for(timeaggs in TimeGroups) { # Counter incrementing Counter <- Counter + 1L # Copy data---- tempData <- data.table::copy(data) # Check if timeaggs is same of TimeUnit ---- if(Counter > 1L) { # Floor Date column to timeagg level ---- tempData[, eval(DateColumn) := lubridate::floor_date(x = get(DateColumn), unit = timeaggs)] # Agg by date column---- tempData <- tempData[, lapply(.SD, mean, na.rm = TRUE), .SDcols = c(eval(Targets)), by = c(eval(DateColumn),eval(Fact))] # Build GDL Features---- data.table::setkeyv(tempData <- DT_GDL_Feature_Engineering( tempData, lags = if(is.list(Lags)) Lags[[timeaggs]] else Lags, periods = if(is.list(MA_RollWindows)) MA_RollWindows[[timeaggs]] else MA_RollWindows, SDperiods = if(is.list(SD_RollWindows)) SD_RollWindows[[timeaggs]] else SD_RollWindows, Skewperiods = if(is.list(Skew_RollWindows)) Skew_RollWindows[[timeaggs]] else Skew_RollWindows, Kurtperiods = if(is.list(Kurt_RollWindows)) Kurt_RollWindows[[timeaggs]] else Kurt_RollWindows, Quantileperiods = if(is.list(Quantile_RollWindows)) Quantile_RollWindows[[timeaggs]] else Quantile_RollWindows, statsFUNs = RollFunctions, targets = Targets, groupingVars = Fact, sortDateName = DateColumn, timeDiffTarget = NULL, timeAgg = timeaggs, ShortName = ShortName, WindowingLag = RollOnLag1, Type = Type, SimpleImpute = SimpleImpute), c(Fact, DateColumn)) } else { # Set up for binary search instead of vector scan data.table::setkeyv(x = data, cols = c(eval(Fact),eval(DateColumn))) # Build GDL Features data <- DT_GDL_Feature_Engineering( data, lags = if(is.list(Lags)) Lags[[timeaggs]] else Lags, periods = if(is.list(MA_RollWindows)) MA_RollWindows[[timeaggs]] else MA_RollWindows, SDperiods = if(is.list(SD_RollWindows)) SD_RollWindows[[timeaggs]] else SD_RollWindows, Skewperiods = if(is.list(Skew_RollWindows)) Skew_RollWindows[[timeaggs]] else Skew_RollWindows, Kurtperiods = if(is.list(Kurt_RollWindows)) Kurt_RollWindows[[timeaggs]] else Kurt_RollWindows, Quantileperiods = if(is.list(Quantile_RollWindows)) Quantile_RollWindows[[timeaggs]] else Quantile_RollWindows, statsFUNs = RollFunctions, targets = Targets, groupingVars = Fact, sortDateName = DateColumn, timeDiffTarget = TimeBetween, timeAgg = timeaggs, WindowingLag = RollOnLag1, Type = Type, ShortName = ShortName, SimpleImpute = SimpleImpute) } # Check if timeaggs is same of TimeUnit ---- if(Counter > 1L) { data.table::setkeyv(data[, TEMPDATE := lubridate::floor_date(get(DateColumn), unit = eval(timeaggs))], c(Fact, "TEMPDATE")) data[tempData, (setdiff(names(tempData), names(data))) := mget(paste0("i.", setdiff(names(tempData), names(data))))] data.table::set(data, j = "TEMPDATE", value = NULL) } } } } # Simple impute missed ---- if(SimpleImpute) { for(miss in seq_along(data)) { data.table::set(data, i = which(is.na(data[[miss]])), j = miss, value = -1) } } # Return data ---- if("TEMPDATE" %chin% names(data)) data.table::set(data, j = "TEMPDATE", value = NULL) return(data) } #' @title DT_GDL_Feature_Engineering #' #' @description Builds autoregressive and moving average from target columns and distributed lags and distributed moving average for independent features distributed across time. On top of that, you can also create time between instances along with their associated lags and moving averages. This function works for data with groups and without groups. #' #' @author Adrian Antico #' @family Feature Engineering #' #' @param data A data.table you want to run the function on #' @param lags A numeric vector of the specific lags you want to have generated. You must include 1 if WindowingLag = 1. #' @param periods A numeric vector of the specific rolling statistics window sizes you want to utilize in the calculations. #' @param SDperiods A numeric vector of Standard Deviation rolling statistics window sizes you want to utilize in the calculations. #' @param Skewperiods A numeric vector of Skewness rolling statistics window sizes you want to utilize in the calculations. #' @param Kurtperiods A numeric vector of Kurtosis rolling statistics window sizes you want to utilize in the calculations. #' @param Quantileperiods A numeric vector of Quantile rolling statistics window sizes you want to utilize in the calculations. #' @param statsFUNs Select from the following c("mean","sd","skew","kurt","q5","q10","q15","q20","q25","q30","q35","q40","q45","q50","q55","q60","q65","q70","q75","q80","q85","q90","q95") #' @param targets A character vector of the column names for the reference column in which you will build your lags and rolling stats #' @param groupingVars A character vector of categorical variable names you will build your lags and rolling stats by #' @param sortDateName The column name of your date column used to sort events over time #' @param timeDiffTarget Specify a desired name for features created for time between events. Set to NULL if you don't want time between events features created. #' @param timeAgg List the time aggregation level for the time between events features, such as "hour", "day", "week", "month", "quarter", or "year" #' @param WindowingLag Set to 0 to build rolling stats off of target columns directly or set to 1 to build the rolling stats off of the lag-1 target #' @param Type List either "Lag" if you want features built on historical values or "Lead" if you want features built on future values #' @param ShortName Default TRUE. If FALSE, Group Variable names will be added to the rolling stat and lag names. If you plan on have multiple versions of lags and rollings stats by different group variables then set this to FALSE. #' @param SimpleImpute Set to TRUE for factor level imputation of "0" and numeric imputation of -1 #' @return data.table of original data plus created lags, rolling stats, and time between event lags and rolling stats #' @noRd DT_GDL_Feature_Engineering <- function(data, lags = 1, periods = 0, SDperiods = 0, Skewperiods = 0, Kurtperiods = 0, Quantileperiods = 0, statsFUNs = c("mean"), targets = NULL, groupingVars = NULL, sortDateName = NULL, timeDiffTarget = NULL, timeAgg = c("days"), WindowingLag = 0, ShortName = TRUE, Type = c("Lag"), SimpleImpute = TRUE) { # timeAgg if(is.null(timeAgg)) { timeAgg <- "TimeUnitNULL" } else if(tolower(timeAgg) == "raw") { timeAggss <- "transactional" timeAgg <- "day" } else { timeAggss <- timeAgg } # Number of targets tarNum <- length(targets) # Argument Checks if(is.null(lags) && WindowingLag == 1) lags <- 1 if(!(1 %in% lags) && WindowingLag == 1) lags <- c(1, lags) if(any(lags < 0)) stop("lags need to be positive integers") if(!is.null(groupingVars)) if(!is.character(groupingVars)) stop("groupingVars needs to be a character scalar or vector") if(!is.character(targets)) stop("targets needs to be a character scalar or vector") if(!is.character(sortDateName)) stop("sortDateName needs to be a character scalar or vector") if(!is.null(timeAgg)) if(!is.character(timeAgg)) stop("timeAgg needs to be a character scalar or vector") if(!(WindowingLag %in% c(0, 1))) stop("WindowingLag needs to be either 0 or 1") if(!(tolower(Type) %chin% c("lag", "lead"))) stop("Type needs to be either Lag or Lead") if(!is.logical(SimpleImpute)) stop("SimpleImpute needs to be TRUE or FALSE") # Ensure enough columns are allocated beforehand if(!is.null(groupingVars)) { if(ncol(data) + (length(lags) + length(periods)) * tarNum * length(groupingVars) * length(statsFUNs) > data.table::truelength(data)) { data.table::alloc.col(DT = data, n = ncol(data) + (length(lags) + length(periods)) * tarNum * length(groupingVars) * length(statsFUNs)) } } else { if(ncol(data) + (length(lags) + length(periods)) * tarNum * length(statsFUNs) > data.table::truelength(data)) { data.table::alloc.col(DT = data, n = ncol(data) + (length(lags) + length(periods)) * tarNum * length(statsFUNs)) } } # Begin feature engineering---- if(!is.null(groupingVars)) { for(i in seq_along(groupingVars)) {# i = 1 Targets <- targets # Sort data---- if(tolower(Type) == "lag") { colVar <- c(groupingVars[i], sortDateName[1L]) data.table::setorderv(data, colVar, order = 1L) } else { colVar <- c(groupingVars[i], sortDateName[1L]) data.table::setorderv(data, colVar, order = -1L) } # Lags ---- LAG_Names <- c() for(t in Targets) { if(ShortName) { LAG_Names <- c(LAG_Names, paste0(timeAggss, "_LAG_", lags, "_", t)) } else { LAG_Names <- c(LAG_Names, paste0(timeAggss, "_", groupingVars[i], "_LAG_", lags, "_", t)) } } data[, paste0(LAG_Names) := data.table::shift(.SD, n = lags, type = "lag"), by = c(groupingVars[i]), .SDcols = c(Targets)] # Define targets---- if(WindowingLag != 0L) { if(ShortName) { Targets <- paste0(timeAggss, "_LAG_", WindowingLag, "_", Targets) } else { Targets <- paste0(timeAggss, "_", groupingVars[i], "_LAG_", WindowingLag, "_", Targets) } } # MA stats ---- if(any(tolower(statsFUNs) %chin% "mean") && !all(periods %in% c(0L, 1L))) { periods <- periods[periods > 1L] MA_Names <- c() for(t in Targets) for(j in seq_along(periods)) MA_Names <- c(MA_Names, paste0("Mean_", periods[j],"_", t)) data[, paste0(MA_Names) := data.table::frollmean( x = .SD, n = periods, fill = NA, algo = "fast", align = "right", na.rm = TRUE, hasNA = TRUE, adaptive = FALSE), by = c(groupingVars[i]), .SDcols = c(Targets)] } # SD stats ---- if(any(tolower(statsFUNs) %chin% c("sd")) && !all(SDperiods %in% c(0L,1L))) { tempperiods <- SDperiods[SDperiods > 1L] SD_Names <- c() for(t in Targets) for(j in seq_along(tempperiods)) SD_Names <- c(SD_Names, paste0("SD_", tempperiods[j], "_", t)) data[, paste0(SD_Names) := data.table::frollapply(x = .SD, n = tempperiods, FUN = sd, na.rm = TRUE), by = c(groupingVars[i]), .SDcols = c(Targets)] } # Skewness stats ---- if(any(tolower(statsFUNs) %chin% c("skew")) && !all(Skewperiods %in% c(0L,1L,2L))) { tempperiods <- Skewperiods[Skewperiods > 2L] Skew_Names <- c() for(t in Targets) for(j in seq_along(tempperiods)) Skew_Names <- c(Skew_Names, paste0("Skew_", tempperiods[j], "_", t)) data[, paste0(Skew_Names) := data.table::frollapply(x = .SD, n = tempperiods, FUN = e1071::skewness, na.rm = TRUE), by = c(groupingVars[i]), .SDcols = Targets] } # Kurtosis stats ---- if(any(tolower(statsFUNs) %chin% c("kurt")) && !all(Kurtperiods %in% c(0L,1L,2L,3L,4L))) { tempperiods <- Kurtperiods[Kurtperiods > 3L] Kurt_Names <- c() for(t in Targets) for(j in seq_along(tempperiods)) Kurt_Names <- c(Kurt_Names, paste0("Kurt_", tempperiods[j], "_", t)) data[, paste0(Kurt_Names) := data.table::frollapply(x = .SD, n = tempperiods, FUN = e1071::kurtosis, na.rm = TRUE), by = c(groupingVars[i]), .SDcols = c(Targets)] } # Quantiles ---- if(!all(Quantileperiods %in% c(0L,1L,2L,3L,4L))) { tempperiods <- Quantileperiods[Quantileperiods > 4L] for(z in c(seq(5L,95L,5L))) { if(any(paste0("q",z) %chin% statsFUNs)) { Names <- c() for(t in Targets) for(j in seq_along(tempperiods)) Names <- c(Names, paste0("Q_", z, "_", tempperiods[j], "_", t)) data[, paste0(Names) := data.table::frollapply(x = .SD, n = tempperiods, FUN = quantile, probs = z/100, na.rm = TRUE), by = c(groupingVars[i]), .SDcols = c(Targets)] } } } } # Impute missing values ---- if(SimpleImpute) { for(j in seq_along(data)) { if(is.factor(data[[j]])) { data.table::set(data, which(!(data[[j]] %in% levels(data[[j]]))), j, "0") } else { data.table::set(data, which(is.na(data[[j]])), j, -1) } } } # Done!! ---- return(data) } else { # Sort data if(tolower(Type) == "lag") { data.table::setorderv(data, c(sortDateName[1L]), order = 1L) } else { data.table::setorderv(data, c(sortDateName[1L]), order = -1L) } Targets <- targets # Lags ---- LAG_Names <- c() for(t in Targets) LAG_Names <- c(LAG_Names, paste0(timeAggss, "_", "LAG_", lags, "_", t)) # Build features ---- data[, eval(LAG_Names) := data.table::shift(.SD, n = lags, type = "lag"), .SDcols = c(Targets)] # Define targets ---- if(WindowingLag != 0L) { Targets <- paste0(timeAggss, "_", "LAG_", WindowingLag, "_", Targets) } else { Targets <- Targets } # MA stats ---- if(any(tolower(statsFUNs) %chin% "mean") && !all(periods %in% c(0L, 1L))) { periods <- periods[periods > 1L] MA_Names <- c() for(t in Targets) for(j in seq_along(periods)) MA_Names <- c(MA_Names, paste0("Mean_", periods[j], "_", t)) data[, paste0(MA_Names) := data.table::frollmean(x = .SD, n = periods, fill = NA, algo = "fast", align = "right", na.rm = TRUE, hasNA = TRUE, adaptive = FALSE), .SDcols = c(Targets)] } # SD stats ---- if(any(tolower(statsFUNs) %chin% c("sd")) && !all(SDperiods %in% c(0L,1L))) { tempperiods <- SDperiods[SDperiods > 1L] SD_Names <- c() for(t in Targets) for(j in seq_along(tempperiods)) SD_Names <- c(SD_Names, paste0("SD_", tempperiods[j], "_", t)) data[, paste0(SD_Names) := data.table::frollapply(x = .SD, n = tempperiods, FUN = sd, na.rm = TRUE), .SDcols = c(Targets)] } # Skewness stats ---- if(any(tolower(statsFUNs) %chin% c("skew")) && !all(Skewperiods %in% c(0L,1L,2L))) { tempperiods <- Skewperiods[Skewperiods > 2L] Skew_Names <- c() for(t in Targets) for(j in seq_along(tempperiods)) Skew_Names <- c(Skew_Names, paste0("Skew_", tempperiods[j], "_", t)) data[, paste0(Skew_Names) := data.table::frollapply(x = .SD, n = tempperiods, FUN = e1071::skewness, na.rm = TRUE), .SDcols = c(Targets)] } # Kurtosis stats ---- if(any(tolower(statsFUNs) %chin% c("kurt")) && !all(Kurtperiods %in% c(0L,1L,2L,3L))) { tempperiods <- Kurtperiods[Kurtperiods > 3L] Kurt_Names <- c() for(t in Targets) for(j in seq_along(tempperiods)) Kurt_Names <- c(Kurt_Names, paste0("Kurt_", tempperiods[j], "_", t)) data[, paste0(Kurt_Names) := data.table::frollapply(x = .SD, n = tempperiods, FUN = e1071::kurtosis, na.rm = TRUE), .SDcols = c(Targets)] } # Quantiles ---- if(!all(Quantileperiods %in% c(0L,1L,2L,3L,4L))) { tempperiods <- Quantileperiods[Quantileperiods > 4L] for(z in c(seq(5L,95L,5L))) { if(any(paste0("q",z) %chin% statsFUNs)) { Names <- c() for(t in Targets) for(j in seq_along(tempperiods)) Names <- c(Names, paste0("Q_", z, "_", tempperiods[j], "_", t)) data[, paste0(Names) := data.table::frollapply(x = .SD, n = tempperiods, FUN = quantile, probs = z/100, na.rm = TRUE), .SDcols = c(Targets)] } } } # Impute missing values ---- if(SimpleImpute) { for(j in seq_along(data)) { if(is.factor(data[[j]])) { data.table::set(data, which(!(data[[j]] %in% levels(data[[j]]))), j, "0") } else { data.table::set(data, which(is.na(data[[j]])), j, -1) } } } # Done!! ---- return(data) } } #' @title FullFactorialCatFeatures #' #' @description FullFactorialCatFeatures reverses the difference #' #' @family Data Wrangling #' #' @author Adrian Antico #' #' @param GroupVars Character vector of categorical columns to fully interact #' @param MaxCombin The max K in N choose K. If NULL, K will loop through 1 to length(GroupVars) #' @param BottomsUp TRUE or FALSE. TRUE starts with the most comlex interaction to the main effects #' #' @noRd FullFactorialCatFeatures <- function(GroupVars = NULL, MaxCombin = NULL, BottomsUp = TRUE) { if(is.null(MaxCombin)) { MaxCombin <- N <- length(GroupVars) } else { N <- MaxCombin } Categoricals <- c() # N choose 1 case for(j in seq_along(GroupVars)) Categoricals <- c(Categoricals,GroupVars[j]) # N choose i for 2 <= i < N for(i in seq_len(N)[-1L]) { # Case 2: N choose 2 up to N choose N-1: Middle-Hierarchy Interactions if(MaxCombin == length(GroupVars)) { if(i < N) { temp <- combinat::combn(GroupVars, m = i) temp2 <- c() for(k in seq_len(ncol(temp))) { for(l in seq_len(i)) { if(l == 1L) { temp2 <- temp[l,k] } else { temp2 <- paste(temp2,temp[l,k], sep = '_') } } Categoricals <- c(Categoricals, temp2) } # Case 3: N choose N - Full Interaction } else if(i == length(GroupVars)) { temp <- combinat::combn(GroupVars, m = i) for(m in seq_len(N)) { if(m == 1) { temp2 <- temp[m] } else { temp2 <- paste(temp2,temp[m], sep = '_') } } Categoricals <- c(Categoricals, temp2) } } else { if(i <= N) { temp <- combinat::combn(GroupVars, m = i) temp2 <- c() for(k in seq_len(ncol(temp))) { for(l in seq_len(i)) { if(l == 1L) { temp2 <- temp[l,k] } else { temp2 <- paste(temp2,temp[l,k], sep = '_') } } Categoricals <- c(Categoricals, temp2) } # Case 3: N choose N - Full Interaction } else if(i == length(GroupVars)) { temp <- combinat::combn(GroupVars, m = i) for(m in seq_len(N)) { if(m == 1) { temp2 <- temp[m] } else { temp2 <- paste(temp2,temp[m], sep = '_') } } Categoricals <- c(Categoricals, temp2) } } } # Order of output if(BottomsUp) return(rev(Categoricals)) else return(Categoricals) } # ---- # ----
/scratch/gouwar.j/cran-all/cranData/AutoPlots/R/AccessoryFunctions.R
# AutoQuant is a package for quickly creating high quality visualizations under a common and easy api. # Copyright (C) <year> <name of author> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <https://www.gnu.org/licenses/>. utils::globalVariables( names = c( "1 - Specificity", "Adrian", "Appointments", "Buckets", "CalendarDateColumn", "ClassWeights", "CohortDateColumn", "CohortDays", "Comment", "CostMatrixWeights", "Date", "DateTime", "FP", "Gain", "GroupVariables", "GroupVars", "Importance", "Independent_Variable1", "Independent_Variable10", "Independent_Variable2", "Independent_Variable3", "Independent_Variable4", "Independent_Variable5", "Independent_Variable6", "Independent_Variable7", "Independent_Variable8", "Independent_Variable9", "Leads", "Level", "Lift", "Mean.X", "Measure_Variable", "Measures", "MethodName", "Metric", "ModelID", "N", "NegScore", "Normal Line", "NormalizedStatistics", "NumNull", "P_Predicted", "Percentile", "Plot.Polar", "Population", "Proportion in Target", "Rates", "RowSum", "Sales", "SaveModelObjects", "Specificity", "TEMPDATE", "TP", "Target - Predicted", "TargetColumnName", "Theoretical Quantiles", "TimeLine", "TrainOnFull", "ValidationData", "Weights", "Y_Scroll", "V1", "ZVar", "classPredict", "i.Metric", "metadata_path", "model_path", "size_vals", "spearman", "temp__", "temp_i", "x1", "x2", "xx" ) )
/scratch/gouwar.j/cran-all/cranData/AutoPlots/R/GlobalVariables.R
# AutoPlots is a package for quickly creating high quality visualizations under a common and easy api. # Copyright (C) <year> <name of author> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <https://www.gnu.org/licenses/>. #' @import data.table #' @importFrom data.table data.table %chin% .I .N .SD := as.data.table fwrite is.data.table rbindlist set setcolorder setnames setorderv as.IDate as.ITime %like% #' @importFrom lubridate %m+% #' @importFrom utils installed.packages #' @importFrom stats as.formula cor cor.test dgeom lm median na.omit optimize pnorm qnorm quantile runif sd setNames var #' @importFrom utils head NULL .datatable.aware = TRUE
/scratch/gouwar.j/cran-all/cranData/AutoPlots/R/Imports.R
# AutoPlots is a package for quickly creating high quality visualizations under a common and easy api. # Copyright (C) <year> <name of author> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WAfppRRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <https://www.gnu.org/licenses/>. # @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ---- # > Automated Plot Functions ---- # @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ---- #' @title Plot.StandardPlots #' #' @description Helper for standard plots #' #' @author Adrian Antico #' @family Auto Plotting #' #' @param PlotType character #' @param dt source data.table #' @param PreAgg FALSE #' @param AggMethod character #' @param SampleSize character #' @param YVar Y-Axis variable name #' @param DualYVar Secondary Axis for Line, Step, and Area plots #' @param XVar X-Axis variable name #' @param ZVar Z-Axis variable name #' @param GroupVar Character variable variable #' @param YVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param DualYVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param XVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param ZVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param FacetRows Defaults to 1 which causes no faceting to occur vertically. Otherwise, supply a numeric value for the number of output grid rows #' @param FacetCols Defaults to 1 which causes no faceting to occur horizontally. Otherwise, supply a numeric value for the number of output grid columns #' @param FacetLevels Faceting rows x columns is the max number of levels allowed in a grid. If your GroupVar has more you can supply the levels to display. #' @param NumberBins For histograms #' @param NumLevels_Y Numeric #' @param NumLevels_X Numeric #' @param Height NULL or valid css unit #' @param Width NULL or valid css unit #' @param EchartsTheme "auritus","azul","bee-inspired","blue","caravan","carp","chalk","cool","dark-bold","dark","eduardo", #' "essos","forest","fresh-cut","fruit","gray","green","halloween","helianthus","infographic","inspired", #' "jazz","london","dark","macarons","macarons2","mint","purple-passion","red-velvet","red","roma","royal", #' "sakura","shine","tech-blue","vintage","walden","wef","weforum","westeros","wonderland" #' @param MouseScroll logical, zoom via mouse scroll #' @param TimeLine character #' @param Title character #' @param ShowLabels character #' @param Title.YAxis character #' @param Title.XAxis character #' @param TextColor character #' @param FontSize numeric #' @param Debug Debugging purposes #' @return plot #' @export Plot.StandardPlots <- function(dt = NULL, PreAgg = FALSE, PlotType = 'Scatter', SampleSize = 100000L, AggMethod = 'mean', NumberBins = 30, YVar = NULL, DualYVar = NULL, XVar = NULL, ZVar = NULL, GroupVar = NULL, YVarTrans = NULL, DualYVarTrans = NULL, XVarTrans = NULL, ZVarTrans = NULL, FacetRows = 1, FacetCols = 1, FacetLevels = NULL, Height = NULL, Width = NULL, EchartsTheme = "dark-blue", MouseScroll = FALSE, TimeLine = FALSE, Title = NULL, ShowLabels = FALSE, Title.YAxis = NULL, Title.XAxis = NULL, NumLevels_Y = 75, NumLevels_X = 40, TextColor = "white", FontSize = 14, Debug = FALSE) { if(!data.table::is.data.table(dt)) tryCatch({data.table::setDT(dt)}, error = function(x) { dt <- data.table::as.data.table(dt) }) # Debug if(Debug) print(paste0('Plot.StandardPlots() begin, PlotType = ', PlotType)) Title.FontSize <- FontSize + 8L # Pie Plot if(tolower(PlotType) == 'pieplot') { p1 <- Plot.Pie( dt = dt, PreAgg = PreAgg, AggMethod = AggMethod, XVar = if(length(XVar) == 0 && length(GroupVar) > 0L) GroupVar[1L] else XVar, YVar = YVar, GroupVar = NULL, YVarTrans = YVarTrans, XVarTrans = XVarTrans, FacetRows = FacetRows, FacetCols = FacetCols, FacetLevels = FacetLevels, Width = Width, Height = Height, Title = Title, ShowLabels = ShowLabels, Title.YAxis = Title.YAxis, Title.XAxis = Title.XAxis, EchartsTheme = EchartsTheme, TimeLine = TimeLine, TextColor = TextColor, title.fontSize = Title.FontSize, Debug = Debug) Code <- paste0( "\n\n", "p1 <- AutoPlots::Plot.Pie(", "\n ", "dt = data1", ",\n ", "AggMethod = ", CEP(AggMethod), ",\n ", "PreAgg = ", CEPP(PreAgg), "\n ", "XVar = ", ExpandText(if(length(XVar) == 0 && length(GroupVar) > 0L) GroupVar[1L] else XVar), ",\n ", "YVar = ", ExpandText(YVar), ",\n ", "YVarTrans = ", CEP(YVarTrans), ",\n ", "XVarTrans = ", CEP(XVarTrans), ",\n ", "FacetRows = ", CEPP(FacetRows), ",\n ", "FacetCols = ", CEPP(FacetCols), ",\n ", "FacetLevels = ", ExpandText(FacetLevels), ",\n ", "Width = ", CEP(Width), ",\n ", "Height = ", CEP(Height), ",\n ", "Title = ", CEP(Title), ",\n ", "ShowLabels = ", CEPP(ShowLabels), ",\n ", "Title.YAxis = ", CEP(Title.YAxis), ",\n ", "Title.XAxis = ", CEP(Title.XAxis), ",\n ", "EchartsTheme = ", CEP(EchartsTheme), ",\n ", "TimeLine = ", CEPP(TimeLine), ",\n ", "TextColor = ", CEP(TextColor), ",\n ", "title.fontSize = ", CEPP(Title.FontSize), ")\n") return(list(Plot = p1, Code = Code)) } # Donut Plot if(tolower(PlotType) == 'donutplot') { p1 <- Plot.Donut( dt = dt, PreAgg = PreAgg, AggMethod = AggMethod, XVar = if(length(XVar) == 0 && length(GroupVar) > 0L) GroupVar[1L] else XVar, YVar = YVar, GroupVar = NULL, YVarTrans = YVarTrans, XVarTrans = XVarTrans, FacetRows = FacetRows, FacetCols = FacetCols, FacetLevels = FacetLevels, Width = Width, Height = Height, Title = Title, ShowLabels = ShowLabels, Title.YAxis = Title.YAxis, Title.XAxis = Title.XAxis, EchartsTheme = EchartsTheme, TimeLine = TimeLine, TextColor = TextColor, title.fontSize = Title.FontSize, Debug = Debug) Code <- paste0( "\n\n", "p1 <- AutoPlots::Plot.Donut(", "\n ", "dt = data1", ",\n ", "AggMethod = ", CEP(AggMethod), ",\n ", "PreAgg = ", CEPP(PreAgg), "\n ", "XVar = ", ExpandText(if(length(XVar) == 0 && length(GroupVar) > 0L) GroupVar[1L] else XVar), ",\n ", "YVar = ", ExpandText(YVar), ",\n ", "YVarTrans = ", CEP(YVarTrans), ",\n ", "XVarTrans = ", CEP(XVarTrans), ",\n ", "FacetRows = ", CEPP(FacetRows), ",\n ", "FacetCols = ", CEPP(FacetCols), ",\n ", "FacetLevels = ", ExpandText(FacetLevels), ",\n ", "Width = ", CEP(Width), ",\n ", "Height = ", CEP(Height), ",\n ", "Title = ", CEP(Title), ",\n ", "ShowLabels = ", CEPP(ShowLabels), ",\n ", "Title.YAxis = ", CEP(Title.YAxis), ",\n ", "Title.XAxis = ", CEP(Title.XAxis), ",\n ", "EchartsTheme = ", CEP(EchartsTheme), ",\n ", "TimeLine = ", CEPP(TimeLine), ",\n ", "TextColor = ", CEP(TextColor), ",\n ", "title.fontSize = ", CEPP(Title.FontSize), ")\n") return(list(Plot = p1, Code = Code)) } # Rosetype Plot if(tolower(PlotType) == 'rosetypeplot') { p1 <- Plot.Rosetype( dt = dt, PreAgg = PreAgg, AggMethod = AggMethod, XVar = if(length(XVar) == 0 && length(GroupVar) > 0L) GroupVar[1L] else XVar, YVar = YVar, GroupVar = NULL, YVarTrans = YVarTrans, XVarTrans = XVarTrans, FacetRows = FacetRows, FacetCols = FacetCols, FacetLevels = FacetLevels, Width = Width, Height = Height, Title = Title, ShowLabels = ShowLabels, Title.YAxis = Title.YAxis, Title.XAxis = Title.XAxis, EchartsTheme = EchartsTheme, TimeLine = TimeLine, TextColor = TextColor, title.fontSize = Title.FontSize, Debug = Debug) Code <- paste0( "\n\n", "p1 <- AutoPlots::Plot.Rosetype(", "\n ", "dt = data1", ",\n ", "AggMethod = ", CEP(AggMethod), ",\n ", "PreAgg = ", CEPP(PreAgg), "\n ", "XVar = ", ExpandText(if(length(XVar) == 0 && length(GroupVar) > 0L) GroupVar[1L] else XVar), ",\n ", "YVar = ", ExpandText(YVar), ",\n ", "YVarTrans = ", CEP(YVarTrans), ",\n ", "XVarTrans = ", CEP(XVarTrans), ",\n ", "FacetRows = ", CEPP(FacetRows), ",\n ", "FacetCols = ", CEPP(FacetCols), ",\n ", "FacetLevels = ", ExpandText(FacetLevels), ",\n ", "Width = ", CEP(Width), ",\n ", "Height = ", CEP(Height), ",\n ", "Title = ", CEP(Title), ",\n ", "ShowLabels = ", CEPP(ShowLabels), ",\n ", "Title.YAxis = ", CEP(Title.YAxis), ",\n ", "Title.XAxis = ", CEP(Title.XAxis), ",\n ", "EchartsTheme = ", CEP(EchartsTheme), ",\n ", "TimeLine = ", CEPP(TimeLine), ",\n ", "TextColor = ", CEP(TextColor), ",\n ", "title.fontSize = ", CEPP(Title.FontSize), ")\n") return(list(Plot = p1, Code = Code)) } # Box Plot if(tolower(PlotType) == 'boxplot') { p1 <- Plot.Box( dt = dt, SampleSize = SampleSize, XVar = XVar, YVar = YVar, GroupVar = GroupVar, YVarTrans = YVarTrans, XVarTrans = XVarTrans, FacetRows = FacetRows, FacetCols = FacetCols, FacetLevels = FacetLevels, Width = Width, Height = Height, Title = Title, MouseScroll = MouseScroll, ShowLabels = ShowLabels, Title.YAxis = Title.YAxis, Title.XAxis = Title.XAxis, EchartsTheme = EchartsTheme, TimeLine = TimeLine, TextColor = TextColor, title.fontSize = Title.FontSize, Debug = Debug) Code <- paste0( "\n\n", "p1 <- AutoPlots::Plot.Box(", "\n ", "dt = data1", ",\n ", "SampleSize = ", CEPP(SampleSize), ",\n ", "XVar = ", ExpandText(XVar), ",\n ", "YVar = ", ExpandText(YVar), ",\n ", "GroupVar = ", CEP(GroupVar), ",\n ", "YVarTrans = ", CEP(YVarTrans), ",\n ", "XVarTrans = ", CEP(XVarTrans), ",\n ", "FacetRows = ", CEPP(FacetRows), ",\n ", "FacetCols = ", CEPP(FacetCols), ",\n ", "FacetLevels = ", ExpandText(FacetLevels), ",\n ", "Width = ", CEP(Width), ",\n ", "Height = ", CEP(Height), ",\n ", "Title = ", CEP(Title), ",\n ", "ShowLabels = ", CEPP(ShowLabels), ",\n ", "Title.YAxis = ", CEP(Title.YAxis), ",\n ", "Title.XAxis = ", CEP(Title.XAxis), ",\n ", "EchartsTheme = ", CEP(EchartsTheme), ",\n ", "TimeLine = ", CEPP(TimeLine), ",\n ", "TextColor = ", CEP(TextColor), ",\n ", "title.fontSize = ", CEPP(Title.FontSize), ")\n") return(list(Plot = p1, Code = Code)) } # Histogram Plot if(tolower(PlotType) == 'histogramplot') { p1 <- Plot.Histogram( dt = dt, SampleSize = SampleSize, XVar = XVar, YVar = YVar, GroupVar = GroupVar, YVarTrans = YVarTrans, XVarTrans = XVarTrans, FacetRows = FacetRows, FacetCols = FacetCols, FacetLevels = FacetLevels, NumberBins = NumberBins, Width = Width, Height = Height, Title = Title, MouseScroll = MouseScroll, ShowLabels = ShowLabels, Title.YAxis = Title.YAxis, Title.XAxis = Title.XAxis, EchartsTheme = EchartsTheme, TimeLine = TimeLine, TextColor = TextColor, title.fontSize = Title.FontSize, Debug = Debug) Code <- paste0( "\n\n", "p1 <- AutoPlots::Plot.Histogram(", "\n ", "dt = data1", ",\n ", "SampleSize = ", CEPP(SampleSize), ",\n ", "XVar = ", ExpandText(XVar), ",\n ", "YVar = ", ExpandText(YVar), ",\n ", "GroupVar = ", CEP(GroupVar), ",\n ", "YVarTrans = ", CEP(YVarTrans), ",\n ", "XVarTrans = ", CEP(XVarTrans), ",\n ", "FacetRows = ", CEPP(FacetRows), ",\n ", "FacetCols = ", CEPP(FacetCols), ",\n ", "FacetLevels = ", ExpandText(FacetLevels), ",\n ", "NumberBins = ", CEPP(NumberBins), ",\n ", "Width = ", CEP(Width), ",\n ", "Height = ", CEP(Height), ",\n ", "Title = ", CEP(Title), ",\n ", "ShowLabels = ", CEPP(ShowLabels), ",\n ", "Title.YAxis = ", CEP(Title.YAxis), ",\n ", "Title.XAxis = ", CEP(Title.XAxis), ",\n ", "EchartsTheme = ", CEP(EchartsTheme), ",\n ", "TimeLine = ", CEPP(TimeLine), ",\n ", "TextColor = ", CEP(TextColor), ",\n ", "title.fontSize = ", CEPP(Title.FontSize), ")\n") return(list(Plot = p1, Code = Code)) } # Density Plot if(tolower(PlotType) == 'densityplot') { p1 <- Plot.Density( dt = dt, SampleSize = SampleSize, GroupVar=GroupVar, YVarTrans = YVarTrans, XVarTrans = XVarTrans, FacetRows = FacetRows, FacetCols = FacetCols, FacetLevels = FacetLevels, Title = Title, ShowLabels = ShowLabels, Title.YAxis = Title.YAxis, Title.XAxis = Title.XAxis, XVar = NULL, YVar = if(length(YVar) > 0L) YVar else XVar, Width = Width, Height = Height, MouseScroll = MouseScroll, EchartsTheme = EchartsTheme, TimeLine = TimeLine, TextColor = TextColor, title.fontSize = Title.FontSize, Debug = Debug) Code <- paste0( "\n\n", "p1 <- AutoPlots::Plot.Density(", "\n ", "dt = data1", ",\n ", "SampleSize = ", CEPP(SampleSize), ",\n ", "XVar = ", ExpandText(XVar), ",\n ", "YVar = ", CEP(if(length(YVar) > 0L) YVar else XVar), ",\n ", "GroupVar = ", CEP(GroupVar), ",\n ", "YVarTrans = ", CEP(YVarTrans), ",\n ", "XVarTrans = ", CEP(XVarTrans), ",\n ", "FacetRows = ", CEPP(FacetRows), ",\n ", "FacetCols = ", CEPP(FacetCols), ",\n ", "FacetLevels = ", ExpandText(FacetLevels), ",\n ", "Width = ", CEP(Width), ",\n ", "Height = ", CEP(Height), ",\n ", "Title = ", CEP(Title), ",\n ", "ShowLabels = ", CEPP(ShowLabels), ",\n ", "Title.YAxis = ", CEP(Title.YAxis), ",\n ", "Title.XAxis = ", CEP(Title.XAxis), ",\n ", "EchartsTheme = ", CEP(EchartsTheme), ",\n ", "TimeLine = ", CEPP(TimeLine), ",\n ", "TextColor = ", CEP(TextColor), ",\n ", "title.fontSize = ", CEPP(Title.FontSize), ")\n") return(list(Plot = p1, Code = Code)) } # Line Plot if(tolower(PlotType) == 'lineplot') { p1 <- AutoPlots::Plot.Line( dt = dt, PreAgg = PreAgg, AggMethod = AggMethod, XVar = XVar, YVar = YVar, DualYVar = DualYVar, GroupVar = GroupVar, YVarTrans = YVarTrans, DualYVarTrans = DualYVarTrans, XVarTrans = XVarTrans, FacetRows = FacetRows, FacetCols = FacetCols, FacetLevels = FacetLevels, Width = Width, Height = Height, Title = Title, MouseScroll = MouseScroll, ShowLabels = ShowLabels, Title.YAxis = Title.YAxis, Title.XAxis = Title.XAxis, EchartsTheme = EchartsTheme, TimeLine = TimeLine, TextColor = TextColor, title.fontSize = Title.FontSize, Debug = Debug) Code <- paste0( "\n\n", "p1 <- AutoPlots::Plot.Line(", "\n ", "dt = data1", ",\n ", "AggMethod = ", CEP(AggMethod), ",\n ", "PreAgg = ", CEPP(PreAgg), "\n ", "XVar = ", CEP(XVar), ",\n ", "YVar = ", ExpandText(YVar), ",\n ", "GroupVar = ", CEP(GroupVar),",\n ", "DualYVar = ", ExpandText(DualYVar), ",\n ", "YVarTrans = ", CEP(YVarTrans), ",\n ", "DualYVarTrans = ", CEP(DualYVarTrans), ",\n ", "XVarTrans = ", CEP(XVarTrans), ",\n ", "FacetRows = ", CEPP(FacetRows), ",\n ", "FacetCols = ", CEPP(FacetCols), ",\n ", "FacetLevels = ", ExpandText(FacetLevels), ",\n ", "Width = ", CEP(Width), ",\n ", "Height = ", CEP(Height), ",\n ", "Title = ", CEP(Title), ",\n ", "ShowLabels = ", CEPP(ShowLabels), ",\n ", "Title.YAxis = ", CEP(Title.YAxis), ",\n ", "Title.XAxis = ", CEP(Title.XAxis), ",\n ", "EchartsTheme = ", CEP(EchartsTheme), ",\n ", "TimeLine = ", CEPP(TimeLine), ",\n ", "TextColor = ", CEP(TextColor), ",\n ", "title.fontSize = ", CEPP(Title.FontSize), ")\n") return(list(Plot = p1, Code = Code)) } # Area Plot if(tolower(PlotType) == 'areaplot') { p1 <- AutoPlots::Plot.Area( dt = dt, PreAgg = PreAgg, AggMethod = AggMethod, XVar = XVar, YVar = YVar, DualYVar = DualYVar, GroupVar = GroupVar, YVarTrans = YVarTrans, DualYVarTrans = DualYVarTrans, XVarTrans = XVarTrans, FacetRows = FacetRows, FacetCols = FacetCols, FacetLevels = FacetLevels, Width = Width, Height = Height, Title = Title, MouseScroll = MouseScroll, ShowLabels = ShowLabels, Title.YAxis = Title.YAxis, Title.XAxis = Title.XAxis, EchartsTheme = EchartsTheme, TimeLine = TimeLine, TextColor = TextColor, title.fontSize = Title.FontSize, Debug = Debug) Code <- paste0( "\n\n", "p1 <- AutoPlots::Plot.Area(", "\n ", "dt = data1", ",\n ", "AggMethod = ", CEP(AggMethod), ",\n ", "PreAgg = ", CEPP(PreAgg), "\n ", "XVar = ", CEP(XVar), ",\n ", "YVar = ", ExpandText(YVar), ",\n ", "GroupVar = ", CEP(GroupVar),",\n ", "DualYVar = ", ExpandText(DualYVar), ",\n ", "YVarTrans = ", CEP(YVarTrans), ",\n ", "DualYVarTrans = ", CEP(DualYVarTrans), ",\n ", "XVarTrans = ", CEP(XVarTrans), ",\n ", "FacetRows = ", CEPP(FacetRows), ",\n ", "FacetCols = ", CEPP(FacetCols), ",\n ", "FacetLevels = ", ExpandText(FacetLevels), ",\n ", "Width = ", CEP(Width), ",\n ", "Height = ", CEP(Height), ",\n ", "Title = ", CEP(Title), ",\n ", "ShowLabels = ", CEPP(ShowLabels), ",\n ", "Title.YAxis = ", CEP(Title.YAxis), ",\n ", "Title.XAxis = ", CEP(Title.XAxis), ",\n ", "EchartsTheme = ", CEP(EchartsTheme), ",\n ", "TimeLine = ", CEPP(TimeLine), ",\n ", "TextColor = ", CEP(TextColor), ",\n ", "title.fontSize = ", CEPP(Title.FontSize), ")\n") return(list(Plot = p1, Code = Code)) } # Step Plot if(tolower(PlotType) == 'stepplot') { p1 <- AutoPlots::Plot.Step( dt = dt, PreAgg = PreAgg, AggMethod = AggMethod, XVar = XVar, YVar = YVar, DualYVar = DualYVar, GroupVar = GroupVar, YVarTrans = YVarTrans, DualYVarTrans = DualYVarTrans, XVarTrans = XVarTrans, FacetRows = FacetRows, FacetCols = FacetCols, FacetLevels = FacetLevels, Width = Width, Height = Height, Title = Title, MouseScroll = MouseScroll, ShowLabels = ShowLabels, Title.YAxis = Title.YAxis, Title.XAxis = Title.XAxis, EchartsTheme = EchartsTheme, TimeLine = TimeLine, TextColor = TextColor, title.fontSize = Title.FontSize, Debug = Debug) Code <- paste0( "\n\n", "p1 <- AutoPlots::Plot.Step(", "\n ", "dt = data1", ",\n ", "AggMethod = ", CEP(AggMethod), ",\n ", "PreAgg = ", CEPP(PreAgg), "\n ", "XVar = ", CEP(XVar), ",\n ", "YVar = ", ExpandText(YVar), ",\n ", "GroupVar = ", CEP(GroupVar),",\n ", "DualYVar = ", ExpandText(DualYVar), ",\n ", "YVarTrans = ", CEP(YVarTrans), ",\n ", "DualYVarTrans = ", CEP(DualYVarTrans), ",\n ", "XVarTrans = ", CEP(XVarTrans), ",\n ", "FacetRows = ", CEPP(FacetRows), ",\n ", "FacetCols = ", CEPP(FacetCols), ",\n ", "FacetLevels = ", ExpandText(FacetLevels), ",\n ", "Width = ", CEP(Width), ",\n ", "Height = ", CEP(Height), ",\n ", "Title = ", CEP(Title), ",\n ", "ShowLabels = ", CEPP(ShowLabels), ",\n ", "Title.YAxis = ", CEP(Title.YAxis), ",\n ", "Title.XAxis = ", CEP(Title.XAxis), ",\n ", "EchartsTheme = ", CEP(EchartsTheme), ",\n ", "TimeLine = ", CEPP(TimeLine), ",\n ", "TextColor = ", CEP(TextColor), ",\n ", "title.fontSize = ", CEPP(Title.FontSize), ")\n") return(list(Plot = p1, Code = Code)) } # River Plot if(tolower(PlotType) == 'riverplot') { p1 <- AutoPlots::Plot.River( dt = dt, PreAgg = PreAgg, AggMethod = AggMethod, XVar = XVar, YVar = YVar, GroupVar = GroupVar, YVarTrans = YVarTrans, XVarTrans = XVarTrans, FacetRows = FacetRows, FacetCols = FacetCols, FacetLevels = FacetLevels, Width = Width, Height = Height, Title = Title, ShowLabels = ShowLabels, Title.YAxis = Title.YAxis, Title.XAxis = Title.XAxis, EchartsTheme = EchartsTheme, TimeLine = TimeLine, MouseScroll = MouseScroll, ShowSymbol = FALSE, TextColor = TextColor, title.fontSize = Title.FontSize, Debug = Debug) Code <- paste0( "\n\n", "p1 <- AutoPlots::Plot.River(", "\n ", "dt = data1", ",\n ", "AggMethod = ", CEP(AggMethod), ",\n ", "PreAgg = ", CEPP(PreAgg), "\n ", "XVar = ", CEP(XVar), ",\n ", "YVar = ", ExpandText(YVar), ",\n ", "GroupVar = ", CEP(GroupVar),",\n ", "YVarTrans = ", CEP(YVarTrans), ",\n ", "XVarTrans = ", CEP(XVarTrans), ",\n ", "FacetRows = ", CEPP(FacetRows), ",\n ", "FacetCols = ", CEPP(FacetCols), ",\n ", "FacetLevels = ", ExpandText(FacetLevels), ",\n ", "Width = ", CEP(Width), ",\n ", "Height = ", CEP(Height), ",\n ", "Title = ", CEP(Title), ",\n ", "ShowLabels = ", CEPP(ShowLabels), ",\n ", "Title.YAxis = ", CEP(Title.YAxis), ",\n ", "Title.XAxis = ", CEP(Title.XAxis), ",\n ", "EchartsTheme = ", CEP(EchartsTheme), ",\n ", "TimeLine = ", CEPP(TimeLine), ",\n ", "TextColor = ", CEP(TextColor), ",\n ", "title.fontSize = ", CEPP(Title.FontSize), ")\n") return(list(Plot = p1, Code = Code)) } # Polar Plot if(tolower(PlotType) == 'polarplot') { p1 <- Plot.Polar( dt = dt, PreAgg = PreAgg, AggMethod = AggMethod, XVar = XVar, YVar = YVar, YVarTrans = YVarTrans, XVarTrans = XVarTrans, FacetRows = FacetRows, FacetCols = FacetCols, FacetLevels = FacetLevels, Width = Width, Height = Height, Title = Title, ShowLabels = ShowLabels, Title.YAxis = Title.YAxis, Title.XAxis = Title.XAxis, EchartsTheme = EchartsTheme, TimeLine = TimeLine, TextColor = TextColor, title.fontSize = Title.FontSize, Debug = Debug) Code <- paste0( "\n\n", "p1 <- AutoPlots::Plot.Polar(", "\n ", "dt = data1", ",\n ", "AggMethod = ", CEP(AggMethod), ",\n ", "PreAgg = ", CEPP(PreAgg), "\n ", "XVar = ", CEP(XVar), ",\n ", "YVar = ", ExpandText(YVar), ",\n ", "YVarTrans = ", CEP(YVarTrans), ",\n ", "XVarTrans = ", CEP(XVarTrans), ",\n ", "FacetRows = ", CEPP(FacetRows), ",\n ", "FacetCols = ", CEPP(FacetCols), ",\n ", "FacetLevels = ", ExpandText(FacetLevels), ",\n ", "Width = ", CEP(Width), ",\n ", "Height = ", CEP(Height), ",\n ", "Title = ", CEP(Title), ",\n ", "ShowLabels = ", CEPP(ShowLabels), ",\n ", "Title.YAxis = ", CEP(Title.YAxis), ",\n ", "Title.XAxis = ", CEP(Title.XAxis), ",\n ", "EchartsTheme = ", CEP(EchartsTheme), ",\n ", "TimeLine = ", CEPP(TimeLine), ",\n ", "TextColor = ", CEP(TextColor), ",\n ", "title.fontSize = ", CEPP(Title.FontSize), ")\n") return(list(Plot = p1, Code = Code)) } # Bar Plot if(tolower(PlotType) == 'barplot') { p1 <- Plot.Bar( dt = dt, PreAgg = PreAgg, AggMethod = AggMethod, XVar = XVar, YVar = YVar, GroupVar = if(all(XVar == GroupVar)) NULL else GroupVar, YVarTrans = YVarTrans, XVarTrans = XVarTrans, FacetRows = FacetRows, FacetCols = FacetCols, FacetLevels = FacetLevels, Width = Width, Height = Height, Title = Title, ShowLabels = ShowLabels, MouseScroll = MouseScroll, Title.YAxis = Title.YAxis, Title.XAxis = Title.XAxis, EchartsTheme = EchartsTheme, TimeLine = TimeLine, TextColor = TextColor, title.fontSize = Title.FontSize, Debug = Debug) Code <- paste0( "\n\n", "p1 <- AutoPlots::Plot.Bar(", "\n ", "dt = data1", ",\n ", "AggMethod = ", CEP(AggMethod), ",\n ", "PreAgg = ", CEPP(PreAgg), "\n ", "XVar = ", CEP(XVar), ",\n ", "YVar = ", ExpandText(YVar), ",\n ", "GroupVar = ", CEP(if(all(XVar == GroupVar)) NULL else GroupVar), ",\n ", "YVarTrans = ", CEP(YVarTrans), ",\n ", "XVarTrans = ", CEP(XVarTrans), ",\n ", "FacetRows = ", CEPP(FacetRows), ",\n ", "FacetCols = ", CEPP(FacetCols), ",\n ", "FacetLevels = ", ExpandText(FacetLevels), ",\n ", "Width = ", CEP(Width), ",\n ", "Height = ", CEP(Height), ",\n ", "Title = ", CEP(Title), ",\n ", "ShowLabels = ", CEPP(ShowLabels), ",\n ", "Title.YAxis = ", CEP(Title.YAxis), ",\n ", "Title.XAxis = ", CEP(Title.XAxis), ",\n ", "EchartsTheme = ", CEP(EchartsTheme), ",\n ", "TimeLine = ", CEPP(TimeLine), ",\n ", "TextColor = ", CEP(TextColor), ",\n ", "title.fontSize = ", CEPP(Title.FontSize), ")\n") return(list(Plot = p1, Code = Code)) } # Stacked Bar Plot if(tolower(PlotType) == 'stackedbarplot') { p1 <- Plot.StackedBar( dt = dt, PreAgg = PreAgg, AggMethod = AggMethod, XVar = XVar, YVar = YVar, GroupVar = if(all(XVar == GroupVar)) NULL else GroupVar, YVarTrans = YVarTrans, XVarTrans = XVarTrans, FacetRows = FacetRows, FacetCols = FacetCols, FacetLevels = FacetLevels, Width = Width, Height = Height, Title = Title, MouseScroll = MouseScroll, ShowLabels = ShowLabels, Title.YAxis = Title.YAxis, Title.XAxis = Title.XAxis, EchartsTheme = EchartsTheme, TimeLine = TimeLine, TextColor = TextColor, title.fontSize = Title.FontSize, Debug = Debug) Code <- paste0( "\n\n", "p1 <- AutoPlots::Plot.StackedBar(", "\n ", "dt = data1", ",\n ", "AggMethod = ", CEP(AggMethod), ",\n ", "PreAgg = ", CEPP(PreAgg), "\n ", "XVar = ", CEP(XVar), ",\n ", "YVar = ", ExpandText(YVar), ",\n ", "GroupVar = ", CEP(if(all(XVar == GroupVar)) NULL else GroupVar), ",\n ", "YVarTrans = ", CEP(YVarTrans), ",\n ", "XVarTrans = ", CEP(XVarTrans), ",\n ", "FacetRows = ", CEPP(FacetRows), ",\n ", "FacetCols = ", CEPP(FacetCols), ",\n ", "FacetLevels = ", ExpandText(FacetLevels), ",\n ", "Width = ", CEP(Width), ",\n ", "Height = ", CEP(Height), ",\n ", "Title = ", CEP(Title), ",\n ", "ShowLabels = ", CEPP(ShowLabels), ",\n ", "Title.YAxis = ", CEP(Title.YAxis), ",\n ", "Title.XAxis = ", CEP(Title.XAxis), ",\n ", "EchartsTheme = ", CEP(EchartsTheme), ",\n ", "TimeLine = ", CEPP(TimeLine), ",\n ", "TextColor = ", CEP(TextColor), ",\n ", "title.fontSize = ", CEPP(Title.FontSize), ")\n") return(list(Plot = p1, Code = Code)) } # 3D Bar Plot if(tolower(PlotType) %in% c('barplot3d','barplotd')) { p1 <- AutoPlots::Plot.BarPlot3D( PreAgg = PreAgg, dt = dt, YVar = YVar, XVar = XVar, ZVar = ZVar, YVarTrans = YVarTrans, XVarTrans = XVarTrans, ZVarTrans = ZVarTrans, FacetRows = FacetRows, FacetCols = FacetCols, FacetLevels = FacetLevels, AggMethod = AggMethod, NumberBins = 21, NumLevels_X = NumLevels_Y, NumLevels_Y = NumLevels_X, Width = Width, Height = Height, EchartsTheme = EchartsTheme, MouseScroll = MouseScroll, Title = Title, ShowLabels = ShowLabels, Title.YAxis = Title.YAxis, Title.XAxis = Title.XAxis, TextColor = TextColor, title.fontSize = Title.FontSize, Debug = Debug) Code <- paste0( "\n\n", "p1 <- AutoPlots::Plot.BarPlot3D(", "\n ", "dt = data1", ",\n ", "AggMethod = ", CEP(AggMethod), ",\n ", "PreAgg = ", CEPP(PreAgg), "\n ", "XVar = ", CEP(XVar), ",\n ", "YVar = ", ExpandText(YVar), ",\n ", "ZVar = ", CEP(ZVar), ",\n ", "YVarTrans = ", CEP(YVarTrans), ",\n ", "XVarTrans = ", CEP(XVarTrans), ",\n ", "ZVarTrans = ", CEP(ZVarTrans), ",\n ", "NumberBins = ", CEPP(21), ",\n ", "NumLevels_X = ", CEPP(NumLevels_Y), ",\n ", "NumLevels_Y = ", CEPP(NumLevels_X), ",\n ", "FacetRows = ", CEPP(FacetRows), ",\n ", "FacetCols = ", CEPP(FacetCols), ",\n ", "FacetLevels = ", ExpandText(FacetLevels), ",\n ", "Width = ", CEP(Width), ",\n ", "Height = ", CEP(Height), ",\n ", "Title = ", CEP(Title), ",\n ", "ShowLabels = ", CEPP(ShowLabels), ",\n ", "Title.YAxis = ", CEP(Title.YAxis), ",\n ", "Title.XAxis = ", CEP(Title.XAxis), ",\n ", "EchartsTheme = ", CEP(EchartsTheme), ",\n ", "TimeLine = ", CEPP(TimeLine), ",\n ", "TextColor = ", CEP(TextColor), ",\n ", "title.fontSize = ", CEPP(Title.FontSize), ")\n") return(list(Plot = p1, Code = Code)) } # Heat Map if(tolower(PlotType) %in% 'heatmapplot') { p1 <- AutoPlots::Plot.HeatMap( PreAgg = PreAgg, dt = dt, YVar = YVar, XVar = XVar, ZVar = ZVar, YVarTrans = YVarTrans, XVarTrans = XVarTrans, ZVarTrans = ZVarTrans, FacetRows = FacetRows, FacetCols = FacetCols, FacetLevels = FacetLevels, AggMethod = AggMethod, NumberBins = 21, NumLevels_X = NumLevels_Y, NumLevels_Y = NumLevels_X, MouseScroll = MouseScroll, Width = Width, Height = Height, EchartsTheme = EchartsTheme, Title = Title, ShowLabels = ShowLabels, Title.YAxis = Title.YAxis, Title.XAxis = Title.XAxis, title.fontSize = Title.FontSize, Debug = Debug) Code <- paste0( "\n\n", "p1 <- AutoPlots::Plot.HeatMap(", "\n ", "dt = data1", ",\n ", "AggMethod = ", CEP(AggMethod), ",\n ", "PreAgg = ", CEPP(PreAgg), "\n ", "XVar = ", CEP(XVar), ",\n ", "YVar = ", ExpandText(YVar), ",\n ", "ZVar = ", CEP(ZVar), ",\n ", "YVarTrans = ", CEP(YVarTrans), ",\n ", "XVarTrans = ", CEP(XVarTrans), ",\n ", "ZVarTrans = ", CEP(ZVarTrans), ",\n ", "NumberBins = ", CEPP(21), ",\n ", "NumLevels_X = ", CEPP(NumLevels_Y), ",\n ", "NumLevels_Y = ", CEPP(NumLevels_X), ",\n ", "FacetRows = ", CEPP(FacetRows), ",\n ", "FacetCols = ", CEPP(FacetCols), ",\n ", "FacetLevels = ", ExpandText(FacetLevels), ",\n ", "Width = ", CEP(Width), ",\n ", "Height = ", CEP(Height), ",\n ", "Title = ", CEP(Title), ",\n ", "ShowLabels = ", CEPP(ShowLabels), ",\n ", "Title.YAxis = ", CEP(Title.YAxis), ",\n ", "Title.XAxis = ", CEP(Title.XAxis), ",\n ", "EchartsTheme = ", CEP(EchartsTheme), ",\n ", "TimeLine = ", CEPP(TimeLine), ",\n ", "TextColor = ", CEP(TextColor), ",\n ", "title.fontSize = ", CEPP(Title.FontSize), ")\n") return(list(Plot = p1, Code = Code)) } # Correlation Matrix Plot if(tolower(PlotType) == 'correlogramplot') { p1 <- Plot.CorrMatrix( dt = dt, PreAgg = PreAgg, CorrVars = YVar, FacetRows = FacetRows, FacetCols = FacetCols, FacetLevels = FacetLevels, Width = Width, Height = Height, EchartsTheme = EchartsTheme, MouseScroll = MouseScroll, Method = "spearman", ShowLabels = ShowLabels, Title.YAxis = Title.YAxis, Title.XAxis = Title.XAxis, TextColor = TextColor, title.fontSize = Title.FontSize, Debug = Debug) Code <- paste0( "\n\n", "p1 <- AutoPlots::Plot.CorrMatrix(", "\n ", "dt = data1", ",\n ", "PreAgg = ", CEPP(PreAgg), "\n ", "CorrVars = ", ExpandText(YVar), ",\n ", "Method = ", CEP("spearman"), ",\n ", "FacetRows = ", CEPP(FacetRows), ",\n ", "FacetCols = ", CEPP(FacetCols), ",\n ", "FacetLevels = ", ExpandText(FacetLevels), ",\n ", "Width = ", CEP(Width), ",\n ", "Height = ", CEP(Height), ",\n ", "ShowLabels = ", CEPP(ShowLabels), ",\n ", "Title.YAxis = ", CEP(Title.YAxis), ",\n ", "Title.XAxis = ", CEP(Title.XAxis), ",\n ", "EchartsTheme = ", CEP(EchartsTheme), ",\n ", "TextColor = ", CEP(TextColor), ",\n ", "title.fontSize = ", CEPP(Title.FontSize), ")\n") return(list(Plot = p1, Code = Code)) } # Scatter Plot if(tolower(PlotType) %in% 'scatterplot') { if(SampleSize > 30000) SampleSize <- 30000 p1 <- Plot.Scatter( dt = dt, SampleSize = SampleSize, XVar = XVar, YVar = YVar, GroupVar = if(all(XVar == GroupVar)) NULL else GroupVar, YVarTrans = YVarTrans, XVarTrans = XVarTrans, FacetRows = FacetRows, FacetCols = FacetCols, FacetLevels = FacetLevels, Width = Width, Height = Height, Title = Title, MouseScroll = MouseScroll, ShowLabels = ShowLabels, Title.YAxis = Title.YAxis, Title.XAxis = Title.XAxis, EchartsTheme = EchartsTheme, TimeLine = TimeLine, TextColor = TextColor, title.fontSize = Title.FontSize, Debug = Debug) Code <- paste0( "\n\n", "p1 <- AutoPlots::Plot.Scatter(", "\n ", "dt = data1", ",\n ", "SampleSize = ", CEP(SampleSize), ",\n ", "XVar = ", CEP(XVar), ",\n ", "YVar = ", ExpandText(YVar), ",\n ", "GroupVar = ", CEP(if(all(XVar == GroupVar)) NULL else GroupVar), ",\n ", "YVarTrans = ", CEP(YVarTrans), ",\n ", "XVarTrans = ", CEP(XVarTrans), ",\n ", "FacetRows = ", CEPP(FacetRows), ",\n ", "FacetCols = ", CEPP(FacetCols), ",\n ", "FacetLevels = ", ExpandText(FacetLevels), ",\n ", "Width = ", CEP(Width), ",\n ", "Height = ", CEP(Height), ",\n ", "Title = ", CEP(Title), ",\n ", "ShowLabels = ", CEPP(ShowLabels), ",\n ", "Title.YAxis = ", CEP(Title.YAxis), ",\n ", "Title.XAxis = ", CEP(Title.XAxis), ",\n ", "EchartsTheme = ", CEP(EchartsTheme), ",\n ", "TimeLine = ", CEPP(TimeLine), ",\n ", "TextColor = ", CEP(TextColor), ",\n ", "title.fontSize = ", CEPP(Title.FontSize), ")\n") return(list(Plot = p1, Code = Code)) } # Copula Plot if(tolower(PlotType) %in% 'copulaplot') { if(SampleSize > 30000) SampleSize <- 30000 p1 <- Plot.Copula( dt = dt, SampleSize = SampleSize, XVar = XVar, YVar = YVar, GroupVar = if(all(XVar == GroupVar)) NULL else GroupVar, YVarTrans = YVarTrans, XVarTrans = XVarTrans, FacetRows = FacetRows, FacetCols = FacetCols, FacetLevels = FacetLevels, Width = Width, Height = Height, EchartsTheme = EchartsTheme, MouseScroll = MouseScroll, TimeLine = TimeLine, Title = Title, ShowLabels = ShowLabels, Title.YAxis = Title.YAxis, Title.XAxis = Title.XAxis, TextColor = TextColor, title.fontSize = Title.FontSize, Debug = Debug) Code <- paste0( "\n\n", "p1 <- AutoPlots::Plot.Copula(", "\n ", "dt = data1", ",\n ", "SampleSize = ", CEP(SampleSize), ",\n ", "XVar = ", CEP(XVar), ",\n ", "YVar = ", ExpandText(YVar), ",\n ", "GroupVar = ", CEP(if(all(XVar == GroupVar)) NULL else GroupVar), ",\n ", "YVarTrans = ", CEP(YVarTrans), ",\n ", "XVarTrans = ", CEP(XVarTrans), ",\n ", "FacetRows = ", CEPP(FacetRows), ",\n ", "FacetCols = ", CEPP(FacetCols), ",\n ", "FacetLevels = ", ExpandText(FacetLevels), ",\n ", "Width = ", CEP(Width), ",\n ", "Height = ", CEP(Height), ",\n ", "Title = ", CEP(Title), ",\n ", "ShowLabels = ", CEPP(ShowLabels), ",\n ", "Title.YAxis = ", CEP(Title.YAxis), ",\n ", "Title.XAxis = ", CEP(Title.XAxis), ",\n ", "EchartsTheme = ", CEP(EchartsTheme), ",\n ", "TimeLine = ", CEPP(TimeLine), ",\n ", "TextColor = ", CEP(TextColor), ",\n ", "title.fontSize = ", CEPP(Title.FontSize), ")\n") return(list(Plot = p1, Code = Code)) } # Scatter3D Plot if(tolower(PlotType) %in% c('scatterplot3d','scatterplotd')) { p1 <- Plot.Scatter3D( dt = dt, SampleSize = SampleSize, XVar = XVar, YVar = YVar, ZVar = ZVar, GroupVar = if(all(XVar == GroupVar)) NULL else GroupVar, YVarTrans = YVarTrans, XVarTrans = XVarTrans, ZVarTrans = ZVarTrans, FacetRows = FacetRows, FacetCols = FacetCols, FacetLevels = FacetLevels, Width = Width, Height = Height, Title = Title, ShowLabels = ShowLabels, Title.YAxis = Title.YAxis, Title.XAxis = Title.XAxis, EchartsTheme = EchartsTheme, TimeLine = TimeLine, TextColor = TextColor, title.fontSize = Title.FontSize, Debug = Debug) Code <- paste0( "\n\n", "p1 <- AutoPlots::Plot.Scatter3D(", "\n ", "dt = data1", ",\n ", "SampleSize = ", CEP(SampleSize), ",\n ", "XVar = ", CEP(XVar), ",\n ", "YVar = ", CEP(YVar), ",\n ", "ZVar = ", CEP(ZVar), ",\n ", "GroupVar = ", CEP(if(all(XVar == GroupVar)) NULL else GroupVar), ",\n ", "YVarTrans = ", CEP(YVarTrans), ",\n ", "XVarTrans = ", CEP(XVarTrans), ",\n ", "ZVarTrans = ", CEP(ZVarTrans), ",\n ", "FacetRows = ", CEPP(FacetRows), ",\n ", "FacetCols = ", CEPP(FacetCols), ",\n ", "FacetLevels = ", ExpandText(FacetLevels), ",\n ", "Width = ", CEP(Width), ",\n ", "Height = ", CEP(Height), ",\n ", "Title = ", CEP(Title), ",\n ", "ShowLabels = ", CEPP(ShowLabels), ",\n ", "Title.YAxis = ", CEP(Title.YAxis), ",\n ", "Title.XAxis = ", CEP(Title.XAxis), ",\n ", "EchartsTheme = ", CEP(EchartsTheme), ",\n ", "TimeLine = ", CEPP(TimeLine), ",\n ", "TextColor = ", CEP(TextColor), ",\n ", "title.fontSize = ", CEPP(Title.FontSize), ")\n") return(list(Plot = p1, Code = Code)) } # Copula3D Plot if(tolower(PlotType) %in% c('copulaplot3d','copulaplotd')) { p1 <- Plot.Copula3D( dt = dt, SampleSize = SampleSize, XVar = XVar, YVar = YVar, ZVar = ZVar, GroupVar = if(all(XVar == GroupVar)) NULL else GroupVar, YVarTrans = YVarTrans, XVarTrans = XVarTrans, ZVarTrans = ZVarTrans, FacetRows = FacetRows, FacetCols = FacetCols, FacetLevels = FacetLevels, Width = Width, Height = Height, Title = Title, ShowLabels = ShowLabels, Title.YAxis = Title.YAxis, Title.XAxis = Title.XAxis, EchartsTheme = EchartsTheme, TimeLine = TimeLine, TextColor = TextColor, title.fontSize = Title.FontSize, Debug = Debug) Code <- paste0( "\n\n", "p1 <- AutoPlots::Plot.Copula3D(", "\n ", "dt = data1", ",\n ", "SampleSize = ", CEP(SampleSize), ",\n ", "XVar = ", CEP(XVar), ",\n ", "YVar = ", CEP(YVar), ",\n ", "ZVar = ", CEP(ZVar), ",\n ", "GroupVar = ", CEP(if(all(XVar == GroupVar)) NULL else GroupVar), ",\n ", "YVarTrans = ", CEP(YVarTrans), ",\n ", "XVarTrans = ", CEP(XVarTrans), ",\n ", "ZVarTrans = ", CEP(ZVarTrans), ",\n ", "FacetRows = ", CEPP(FacetRows), ",\n ", "FacetCols = ", CEPP(FacetCols), ",\n ", "FacetLevels = ", ExpandText(FacetLevels), ",\n ", "Width = ", CEP(Width), ",\n ", "Height = ", CEP(Height), ",\n ", "Title = ", CEP(Title), ",\n ", "ShowLabels = ", CEPP(ShowLabels), ",\n ", "Title.YAxis = ", CEP(Title.YAxis), ",\n ", "Title.XAxis = ", CEP(Title.XAxis), ",\n ", "EchartsTheme = ", CEP(EchartsTheme), ",\n ", "TimeLine = ", CEPP(TimeLine), ",\n ", "TextColor = ", CEP(TextColor), ",\n ", "title.fontSize = ", CEPP(Title.FontSize), ")\n") return(list(Plot = p1, Code = Code)) } } #' @title Plots.ModelEvaluation #' #' @description Plot helper for model evaluation plot types #' #' @author Adrian Antico #' @family Auto Plotting #' #' @param dt source data.table #' @param AggMethod character #' @param SampleSize 100000L #' @param EchartsTheme "auritus","azul","bee-inspired","blue","caravan","carp","chalk","cool","dark-bold","dark","eduardo", #' "essos","forest","fresh-cut","fruit","gray","green","halloween","helianthus","infographic","inspired", #' "jazz","london","dark","macarons","macarons2","mint","purple-passion","red-velvet","red","roma","royal", #' "sakura","shine","tech-blue","vintage","walden","wef","weforum","westeros","wonderland" #' @param TimeLine logical #' @param PlotType character #' @param YVar Y-Axis variable name #' @param XVar X-Axis variable name #' @param ZVar Z-Axis variable name #' @param GroupVar Character variable #' @param YVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param XVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param ZVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param FacetRows Defaults to 1 which causes no faceting to occur vertically. Otherwise, supply a numeric value for the number of output grid rows #' @param FacetCols Defaults to 1 which causes no faceting to occur horizontally. Otherwise, supply a numeric value for the number of output grid columns #' @param FacetLevels Faceting rows x columns is the max number of levels allowed in a grid. If your GroupVar has more you can supply the levels to display. #' @param NumLevels_Y = 75 #' @param NumLevels_X = 40 #' @param MouseScroll logical, zoom via mouse scroll #' @param Height "400px" #' @param Width "200px" #' @param TargetLevel character #' @param Title character #' @param ShowLabels logical #' @param Title.YAxis character #' @param Title.XAxis character #' @param FontSize numeric #' @param TextColor hex #' @param NumberBins numeric #' @param Debug Debugging purposes #' @return plot #' @export Plots.ModelEvaluation <- function(dt = NULL, AggMethod = "mean", SampleSize = 100000L, PlotType = NULL, YVar = NULL, TargetLevel = NULL, ZVar = NULL, XVar = NULL, GroupVar = NULL, YVarTrans = "Identity", XVarTrans = "Identity", ZVarTrans = "Identity", FacetRows = 1, FacetCols = 1, FacetLevels = NULL, NumLevels_Y = 75, NumLevels_X = 40, MouseScroll = FALSE, Height = NULL, Width = NULL, Title = NULL, ShowLabels = FALSE, Title.YAxis = NULL, Title.XAxis = NULL, EchartsTheme = "dark-blue", TimeLine = FALSE, TextColor = "white", FontSize = 14L, NumberBins = 20, Debug = FALSE) { if(!data.table::is.data.table(dt)) tryCatch({data.table::setDT(dt)}, error = function(x) { dt <- data.table::as.data.table(dt) }) # Debugging if(Debug) {print('Running Plots.ModelEvaluation')} if(length(SampleSize) == 0L) SampleSize <- 30000L Title.FontSize = FontSize + 8L if(Debug) print(paste0("Plots.ModelEvaluation == ", PlotType)) # Copula Plot ---- if(PlotType %in% 'Residuals') { p1 <- AutoPlots::Plot.Residuals.Histogram( dt = dt, SampleSize = 50000L, XVar = XVar, YVar = YVar, GroupVar = GroupVar, YVarTrans = YVarTrans, XVarTrans = XVarTrans, FacetRows = FacetRows, FacetCols = FacetCols, FacetLevels = FacetLevels, Height = Height, Width = Width, NumberBins = NumberBins, MouseScroll = MouseScroll, Title = Title, ShowLabels = ShowLabels, Title.YAxis = Title.YAxis, Title.XAxis = Title.XAxis, EchartsTheme = EchartsTheme, TimeLine = TimeLine, TextColor = TextColor, title.fontSize = Title.FontSize, Debug = Debug) return(p1) } # ---- # Residuals_2 Scatter Plot ---- if(PlotType %chin% "ResidScatter") { p1 <- AutoPlots::Plot.Residuals.Scatter( dt = dt, SampleSize = min(SampleSize, 30000L), XVar = XVar, YVar = YVar, GroupVar = GroupVar, YVarTrans = YVarTrans, XVarTrans = XVarTrans, FacetRows = FacetRows, FacetCols = FacetCols, FacetLevels = FacetLevels, Height = Height, Width = Width, Title = Title, ShowLabels = ShowLabels, MouseScroll = MouseScroll, Title.YAxis = Title.YAxis, Title.XAxis = Title.XAxis, EchartsTheme = EchartsTheme, TimeLine = TimeLine, TextColor = TextColor, Debug = Debug) return(p1) } # ---- # Evaluation Plot ---- if(PlotType == "CalibrationLine") { p1 <- AutoPlots::Plot.Calibration.Line( dt = dt, EchartsTheme = EchartsTheme, TimeLine = TimeLine, XVar = XVar, YVar = YVar, GroupVar = GroupVar, YVarTrans = YVarTrans, XVarTrans = XVarTrans, FacetRows = FacetRows, FacetCols = FacetCols, FacetLevels = FacetLevels, Height = Height, Width = Width, AggMethod = AggMethod, MouseScroll = MouseScroll, NumberBins = 21, Title = Title, ShowLabels = ShowLabels, Title.YAxis = Title.YAxis, Title.XAxis = Title.XAxis, TextColor = TextColor, Debug = Debug) return(eval(p1)) } # ---- # Evaluation Heatmap ---- if(PlotType == "CalibrationBox") { p1 <- AutoPlots::Plot.Calibration.Box( dt = dt, EchartsTheme = EchartsTheme, TimeLine = TimeLine, XVar = XVar, YVar = YVar, GroupVar = GroupVar, YVarTrans = YVarTrans, XVarTrans = XVarTrans, FacetRows = FacetRows, FacetCols = FacetCols, FacetLevels = FacetLevels, Height = Height, Width = Width, AggMethod = 'mean', NumberBins = 21, Title = Title, ShowLabels = ShowLabels, MouseScroll = MouseScroll, Title.YAxis = Title.YAxis, Title.XAxis = Title.XAxis, SampleSize = SampleSize, TextColor = TextColor, Debug = FALSE) return(eval(p1)) } # ---- # ROC Plot ---- if(PlotType == "ROCPlot") { p1 <- tryCatch({AutoPlots::Plot.ROC( dt = dt, SampleSize = SampleSize, XVar = XVar, YVar = YVar, GroupVar = GroupVar, YVarTrans = YVarTrans, XVarTrans = XVarTrans, FacetRows = FacetRows, FacetCols = FacetCols, FacetLevels = FacetLevels, Height = Height, Width = Width, Title = Title, ShowLabels = ShowLabels, MouseScroll = MouseScroll, Title.YAxis = "True Positive Rate", Title.XAxis = "1 - False Positive Rate", EchartsTheme = EchartsTheme, TimeLine = TimeLine, TextColor = TextColor, Debug = Debug)}, error = function(x) NULL) return(p1) } # ---- # Gains Plot ---- if(PlotType == "GainsPlot") { p1 <- AutoPlots::Plot.Gains( dt = dt, PreAgg = FALSE, XVar = XVar, YVar = YVar, ZVar = NULL, GroupVar = NULL, FacetLevels = FacetLevels, Height = Height, Width = Width, YVarTrans = YVarTrans, XVarTrans = XVarTrans, ZVarTrans = ZVarTrans, FacetRows = FacetRows, FacetCols = FacetCols, MouseScroll = MouseScroll, NumberBins = 20, Title = Title, ShowLabels = ShowLabels, Title.YAxis = Title.YAxis, Title.XAxis = Title.XAxis, EchartsTheme = EchartsTheme, TimeLine = TimeLine, TextColor = TextColor, Debug = FALSE) return(p1) } # ---- # Lift Plot ---- if(PlotType == "LiftPlot") { p1 <- AutoPlots::Plot.Lift( dt = dt, PreAgg = FALSE, XVar = XVar, YVar = YVar, ZVar = NULL, GroupVar = NULL, YVarTrans = YVarTrans, XVarTrans = XVarTrans, ZVarTrans = ZVarTrans, FacetRows = FacetRows, FacetCols = FacetCols, FacetLevels = FacetLevels, Height = Height, Width = Width, NumberBins = 20, Title = Title, ShowLabels = ShowLabels, MouseScroll = MouseScroll, Title.YAxis = "Lift", Title.XAxis = "% Positive Classified", EchartsTheme = EchartsTheme, TimeLine = TimeLine, TextColor = TextColor, Debug = FALSE) return(p1) } # ---- # Variable Importance Plot ---- if(PlotType == "VariableImportance") { p1 <- AutoPlots::Plot.VariableImportance( dt = dt, AggMethod = 'mean', XVar = "Variable", YVar = "Importance", GroupVar = NULL, YVarTrans = YVarTrans, XVarTrans = XVarTrans, FacetRows = FacetRows, FacetCols = FacetCols, FacetLevels = FacetLevels, Height = Height, Width = Width, Title = Title, ShowLabels = ShowLabels, Title.YAxis = Title.YAxis, Title.XAxis = Title.XAxis, EchartsTheme = EchartsTheme, TimeLine = TimeLine, TextColor = TextColor, Debug = FALSE) return(p1) } # ---- # Shap VI ---- if(PlotType == 'ShapleyImportance') { p1 <- AutoPlots::Plot.ShapImportance( PreAgg = FALSE, dt = dt, YVar = NULL, GroupVar = GroupVar, FacetRows = FacetRows, FacetCols = FacetCols, FacetLevels = FacetLevels, Height = Height, Width = Width, AggMethod = AggMethod, NumberBins = 21, NumLevels_X = NumLevels_Y, NumLevels_Y = NumLevels_X, EchartsTheme = EchartsTheme, Title = Title, ShowLabels = ShowLabels, Title.YAxis = Title.YAxis, Title.XAxis = Title.XAxis) return(p1) } # ---- # Confusion Matrix Heatmap ---- if(PlotType == "ConfusionMatrixHeatmap") { p1 <- AutoPlots::Plot.ConfusionMatrix( dt = dt, EchartsTheme = EchartsTheme, TimeLine = TimeLine, XVar = XVar, YVar = YVar, ZVar = NULL, YVarTrans = YVarTrans, XVarTrans = XVarTrans, FacetRows = FacetRows, FacetCols = FacetCols, FacetLevels = FacetLevels, MouseScroll = MouseScroll, Height = Height, Width = Width, PreAgg = FALSE, NumberBins = 21, NumLevels_X = 50, NumLevels_Y = 50, Title = Title, ShowLabels = ShowLabels, Title.YAxis = Title.YAxis, Title.XAxis = Title.XAxis, TextColor = TextColor) return(p1) } # ---- # Partial Dependence Plot ---- if(PlotType == 'PartialDependenceLine' && length(XVar) > 0L) { p1 <- AutoPlots::Plot.PartialDependence.Line( dt = dt, XVar = XVar, YVar = YVar, ZVar = ZVar, GroupVar = GroupVar, YVarTrans = YVarTrans, XVarTrans = XVarTrans, ZVarTrans = ZVarTrans, FacetRows = FacetRows, FacetCols = FacetCols, FacetLevels = FacetLevels, Height = Height, Width = Width, AggMethod = 'mean', NumberBins = 21, Title = Title, MouseScroll = MouseScroll, ShowLabels = ShowLabels, Title.YAxis = Title.YAxis, Title.XAxis = Title.XAxis, EchartsTheme = EchartsTheme, TimeLine = TimeLine, TextColor = TextColor, Debug = Debug) return(p1) } # ---- # Partial Dependence Box Plot ---- if(PlotType == 'PartialDependenceHeatMap' && length(XVar) > 0L) { p1 <- tryCatch({AutoPlots::Plot.PartialDependence.HeatMap( dt = dt, AggMethod = 'mean', XVar = XVar, YVar = YVar, ZVar = ZVar, GroupVar = NULL, YVarTrans = YVarTrans, XVarTrans = XVarTrans, ZVarTrans = ZVarTrans, FacetRows = FacetRows, FacetCols = FacetCols, FacetLevels = FacetLevels, Height = Height, Width = Width, NumberBins = 21, Title = Title, MouseScroll = MouseScroll, ShowLabels = ShowLabels, Title.YAxis = Title.YAxis, Title.XAxis = Title.XAxis, EchartsTheme = EchartsTheme, TimeLine = TimeLine, TextColor = TextColor, Debug = Debug)}, error = function(x) NULL) return(p1) } # ---- if(!exists('p1')) p1 <- NULL return(p1) } # ---- # ---- # @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ---- # > Distribution Plot Functions ---- # @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ---- #' @title Plot.ProbabilityPlot #' #' @description Build a normal probability plot #' #' @family Standard Plots #' #' @author Adrian Antico #' #' @param dt source data.table #' @param SampleSize An integer for the number of rows to use. Sampled data is randomized. If NULL then ignored #' @param YVar Y-Axis variable name #' @param YVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param Height "400px" #' @param Width "200px" #' @param Title 'Violin Plot' #' @param ShowLabels character #' @param EchartsTheme "macaron" #' @param TextColor 'darkblue' #' @param title.fontSize Default 22 #' @param title.fontWeight Default "bold" #' @param title.textShadowColor Default '#63aeff' #' @param title.textShadowBlur Default 3 #' @param title.textShadowOffsetY Default 1 #' @param title.textShadowOffsetX Default -1 #' @param yaxis.fontSize Default 14 #' @param yaxis.rotate Default 0 #' @param ContainLabel Default TRUE #' @param tooltip.trigger Default "axis" #' @param Debug Debugging purposes #' #' @examples #' # Create fake data #' dt <- data.table::data.table(Y = qnorm(p = runif(10000))) #' #' # Create plot #' AutoPlots::Plot.ProbabilityPlot( #' dt = dt, #' SampleSize = 1000L, #' YVar = "Y", #' YVarTrans = "Identity", #' Height = NULL, #' Width = NULL, #' Title = 'Normal Probability Plot', #' ShowLabels = FALSE, #' EchartsTheme = "blue", #' TextColor = "black", #' title.fontSize = 22, #' title.fontWeight = "bold", #' title.textShadowColor = '#63aeff', #' title.textShadowBlur = 3, #' title.textShadowOffsetY = 1, #' title.textShadowOffsetX = -1, #' yaxis.fontSize = 14, #' yaxis.rotate = 0, #' ContainLabel = TRUE, #' tooltip.trigger = "axis", #' Debug = FALSE) #' #' @return plot #' @export Plot.ProbabilityPlot <- function(dt = NULL, SampleSize = 1000L, YVar = NULL, YVarTrans = "Identity", Height = NULL, Width = NULL, Title = 'Normal Probability Plot', ShowLabels = FALSE, EchartsTheme = "macarons", TextColor = "white", title.fontSize = 22, title.fontWeight = "bold", title.textShadowColor = '#63aeff', title.textShadowBlur = 3, title.textShadowOffsetY = 1, title.textShadowOffsetX = -1, yaxis.fontSize = 14, yaxis.rotate = 0, ContainLabel = TRUE, tooltip.trigger = "axis", Debug = FALSE) { # Subset cols, define Target - Predicted, NULL YVar in data, Update YVar def, Ensure GroupVar is length(1) if(length(SampleSize) == 0L) SampleSize <- 30000L if(!data.table::is.data.table(dt)) tryCatch({data.table::setDT(dt)}, error = function(x) { dt <- data.table::as.data.table(dt) }) if(Debug) print("here 1") if(Debug) print(head(dt)) # Subset columns dt1 <- dt[, .SD, .SDcols = c(YVar)] # Transformation # "PercRank" "Standardize" # "Asinh" "Log" "LogPlus1" "Sqrt" "Asin" "Logit" "BoxCox" "YeoJohnson" if(YVarTrans != "Identity") { dt1 <- tryCatch({AutoTransformationCreate(data = dt1, ColumnNames = YVar, Methods = YVarTrans)$Data}, error = function(x) dt1) } # Theoretical Quantiles data.table::setorderv(x = dt1, cols = YVar, 1) dt1[, temp_i := seq_len(.N)] dt1[, `Theoretical Quantiles` := qnorm((temp_i-0.5)/.N)] dt1[, temp_i := NULL] # Normal Line meanX <- dt1[, mean(get(YVar), na.rm = TRUE)] sdX <- dt1[, sd(get(YVar), na.rm = TRUE)] dt1[, `Normal Line` := eval(meanX) + sdX * `Theoretical Quantiles`] # Actual Quantiles p1 <- AutoPlots::Plot.Scatter( dt = dt1, SampleSize = SampleSize, XVar = "Theoretical Quantiles", YVar = YVar, YVarTrans = "Identity", Height = Height, Width = Width, Title = Title, Title.YAxis = YVar, Title.XAxis = "Theoretical Quantiles", EchartsTheme = EchartsTheme, TextColor = TextColor, title.fontSize = title.fontSize, title.fontWeight = title.fontWeight, title.textShadowColor = title.textShadowColor, title.textShadowBlur = title.textShadowBlur, title.textShadowOffsetY = title.textShadowOffsetY, title.textShadowOffsetX = title.textShadowOffsetX, yaxis.fontSize = yaxis.fontSize, yaxis.rotate = yaxis.rotate, ContainLabel = ContainLabel, tooltip.trigger = tooltip.trigger, Debug = Debug) # Add Normal Line p1 <- echarts4r::e_line_(e = p1, "Normal Line") return(p1) } #' @title Plot.Histogram #' #' @description Build a histogram plot by simply passing arguments to a single function. It will sample your data using SampleSize number of rows. Sampled data is randomized. #' #' @family Standard Plots #' #' @author Adrian Antico #' #' @param dt source data.table #' @param SampleSize An integer for the number of rows to use. Sampled data is randomized. If NULL then ignored #' @param YVar Y-Axis variable name #' @param XVar X-Axis variable name #' @param GroupVar Column name of Group Variable for distinct colored histograms by group levels #' @param YVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param XVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param FacetRows Defaults to 1 which causes no faceting to occur vertically. Otherwise, supply a numeric value for the number of output grid rows #' @param FacetCols Defaults to 1 which causes no faceting to occur horizontally. Otherwise, supply a numeric value for the number of output grid columns #' @param FacetLevels Faceting rows x columns is the max number of levels allowed in a grid. If your GroupVar has more you can supply the levels to display. #' @param NumberBins = 30 #' @param Height "400px" #' @param Width "200px" #' @param EchartsTheme = EchartsTheme, #' @param TimeLine logical #' @param Title character #' @param MouseScroll logical, zoom via mouse scroll #' @param ShowLabels FALSE #' @param Title.YAxis NULL #' @param Title.XAxis NULL #' @param TextColor "white" #' @param title.fontSize 22 #' @param title.fontWeight "bold" #' @param title.textShadowColor '#63aeff' #' @param title.textShadowBlur 3 #' @param title.textShadowOffsetY 1 #' @param title.textShadowOffsetX -1 #' @param xaxis.fontSize 14 #' @param yaxis.fontSize 14 #' @param Debug Debugging purposes #' #' @examples #' # Create fake data #' dt <- data.table::data.table(Y = qnorm(p = runif(10000))) #' #' # Create plot #' AutoPlots::Plot.Histogram( #' dt = dt, #' SampleSize = 30000L, #' XVar = NULL, #' YVar = "Y", #' GroupVar = NULL, #' YVarTrans = "Identity", #' XVarTrans = "Identity", #' FacetRows = 1, #' FacetCols = 1, #' FacetLevels = NULL, #' NumberBins = 30, #' Height = NULL, #' Width = NULL, #' EchartsTheme = "macarons", #' Title = "Histogram", #' MouseScroll = TRUE, #' TimeLine = FALSE, #' ShowLabels = FALSE, #' Title.YAxis = NULL, #' Title.XAxis = NULL, #' TextColor = "white", #' title.fontSize = 22, #' title.fontWeight = "bold", #' title.textShadowColor = '#63aeff', #' title.textShadowBlur = 3, #' title.textShadowOffsetY = 1, #' title.textShadowOffsetX = -1, #' xaxis.fontSize = 14, #' yaxis.fontSize = 14, #' Debug = FALSE) #' @return plot #' @export Plot.Histogram <- function(dt = NULL, SampleSize = 30000L, XVar = NULL, YVar = NULL, GroupVar = NULL, YVarTrans = "Identity", XVarTrans = "Identity", FacetRows = 1, FacetCols = 1, FacetLevels = NULL, NumberBins = 30, Height = NULL, Width = NULL, EchartsTheme = "macarons", Title = "Histogram", MouseScroll = TRUE, TimeLine = FALSE, ShowLabels = FALSE, Title.YAxis = NULL, Title.XAxis = NULL, TextColor = "white", title.fontSize = 22, title.fontWeight = "bold", title.textShadowColor = '#63aeff', title.textShadowBlur = 3, title.textShadowOffsetY = 1, title.textShadowOffsetX = -1, xaxis.fontSize = 14, yaxis.fontSize = 14, Debug = FALSE) { if(!data.table::is.data.table(dt)) tryCatch({data.table::setDT(dt)}, error = function(x) { dt <- data.table::as.data.table(dt) }) # Convert factor to character if(length(GroupVar) > 0L && class(dt[[GroupVar]])[1L] == "factor") { dt[, eval(GroupVar) := as.character(get(GroupVar))] } TimeLine <- FALSE # Cap number of records if(length(SampleSize) == 0L) SampleSize <- 30000 if(dt[, .N] > SampleSize) { dt1 <- dt[order(runif(.N))][seq_len(SampleSize)] } else { dt1 <- data.table::copy(dt) } # Define Plotting Variable if(length(YVar) == 0L && length(XVar) == 0) return(NULL) if(length(YVar) == 0L) { YVar <- XVar YVarTrans <- XVarTrans } if(length(XVar) > 0L && length(GroupVar) == 0L) { GroupVar <- XVar XVar <- NULL } GroupVar <- tryCatch({GroupVar[1L]}, error = function(x) NULL) # Faceting shrink if(length(GroupVar) > 0L && (FacetRows > 1L || FacetCols > 1L)) { dt1 <- dt1[get(GroupVar) %in% c(eval(FacetLevels)), .SD, .SDcols = c(YVar,GroupVar)] } else { dt1 <- dt1[, .SD, .SDcols = c(YVar,GroupVar)] } # Multiple YVars if(length(YVar) > 1L) { sqroots <- sqrt(length(YVar)) if(FacetCols == 1 && FacetRows == 1L) { FacetCols <- max(ceiling(sqroots), 6) FacetRows <- ceiling(sqroots) if((FacetRows - 1L) * FacetCols == length(YVar)) { FacetRows <- FacetRows - 1L } else if(FacetRows * FacetCols < length(YVar)) { while(FacetRows * FacetCols < length(YVar)) { FacetRows <- FacetRows + 1L } } } XVar <- NULL GroupVar <- NULL dt1[, temp__ := "a"] dt1 <- data.table::melt.data.table(data = dt1, id.vars = "temp__", measure.vars = YVar, variable.name = "Measures", value.name = "Values") dt1[, temp__ := NULL] GroupVar <- "Measures" YVar <- "Values" } # Transformation # "PercRank" "Standardize" # "Asinh" "Log" "LogPlus1" "Sqrt" "Asin" "Logit" "BoxCox" "YeoJohnson" if(YVarTrans != "Identity") { for(ggss in YVar) { dt1 <- tryCatch({AutoTransformationCreate(data = dt1, ColumnNames = ggss, Methods = YVarTrans)$Data}, error = function(x) dt1) } } # Create histogram data if(length(GroupVar) == 0L) { Min <- dt1[, min(get(YVar), na.rm = TRUE)] Max <- dt1[, max(get(YVar), na.rm = TRUE)] Range <- Max - Min if(Range < NumberBins) { acc <- round(Range / NumberBins, 2) dt1[, Buckets := round(get(YVar) / acc) * acc] dt1 <- dt1[, .N, by = "Buckets"][order(Buckets)] } else { acc <- ceiling(Range / NumberBins) dt1[, Buckets := round(get(YVar) / acc) * acc] dt1 <- dt1[, .N, by = "Buckets"][order(Buckets)] } } else { levs <- unique(as.character(dt1[[GroupVar]])) gg <- list() for(i in levs) {# i <- levs[1] temp <- dt1[get(GroupVar) == eval(i)] Min <- temp[, min(get(YVar), na.rm = TRUE)] Max <- temp[, max(get(YVar), na.rm = TRUE)] Range <- Max - Min if(Range < NumberBins) { acc <- round(Range / NumberBins, 2) } else { acc <- ceiling(Range / NumberBins) } temp[, Buckets := round(get(YVar) / acc) * acc] gg[[i]] <- temp[, .N, by = c("Buckets",GroupVar)][order(Buckets)] } dt1 <- data.table::rbindlist(gg) } # Run Bar Plot for no Group and Stacked Bar for Groups? dt1[, Buckets := as.character(Buckets)] if(length(GroupVar) == 0L) { p1 <- Plot.Bar( dt = dt1, PreAgg = TRUE, XVar = "Buckets", YVar = "N", Height = Height, Width = Width, Title = 'Histogram Plot', Title.YAxis = "Counts", Title.XAxis = YVar, EchartsTheme = EchartsTheme, MouseScroll = MouseScroll, TimeLine = TimeLine, TextColor = TextColor, title.fontSize = title.fontSize, title.fontWeight = title.fontWeight, title.textShadowColor = title.textShadowColor, title.textShadowBlur = title.textShadowBlur, title.textShadowOffsetY = title.textShadowOffsetY, title.textShadowOffsetX = title.textShadowOffsetX, xaxis.fontSize = xaxis.fontSize, yaxis.fontSize = yaxis.fontSize, Debug = Debug) } else { p1 <- Plot.Bar( dt = dt1, PreAgg = TRUE, XVar = "Buckets", YVar = "N", GroupVar = GroupVar, FacetRows = FacetRows, FacetCols = FacetCols, FacetLevels = FacetLevels, Height = Height, Width = Width, Title = 'Histogram Plot', MouseScroll = MouseScroll, Title.YAxis = "Counts", Title.XAxis = YVar, EchartsTheme = EchartsTheme, TimeLine = TimeLine, TextColor = TextColor, title.fontSize = title.fontSize, title.fontWeight = title.fontWeight, title.textShadowColor = title.textShadowColor, title.textShadowBlur = title.textShadowBlur, title.textShadowOffsetY = title.textShadowOffsetY, title.textShadowOffsetX = title.textShadowOffsetX, xaxis.fontSize = xaxis.fontSize, yaxis.fontSize = yaxis.fontSize, Debug = Debug) } return(p1) } #' @title Plot.Density #' #' @description Density plots, by groups, with transparent continuous plots #' #' @family Standard Plots #' #' @param dt source data.table #' @param SampleSize = 100000L #' @param YVar Y-Axis variable name #' @param XVar X-Axis variable name #' @param GroupVar Character variable #' @param YVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param XVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param FacetRows Defaults to 1 which causes no faceting to occur vertically. Otherwise, supply a numeric value for the number of output grid rows #' @param FacetCols Defaults to 1 which causes no faceting to occur horizontally. Otherwise, supply a numeric value for the number of output grid columns #' @param FacetLevels Faceting rows x columns is the max number of levels allowed in a grid. If your GroupVar has more you can supply the levels to display. #' @param Height "400px" #' @param Width "200px" #' @param MouseScroll logical, zoom via mouse scroll #' @param Title = "Density Plot" #' @param ShowLabels character #' @param Title.YAxis character #' @param Title.XAxis character #' @param EchartsTheme "auritus","azul","bee-inspired","blue","caravan","carp","chalk","cool","dark-bold","dark","eduardo", #' "essos","forest","fresh-cut","fruit","gray","green","halloween","helianthus","infographic","inspired", #' "jazz","london","dark","macarons","macarons2","mint","purple-passion","red-velvet","red","roma","royal", #' "sakura","shine","tech-blue","vintage","walden","wef","weforum","westeros","wonderland" #' @param TimeLine logical #' @param TextColor "white" #' @param title.fontSize 22 #' @param title.fontWeight "bold" #' @param title.textShadowColor '#63aeff' #' @param title.textShadowBlur 3 #' @param title.textShadowOffsetY 1 #' @param title.textShadowOffsetX -1 #' @param xaxis.fontSize 14 #' @param yaxis.fontSize 14 #' @param xaxis.rotate 0 #' @param yaxis.rotate 0 #' @param ContainLabel TRUE #' @param Debug Debugging purposes #' #' @examples #' # Create fake data #' dt <- data.table::data.table(Y = qnorm(p = runif(10000))) #' #' # Create plot #' AutoPlots::Plot.Density( #' dt = dt, #' SampleSize = 30000L, #' XVar = NULL, #' YVar = "Y", #' GroupVar = NULL, #' YVarTrans = "Identity", #' XVarTrans = "Identity", #' FacetRows = 1, #' FacetCols = 1, #' FacetLevels = NULL, #' Height = NULL, #' Width = NULL, #' EchartsTheme = "macarons", #' Title = "Histogram", #' MouseScroll = TRUE, #' TimeLine = FALSE, #' ShowLabels = FALSE, #' Title.YAxis = NULL, #' Title.XAxis = NULL, #' TextColor = "white", #' title.fontSize = 22, #' title.fontWeight = "bold", #' title.textShadowColor = '#63aeff', #' title.textShadowBlur = 3, #' title.textShadowOffsetY = 1, #' title.textShadowOffsetX = -1, #' xaxis.fontSize = 14, #' yaxis.fontSize = 14, #' Debug = FALSE) #' #' @return plot #' @export Plot.Density <- function(dt = NULL, SampleSize = 100000L, YVar = NULL, XVar = NULL, GroupVar = NULL, YVarTrans = "Identity", XVarTrans = "Identity", FacetRows = 1, FacetCols = 1, FacetLevels = NULL, Height = NULL, Width = NULL, MouseScroll = TRUE, Title = "Density Plot", ShowLabels = FALSE, Title.YAxis = NULL, Title.XAxis = NULL, EchartsTheme = "macarons", TimeLine = FALSE, TextColor = "white", title.fontSize = 22, title.fontWeight = "bold", title.textShadowColor = '#63aeff', title.textShadowBlur = 3, title.textShadowOffsetY = 1, title.textShadowOffsetX = -1, xaxis.fontSize = 14, yaxis.fontSize = 14, xaxis.rotate = 0, yaxis.rotate = 0, ContainLabel = TRUE, Debug = FALSE) { # Cap number of records if(length(SampleSize) == 0L) SampleSize <- 30000 if(!data.table::is.data.table(dt)) tryCatch({data.table::setDT(dt)}, error = function(x) { dt <- data.table::as.data.table(dt) }) # Convert factor to character if(length(GroupVar) > 0L && class(dt[[GroupVar]])[1L] == "factor") { dt[, eval(GroupVar) := as.character(get(GroupVar))] } if(dt[, .N] > SampleSize) { dt1 <- dt[order(runif(.N))][seq_len(SampleSize)] } else { dt1 <- data.table::copy(dt) } # Define Plotting Variable if(length(YVar) == 0L && length(XVar) == 0) return(NULL) if(length(YVar) == 0L) { YVar <- XVar YVarTrans <- XVarTrans } if(length(XVar) > 0L && length(GroupVar) == 0L) { GroupVar <- XVar XVar <- NULL } GroupVar <- tryCatch({GroupVar[1L]}, error = function(x) NULL) YVar <- tryCatch({YVar}, error = function(x) NULL) # Faceting shrink if(length(GroupVar) > 0L && (FacetRows > 1L || FacetCols > 1L) && length(FacetLevels) > 0L) { dt1 <- dt1[get(GroupVar) %in% c(eval(FacetLevels)), .SD, .SDcols = c(YVar,GroupVar)] } else { dt1 <- dt1[, .SD, .SDcols = c(YVar,GroupVar)] } # Multiple YVars if(length(YVar) > 1L) { sqroots <- sqrt(length(YVar)) if(FacetCols == 1 && FacetRows == 1L) { FacetCols <- max(ceiling(sqroots), 6) FacetRows <- ceiling(sqroots) if((FacetRows - 1L) * FacetCols == length(YVar)) { FacetRows <- FacetRows - 1L } else if(FacetRows * FacetCols < length(YVar)) { while(FacetRows * FacetCols < length(YVar)) { FacetRows <- FacetRows + 1L } } } XVar <- NULL GroupVar <- NULL dt1[, temp__ := "a"] dt1 <- data.table::melt.data.table(data = dt1, id.vars = "temp__", measure.vars = YVar, variable.name = "Measures", value.name = "Values") dt1[, temp__ := NULL] GroupVar <- "Measures" YVar <- "Values" } # Transformation # "PercRank" "Standardize" # "Asinh" "Log" "LogPlus1" "Sqrt" "Asin" "Logit" "BoxCox" "YeoJohnson" if(YVarTrans != "Identity") { for(ggss in YVar) { dt1 <- AutoTransformationCreate(data = dt1, ColumnNames = ggss, Methods = YVarTrans)$Data } } # Create base plot object if(Debug) print('Create Plot with only data') if(length(GroupVar) == 0L) { p1 <- echarts4r::e_charts_( dt1, x = NULL, dispose = TRUE, darkMode = TRUE, width = Width, height = Height) if(ShowLabels) { p1 <- echarts4r::e_density_( e = p1, YVar, areaStyle = list(opacity = .4), smooth = TRUE, y_index = 1, label = list(show = TRUE)) } else { p1 <- echarts4r::e_density_( e = p1, YVar, areaStyle = list(opacity = .4), smooth = TRUE, y_index = 1) } if(MouseScroll) { p1 <- echarts4r::e_datazoom(e = p1, type = "inside", x_index = c(0,1)) } else { p1 <- echarts4r::e_datazoom(e = p1, x_index = c(0,1)) } p1 <- echarts4r::e_theme(e = p1, name = EchartsTheme) p1 <- echarts4r::e_aria(e = p1, enabled = TRUE) p1 <- echarts4r::e_tooltip(e = p1, trigger = "axis", backgroundColor = "aliceblue") p1 <- echarts4r::e_toolbox_feature(e = p1, feature = c("saveAsImage","dataZoom")) p1 <- echarts4r::e_show_loading(e = p1, hide_overlay = TRUE, text = "Calculating...", color = "#000", text_color = TextColor, mask_color = "#000") if(length(Title.XAxis) == 0L && length(Title.YAxis) == 0L) { if(length(XVar) > 0L) { p1 <- echarts4r::e_axis_(e = p1, serie = NULL, axis = "x", name = XVar, nameLocation = "middle", nameGap = 45, nameTextStyle = list(color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = xaxis.fontSize)) } else { p1 <- echarts4r::e_axis_(e = p1, serie = NULL, axis = "x", name = YVar, nameLocation = "middle", nameGap = 45, nameTextStyle = list(color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = xaxis.fontSize)) } } else if(length(Title.XAxis) > 0L) { p1 <- echarts4r::e_axis_(e = p1, serie = NULL, axis = "x", name = Title.XAxis, nameLocation = "middle", nameGap = 45, nameTextStyle = list(color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = xaxis.fontSize)) } else { p1 <- echarts4r::e_axis_(e = p1, serie = NULL, axis = "x", name = Title.YAxis, nameLocation = "middle", nameGap = 45, nameTextStyle = list(color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = xaxis.fontSize)) } p1 <- echarts4r::e_brush(e = p1) p1 <- echarts4r::e_title( p1, Title, textStyle = list( color = TextColor, fontWeight = title.fontWeight, overflow = "truncate", # "none", "truncate", "break", ellipsis = '...', fontSize = title.fontSize, textShadowColor = title.textShadowColor, textShadowBlur = title.textShadowBlur, textShadowOffsetY = title.textShadowOffsetY, textShadowOffsetX = title.textShadowOffsetX)) return(p1) } else { data.table::setorderv(x = dt1, cols = GroupVar[1L], 1) if(ShowLabels) { p1 <- echarts4r::e_charts_( dt1 |> dplyr::group_by(get(GroupVar[1L])), timeline = TimeLine, dispose = TRUE, darkMode = TRUE, emphasis = list(focus = "series"), width = Width, height = Height, label = list(show = TRUE)) } else { p1 <- echarts4r::e_charts_( dt1 |> dplyr::group_by(get(GroupVar[1L])), timeline = TimeLine, dispose = TRUE, darkMode = TRUE, emphasis = list(focus = "series"), width = Width, height = Height) } p1 <- echarts4r::e_density_(e = p1, YVar, areaStyle = list(opacity = .4), smooth = TRUE, y_index = 1) if(MouseScroll && FacetRows == 1L && FacetCols == 1L) { p1 <- echarts4r::e_datazoom(e = p1, type = "inside", x_index = c(0,1)) } else if(MouseScroll && (FacetRows > 1L || FacetCols > 1L)) { p1 <- echarts4r::e_datazoom(e = p1, type = "inside", x_index = seq(0, FacetRows * FacetCols - 1, 1)) } else { p1 <- echarts4r::e_datazoom(e = p1, x_index = c(0,1)) } p1 <- echarts4r::e_theme(e = p1, name = EchartsTheme) p1 <- echarts4r::e_aria(e = p1, enabled = TRUE) p1 <- echarts4r::e_tooltip(e = p1, trigger = "axis", backgroundColor = "aliceblue") p1 <- echarts4r::e_toolbox_feature(e = p1, feature = c("saveAsImage","dataZoom")) p1 <- echarts4r::e_show_loading(e = p1, hide_overlay = TRUE, text = "Calculating...", color = "#000", text_color = TextColor, mask_color = "#000") if(length(Title.XAxis) == 0L) { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "x", name = XVar, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = xaxis.fontSize), axisLabel = list( rotate = xaxis.rotate, grid = list(containLabel = ContainLabel))) } else { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "x", name = Title.XAxis, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = xaxis.fontSize), axisLabel = list( rotate = xaxis.rotate, grid = list(containLabel = ContainLabel))) } p1 <- echarts4r::e_brush(e = p1) p1 <- echarts4r::e_title( p1, Title, textStyle = list( color = TextColor, fontWeight = title.fontWeight, overflow = "truncate", # "none", "truncate", "break", ellipsis = '...', fontSize = title.fontSize, textShadowColor = title.textShadowColor, textShadowBlur = title.textShadowBlur, textShadowOffsetY = title.textShadowOffsetY, textShadowOffsetX = title.textShadowOffsetX)) if(FacetRows > 1L || FacetCols > 1L) { p1 <- echarts4r::e_facet(e = p1, rows = FacetRows, cols = FacetCols, legend_space = 16, legend_pos = "top") p1 <- echarts4r::e_legend(e = p1, type = "scroll", orient = "horizontal", right = 50, top = 40, height = "240px", textStyle = list(color = TextColor, fontWeight = "bold")) } else { p1 <- echarts4r::e_legend(e = p1, type = "scroll", orient = "vertical", right = 50, top = 40, height = "240px", textStyle = list(color = TextColor, fontWeight = "bold")) } return(p1) } } #' @title Plot.Pie #' #' @description Build a pie chart by simply passing arguments to a single function #' #' @family Standard Plots #' #' @author Adrian Antico #' #' @param dt source data.table #' @param PreAgg logical #' @param YVar Y-Axis variable name #' @param XVar X-Axis variable name #' @param GroupVar Column name of Group Variable for distinct colored histograms by group levels #' @param YVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param XVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param FacetRows Defaults to 1 which causes no faceting to occur vertically. Otherwise, supply a numeric value for the number of output grid rows #' @param FacetCols Defaults to 1 which causes no faceting to occur horizontally. Otherwise, supply a numeric value for the number of output grid columns #' @param FacetLevels Faceting rows x columns is the max number of levels allowed in a grid. If your GroupVar has more you can supply the levels to display. #' @param AggMethod Choose from 'mean', 'sum', 'sd', and 'median' #' @param Height "400px" #' @param Width "200px" #' @param Title title #' @param ShowLabels character #' @param Title.YAxis character #' @param Title.XAxis character #' @param EchartsTheme "auritus","azul","bee-inspired","blue","caravan","carp","chalk","cool","dark-bold","dark","eduardo","essos","forest","fresh-cut","fruit","gray","green","halloween","helianthus","infographic","inspired","jazz","london","dark","macarons","macarons2","mint","purple-passion","red-velvet","red","roma","royal","sakura","shine","tech-blue","vintage","walden","wef","weforum","westeros","wonderland" #' @param TimeLine logical #' @param TextColor 'darkblue' #' @param title.fontSize Defaults to size 22. Numeric. This changes the size of the title. #' @param title.fontSize 22 #' @param title.fontWeight "bold" #' @param title.textShadowColor '#63aeff' #' @param title.textShadowBlur 3 #' @param title.textShadowOffsetY 1 #' @param title.textShadowOffsetX -1 #' @param xaxis.fontSize 14 #' @param yaxis.fontSize 14 #' @param Debug Debugging purposes #' #' @examples #' # Create fake data #' dt <- data.table::data.table(Y = qnorm(p = runif(10000)), GV = sample(LETTERS, 1000, TRUE)) #' #' # Create plot #' AutoPlots::Plot.Pie( #' dt = dt, #' PreAgg = FALSE, #' XVar = "GV", #' YVar = "Y", #' GroupVar = NULL, #' YVarTrans = "Identity", #' XVarTrans = "Identity", #' FacetRows = 1, #' FacetCols = 1, #' FacetLevels = NULL, #' AggMethod = 'mean', #' Height = NULL, #' Width = NULL, #' Title = 'Pie Chart', #' ShowLabels = FALSE, #' Title.YAxis = NULL, #' Title.XAxis = NULL, #' EchartsTheme = "macarons", #' TimeLine = TRUE, #' TextColor = "black", #' title.fontSize = 22, #' title.fontWeight = "bold", #' title.textShadowColor = '#63aeff', #' title.textShadowBlur = 3, #' title.textShadowOffsetY = 1, #' title.textShadowOffsetX = -1, #' xaxis.fontSize = 14, #' yaxis.fontSize = 14, #' Debug = FALSE) #' #' @return plot #' @export Plot.Pie <- function(dt = NULL, PreAgg = FALSE, XVar = NULL, YVar = NULL, GroupVar = NULL, YVarTrans = "Identity", XVarTrans = "Identity", FacetRows = 1, FacetCols = 1, FacetLevels = NULL, AggMethod = 'mean', Height = NULL, Width = NULL, Title = 'Pie Chart', ShowLabels = FALSE, Title.YAxis = NULL, Title.XAxis = NULL, EchartsTheme = "macarons", TimeLine = TRUE, TextColor = "white", title.fontSize = 22, title.fontWeight = "bold", title.textShadowColor = '#63aeff', title.textShadowBlur = 3, title.textShadowOffsetY = 1, title.textShadowOffsetX = -1, xaxis.fontSize = 14, yaxis.fontSize = 14, Debug = FALSE) { if(length(YVar) > 0L) YVar <- YVar[1L] if(length(XVar) > 0L) XVar <- XVar[1L] # Used multiple times check1 <- length(XVar) != 0 && length(YVar) != 0 if(!PreAgg) { if(!data.table::is.data.table(dt)) tryCatch({data.table::setDT(dt)}, error = function(x) { dt <- data.table::as.data.table(dt) }) aggFunc <- SummaryFunction(AggMethod) } # Convert factor to character if(length(GroupVar) > 0L && class(dt[[GroupVar]])[1L] == "factor") { dt[, eval(GroupVar) := as.character(get(GroupVar))] } if(length(XVar) > 0L && class(dt[[XVar]])[1L] == "factor") { dt[, eval(XVar) := as.character(get(XVar))] } # Create base plot object numvars <- c() byvars <- c() if(check1) { if(Debug) print("BarPlot 2.b") if(!PreAgg) { if(tryCatch({class(dt[[eval(YVar)]])[1L]}, error = function(x) "bla") %in% c('numeric','integer')) { numvars <- unique(c(numvars, YVar)) } else { byvars <- unique(c(byvars, YVar)) } if(tryCatch({class(dt[[eval(XVar)]])[1L]}, error = function(x) "bla") %in% c('numeric','integer')) { if(length(numvars) > 0) { x <- length(unique(dt[[XVar]])) y <- length(unique(dt[[YVar]])) if(x > y) { byvars <- unique(c(byvars, YVar)) numvars[1L] <- XVar } else { byvars <- unique(c(byvars, XVar)) } } else { numvars <- unique(c(numvars, XVar)) } } else { byvars <- unique(c(byvars, XVar)) } if(!is.null(byvars)) { temp <- dt[, lapply(.SD, noquote(aggFunc)), .SDcols = c(numvars), by = c(byvars)] for(i in byvars) { if(class(temp[[i]])[1L] %in% c('numeric','integer')) { temp[, eval(i) := as.character(get(i))] } } } else { temp <- dt[, lapply(.SD, noquote(aggFunc)), .SDcols = c(numvars)] } } else { if(Debug) print("BarPlot 2.bb") temp <- data.table::copy(dt) if(Debug) print("BarPlot 2.bbb") numvars <- ColNameFilter(data = temp, Types = 'numeric')[[1L]] byvars <- unlist(ColNameFilter(data = temp, Types = "character")) } # yvar <- temp[[YVar]] # xvar <- temp[[XVar]] if(Debug) print("BarPlot 2.bbbb") # Transformation if(YVarTrans != "Identity") { temp <- AutoTransformationCreate(data = temp, ColumnNames = numvars, Methods = YVarTrans)$Data } p1 <- echarts4r::e_charts_( temp, x = XVar, dispose = TRUE, darkMode = TRUE, emphasis = list(focus = "series"), width = Width, height = Height) if(ShowLabels) { p1 <- echarts4r::e_pie_(e = p1, YVar, stack = XVar, label = list(show = TRUE)) } else { p1 <- echarts4r::e_pie_(e = p1, YVar, stack = XVar) } p1 <- echarts4r::e_theme(e = p1, name = EchartsTheme) p1 <- echarts4r::e_aria(e = p1, enabled = TRUE) p1 <- echarts4r::e_tooltip(e = p1, trigger = "item", backgroundColor = "aliceblue") p1 <- echarts4r::e_toolbox_feature(e = p1, feature = c("saveAsImage","dataZoom")) p1 <- echarts4r::e_show_loading(e = p1, hide_overlay = TRUE, text = "Calculating...", color = "#000", text_color = TextColor, mask_color = "#000") p1 <- echarts4r::e_legend(e = p1, type = "scroll", orient = "vertical", right = 50, top = 40, height = "240px", textStyle = list(color = TextColor, fontWeight = "bold")) p1 <- echarts4r::e_brush(e = p1) p1 <- echarts4r::e_title( p1, Title, textStyle = list( color = TextColor, fontWeight = title.fontWeight, overflow = "truncate", # "none", "truncate", "break", ellipsis = '...', fontSize = title.fontSize, textShadowColor = title.textShadowColor, textShadowBlur = title.textShadowBlur, textShadowOffsetY = title.textShadowOffsetY, textShadowOffsetX = title.textShadowOffsetX)) return(p1) } } #' @title Plot.Donut #' #' @description Build a donut plot by simply passing arguments to a single function #' #' @family Standard Plots #' #' @author Adrian Antico #' #' @param dt source data.table #' @param PreAgg logical #' @param YVar Y-Axis variable name #' @param XVar X-Axis variable name #' @param GroupVar Column name of Group Variable for distinct colored histograms by group levels #' @param YVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param XVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param FacetRows Defaults to 1 which causes no faceting to occur vertically. Otherwise, supply a numeric value for the number of output grid rows #' @param FacetCols Defaults to 1 which causes no faceting to occur horizontally. Otherwise, supply a numeric value for the number of output grid columns #' @param FacetLevels Faceting rows x columns is the max number of levels allowed in a grid. If your GroupVar has more you can supply the levels to display. #' @param AggMethod Choose from 'mean', 'sum', 'sd', and 'median' #' @param Height "400px" #' @param Width "200px" #' @param Title title #' @param ShowLabels character #' @param Title.YAxis character #' @param Title.XAxis character #' @param EchartsTheme "auritus","azul","bee-inspired","blue","caravan","carp","chalk","cool","dark-bold","dark","eduardo","essos","forest","fresh-cut","fruit","gray","green","halloween","helianthus","infographic","inspired","jazz","london","dark","macarons","macarons2","mint","purple-passion","red-velvet","red","roma","royal","sakura","shine","tech-blue","vintage","walden","wef","weforum","westeros","wonderland" #' @param TimeLine logical #' @param TextColor 'darkblue' #' @param title.fontSize Defaults to size 22. Numeric. This changes the size of the title. #' @param title.fontWeight "bold" #' @param title.textShadowColor '#63aeff' #' @param title.textShadowBlur 3 #' @param title.textShadowOffsetY 1 #' @param title.textShadowOffsetX -1 #' @param xaxis.fontSize 14 #' @param yaxis.fontSize 14 #' @param Debug Debugging purposes #' #' @examples #' #' # Create fake data #' dt <- data.table::data.table(Y = qnorm(p = runif(10000)), GV = sample(LETTERS, 1000, TRUE)) #' #' # Create plot #' AutoPlots::Plot.Donut( #' dt = dt, #' PreAgg = FALSE, #' XVar = "GV", #' YVar = "Y", #' GroupVar = NULL, #' YVarTrans = "Identity", #' XVarTrans = "Identity", #' FacetRows = 1, #' FacetCols = 1, #' FacetLevels = NULL, #' AggMethod = 'mean', #' Height = NULL, #' Width = NULL, #' Title = 'Pie Chart', #' ShowLabels = FALSE, #' Title.YAxis = NULL, #' Title.XAxis = NULL, #' EchartsTheme = "macarons", #' TimeLine = TRUE, #' TextColor = "black", #' title.fontSize = 22, #' title.fontWeight = "bold", #' title.textShadowColor = '#63aeff', #' title.textShadowBlur = 3, #' title.textShadowOffsetY = 1, #' title.textShadowOffsetX = -1, #' xaxis.fontSize = 14, #' yaxis.fontSize = 14, #' Debug = FALSE) #' #' @return plot #' @export Plot.Donut <- function(dt = NULL, PreAgg = FALSE, XVar = NULL, YVar = NULL, GroupVar = NULL, YVarTrans = "Identity", XVarTrans = "Identity", FacetRows = 1, FacetCols = 1, FacetLevels = NULL, AggMethod = 'mean', Height = NULL, Width = NULL, Title = 'Donut Plot', ShowLabels = FALSE, Title.YAxis = NULL, Title.XAxis = NULL, EchartsTheme = "macarons", TimeLine = TRUE, TextColor = "white", title.fontSize = 22, title.fontWeight = "bold", title.textShadowColor = '#63aeff', title.textShadowBlur = 3, title.textShadowOffsetY = 1, title.textShadowOffsetX = -1, xaxis.fontSize = 14, yaxis.fontSize = 14, Debug = FALSE) { if(length(YVar) > 0L) YVar <- YVar[1L] if(length(XVar) > 0L) XVar <- XVar[1L] # Used multiple times check1 <- length(XVar) != 0 && length(YVar) != 0 if(!PreAgg) { if(!data.table::is.data.table(dt)) tryCatch({data.table::setDT(dt)}, error = function(x) { dt <- data.table::as.data.table(dt) }) aggFunc <- SummaryFunction(AggMethod) } # Convert factor to character if(length(GroupVar) > 0L && class(dt[[GroupVar]])[1L] == "factor") { dt[, eval(GroupVar) := as.character(get(GroupVar))] } if(length(XVar) > 0L && class(dt[[XVar]])[1L] == "factor") { dt[, eval(XVar) := as.character(get(XVar))] } # Create base plot object numvars <- c() byvars <- c() if(check1) { if(Debug) print("BarPlot 2.b") if(!PreAgg) { if(tryCatch({class(dt[[eval(YVar)]])[1L]}, error = function(x) "bla") %in% c('numeric','integer')) { numvars <- unique(c(numvars, YVar)) } else { byvars <- unique(c(byvars, YVar)) } if(tryCatch({class(dt[[eval(XVar)]])[1L]}, error = function(x) "bla") %in% c('numeric','integer')) { if(length(numvars) > 0) { x <- length(unique(dt[[XVar]])) y <- length(unique(dt[[YVar]])) if(x > y) { byvars <- unique(c(byvars, YVar)) numvars[1L] <- XVar } else { byvars <- unique(c(byvars, XVar)) } } else { numvars <- unique(c(numvars, XVar)) } } else { byvars <- unique(c(byvars, XVar)) } if(!is.null(byvars)) { temp <- dt[, lapply(.SD, noquote(aggFunc)), .SDcols = c(numvars), by = c(byvars)] for(i in byvars) { if(class(temp[[i]])[1L] %in% c('numeric','integer')) { temp[, eval(i) := as.character(get(i))] } } } else { temp <- dt[, lapply(.SD, noquote(aggFunc)), .SDcols = c(numvars)] } } else { temp <- data.table::copy(dt) numvars <- ColNameFilter(data = temp, Types = 'numeric')[[1L]] byvars <- unlist(ColNameFilter(data = temp, Types = "character")) } yvar <- temp[[YVar]] xvar <- temp[[XVar]] # Transformation if(YVarTrans != "Identity") { temp <- AutoTransformationCreate(data = temp, ColumnNames = numvars, Methods = YVarTrans)$Data } p1 <- echarts4r::e_charts_( temp, x = XVar, dispose = TRUE, darkMode = TRUE, emphasis = list(focus = "series"), width = Width, height = Height) if(ShowLabels) { p1 <- echarts4r::e_pie_(e = p1, YVar, stack = XVar, label = list(show = TRUE), radius = c("50%", "70%")) } else { p1 <- echarts4r::e_pie_(e = p1, YVar, stack = XVar, radius = c("50%", "70%")) } p1 <- echarts4r::e_theme(e = p1, name = EchartsTheme) p1 <- echarts4r::e_aria(e = p1, enabled = TRUE) p1 <- echarts4r::e_tooltip(e = p1, trigger = "item", backgroundColor = "aliceblue") p1 <- echarts4r::e_toolbox_feature(e = p1, feature = c("saveAsImage","dataZoom")) p1 <- echarts4r::e_show_loading(e = p1, hide_overlay = TRUE, text = "Calculating...", color = "#000", text_color = TextColor, mask_color = "#000") p1 <- echarts4r::e_legend(e = p1, type = "scroll", orient = "vertical", right = 50, top = 40, height = "240px", textStyle = list(color = TextColor, fontWeight = "bold")) p1 <- echarts4r::e_brush(e = p1) p1 <- echarts4r::e_title( p1, Title, textStyle = list( color = TextColor, fontWeight = title.fontWeight, overflow = "truncate", # "none", "truncate", "break", ellipsis = '...', fontSize = title.fontSize, textShadowColor = title.textShadowColor, textShadowBlur = title.textShadowBlur, textShadowOffsetY = title.textShadowOffsetY, textShadowOffsetX = title.textShadowOffsetX)) return(p1) } } #' @title Plot.Rosetype #' #' @description Build a donut plot by simply passing arguments to a single function #' #' @family Standard Plots #' #' @author Adrian Antico #' #' @param dt source data.table #' @param PreAgg logical #' @param YVar Y-Axis variable name #' @param XVar X-Axis variable name #' @param GroupVar Column name of Group Variable for distinct colored histograms by group levels #' @param YVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param XVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param FacetRows Defaults to 1 which causes no faceting to occur vertically. Otherwise, supply a numeric value for the number of output grid rows #' @param FacetCols Defaults to 1 which causes no faceting to occur horizontally. Otherwise, supply a numeric value for the number of output grid columns #' @param FacetLevels Faceting rows x columns is the max number of levels allowed in a grid. If your GroupVar has more you can supply the levels to display. #' @param AggMethod Choose from 'mean', 'sum', 'sd', and 'median' #' @param Height "400px" #' @param Width "200px" #' @param Title title #' @param ShowLabels character #' @param Title.YAxis character #' @param Title.XAxis character #' @param EchartsTheme "auritus","azul","bee-inspired","blue","caravan","carp","chalk","cool","dark-bold","dark","eduardo","essos","forest","fresh-cut","fruit","gray","green","halloween","helianthus","infographic","inspired","jazz","london","dark","macarons","macarons2","mint","purple-passion","red-velvet","red","roma","royal","sakura","shine","tech-blue","vintage","walden","wef","weforum","westeros","wonderland" #' @param TimeLine logical #' @param TextColor 'darkblue' #' @param title.fontSize Defaults to size 22. Numeric. This changes the size of the title. #' @param title.fontWeight "bold" #' @param title.textShadowColor '#63aeff' #' @param title.textShadowBlur 3 #' @param title.textShadowOffsetY 1 #' @param title.textShadowOffsetX -1 #' @param xaxis.fontSize 14 #' @param yaxis.fontSize 14 #' @param Debug Debugging purposes #' #' @examples #' # Create fake data #' dt <- data.table::data.table(Y = qnorm(p = runif(10000)), GV = sample(LETTERS, 1000, TRUE)) #' #' # Create plot #' AutoPlots::Plot.Rosetype( #' dt = dt, #' PreAgg = FALSE, #' XVar = "GV", #' YVar = "Y", #' GroupVar = NULL, #' YVarTrans = "Identity", #' XVarTrans = "Identity", #' FacetRows = 1, #' FacetCols = 1, #' FacetLevels = NULL, #' AggMethod = 'mean', #' Height = NULL, #' Width = NULL, #' Title = 'Pie Chart', #' ShowLabels = FALSE, #' Title.YAxis = NULL, #' Title.XAxis = NULL, #' EchartsTheme = "macarons", #' TimeLine = TRUE, #' TextColor = "black", #' title.fontSize = 22, #' title.fontWeight = "bold", #' title.textShadowColor = '#63aeff', #' title.textShadowBlur = 3, #' title.textShadowOffsetY = 1, #' title.textShadowOffsetX = -1, #' xaxis.fontSize = 14, #' yaxis.fontSize = 14, #' Debug = FALSE) #' #' @return plot #' @export Plot.Rosetype <- function(dt = NULL, PreAgg = FALSE, XVar = NULL, YVar = NULL, GroupVar = NULL, YVarTrans = "Identity", XVarTrans = "Identity", FacetRows = 1, FacetCols = 1, FacetLevels = NULL, AggMethod = 'mean', Height = NULL, Width = NULL, Title = 'Donut Plot', ShowLabels = FALSE, Title.YAxis = NULL, Title.XAxis = NULL, EchartsTheme = "macarons", TimeLine = TRUE, TextColor = "white", title.fontSize = 22, title.fontWeight = "bold", title.textShadowColor = '#63aeff', title.textShadowBlur = 3, title.textShadowOffsetY = 1, title.textShadowOffsetX = -1, xaxis.fontSize = 14, yaxis.fontSize = 14, Debug = FALSE) { if(length(YVar) > 0L) YVar <- YVar[1L] if(length(XVar) > 0L) XVar <- XVar[1L] # Used multiple times check1 <- length(XVar) != 0 && length(YVar) != 0 if(!PreAgg) { if(!data.table::is.data.table(dt)) tryCatch({data.table::setDT(dt)}, error = function(x) { dt <- data.table::as.data.table(dt) }) aggFunc <- SummaryFunction(AggMethod) } # Convert factor to character if(length(GroupVar) > 0L && class(dt[[GroupVar]])[1L] == "factor") { dt[, eval(GroupVar) := as.character(get(GroupVar))] } if(length(XVar) > 0L && class(dt[[XVar]])[1L] == "factor") { dt[, eval(XVar) := as.character(get(XVar))] } # Create base plot object numvars <- c() byvars <- c() if(check1) { if(Debug) print("BarPlot 2.b") if(!PreAgg) { if(tryCatch({class(dt[[eval(YVar)]])[1L]}, error = function(x) "bla") %in% c('numeric','integer')) { numvars <- unique(c(numvars, YVar)) } else { byvars <- unique(c(byvars, YVar)) } if(tryCatch({class(dt[[eval(XVar)]])[1L]}, error = function(x) "bla") %in% c('numeric','integer')) { if(length(numvars) > 0) { x <- length(unique(dt[[XVar]])) y <- length(unique(dt[[YVar]])) if(x > y) { byvars <- unique(c(byvars, YVar)) numvars[1L] <- XVar } else { byvars <- unique(c(byvars, XVar)) } } else { numvars <- unique(c(numvars, XVar)) } } else { byvars <- unique(c(byvars, XVar)) } if(!is.null(byvars)) { temp <- dt[, lapply(.SD, noquote(aggFunc)), .SDcols = c(numvars), by = c(byvars)] for(i in byvars) { if(class(temp[[i]])[1L] %in% c('numeric','integer')) { temp[, eval(i) := as.character(get(i))] } } } else { temp <- dt[, lapply(.SD, noquote(aggFunc)), .SDcols = c(numvars)] } } else { temp <- data.table::copy(dt) numvars <- ColNameFilter(data = temp, Types = 'numeric')[[1L]] byvars <- unlist(ColNameFilter(data = temp, Types = "character")) } yvar <- temp[[YVar]] xvar <- temp[[XVar]] # Transformation if(YVarTrans != "Identity") { temp <- AutoTransformationCreate(data = temp, ColumnNames = numvars, Methods = YVarTrans)$Data } p1 <- echarts4r::e_charts_( temp, x = XVar, dispose = TRUE, darkMode = TRUE, emphasis = list(focus = "series"), width = Width, height = Height) if(ShowLabels) { p1 <- echarts4r::e_pie_(e = p1, YVar, stack = XVar, label = list(show = TRUE), roseType = "radius") } else { p1 <- echarts4r::e_pie_(e = p1, YVar, stack = XVar, roseType = "radius") } p1 <- echarts4r::e_theme(e = p1, name = EchartsTheme) p1 <- echarts4r::e_aria(e = p1, enabled = TRUE) p1 <- echarts4r::e_tooltip(e = p1, trigger = "item", backgroundColor = "aliceblue") p1 <- echarts4r::e_toolbox_feature(e = p1, feature = c("saveAsImage","dataZoom")) p1 <- echarts4r::e_show_loading(e = p1, hide_overlay = TRUE, text = "Calculating...", color = "#000", text_color = TextColor, mask_color = "#000") p1 <- echarts4r::e_legend(e = p1, type = "scroll", orient = "vertical", right = 50, top = 40, height = "240px", textStyle = list(color = TextColor, fontWeight = "bold")) p1 <- echarts4r::e_brush(e = p1) p1 <- echarts4r::e_title( p1, Title, textStyle = list( color = TextColor, fontWeight = title.fontWeight, overflow = "truncate", # "none", "truncate", "break", ellipsis = '...', fontSize = title.fontSize, textShadowColor = title.textShadowColor, textShadowBlur = title.textShadowBlur, textShadowOffsetY = title.textShadowOffsetY, textShadowOffsetX = title.textShadowOffsetX)) return(p1) } } #' @title Plot.Box #' #' @description Build a box plot by simply passing arguments to a single function. It will sample your data using SampleSize number of rows. Sampled data is randomized. #' #' @family Standard Plots #' #' @author Adrian Antico #' #' @param dt source data.table #' @param SampleSize numeric #' @param YVar Y-Axis variable name #' @param XVar X-Axis variable name #' @param GroupVar Character variable #' @param YVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param XVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param FacetRows Defaults to 1 which causes no faceting to occur vertically. Otherwise, supply a numeric value for the number of output grid rows #' @param FacetCols Defaults to 1 which causes no faceting to occur horizontally. Otherwise, supply a numeric value for the number of output grid columns #' @param FacetLevels Faceting rows x columns is the max number of levels allowed in a grid. If your GroupVar has more you can supply the levels to display. #' @param Height "400px" #' @param Width "200px" #' @param Title character #' @param ShowLabels character #' @param Title.YAxis character #' @param Title.XAxis character #' @param EchartsTheme "auritus","azul","bee-inspired","blue","caravan","carp","chalk","cool","dark-bold","dark","eduardo", #' "essos","forest","fresh-cut","fruit","gray","green","halloween","helianthus","infographic","inspired", #' "jazz","london","dark","macarons","macarons2","mint","purple-passion","red-velvet","red","roma","royal", #' "sakura","shine","tech-blue","vintage","walden","wef","weforum","westeros","wonderland" #' @param TimeLine Logical #' @param MouseScroll logical, zoom via mouse scroll #' @param TextColor character hex #' @param title.fontSize 22 #' @param title.fontWeight "bold" #' @param title.textShadowColor '#63aeff' #' @param title.textShadowBlur 3 #' @param title.textShadowOffsetY 1 #' @param title.textShadowOffsetX -1 #' @param xaxis.fontSize 14 #' @param yaxis.fontSize 14 #' @param xaxis.rotate 0 #' @param yaxis.rotate 0 #' @param ContainLabel TRUE #' @param Debug Debugging purposes #' #' @examples #' # Create fake data #' dt <- data.table::data.table(Y = qnorm(p = runif(10000)), GV = sample(LETTERS, 1000, TRUE)) #' #' AutoPlots::Plot.Box( #' dt = dt, #' SampleSize = 100000L, #' XVar = "GV", #' YVar = "Y", #' GroupVar = NULL, #' YVarTrans = "Identity", #' XVarTrans = "Identity", #' FacetRows = 1, #' FacetCols = 1, #' FacetLevels = NULL, #' Height = NULL, #' Width = NULL, #' Title = 'Box Plot', #' ShowLabels = FALSE, #' Title.YAxis = NULL, #' Title.XAxis = NULL, #' EchartsTheme = "macarons", #' MouseScroll = TRUE, #' TimeLine = FALSE, #' TextColor = "black", #' title.fontSize = 22, #' title.fontWeight = "bold", #' title.textShadowColor = '#63aeff', #' title.textShadowBlur = 3, #' title.textShadowOffsetY = 1, #' title.textShadowOffsetX = -1, #' xaxis.fontSize = 14, #' yaxis.fontSize = 14, #' xaxis.rotate = 0, #' yaxis.rotate = 0, #' ContainLabel = TRUE, #' Debug = FALSE) #' #' @return plot #' @export Plot.Box <- function(dt = NULL, SampleSize = 100000L, XVar = NULL, YVar = NULL, GroupVar = NULL, YVarTrans = "Identity", XVarTrans = "Identity", FacetRows = 1, FacetCols = 1, FacetLevels = NULL, Height = NULL, Width = NULL, Title = 'Box Plot', ShowLabels = FALSE, Title.YAxis = NULL, Title.XAxis = NULL, EchartsTheme = "macarons", MouseScroll = TRUE, TimeLine = FALSE, TextColor = "white", title.fontSize = 22, title.fontWeight = "bold", title.textShadowColor = '#63aeff', title.textShadowBlur = 3, title.textShadowOffsetY = 1, title.textShadowOffsetX = -1, xaxis.fontSize = 14, yaxis.fontSize = 14, xaxis.rotate = 0, yaxis.rotate = 0, ContainLabel = TRUE, Debug = FALSE) { if(Debug) print("Box 1") # Turn off Faceting until I can figure out how to supply it FacetRows <- 1L FacetCols <- 1L # Ensure data.table if(!data.table::is.data.table(dt)) tryCatch({data.table::setDT(dt)}, error = function(x) { dt <- data.table::as.data.table(dt) }) if(Debug) print("Box 2") # Convert factor to character if(length(GroupVar) > 0L && class(dt[[GroupVar]])[1L] == "factor") { dt[, eval(GroupVar) := as.character(get(GroupVar))] } if(Debug) print("Box 3") if(length(XVar) > 0L && class(dt[[XVar]])[1L] == "factor") { dt[, eval(XVar) := as.character(get(XVar))] } if(Debug) print("Box 4") if(Debug) print("Plot.BoxPlot 1") # Cap number of records if(length(YVar) > 0L) { SampleSize <- SampleSize / length(YVar) } if(dt[,.N] > SampleSize) { dt1 <- dt[order(runif(.N))][seq_len(SampleSize)] } else { dt1 <- data.table::copy(dt) } if(Debug) print("Box 5") if(length(YVar) > 0L && length(XVar) == 0L && length(GroupVar) > 0L) { XVar <- GroupVar; GroupVar <- NULL CoordFlip <- FALSE } else if(length(XVar) > 0L && length(YVar) == 0L && length(GroupVar) > 0L) { YVar <- XVar; XVar <- GroupVar; GroupVar <- NULL CoordFlip <- TRUE } else { CoordFlip <- FALSE if(length(XVar) > 0L && class(dt1[[XVar]])[1L] %in% c("numeric","integer")) { YVarTrans <- XVarTrans YVar <- XVar XVar <- NULL } } # Multiple YVars if(length(YVar) > 1L) { XVar <- NULL GroupVar <- NULL dt1[, temp__ := "a"] dt1 <- data.table::melt.data.table(data = dt1, id.vars = "temp__", measure.vars = YVar, variable.name = "Measures", value.name = "Values") dt1[, temp__ := NULL] XVar <- "Measures" YVar <- "Values" } if(Debug) print("Box 6") if(length(GroupVar) > 0L && FacetRows > 1L && FacetCols > 1L) { dt1 <- dt1[get(GroupVar) %in% c(eval(FacetLevels)), .SD, .SDcols = c(YVar,XVar,GroupVar)] } if(Debug) print("Box 7") # Transformation if(YVarTrans != "Identity") { for(ggss in YVar) { dt1 <- AutoTransformationCreate(data = dt1, ColumnNames = ggss, Methods = YVarTrans)$Data } } if(Debug) print("Box 8") # Build Plot Based on Available Variables # Create logic checks to determine each case distinctly if(Debug) print("Plot.BoxPlot 2") X_and_Y_and_GroupVars <- length(XVar) > 0L && length(YVar) > 0L && length(GroupVar) > 0L X_and_Y <- length(XVar) > 0L && length(YVar) > 0L if(Debug) print("Box 9") # X,Y,GroupVar if(X_and_Y_and_GroupVars) { if(Debug) print("Box 10") if(Debug) print("Plot.Box Echarts") p1 <- echarts4r::e_charts_( data = dt1 |> dplyr::group_by(get(GroupVar[1L])), x = XVar, dispose = TRUE, darkMode = TRUE, emphasis = list(focus = "series"), width = Width, height = Height) if(Debug) print("Box 11") if(ShowLabels) { p1 <- echarts4r::e_boxplot_(e = p1, YVar, label = list(show = TRUE)) } else { p1 <- echarts4r::e_boxplot_(e = p1, YVar) } if(Debug) print("Box 12") p1 <- echarts4r::e_visual_map_(e = p1, YVar, show = FALSE) if(MouseScroll && FacetRows == 1L && FacetCols == 1L) { p1 <- echarts4r::e_datazoom(e = p1, type = "inside", x_index = c(0,1)) } else if(MouseScroll && (FacetRows > 1L || FacetCols > 1L)) { p1 <- echarts4r::e_datazoom(e = p1, type = "inside", x_index = seq(0, FacetRows * FacetCols - 1, 1)) } else { p1 <- echarts4r::e_datazoom(e = p1, x_index = c(0,1)) } if(Debug) print("Box 13") p1 <- echarts4r::e_theme(e = p1, name = EchartsTheme) p1 <- echarts4r::e_aria(e = p1, enabled = TRUE) p1 <- echarts4r::e_tooltip(e = p1, trigger = "item", backgroundColor = "aliceblue") p1 <- echarts4r::e_toolbox_feature(e = p1, feature = c("saveAsImage","dataZoom")) p1 <- echarts4r::e_show_loading(e = p1, hide_overlay = TRUE, text = "Calculating...", color = "#000", text_color = TextColor, mask_color = "#000") if(Debug) print("Box 14") if(length(Title.XAxis) == 0L) { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "x", name = XVar, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = xaxis.fontSize), axisLabel = list( rotate = xaxis.rotate, grid = list(containLabel = ContainLabel))) } else { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "x", name = Title.XAxis, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = xaxis.fontSize), axisLabel = list( rotate = xaxis.rotate, grid = list(containLabel = ContainLabel))) } if(Debug) print("Box 15") if(length(Title.YAxis) == 0L) { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "y", name = YVar, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = yaxis.fontSize), axisLabel = list( rotate = yaxis.rotate, grid = list(containLabel = ContainLabel))) } else { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "y", name = Title.YAxis, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = yaxis.fontSize), axisLabel = list( rotate = yaxis.rotate, grid = list(containLabel = ContainLabel))) } if(Debug) print("Box 16") if(CoordFlip) p1 <- echarts4r::e_flip_coords(e = p1) p1 <- echarts4r::e_brush(e = p1) p1 <- echarts4r::e_title( p1, Title, textStyle = list( color = TextColor, fontWeight = title.fontWeight, overflow = "truncate", # "none", "truncate", "break", ellipsis = '...', fontSize = title.fontSize, textShadowColor = title.textShadowColor, textShadowBlur = title.textShadowBlur, textShadowOffsetY = title.textShadowOffsetY, textShadowOffsetX = title.textShadowOffsetX)) if(FacetRows > 1L || FacetCols > 1L) p1 <- echarts4r::e_facet(e = p1, rows = FacetRows, cols = FacetCols, legend_space = 16, legend_pos = "top") return(p1) } # X,Y if(X_and_Y) { if(Debug) print("Box 10.a") if(Debug) print("Plot.Box X_and_Y") if(Debug) print("Plot.Box Echarts") p1 <- echarts4r::e_charts_( dt1 |> dplyr::group_by(get(XVar)), x = YVar, darkMode = TRUE, dispose = TRUE, color = GroupVar, width = Width, height = Height) if(ShowLabels) { p1 <- echarts4r::e_boxplot_(e = p1, YVar, label = list(show = TRUE)) } else { p1 <- echarts4r::e_boxplot_(e = p1, YVar) } p1 <- echarts4r::e_visual_map_(e = p1, YVar, show = FALSE) if(MouseScroll && FacetRows == 1L && FacetCols == 1L) { p1 <- echarts4r::e_datazoom(e = p1, type = "inside", x_index = c(0,1)) } else if(MouseScroll && (FacetRows > 1L || FacetCols > 1L)) { p1 <- echarts4r::e_datazoom(e = p1, type = "inside", x_index = seq(0, FacetRows * FacetCols - 1, 1)) } else { p1 <- echarts4r::e_datazoom(e = p1, x_index = c(0,1)) } p1 <- echarts4r::e_theme(e = p1, name = EchartsTheme) p1 <- echarts4r::e_aria(e = p1, enabled = TRUE) p1 <- echarts4r::e_tooltip(e = p1, trigger = "item", backgroundColor = "aliceblue") p1 <- echarts4r::e_toolbox_feature(e = p1, feature = c("saveAsImage","dataZoom")) p1 <- echarts4r::e_show_loading(e = p1, hide_overlay = TRUE, text = "Calculating...", color = "#000", text_color = TextColor, mask_color = "#000") if(length(Title.XAxis) == 0L) { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "x", name = XVar, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = xaxis.fontSize), axisLabel = list( rotate = xaxis.rotate, grid = list(containLabel = ContainLabel))) } else { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "x", name = Title.XAxis, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = xaxis.fontSize), axisLabel = list( rotate = xaxis.rotate, grid = list(containLabel = ContainLabel))) } if(length(Title.YAxis) == 0L) { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "y", name = YVar, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = yaxis.fontSize), axisLabel = list( rotate = yaxis.rotate, grid = list(containLabel = ContainLabel))) } else { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "y", name = Title.YAxis, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = yaxis.fontSize), axisLabel = list( rotate = yaxis.rotate, grid = list(containLabel = ContainLabel))) } if(CoordFlip) p1 <- echarts4r::e_flip_coords(e = p1) p1 <- echarts4r::e_brush(e = p1) p1 <- echarts4r::e_title( p1, Title, textStyle = list( color = TextColor, fontWeight = title.fontWeight, overflow = "truncate", # "none", "truncate", "break", ellipsis = '...', fontSize = title.fontSize, textShadowColor = title.textShadowColor, textShadowBlur = title.textShadowBlur, textShadowOffsetY = title.textShadowOffsetY, textShadowOffsetX = title.textShadowOffsetX)) if(FacetRows > 1L || FacetCols > 1L) p1 <- echarts4r::e_facet(e = p1, rows = FacetRows, cols = FacetCols, legend_space = 16, legend_pos = "top") # Return return(p1) } # Y Only if(length(YVar) > 0L) { if(Debug) print("Box 10.b") if(Debug) print("Plot.Box Y Only") if(Debug) print("Plot.Box Echarts") p1 <- echarts4r::e_charts_( dt1, dispose = TRUE, darkMode = TRUE, width = Width, height = Height) if(ShowLabels) { p1 <- echarts4r::e_boxplot_(e = p1, YVar, label = list(show = TRUE)) } else { p1 <- echarts4r::e_boxplot_(e = p1, YVar) } p1 <- echarts4r::e_visual_map_(e = p1, YVar, show = FALSE) if(MouseScroll && FacetRows == 1L && FacetCols == 1L) { p1 <- echarts4r::e_datazoom(e = p1, type = "inside", x_index = c(0,1)) } else if(MouseScroll && (FacetRows > 1L || FacetCols > 1L)) { p1 <- echarts4r::e_datazoom(e = p1, type = "inside", x_index = seq(0, FacetRows * FacetCols - 1, 1)) } else { p1 <- echarts4r::e_datazoom(e = p1, x_index = c(0,1)) } p1 <- echarts4r::e_theme(e = p1, name = EchartsTheme) p1 <- echarts4r::e_aria(e = p1, enabled = TRUE) p1 <- echarts4r::e_tooltip(e = p1, trigger = "item", backgroundColor = "aliceblue") p1 <- echarts4r::e_toolbox_feature(e = p1, feature = c("saveAsImage","dataZoom")) p1 <- echarts4r::e_show_loading(e = p1, hide_overlay = TRUE, text = "Calculating...", color = "#000", text_color = TextColor, mask_color = "#000") if(length(Title.XAxis) == 0L) { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "x", name = XVar, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = xaxis.fontSize), axisLabel = list( rotate = xaxis.rotate, grid = list(containLabel = ContainLabel))) } else { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "x", name = Title.XAxis, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = xaxis.fontSize), axisLabel = list( rotate = xaxis.rotate, grid = list(containLabel = ContainLabel))) } if(length(Title.YAxis) == 0L) { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "y", name = YVar, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = yaxis.fontSize), axisLabel = list( rotate = yaxis.rotate, grid = list(containLabel = ContainLabel))) } else { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "y", name = Title.YAxis, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = yaxis.fontSize), axisLabel = list( rotate = yaxis.rotate, grid = list(containLabel = ContainLabel))) } p1 <- echarts4r::e_brush(e = p1) p1 <- echarts4r::e_title( p1, Title, textStyle = list( color = TextColor, fontWeight = title.fontWeight, overflow = "truncate", # "none", "truncate", "break", ellipsis = '...', fontSize = title.fontSize, textShadowColor = title.textShadowColor, textShadowBlur = title.textShadowBlur, textShadowOffsetY = title.textShadowOffsetY, textShadowOffsetX = title.textShadowOffsetX)) return(p1) } # X Only if(length(XVar) > 0L) { if(Debug) print("Box 10.c") if(Debug) print("Plot.Box X Only") if(Debug) print("Plot.Box Echarts") p1 <- echarts4r::e_charts_( dt1, dispose = TRUE, darkMode = TRUE, width = Width, height = Height) if(ShowLabels) { p1 <- echarts4r::e_boxplot_(e = p1, XVar, label = list(show = TRUE)) } else { p1 <- echarts4r::e_boxplot_(e = p1, XVar) } p1 <- echarts4r::e_visual_map_(e = p1, XVar, show = FALSE) if(MouseScroll && FacetRows == 1L && FacetCols == 1L) { p1 <- echarts4r::e_datazoom(e = p1, type = "inside", x_index = c(0,1)) } else if(MouseScroll && (FacetRows > 1L || FacetCols > 1L)) { p1 <- echarts4r::e_datazoom(e = p1, type = "inside", x_index = seq(0, FacetRows * FacetCols - 1, 1)) } else { p1 <- echarts4r::e_datazoom(e = p1, x_index = c(0,1)) } p1 <- echarts4r::e_theme(e = p1, name = EchartsTheme) p1 <- echarts4r::e_aria(e = p1, enabled = TRUE) p1 <- echarts4r::e_tooltip(e = p1, trigger = "item", backgroundColor = "aliceblue") p1 <- echarts4r::e_toolbox_feature(e = p1, feature = c("saveAsImage","dataZoom")) p1 <- echarts4r::e_show_loading(e = p1, hide_overlay = TRUE, text = "Calculating...", color = "#000", text_color = TextColor, mask_color = "#000") if(length(Title.XAxis) == 0L) { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "x", name = XVar, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = xaxis.fontSize), axisLabel = list( rotate = xaxis.rotate, grid = list(containLabel = ContainLabel))) } else { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "x", name = Title.XAxis, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = xaxis.fontSize), axisLabel = list( rotate = xaxis.rotate, grid = list(containLabel = ContainLabel))) } if(length(Title.YAxis) == 0L) { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "y", name = YVar, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = yaxis.fontSize), axisLabel = list( rotate = yaxis.rotate, grid = list(containLabel = ContainLabel))) } else { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "y", name = Title.YAxis, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = yaxis.fontSize), axisLabel = list( rotate = yaxis.rotate, grid = list(containLabel = ContainLabel))) } p1 <- echarts4r::e_brush(e = p1) p1 <- echarts4r::e_title( p1, Title, textStyle = list( color = TextColor, fontWeight = title.fontWeight, overflow = "truncate", # "none", "truncate", "break", ellipsis = '...', fontSize = title.fontSize, textShadowColor = title.textShadowColor, textShadowBlur = title.textShadowBlur, textShadowOffsetY = title.textShadowOffsetY, textShadowOffsetX = title.textShadowOffsetX)) # Return return(p1) } return(NULL) } #' @title Plot.WordCloud #' #' @description WordCloud plots #' #' @family Standard Plots #' #' @param dt source data.table #' @param YVar Y-Axis variable name #' @param Height "400px" #' @param Width "200px" #' @param Title = "Density Plot" #' @param EchartsTheme "auritus","azul","bee-inspired","blue","caravan","carp","chalk","cool","dark-bold","dark","eduardo", "essos","forest","fresh-cut","fruit","gray","green","halloween","helianthus","infographic","inspired", "jazz","london","dark","macarons","macarons2","mint","purple-passion","red-velvet","red","roma","royal", "sakura","shine","tech-blue","vintage","walden","wef","weforum","westeros","wonderland" #' @param TextColor "white", #' @param title.fontSize 22 #' @param title.fontWeight "bold" #' @param title.textShadowColor '#63aeff' #' @param title.textShadowBlur 3 #' @param title.textShadowOffsetY 1 #' @param title.textShadowOffsetX -1 #' @param xaxis.fontSize 14 #' @param yaxis.fontSize 14 #' @param xaxis.rotate 0 #' @param yaxis.rotate 0 #' @param ContainLabel TRUE #' @param Debug Debugging purposes #' #' @examples #' # Create fake data #' dt <- FakeDataGenerator(AddComment = TRUE) #' #' # Create plot #' AutoPlots::Plot.WordCloud( #' dt = dt, #' YVar = "Comment", #' Height = NULL, #' Width = NULL, #' Title = "Word Cloud", #' EchartsTheme = "macarons", #' TextColor = "black", #' title.fontSize = 22, #' title.fontWeight = "bold", #' title.textShadowColor = '#63aeff', #' title.textShadowBlur = 3, #' title.textShadowOffsetY = 1, #' title.textShadowOffsetX = -1, #' xaxis.fontSize = 14, #' yaxis.fontSize = 14, #' xaxis.rotate = 0, #' yaxis.rotate = 0, #' ContainLabel = TRUE, #' Debug = FALSE) #' #' @return plot #' @export Plot.WordCloud <- function(dt = NULL, YVar = NULL, Height = NULL, Width = NULL, Title = "Word Cloud", EchartsTheme = "macarons", TextColor = "white", title.fontSize = 22, title.fontWeight = "bold", title.textShadowColor = '#63aeff', title.textShadowBlur = 3, title.textShadowOffsetY = 1, title.textShadowOffsetX = -1, xaxis.fontSize = 14, yaxis.fontSize = 14, xaxis.rotate = 0, yaxis.rotate = 0, ContainLabel = TRUE, Debug = FALSE) { if(EchartsTheme == 'auritus') { ColorVals <- c("#3e4359", "#c5a805", "#4d267e", "#22904f", "red") } else if(EchartsTheme == 'azul') { ColorVals <- c("#bfcca6", "#b07a9a", "#65deff", "#f73372", "#d08e1f") } else if(EchartsTheme == 'bee-inspired') { ColorVals <- c("#24243b", "#c2ba38", "#deeb25", "#ebc625", "#ffe700") } else if(EchartsTheme == 'blue') { ColorVals <- c("#2e69aa", "#99b8d9", "#3a84d4", "#1b67b9", "#046fe1") } else if(EchartsTheme == 'caravan') { ColorVals <- c("#18536d", "#d44545", "#eba565", "#e1c3a7", "#e1dda7") } else if(EchartsTheme == 'carp') { ColorVals <- c("#ff3300", "#fff0bb", "#679898", "#ff8870", "#4d3935") } else if(EchartsTheme == 'chalk') { ColorVals <- c("#e8c69e", "#54afec", "#d9dc89", "#f1a7d6", "#927294") } else if(EchartsTheme == 'cool') { ColorVals <- c("#20146a", "#591b89", "#911ea6", "#8081ba", "#2a74c4") } else if(EchartsTheme == 'dark-bold') { ColorVals <- c("#922e2e", "#d06363", "#d0a463", "#5c845e", "#63d0b9") } else if(EchartsTheme == 'dark') { ColorVals <- c("#e17d7d", "#c1ba54", "#66d5b0", "#b366d5", "#66a9d5") } else if(EchartsTheme == 'eduardo') { ColorVals <- c("#352a61", "#696284", "#c190ba", "#9e8a9b", "#615b60") } else if(EchartsTheme == 'essos') { ColorVals <- c("#753751", "#cfc995", "#c2b53c", "#d89c41") } else if(EchartsTheme == 'forest') { ColorVals <- c("#101010", "#bdb892", "#6c7955", "#3e6e86", "#37412e") } else if(EchartsTheme == 'fresh-cut') { ColorVals <- c("#74b936", "#76e314", "#cfbcb2", "#26609e", "#11b1cf") } else if(EchartsTheme == 'fruit') { ColorVals <- c("#dc965e", "#955828", "#c2b3a6", "#a16464", "#ae8c74") } else if(EchartsTheme == 'gray') { ColorVals <- c("#333333", "#696969", "#989898", "#bababa", "#e3e3e3") } else if(EchartsTheme == 'green') { ColorVals <- c("#2c5e25", "#387830", "#56a14d", "#7cbe74", "#b5e3af") } else if(EchartsTheme == 'halloween') { ColorVals <- c("#d1d134", "#d1953c", "#cc735d", "#7a5dcc", "#564f6a") } else if(EchartsTheme == 'helianthus') { ColorVals <- c("#6235e1", "#e16235", "#e1c135", "#c46aa5", "#5bcf3e") } else if(EchartsTheme == 'infographic') { ColorVals <- c("#d5cb2b", "#b4e771", "#cc4d3d", "#e78971", "#82b053") } else if(EchartsTheme == 'inspired') { ColorVals <- c("#8e1212", "#0f6310", "#d39f03", "#ff0000", "#265d82") } else if(EchartsTheme == 'jazz') { ColorVals <- c("#5e4832", "#000000", "#265057", "#d5dcdd") } else if(EchartsTheme == 'london') { ColorVals <- c("#881010", "#b8d1d4", "#227e89", "#041137", "#1c86c4") } else if(EchartsTheme == 'macarons') { ColorVals <- c("#6382cf", "#8776b9", "#318c9d", "#6d5739", "#7f7f98") } else if(EchartsTheme == 'macarons2') { ColorVals <- c("#6d6ddb", "#d45315", "#6e9fe4", "#b9bc89", "#d37c7c") } else if(EchartsTheme == 'mint') { ColorVals <- c("#c3ebd6", "#859d90", "#6dbaba", "#6dba9b", "#62d17f") } else if(EchartsTheme == 'purple-passion') { ColorVals <- c("#9385ba", "#779fbe", "#b86aac", "#5d9dc8", "#5f3a89") } else if(EchartsTheme == 'red-velvet') { ColorVals <- c("#6f4c41", "#db8469", "#f13d67", "#5e1d2c", "#ff00a9") } else if(EchartsTheme == 'red') { ColorVals <- c("#b4342a", "#8a4d49", "#c08480", "#df745a", "#cca69d") } else if(EchartsTheme == 'roma') { ColorVals <- c("#a580e9", "#d56426", "#cd1450", "#8bbec0", "#91836b") } else if(EchartsTheme == 'royal') { ColorVals <- c("#a06156", "#756054", "#5fac21", "#34708a", "#692525") } else if(EchartsTheme == 'sakura') { ColorVals <- c("#d75869", "#cb979e", "#b12a3d", "#adabc7", "#d0a79b") } else if(EchartsTheme == 'shine') { ColorVals <- c("#3d5995", "#296537", "#3390f7", "#b81717", "#50868c") } else if(EchartsTheme == 'tech-blue') { ColorVals <- c("#356499", "#4e487e", "#524f4b", "#b9addc", "#1c70d8") } else if(EchartsTheme == 'vintage') { ColorVals <- c("#a47e5f", "#638176", "#a46969", "#5d3a3a", "#4f8090") } else if(EchartsTheme == 'walden') { ColorVals <- c("#3b96c4", "#8babba", "#a5d9a2", "#535d84", "#7f79ad") } else if(EchartsTheme == 'wef') { ColorVals <- c("#5981d5", "#3268d9", "#9d938a", "#1f457c", "#524e48") } else if(EchartsTheme == 'weforum') { ColorVals <- c("#8a1b6f", "#4d2876", "#d5bf24", "#2792aa", "#a27322") } else if(EchartsTheme == 'westeros') { ColorVals <- c("#4b4d66", "#a681b0", "#8acccf", "#41a7cf") } else if(EchartsTheme == 'wonderland') { ColorVals <- c("#629291", "#3ec5c2", "#cf95ad", "#cd7097") } # Cap number of records if(!data.table::is.data.table(dt)) tryCatch({data.table::setDT(dt)}, error = function(x) { dt <- data.table::as.data.table(dt) }) # Convert factor to character if(length(YVar) > 0L && class(dt[[YVar]])[1L] == "factor") { dt[, eval(YVar) := as.character(get(YVar))] } # Copy Data dt1 <- data.table::copy(dt) # Define Plotting Variable if(length(YVar) == 0L) return(NULL) # Data YVar <- "Comment" # dt <- AutoNLP::FakeDataGenerator(N = 1000, AddComment = TRUE) dt1 <- quanteda::tokens(dt[[YVar]], remove_punct = TRUE) dt2 <- quanteda::dfm(dt1) dt3 <- data.table::setDT(quanteda.textstats::textstat_frequency(dt2)) dt4 <- dt3[, .SD, .SDcols = c("feature", "frequency")] data.table::setnames(dt4, c("feature", "frequency"),c("term", "freq")) # Create base plot object if(Debug) print('Create Plot with only data') dt5 <- echarts4r::e_color_range_( data = dt4, input = "freq", output = "Color", colors = ColorVals) p1 <- echarts4r::e_charts(data = dt5) p1 <- echarts4r::e_cloud_(e = p1, "term", "freq", "Color", shape = "circle", sizeRange = c(20, 42)) p1 <- echarts4r::e_title( p1, Title, textStyle = list( color = TextColor, fontWeight = title.fontWeight, overflow = "truncate", ellipsis = '...', fontSize = title.fontSize, textShadowColor = title.textShadowColor, textShadowBlur = title.textShadowBlur, textShadowOffsetY = title.textShadowOffsetY, textShadowOffsetX = title.textShadowOffsetX)) p1 <- echarts4r::e_theme(e = p1, name = EchartsTheme) return(p1) } # ---- # ---- # @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ---- # > Aggreagated Plot Functions ---- # @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ---- #' @title Plot.Radar #' #' @author Adrian Antico #' @family Standard Plots #' #' @param dt source data.table #' @param PreAgg logical #' @param AggMethod character #' @param YVar Y-Axis variable name. You can supply multiple YVars #' @param GroupVar One Grouping Variable #' @param YVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param Height "400px" #' @param Width "200px" #' @param Title "Title" #' @param ShowLabels character #' @param EchartsTheme Provide an "Echarts" theme #' @param ShowSymbol = FALSE #' @param TextColor "Not Implemented" #' @param title.fontSize 22 #' @param title.fontWeight "bold" #' @param title.textShadowColor '#63aeff' #' @param title.textShadowBlur 3 #' @param title.textShadowOffsetY 1 #' @param title.textShadowOffsetX -1 #' @param ContainLabel TRUE #' @param DarkMode FALSE #' @param Debug Debugging purposes #' #' @examples #' # Create Data #' dt <- data.table::data.table(Y = pnorm(q = runif(8)), GV = sample(LETTERS[1:4], 8, TRUE)) #' #' # Create plot #' AutoPlots::Plot.Radar( #' dt = dt, #' AggMethod = "mean", #' PreAgg = FALSE, #' YVar = "Y", #' GroupVar = "GV", #' YVarTrans = "Identity", #' Height = NULL, #' Width = NULL, #' Title = 'Radar Plot', #' ShowLabels = FALSE, #' EchartsTheme = "macarons", #' ShowSymbol = FALSE, #' TextColor = "black", #' title.fontSize = 22, #' title.fontWeight = "bold", #' title.textShadowColor = '#63aeff', #' title.textShadowBlur = 3, #' title.textShadowOffsetY = 1, #' title.textShadowOffsetX = -1, #' ContainLabel = TRUE, #' DarkMode = FALSE, #' Debug = FALSE) #' #' @return plot #' @export Plot.Radar <- function(dt = NULL, AggMethod = "mean", PreAgg = TRUE, YVar = NULL, GroupVar = NULL, YVarTrans = "Identity", Height = NULL, Width = NULL, Title = 'Radar Plot', ShowLabels = FALSE, EchartsTheme = "macarons", ShowSymbol = FALSE, TextColor = "white", title.fontSize = 22, title.fontWeight = "bold", title.textShadowColor = '#63aeff', title.textShadowBlur = 3, title.textShadowOffsetY = 1, title.textShadowOffsetX = -1, ContainLabel = TRUE, DarkMode = FALSE, Debug = FALSE) { if(!data.table::is.data.table(dt)) tryCatch({data.table::setDT(dt)}, error = function(x) { dt <- data.table::as.data.table(dt) }) # Convert factor to character if(length(GroupVar) > 0L && class(dt[[GroupVar]])[1L] == "factor") { dt[, eval(GroupVar) := as.character(get(GroupVar))] } # If User Supplies more than 1 YVar, then structure data to be long instead of wide dt1 <- data.table::copy(dt) # Subset columns dt1 <- dt1[, .SD, .SDcols = c(YVar, GroupVar)] # Minimize data before moving on if(!PreAgg) { # Define Aggregation function if(Debug) print("Plot.Radar # Define Aggregation function") aggFunc <- SummaryFunction(AggMethod) # Aggregate data dt1 <- dt1[, lapply(.SD, noquote(aggFunc)), by = c(GroupVar[1L])] } # Transformation if(YVarTrans != "Identity") { for(yvar in YVar) { dt1 <- AutoTransformationCreate(data = dt1, ColumnNames = yvar, Methods = YVarTrans)$Data } } # Make sure the variable with the largest value goes first # Otherwise the radar plot will size to a smaller variable and look stupid mv <- c(rep(0, length(YVar))) for(i in seq_along(YVar)) { mv[i] <- dt1[, max(get(YVar[i]), na.rm = TRUE)] } YVarMod <- YVar[which(mv == max(mv, na.rm = TRUE))] YVarMod <- c(YVarMod, YVar[!YVar %in% YVarMod]) mv <- max(mv, na.rm = TRUE) # Build base plot depending on GroupVar availability p1 <- echarts4r::e_charts_( data = dt1, x = GroupVar, darkMode = TRUE, emphasis = list(focus = "series"), dispose = TRUE, width = Width, height = Height) for(yvar in YVarMod) { p1 <- echarts4r::e_radar_(e = p1, serie = yvar, max = mv, name = yvar) } if(Debug) print("Plot.Radar() Build Echarts 5") p1 <- echarts4r::e_theme(e = p1, name = EchartsTheme) if(Debug) print("Plot.Radar() Build Echarts 6") p1 <- echarts4r::e_aria(e = p1, enabled = TRUE) p1 <- echarts4r::e_tooltip(e = p1, trigger = "item", backgroundColor = "aliceblue") p1 <- echarts4r::e_toolbox_feature(e = p1, feature = c("saveAsImage","dataZoom")) p1 <- echarts4r::e_show_loading(e = p1, hide_overlay = TRUE, text = "Calculating...", color = "#000", text_color = TextColor, mask_color = "#000") p1 <- echarts4r::e_title( p1, Title, textStyle = list( color = TextColor, fontWeight = title.fontWeight, overflow = "truncate", ellipsis = '...', fontSize = title.fontSize, textShadowColor = title.textShadowColor, textShadowBlur = title.textShadowBlur, textShadowOffsetY = title.textShadowOffsetY, textShadowOffsetX = title.textShadowOffsetX)) if(Debug) print("Plot.Radar() Build Echarts 8") p1 <- echarts4r::e_legend(e = p1, type = "scroll", orient = "vertical", right = 50, top = 40, height = "240px", textStyle = list(color = TextColor, fontWeight = "bold")) return(p1) } #' @title Plot.Line #' #' @description This function automatically builds calibration plots and calibration boxplots for model evaluation using regression, quantile regression, and binary and multinomial classification #' #' @author Adrian Antico #' @family Standard Plots #' #' @param dt source data.table #' @param PreAgg logical #' @param AggMethod character #' @param YVar Y-Axis variable name. You can supply multiple YVars #' @param DualYVar Secondary Y-Axis variables. Leave NULL for no secondary axis. Only one variable is allowed and when this is set only one YVar is allowed. An error will be thrown if those conditions are not met #' @param XVar X-Axis variable name #' @param GroupVar One Grouping Variable #' @param YVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param XVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param DualYVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param FacetRows Defaults to 1 which causes no faceting to occur vertically. Otherwise, supply a numeric value for the number of output grid rows #' @param FacetCols Defaults to 1 which causes no faceting to occur horizontally. Otherwise, supply a numeric value for the number of output grid columns #' @param FacetLevels Faceting rows x columns is the max number of levels allowed in a grid. If your GroupVar has more you can supply the levels to display. #' @param Height NULL #' @param Width NULL #' @param Title "Title" #' @param ShowLabels character #' @param Title.YAxis character #' @param Title.XAxis character #' @param EchartsTheme Provide an "Echarts" theme #' @param TimeLine Logical #' @param MouseScroll logical, zoom via mouse scroll #' @param Area logical #' @param Alpha 0 to 1 for setting transparency #' @param Smooth = TRUE #' @param ShowSymbol = FALSE #' @param TextColor "Not Implemented" #' @param title.fontSize 22 #' @param title.fontWeight "bold" #' @param title.textShadowColor '#63aeff' #' @param title.textShadowBlur 3 #' @param title.textShadowOffsetY 1 #' @param title.textShadowOffsetX -1 #' @param xaxis.fontSize 14 #' @param yaxis.fontSize 14 #' @param xaxis.rotate 0 #' @param yaxis.rotate 0 #' @param ContainLabel TRUE #' @param DarkMode FALSE #' @param Debug Debugging purposes #' #' @examples #' # Create fake data #' data <- AutoPlots::FakeDataGenerator(N = 1000) #' #' # Build Line plot #' AutoPlots::Plot.Line( #' dt = data, #' PreAgg = FALSE, #' AggMethod = "mean", #' XVar = "DateTime", #' YVar = "Independent_Variable3", #' YVarTrans = "LogPlus1", #' DualYVar = "Independent_Variable6", #' DualYVarTrans = "LogPlus1", #' GroupVar = NULL, #' EchartsTheme = "macarons") #' #' @return plot #' @export Plot.Line <- function(dt = NULL, AggMethod = "mean", PreAgg = TRUE, XVar = NULL, YVar = NULL, DualYVar = NULL, GroupVar = NULL, YVarTrans = "Identity", DualYVarTrans = "Identity", XVarTrans = "Identity", FacetRows = 1, FacetCols = 1, FacetLevels = NULL, Height = NULL, Width = NULL, Title = 'Line Plot', ShowLabels = FALSE, Title.YAxis = NULL, Title.XAxis = NULL, EchartsTheme = "macarons", MouseScroll = TRUE, TimeLine = TRUE, Area = FALSE, Alpha = 0.50, Smooth = TRUE, ShowSymbol = FALSE, TextColor = "white", title.fontSize = 22, title.fontWeight = "bold", title.textShadowColor = '#63aeff', title.textShadowBlur = 3, title.textShadowOffsetY = 1, title.textShadowOffsetX = -1, xaxis.fontSize = 14, yaxis.fontSize = 14, xaxis.rotate = 0, yaxis.rotate = 0, ContainLabel = TRUE, DarkMode = FALSE, Debug = FALSE) { if(TimeLine && length(FacetLevels) == 0L) X_Scroll <- FALSE if(length(GroupVar) == 0L) TimeLine <- FALSE # Correct args if(length(GroupVar) > 0L && length(XVar) == 0L) { XVar <- GroupVar GroupVar <- NULL } if(!data.table::is.data.table(dt)) tryCatch({data.table::setDT(dt)}, error = function(x) { dt <- data.table::as.data.table(dt) }) # Convert factor to character if(length(GroupVar) > 0L && class(dt[[GroupVar]])[1L] == "factor") { dt[, eval(GroupVar) := as.character(get(GroupVar))] } # If length(YVar) > 1 and a DualYVar is supplied, dual axis take precedence # Throw an error instead of trimming YVar to only the first value if(length(YVar) > 1L && length(DualYVar) > 0) stop("When DualYVar is utilized only one DualYVar is allowed and only one YVar is allowed") if(length(GroupVar) > 0L && length(DualYVar) > 0) stop("When DualYVar is utilized a GroupVar is not allowed") # If User Supplies more than 1 YVar, then structure data to be long instead of wide if(length(YVar) > 1L) { if(length(GroupVar) > 0L) { dt1 <- data.table::melt.data.table(data = dt, id.vars = c(XVar,GroupVar), measure.vars = YVar, variable.name = "Measures", value.name = "Values") dt1[, GroupVars := paste0(Measures, GroupVar)] dt1[, Measures := NULL] dt1[, eval(GroupVar) := NULL] GroupVar <- "GroupVars" YVar <- "Values" } else { dt1 <- data.table::melt.data.table(data = dt, id.vars = XVar, measure.vars = YVar, variable.name = "Measures", value.name = "Values") GroupVar <- "Measures" YVar <- "Values" } } else { dt1 <- data.table::copy(dt) } # Subset columns Ncols <- ncol(dt1) if(Ncols > 2L && length(GroupVar) == 0L) { dt1 <- dt1[, .SD, .SDcols = c(YVar, XVar, DualYVar)] } else if(length(GroupVar) > 0L) { dt1 <- dt1[, .SD, .SDcols = c(YVar, XVar, DualYVar, GroupVar[1L])] if(length(FacetLevels) > 0) { dt1 <- dt1[get(GroupVar[1L]) %in% eval(FacetLevels)] } } # Minimize data before moving on if(!PreAgg) { # Define Aggregation function if(Debug) print("Line # Define Aggregation function") aggFunc <- SummaryFunction(AggMethod) # Aggregate data if(length(GroupVar) > 0L) { dt1 <- dt1[, lapply(.SD, noquote(aggFunc)), by = c(XVar,GroupVar[1L])] data.table::setorderv(x = dt1, cols = c(GroupVar[1L], XVar), c(1L,1L)) } else { dt1 <- dt1[, lapply(.SD, noquote(aggFunc)), by = c(XVar)] data.table::setorderv(x = dt1, cols = XVar, 1L) } } # Transformation if(YVarTrans != "Identity") { dt1 <- AutoTransformationCreate(data = dt1, ColumnNames = YVar, Methods = YVarTrans)$Data } if(length(DualYVar > 0L) && DualYVarTrans != "Identity") { dt1 <- AutoTransformationCreate(data = dt1, ColumnNames = DualYVar, Methods = DualYVarTrans)$Data } # Group Variable Case if(length(GroupVar) > 0L) { # Prepare Data if(Debug) print("Plot.Line() Build 1") gv <- GroupVar[1L] #print(dt1) #print(gv) #print(XVar) if(PreAgg) data.table::setorderv(x = dt1, cols = c(GroupVar[1L], XVar), c(1L,1L)) cxv <- class(dt1[[XVar]])[1L] if(cxv %in% "IDate") { dt1[, eval(XVar) := as.Date(get(XVar))] } else if(cxv %in% "IDateTime") { dt1[, eval(XVar) := as.POSIXct(get(XVar))] } # Build base plot depending on GroupVar availability p1 <- echarts4r::e_charts_( data = dt1 |> dplyr::group_by(get(gv)), x = XVar, darkMode = TRUE, emphasis = list(focus = "series"), timeline = TimeLine, dispose = TRUE, width = Width, height = Height) # Finalize Plot Build if(ShowLabels) { p1 <- echarts4r::e_line_(e = p1, serie = YVar, smooth = Smooth, showSymbol = ShowSymbol, label = list(show = TRUE)) } else { p1 <- echarts4r::e_line_(e = p1, serie = YVar, smooth = Smooth, showSymbol = ShowSymbol) } if(Debug) print("Plot.Line() Build Echarts 4 1") if(MouseScroll && FacetRows == 1L && FacetCols == 1L) { p1 <- echarts4r::e_datazoom(e = p1, type = "inside", x_index = c(0,1)) } else if(MouseScroll && (FacetRows > 1L || FacetCols > 1L)) { p1 <- echarts4r::e_datazoom(e = p1, type = "inside", x_index = seq(0, FacetRows * FacetCols - 1, 1)) } else { p1 <- echarts4r::e_datazoom(e = p1, x_index = c(0,1)) } if(Debug) print("Plot.Line() Build Echarts 5") p1 <- echarts4r::e_theme(e = p1, name = EchartsTheme) if(Debug) print("Plot.Line() Build Echarts 6") p1 <- echarts4r::e_aria(e = p1, enabled = TRUE) p1 <- echarts4r::e_tooltip(e = p1, trigger = "axis", backgroundColor = "aliceblue") p1 <- echarts4r::e_toolbox_feature(e = p1, feature = c("saveAsImage","dataZoom")) p1 <- echarts4r::e_show_loading(e = p1, hide_overlay = TRUE, text = "Calculating...", color = "#000", text_color = TextColor, mask_color = "#000") if(length(Title.XAxis) == 0L) { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "x", name = XVar, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = xaxis.fontSize), axisLabel = list( rotate = xaxis.rotate, grid = list(containLabel = ContainLabel))) } else { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "x", name = Title.XAxis, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = xaxis.fontSize), axisLabel = list( rotate = xaxis.rotate, grid = list(containLabel = ContainLabel))) } if(length(Title.YAxis) == 0L) { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "y", name = YVar, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = yaxis.fontSize), axisLabel = list( rotate = yaxis.rotate, grid = list(containLabel = ContainLabel))) } else { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "y", name = Title.YAxis, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = yaxis.fontSize), axisLabel = list( rotate = yaxis.rotate, grid = list(containLabel = ContainLabel))) } p1 <- echarts4r::e_brush(e = p1) if(Debug) print("Plot.Line() Build Echarts 6") p1 <- echarts4r::e_title( p1, Title, textStyle = list( color = TextColor, fontWeight = title.fontWeight, overflow = "truncate", # "none", "truncate", "break", ellipsis = '...', fontSize = title.fontSize, textShadowColor = title.textShadowColor, textShadowBlur = title.textShadowBlur, textShadowOffsetY = title.textShadowOffsetY, textShadowOffsetX = title.textShadowOffsetX)) if(Debug) print("Plot.Line() Build Echarts 8") if((FacetRows > 1L || FacetCols > 1) && length(FacetLevels) > 0L) { if(Debug) print("Plot.Line() Build Echarts 8 2") p1 <- echarts4r::e_facet(e = p1, rows = FacetRows, cols = FacetCols, legend_space = 16, legend_pos = "top") p1 <- echarts4r::e_legend(e = p1, type = "scroll", orient = "horizontal", right = 50, top = 40, height = "240px", textStyle = list(color = TextColor, fontWeight = "bold")) if(Debug) print("Plot.Line() Build Echarts 8 3") } else { p1 <- echarts4r::e_legend(e = p1, type = "scroll", orient = "vertical", right = 50, top = 40, height = "240px", textStyle = list(color = TextColor, fontWeight = "bold")) } } else { # Plot data.table::setorderv(x = dt1, cols = XVar, 1L) cxv <- class(dt1[[XVar]])[1L] if(cxv %in% "IDate") { dt1[, eval(XVar) := as.Date(get(XVar))] } else if(cxv %in% "IDateTime") { dt1[, eval(XVar) := as.POSIXct(get(XVar))] } # Build base plot depending on GroupVar availability if(Debug) print("Plot.Line no group Echarts") p1 <- echarts4r::e_charts_( data = dt1, x = XVar, dispose = TRUE, darkMode = TRUE, width = Width, height = Height) if(ShowLabels) { p1 <- echarts4r::e_line_(e = p1, serie = YVar, smooth = Smooth, showSymbol = ShowSymbol, label = list(show = TRUE)) } else { p1 <- echarts4r::e_line_(e = p1, serie = YVar, smooth = Smooth, showSymbol = ShowSymbol) } # DualYVar if(length(DualYVar) > 0L) { if(ShowLabels) { p1 <- echarts4r::e_line_(e = p1, serie = DualYVar, smooth = Smooth, showSymbol = ShowSymbol, label = list(show = TRUE), x_index = 1, y_index = 1) } else { p1 <- echarts4r::e_line_(e = p1, serie = DualYVar, smooth = Smooth, showSymbol = ShowSymbol, x_index = 1, y_index = 1) } } # Finalize Plot Build if(MouseScroll && FacetRows == 1L && FacetCols == 1L) { p1 <- echarts4r::e_datazoom(e = p1, type = "inside", x_index = c(0,1)) } else if(MouseScroll && (FacetRows > 1L || FacetCols > 1L)) { p1 <- echarts4r::e_datazoom(e = p1, type = "inside", x_index = seq(0, FacetRows * FacetCols - 1, 1)) } else { p1 <- echarts4r::e_datazoom(e = p1, x_index = c(0,1)) } p1 <- echarts4r::e_theme(e = p1, name = EchartsTheme) p1 <- echarts4r::e_aria(e = p1, enabled = TRUE) p1 <- echarts4r::e_tooltip(e = p1, trigger = "axis", backgroundColor = "aliceblue") p1 <- echarts4r::e_toolbox_feature(e = p1, feature = c("saveAsImage","dataZoom")) p1 <- echarts4r::e_show_loading(e = p1, hide_overlay = TRUE, text = "Calculating...", color = "#000", text_color = TextColor, mask_color = "#000") if(length(Title.XAxis) == 0L) { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "x", name = XVar, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = xaxis.fontSize), axisLabel = list( rotate = xaxis.rotate, grid = list(containLabel = ContainLabel))) } else { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "x", name = Title.XAxis, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = xaxis.fontSize), axisLabel = list( rotate = xaxis.rotate, grid = list(containLabel = ContainLabel))) } if(length(Title.YAxis) == 0L) { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "y", name = YVar, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = yaxis.fontSize), axisLabel = list( rotate = yaxis.rotate, grid = list(containLabel = ContainLabel))) } else { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "y", name = Title.YAxis, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = yaxis.fontSize), axisLabel = list( rotate = yaxis.rotate, grid = list(containLabel = ContainLabel))) } p1 <- echarts4r::e_brush(e = p1) p1 <- echarts4r::e_title( p1, Title, textStyle = list( color = TextColor, fontWeight = title.fontWeight, overflow = "truncate", # "none", "truncate", "break", ellipsis = '...', fontSize = title.fontSize, textShadowColor = title.textShadowColor, textShadowBlur = title.textShadowBlur, textShadowOffsetY = title.textShadowOffsetY, textShadowOffsetX = title.textShadowOffsetX)) } return(p1) } #' @title Plot.Area #' #' @description This function automatically builds calibration plots and calibration boxplots for model evaluation using regression, quantile regression, and binary and multinomial classification #' #' @author Adrian Antico #' @family Standard Plots #' #' @param dt source data.table #' @param PreAgg logical #' @param AggMethod character #' @param YVar Y-Axis variable name. You can supply multiple YVars #' @param DualYVar Secondary Y-Axis variables. Leave NULL for no secondary axis. Only one variable is allowed and when this is set only one YVar is allowed. An error will be thrown if those conditions are not met #' @param XVar X-Axis variable name #' @param GroupVar One Grouping Variable #' @param YVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param DualYVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param XVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param FacetRows Defaults to 1 which causes no faceting to occur vertically. Otherwise, supply a numeric value for the number of output grid rows #' @param FacetCols Defaults to 1 which causes no faceting to occur horizontally. Otherwise, supply a numeric value for the number of output grid columns #' @param FacetLevels Faceting rows x columns is the max number of levels allowed in a grid. If your GroupVar has more you can supply the levels to display. #' @param Height "400px" #' @param Width "200px" #' @param Title "Title" #' @param ShowLabels character #' @param Title.YAxis character #' @param Title.XAxis character #' @param EchartsTheme Provide an "Echarts" theme #' @param TimeLine Logical #' @param MouseScroll logical, zoom via mouse scroll #' @param Area logical #' @param Alpha 0 to 1 for setting transparency #' @param Smooth = TRUE #' @param ShowSymbol = FALSE #' @param TextColor "Not Implemented" #' @param title.fontSize 22 #' @param title.fontWeight "bold" #' @param title.textShadowColor '#63aeff' #' @param title.textShadowBlur 3 #' @param title.textShadowOffsetY 1 #' @param title.textShadowOffsetX -1 #' @param xaxis.fontSize 14 #' @param yaxis.fontSize 14 #' @param xaxis.rotate 0 #' @param yaxis.rotate 0 #' @param ContainLabel TRUE #' @param Debug Debugging purposes #' #' @examples #' # Create fake data #' data <- AutoPlots::FakeDataGenerator(N = 1000) #' #' # Build plot #' AutoPlots::Plot.Area( #' dt = data, #' PreAgg = FALSE, #' AggMethod = "mean", #' XVar = "DateTime", #' YVar = "Independent_Variable3", #' YVarTrans = "Identity", #' DualYVar = "Independent_Variable6", #' DualYVarTrans = "Identity", #' GroupVar = NULL, #' EchartsTheme = "macarons") #' #' @return plot #' @export Plot.Area <- function(dt = NULL, AggMethod = "mean", PreAgg = TRUE, XVar = NULL, YVar = NULL, DualYVar = NULL, GroupVar = NULL, YVarTrans = "Identity", DualYVarTrans = "Identity", XVarTrans = "Identity", FacetRows = 1, FacetCols = 1, FacetLevels = NULL, Height = NULL, Width = NULL, Title = 'Line Plot', ShowLabels = FALSE, Title.YAxis = NULL, Title.XAxis = NULL, EchartsTheme = "macarons", MouseScroll = TRUE, TimeLine = TRUE, Alpha = 0.50, Smooth = TRUE, ShowSymbol = FALSE, TextColor = "white", title.fontSize = 22, title.fontWeight = "bold", title.textShadowColor = '#63aeff', title.textShadowBlur = 3, title.textShadowOffsetY = 1, title.textShadowOffsetX = -1, xaxis.fontSize = 14, yaxis.fontSize = 14, xaxis.rotate = 0, yaxis.rotate = 0, ContainLabel = TRUE, Debug = FALSE) { if(length(GroupVar) == 0L) TimeLine <- FALSE if(TimeLine && length(FacetLevels) > 0) X_Scroll <- FALSE # Correct args if(length(GroupVar) > 0L && length(XVar) == 0L) { XVar <- GroupVar GroupVar <- NULL } if(!data.table::is.data.table(dt)) tryCatch({data.table::setDT(dt)}, error = function(x) { dt <- data.table::as.data.table(dt) }) # Convert factor to character if(length(GroupVar) > 0L && class(dt[[GroupVar]])[1L] == "factor") { dt[, eval(GroupVar) := as.character(get(GroupVar))] } # If length(YVar) > 1 and a DualYVar is supplied, dual axis take precedence # Throw an error instead of trimming YVar to only the first value if(length(YVar) > 1L && length(DualYVar) > 0) stop("When DualYVar is utilized only one DualYVar is allowed and only one YVar is allowed") if(length(GroupVar) > 0L && length(DualYVar) > 0) stop("When DualYVar is utilized a GroupVar is not allowed") # If User Supplies more than 1 YVar, then structure data to be long instead of wide if(length(YVar) > 1L) { if(length(GroupVar) > 0L) { dt1 <- data.table::melt.data.table(data = dt, id.vars = c(XVar,GroupVar), measure.vars = YVar, variable.name = "Measures", value.name = "Values") dt1[, GroupVars := paste0(Measures, GroupVar)] dt1[, Measures := NULL] dt1[, eval(GroupVar) := NULL] GroupVar <- "GroupVars" YVar <- "Values" } else { dt1 <- data.table::melt.data.table(data = dt, id.vars = XVar, measure.vars = YVar, variable.name = "Measures", value.name = "Values") GroupVar <- "Measures" YVar <- "Values" } } else { dt1 <- data.table::copy(dt) } # Subset columns Ncols <- ncol(dt1) if(Ncols > 2L && length(GroupVar) == 0L) { dt1 <- dt1[, .SD, .SDcols = c(YVar, XVar, DualYVar)] } else if(length(GroupVar) > 0L) { dt1 <- dt1[, .SD, .SDcols = c(YVar, XVar, DualYVar, GroupVar[1L])] if(length(FacetLevels) > 0) { dt1 <- dt1[get(GroupVar[1L]) %in% eval(FacetLevels)] } } # Minimize data before moving on if(!PreAgg) { # Define Aggregation function if(Debug) print("Plot.Calibration.Line # Define Aggregation function") aggFunc <- SummaryFunction(AggMethod) # Aggregate data if(length(GroupVar) > 0L) { dt1 <- dt1[, lapply(.SD, noquote(aggFunc)), by = c(XVar,GroupVar[1L])] data.table::setorderv(x = dt1, cols = c(GroupVar[1L], XVar), c(1L,1L)) } else { dt1 <- dt1[, lapply(.SD, noquote(aggFunc)), by = c(XVar)] data.table::setorderv(x = dt1, cols = XVar, 1L) } } # Transformation if(YVarTrans != "Identity") { dt1 <- AutoTransformationCreate(data = dt1, ColumnNames = YVar, Methods = YVarTrans)$Data } if(length(DualYVar > 0L) && DualYVarTrans != "Identity") { dt1 <- AutoTransformationCreate(data = dt1, ColumnNames = DualYVar, Methods = DualYVarTrans)$Data } # Group Variable Case if(length(GroupVar) > 0L) { # Prepare Data if(Debug) print("Plot.Line() Build 1") gv <- GroupVar[1L] if(PreAgg) data.table::setorderv(x = dt1, cols = c(GroupVar[1L], XVar), c(1L,1L)) cxv <- class(dt1[[XVar]])[1L] if(cxv %in% "IDate") { dt1[, eval(XVar) := as.Date(get(XVar))] } else if(cxv %in% "IDateTime") { dt1[, eval(XVar) := as.POSIXct(get(XVar))] } # Plot if(Debug) print("Plot.Line() Build Echarts 1") # Build base plot depending on GroupVar availability if(Debug) print(paste0("Plot.Line TimeLine = ", TimeLine)) p1 <- echarts4r::e_charts_( data = dt1 |> dplyr::group_by(get(gv)), x = XVar, darkMode = TRUE, emphasis = list(focus = "series"), timeline = TimeLine, dispose = TRUE, width = Width, height = Height) # Finalize Plot Build if(Debug) print("Plot.Line() Build Echarts 4") if(ShowLabels) { p1 <- echarts4r::e_area_(e = p1, serie = YVar, smooth = Smooth, showSymbol = ShowSymbol, label = list(show = TRUE)) } else { p1 <- echarts4r::e_area_(e = p1, serie = YVar, smooth = Smooth, showSymbol = ShowSymbol) } if(MouseScroll && FacetRows == 1L && FacetCols == 1L) { p1 <- echarts4r::e_datazoom(e = p1, type = "inside", x_index = c(0,1)) } else if(MouseScroll && (FacetRows > 1L || FacetCols > 1L)) { p1 <- echarts4r::e_datazoom(e = p1, type = "inside", x_index = seq(0, FacetRows * FacetCols - 1, 1)) } else { p1 <- echarts4r::e_datazoom(e = p1, x_index = c(0,1)) } p1 <- echarts4r::e_theme(e = p1, name = EchartsTheme) p1 <- echarts4r::e_aria(e = p1, enabled = TRUE) p1 <- echarts4r::e_tooltip(e = p1, trigger = "axis", backgroundColor = "aliceblue") p1 <- echarts4r::e_toolbox_feature(e = p1, feature = c("saveAsImage","dataZoom")) p1 <- echarts4r::e_show_loading(e = p1, hide_overlay = TRUE, text = "Calculating...", color = "#000", text_color = TextColor, mask_color = "#000") if(length(Title.XAxis) == 0L) { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "x", name = XVar, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = xaxis.fontSize), axisLabel = list( rotate = xaxis.rotate, grid = list(containLabel = ContainLabel))) } else { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "x", name = Title.XAxis, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = xaxis.fontSize), axisLabel = list( rotate = xaxis.rotate, grid = list(containLabel = ContainLabel))) } if(length(Title.YAxis) == 0L) { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "y", name = YVar, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = yaxis.fontSize), axisLabel = list( rotate = yaxis.rotate, grid = list(containLabel = ContainLabel))) } else { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "y", name = Title.YAxis, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = yaxis.fontSize), axisLabel = list( rotate = yaxis.rotate, grid = list(containLabel = ContainLabel))) } p1 <- echarts4r::e_brush(e = p1) p1 <- echarts4r::e_title( p1, Title, textStyle = list( color = TextColor, fontWeight = title.fontWeight, overflow = "truncate", # "none", "truncate", "break", ellipsis = '...', fontSize = title.fontSize, textShadowColor = title.textShadowColor, textShadowBlur = title.textShadowBlur, textShadowOffsetY = title.textShadowOffsetY, textShadowOffsetX = title.textShadowOffsetX)) if((FacetRows > 1L || FacetCols > 1) && length(FacetLevels) > 0L) { p1 <- echarts4r::e_facet(e = p1, rows = FacetRows, cols = FacetCols, legend_space = 16, legend_pos = "top") p1 <- echarts4r::e_legend(e = p1, type = "scroll", orient = "horizontal", right = 50, top = 40, height = "240px", textStyle = list(color = TextColor, fontWeight = "bold")) } else { p1 <- echarts4r::e_legend(e = p1, type = "scroll", orient = "vertical", right = 50, top = 40, height = "240px", textStyle = list(color = TextColor, fontWeight = "bold")) } } else { # Plot data.table::setorderv(x = dt1, cols = XVar, 1L) cxv <- class(dt1[[XVar]])[1L] if(cxv %in% "IDate") { dt1[, eval(XVar) := as.Date(get(XVar))] } else if(cxv %in% "IDateTime") { dt1[, eval(XVar) := as.POSIXct(get(XVar))] } # Build base plot depending on GroupVar availability if(Debug) print("Plot.Line no group Echarts") p1 <- echarts4r::e_charts_( data = dt1, x = XVar, darkMode = TRUE, dispose = TRUE, width = Width, height = Height) if(ShowLabels) { p1 <- echarts4r::e_area_(e = p1, serie = YVar, smooth = Smooth, showSymbol = ShowSymbol, label = list(show = TRUE)) } else { p1 <- echarts4r::e_area_(e = p1, serie = YVar, smooth = Smooth, showSymbol = ShowSymbol) } if(length(DualYVar) > 0L) { if(ShowLabels) { p1 <- echarts4r::e_area_(e = p1, serie = DualYVar, smooth = Smooth, showSymbol = ShowSymbol, label = list(show = TRUE), x_index = 1, y_index = 1) } else { p1 <- echarts4r::e_area_(e = p1, serie = DualYVar, smooth = Smooth, showSymbol = ShowSymbol, x_index = 1, y_index = 1) } } # Finalize Plot Build if(MouseScroll && FacetRows == 1L && FacetCols == 1L) { p1 <- echarts4r::e_datazoom(e = p1, type = "inside", x_index = c(0,1)) } else if(MouseScroll && (FacetRows > 1L || FacetCols > 1L)) { p1 <- echarts4r::e_datazoom(e = p1, type = "inside", x_index = seq(0, FacetRows * FacetCols - 1, 1)) } else { p1 <- echarts4r::e_datazoom(e = p1, x_index = c(0,1)) } p1 <- echarts4r::e_theme(e = p1, name = EchartsTheme) p1 <- echarts4r::e_aria(e = p1, enabled = TRUE) p1 <- echarts4r::e_tooltip(e = p1, trigger = "axis", backgroundColor = "aliceblue") p1 <- echarts4r::e_toolbox_feature(e = p1, feature = c("saveAsImage","dataZoom")) p1 <- echarts4r::e_show_loading(e = p1, hide_overlay = TRUE, text = "Calculating...", color = "#000", text_color = TextColor, mask_color = "#000") if(length(Title.XAxis) == 0L) { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "x", name = XVar, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = xaxis.fontSize), axisLabel = list( rotate = xaxis.rotate, grid = list(containLabel = ContainLabel))) } else { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "x", name = Title.XAxis, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = xaxis.fontSize), axisLabel = list( rotate = xaxis.rotate, grid = list(containLabel = ContainLabel))) } if(length(Title.YAxis) == 0L) { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "y", name = YVar, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = yaxis.fontSize), axisLabel = list( rotate = yaxis.rotate, grid = list(containLabel = ContainLabel))) } else { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "y", name = Title.YAxis, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = yaxis.fontSize), axisLabel = list( rotate = yaxis.rotate, grid = list(containLabel = ContainLabel))) } p1 <- echarts4r::e_brush(e = p1) p1 <- echarts4r::e_title( p1, Title, textStyle = list( color = TextColor, fontWeight = title.fontWeight, overflow = "truncate", # "none", "truncate", "break", ellipsis = '...', fontSize = title.fontSize, textShadowColor = title.textShadowColor, textShadowBlur = title.textShadowBlur, textShadowOffsetY = title.textShadowOffsetY, textShadowOffsetX = title.textShadowOffsetX)) } return(p1) } #' @title Plot.Step #' #' @description This function automatically builds calibration plots and calibration boxplots for model evaluation using regression, quantile regression, and binary and multinomial classification #' #' @author Adrian Antico #' @family Standard Plots #' #' @param dt source data.table #' @param PreAgg logical #' @param AggMethod character #' @param YVar Y-Axis variable name. You can supply multiple YVars #' @param DualYVar Secondary Y-Axis variables. Leave NULL for no secondary axis. Only one variable is allowed and when this is set only one YVar is allowed. An error will be thrown if those conditions are not met #' @param XVar X-Axis variable name #' @param GroupVar One Grouping Variable #' @param YVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param DualYVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param XVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param FacetRows Defaults to 1 which causes no faceting to occur vertically. Otherwise, supply a numeric value for the number of output grid rows #' @param FacetCols Defaults to 1 which causes no faceting to occur horizontally. Otherwise, supply a numeric value for the number of output grid columns #' @param FacetLevels Faceting rows x columns is the max number of levels allowed in a grid. If your GroupVar has more you can supply the levels to display. #' @param Height "400px" #' @param Width "200px" #' @param Title "Title" #' @param ShowLabels character #' @param Title.YAxis character #' @param Title.XAxis character #' @param EchartsTheme Provide an "Echarts" theme #' @param TimeLine Logical #' @param MouseScroll logical, zoom via mouse scroll #' @param ShowSymbol = FALSE #' @param TextColor "Not Implemented" #' @param title.fontSize 22 #' @param title.fontWeight "bold" #' @param title.textShadowColor '#63aeff' #' @param title.textShadowBlur 3 #' @param title.textShadowOffsetY 1 #' @param title.textShadowOffsetX -1 #' @param xaxis.fontSize 14 #' @param yaxis.fontSize 14 #' @param xaxis.rotate 0 #' @param yaxis.rotate 0 #' @param ContainLabel TRUE #' @param Debug Debugging purposes #' #' @examples #' # Create fake data #' data <- AutoPlots::FakeDataGenerator(N = 1000) #' #' # Build plot #' AutoPlots::Plot.Step( #' dt = data, #' PreAgg = FALSE, #' AggMethod = "mean", #' XVar = "DateTime", #' YVar = "Independent_Variable3", #' YVarTrans = "Identity", #' DualYVar = "Independent_Variable6", #' DualYVarTrans = "Identity", #' GroupVar = NULL, #' EchartsTheme = "macarons") #' #' @return plot #' @export Plot.Step <- function(dt = NULL, AggMethod = "mean", PreAgg = TRUE, XVar = NULL, YVar = NULL, DualYVar = NULL, GroupVar = NULL, YVarTrans = "Identity", DualYVarTrans = "Identity", XVarTrans = "Identity", FacetRows = 1, FacetCols = 1, FacetLevels = NULL, Height = NULL, Width = NULL, Title = 'Line Plot', ShowLabels = FALSE, Title.YAxis = NULL, Title.XAxis = NULL, EchartsTheme = "macarons", MouseScroll = TRUE, TimeLine = TRUE, ShowSymbol = FALSE, TextColor = "white", title.fontSize = 22, title.fontWeight = "bold", title.textShadowColor = '#63aeff', title.textShadowBlur = 3, title.textShadowOffsetY = 1, title.textShadowOffsetX = -1, xaxis.fontSize = 14, yaxis.fontSize = 14, xaxis.rotate = 0, yaxis.rotate = 0, ContainLabel = TRUE, Debug = FALSE) { if(length(GroupVar) == 0L) TimeLine <- FALSE if(TimeLine && length(FacetLevels) > 0) X_Scroll <- FALSE # Correct args if(length(GroupVar) > 0L && length(XVar) == 0L) { XVar <- GroupVar GroupVar <- NULL } if(!data.table::is.data.table(dt)) tryCatch({data.table::setDT(dt)}, error = function(x) { dt <- data.table::as.data.table(dt) }) # Convert factor to character if(length(GroupVar) > 0L && class(dt[[GroupVar]])[1L] == "factor") { dt[, eval(GroupVar) := as.character(get(GroupVar))] } # If length(YVar) > 1 and a DualYVar is supplied, dual axis take precedence # Throw an error instead of trimming YVar to only the first value if(length(YVar) > 1L && length(DualYVar) > 0) stop("When DualYVar is utilized only one DualYVar is allowed and only one YVar is allowed") if(length(GroupVar) > 0L && length(DualYVar) > 0) stop("When DualYVar is utilized a GroupVar is not allowed") # If User Supplies more than 1 YVar, then structure data to be long instead of wide if(length(YVar) > 1L) { if(length(GroupVar) > 0L) { dt1 <- data.table::melt.data.table(data = dt, id.vars = c(XVar,GroupVar), measure.vars = YVar, variable.name = "Measures", value.name = "Values") dt1[, GroupVars := paste0(Measures, GroupVar)] dt1[, Measures := NULL] dt1[, eval(GroupVar) := NULL] GroupVar <- "GroupVars" YVar <- "Values" } else { dt1 <- data.table::melt.data.table(data = dt, id.vars = XVar, measure.vars = YVar, variable.name = "Measures", value.name = "Values") GroupVar <- "Measures" YVar <- "Values" } } else { dt1 <- data.table::copy(dt) } # Subset columns Ncols <- ncol(dt1) if(Ncols > 2L && length(GroupVar) == 0L) { dt1 <- dt1[, .SD, .SDcols = c(YVar, XVar, DualYVar)] } else if(length(GroupVar) > 0L) { dt1 <- dt1[, .SD, .SDcols = c(YVar, XVar, DualYVar, GroupVar[1L])] if(length(FacetLevels) > 0) { dt1 <- dt1[get(GroupVar[1L]) %in% eval(FacetLevels)] } } # Minimize data before moving on if(!PreAgg) { # Define Aggregation function if(Debug) print("Plot.Calibration.Line # Define Aggregation function") aggFunc <- SummaryFunction(AggMethod) # Aggregate data if(length(GroupVar) > 0L) { dt1 <- dt1[, lapply(.SD, noquote(aggFunc)), by = c(XVar,GroupVar[1L])] data.table::setorderv(x = dt1, cols = c(GroupVar[1L], XVar), c(1L,1L)) } else { dt1 <- dt1[, lapply(.SD, noquote(aggFunc)), by = c(XVar)] data.table::setorderv(x = dt1, cols = XVar, 1L) } } # Transformation if(YVarTrans != "Identity") { dt1 <- AutoTransformationCreate(data = dt1, ColumnNames = YVar, Methods = YVarTrans)$Data } if(length(DualYVar > 0L) && DualYVarTrans != "Identity") { dt1 <- AutoTransformationCreate(data = dt1, ColumnNames = DualYVar, Methods = DualYVarTrans)$Data } # Group Variable Case if(length(GroupVar) > 0L) { # Prepare Data if(Debug) print("Plot.Line() Build 1") gv <- GroupVar[1L] if(PreAgg) data.table::setorderv(x = dt1, cols = c(GroupVar[1L], XVar), c(1L,1L)) cxv <- class(dt1[[XVar]])[1L] if(cxv %in% "IDate") { dt1[, eval(XVar) := as.Date(get(XVar))] } else if(cxv %in% "IDateTime") { dt1[, eval(XVar) := as.POSIXct(get(XVar))] } # Plot if(Debug) print("Plot.Line() Build Echarts 1") # Build base plot depending on GroupVar availability if(Debug) print(paste0("Plot.Line TimeLine = ", TimeLine)) p1 <- echarts4r::e_charts_( data = dt1 |> dplyr::group_by(get(gv)), x = XVar, timeline = TimeLine, darkMode = TRUE, emphasis = list(focus = "series"), dispose = TRUE, width = Width, height = Height) # Finalize Plot Build if(Debug) print("Plot.Line() Build Echarts 4") if(ShowLabels) { p1 <- echarts4r::e_step_(e = p1, serie = YVar, showSymbol = ShowSymbol, label = list(show = TRUE)) } else { p1 <- echarts4r::e_step_(e = p1, serie = YVar, showSymbol = ShowSymbol) } if(MouseScroll && FacetRows == 1L && FacetCols == 1L) { p1 <- echarts4r::e_datazoom(e = p1, type = "inside", x_index = c(0,1)) } else if(MouseScroll && (FacetRows > 1L || FacetCols > 1L)) { p1 <- echarts4r::e_datazoom(e = p1, type = "inside", x_index = seq(0, FacetRows * FacetCols - 1, 1)) } else { p1 <- echarts4r::e_datazoom(e = p1, x_index = c(0,1)) } p1 <- echarts4r::e_theme(e = p1, name = EchartsTheme) p1 <- echarts4r::e_aria(e = p1, enabled = TRUE) p1 <- echarts4r::e_tooltip(e = p1, trigger = "axis", backgroundColor = "aliceblue") p1 <- echarts4r::e_toolbox_feature(e = p1, feature = c("saveAsImage","dataZoom")) p1 <- echarts4r::e_show_loading(e = p1, hide_overlay = TRUE, text = "Calculating...", color = "#000", text_color = TextColor, mask_color = "#000") if(length(Title.XAxis) == 0L) { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "x", name = XVar, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = xaxis.fontSize), axisLabel = list( rotate = xaxis.rotate, grid = list(containLabel = ContainLabel))) } else { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "x", name = Title.XAxis, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = xaxis.fontSize), axisLabel = list( rotate = xaxis.rotate, grid = list(containLabel = ContainLabel))) } if(length(Title.YAxis) == 0L) { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "y", name = YVar, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = yaxis.fontSize), axisLabel = list( rotate = yaxis.rotate, grid = list(containLabel = ContainLabel))) } else { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "y", name = Title.YAxis, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = yaxis.fontSize), axisLabel = list( rotate = yaxis.rotate, grid = list(containLabel = ContainLabel))) } p1 <- echarts4r::e_brush(e = p1) p1 <- echarts4r::e_title( p1, Title, textStyle = list( color = TextColor, fontWeight = title.fontWeight, overflow = "truncate", # "none", "truncate", "break", ellipsis = '...', fontSize = title.fontSize, textShadowColor = title.textShadowColor, textShadowBlur = title.textShadowBlur, textShadowOffsetY = title.textShadowOffsetY, textShadowOffsetX = title.textShadowOffsetX)) if((FacetRows > 1L || FacetCols > 1) && length(FacetLevels) > 0L) { p1 <- echarts4r::e_facet(e = p1, rows = FacetRows, cols = FacetCols, legend_space = 16, legend_pos = "top") p1 <- echarts4r::e_legend(e = p1, type = "scroll", orient = "horizontal", right = 50, top = 40, height = "240px", textStyle = list(color = TextColor, fontWeight = "bold")) } else { p1 <- echarts4r::e_legend(e = p1, type = "scroll", orient = "vertical", right = 50, top = 40, height = "240px", textStyle = list(color = TextColor, fontWeight = "bold")) } } else { # Plot data.table::setorderv(x = dt1, cols = XVar, 1L) cxv <- class(dt1[[XVar]])[1L] if(cxv %in% "IDate") { dt1[, eval(XVar) := as.Date(get(XVar))] } else if(cxv %in% "IDateTime") { dt1[, eval(XVar) := as.POSIXct(get(XVar))] } # Build base plot depending on GroupVar availability if(Debug) print("Plot.Line no group Echarts") p1 <- echarts4r::e_charts_( data = dt1, x = XVar, dispose = TRUE, darkMode = TRUE, width = Width, height = Height) if(ShowLabels) { p1 <- echarts4r::e_step_(e = p1, serie = YVar, showSymbol = ShowSymbol, label = list(show = TRUE)) } else { p1 <- echarts4r::e_step_(e = p1, serie = YVar, showSymbol = ShowSymbol) } if(length(DualYVar) > 0L) { if(ShowLabels) { p1 <- echarts4r::e_step_(e = p1, serie = DualYVar, showSymbol = ShowSymbol, label = list(show = TRUE), x_index = 1, y_index = 1) } else { p1 <- echarts4r::e_step_(e = p1, serie = DualYVar, showSymbol = ShowSymbol, x_index = 1, y_index = 1) } } # Finalize Plot Build if(MouseScroll && FacetRows == 1L && FacetCols == 1L) { p1 <- echarts4r::e_datazoom(e = p1, type = "inside", x_index = c(0,1)) } else if(MouseScroll && (FacetRows > 1L || FacetCols > 1L)) { p1 <- echarts4r::e_datazoom(e = p1, type = "inside", x_index = seq(0, FacetRows * FacetCols - 1, 1)) } else { p1 <- echarts4r::e_datazoom(e = p1, x_index = c(0,1)) } p1 <- echarts4r::e_theme(e = p1, name = EchartsTheme) p1 <- echarts4r::e_aria(e = p1, enabled = TRUE) p1 <- echarts4r::e_tooltip(e = p1, trigger = "axis", backgroundColor = "aliceblue") p1 <- echarts4r::e_toolbox_feature(e = p1, feature = c("saveAsImage","dataZoom")) p1 <- echarts4r::e_show_loading(e = p1, hide_overlay = TRUE, text = "Calculating...", color = "#000", text_color = TextColor, mask_color = "#000") if(length(Title.XAxis) == 0L) { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "x", name = XVar, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = xaxis.fontSize), axisLabel = list( rotate = xaxis.rotate, grid = list(containLabel = ContainLabel))) } else { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "x", name = Title.XAxis, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = xaxis.fontSize), axisLabel = list( rotate = xaxis.rotate, grid = list(containLabel = ContainLabel))) } if(length(Title.YAxis) == 0L) { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "y", name = YVar, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = yaxis.fontSize), axisLabel = list( rotate = yaxis.rotate, grid = list(containLabel = ContainLabel))) } else { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "y", name = Title.YAxis, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = yaxis.fontSize), axisLabel = list( rotate = yaxis.rotate, grid = list(containLabel = ContainLabel))) } p1 <- echarts4r::e_brush(e = p1) p1 <- echarts4r::e_title( p1, Title, textStyle = list( color = TextColor, fontWeight = title.fontWeight, overflow = "truncate", # "none", "truncate", "break", ellipsis = '...', fontSize = title.fontSize, textShadowColor = title.textShadowColor, textShadowBlur = title.textShadowBlur, textShadowOffsetY = title.textShadowOffsetY, textShadowOffsetX = title.textShadowOffsetX)) } return(p1) } #' @title Plot.River #' #' @description This function automatically builds calibration plots and calibration boxplots for model evaluation using regression, quantile regression, and binary and multinomial classification #' #' @author Adrian Antico #' @family Standard Plots #' #' @param dt source data.table #' @param PreAgg logical #' @param AggMethod character #' @param YVar Y-Axis variable name. You can supply multiple YVars #' @param XVar X-Axis variable name #' @param GroupVar One Grouping Variable #' @param YVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param XVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param FacetRows Defaults to 1 which causes no faceting to occur vertically. Otherwise, supply a numeric value for the number of output grid rows #' @param FacetCols Defaults to 1 which causes no faceting to occur horizontally. Otherwise, supply a numeric value for the number of output grid columns #' @param FacetLevels Faceting rows x columns is the max number of levels allowed in a grid. If your GroupVar has more you can supply the levels to display. #' @param Height "400px" #' @param Width "200px" #' @param Title "Title" #' @param ShowLabels character #' @param Title.YAxis character #' @param Title.XAxis character #' @param EchartsTheme Provide an "Echarts" theme #' @param TimeLine Logical #' @param MouseScroll logical, zoom via mouse scroll #' @param ShowSymbol = FALSE #' @param TextColor "Not Implemented" #' @param title.fontSize 22 #' @param title.fontWeight "bold" #' @param title.textShadowColor '#63aeff' #' @param title.textShadowBlur 3 #' @param title.textShadowOffsetY 1 #' @param title.textShadowOffsetX -1 #' @param xaxis.fontSize 14 #' @param yaxis.fontSize 14 #' @param Debug Debugging purposes #' #' @examples #' # Create fake data #' data <- AutoPlots::FakeDataGenerator(N = 1000) #' #' # Build plot #' AutoPlots::Plot.River( #' dt = data, #' PreAgg = FALSE, #' AggMethod = "mean", #' XVar = "DateTime", #' YVar = c( #' "Independent_Variable1", #' "Independent_Variable2", #' "Independent_Variable3", #' "Independent_Variable4", #' "Independent_Variable5"), #' YVarTrans = "Identity", #' TextColor = "black", #' EchartsTheme = "macarons") #' #' @return plot #' @export Plot.River <- function(dt = NULL, AggMethod = "mean", PreAgg = TRUE, XVar = NULL, YVar = NULL, GroupVar = NULL, YVarTrans = "Identity", XVarTrans = "Identity", FacetRows = 1, FacetCols = 1, FacetLevels = NULL, Height = NULL, Width = NULL, Title = 'River Plot', ShowLabels = FALSE, Title.YAxis = NULL, Title.XAxis = NULL, EchartsTheme = "macarons", MouseScroll = TRUE, TimeLine = TRUE, ShowSymbol = FALSE, TextColor = "white", title.fontSize = 22, title.fontWeight = "bold", title.textShadowColor = '#63aeff', title.textShadowBlur = 3, title.textShadowOffsetY = 1, title.textShadowOffsetX = -1, xaxis.fontSize = 14, yaxis.fontSize = 14, Debug = FALSE) { if(length(GroupVar) == 0L) TimeLine <- FALSE if(length(GroupVar) == 0L && length(YVar) <= 1L) { if(Debug) print("if(length(GroupVar) == 0L && length(YVar) <= 1L) return(NULL)") return(NULL) } if(!data.table::is.data.table(dt)) tryCatch({data.table::setDT(dt)}, error = function(x) { dt <- data.table::as.data.table(dt) }) Ncols <- ncol(dt) if(length(FacetLevels) > 0L) { dt1 <- data.table::copy(dt[get(GroupVar) %in% c(eval(FacetLevels)), .SD, .SDcols = c(YVar, XVar, GroupVar)]) } else { dt1 <- data.table::copy(dt[, .SD, .SDcols = c(YVar, XVar, GroupVar)]) } if(Debug) print("Plot.River 3") # Minimize data before moving on if(!PreAgg) { if(Debug) print("Plot.River 4") # DCast -> redefine YVar -> Proceed as normal if(length(YVar) == 1L && length(GroupVar) > 0L) { dt1 <- data.table::dcast.data.table( data = dt1, formula = get(XVar) ~ get(GroupVar[1L]), fun.aggregate = sum, value.var = eval(YVar)) data.table::setnames(x = dt1, "XVar", c(XVar)) YVar <- names(dt1)[-1L] GroupVar <- NULL } # Define Aggregation function if(Debug) print("Plot.Calibration.Line # Define Aggregation function") aggFunc <- SummaryFunction(AggMethod) # Aggregate data if(length(GroupVar) > 0L) { dt1 <- dt1[, lapply(.SD, noquote(aggFunc)), by = c(XVar,GroupVar[1L])] data.table::setorderv(x = dt1, cols = c(GroupVar[1L], XVar), rep(1L, length(c(GroupVar[1L], XVar)))) } else { dt1 <- dt1[, lapply(.SD, noquote(aggFunc)), by = c(XVar)] data.table::setorderv(x = dt1, cols = XVar, 1L) } } # Transformation for(yvart in YVarTrans) { if(YVarTrans != "Identity") { dt1 <- AutoTransformationCreate(data = dt1, ColumnNames = yvart, Methods = YVarTrans)$Data } } if(Debug) print("Plot.River 6b") # Plot data.table::setorderv(x = dt1, cols = XVar, 1L) cxv <- class(dt1[[XVar]])[1L] if(cxv %in% "IDate") { dt1[, eval(XVar) := as.Date(get(XVar))] } else if(cxv %in% "IDateTime") { dt1[, eval(XVar) := as.POSIXct(get(XVar))] } if(Debug) print("Plot.River 7b") # Build base plot depending on GroupVar availability if(Debug) print("Plot.Line no group Echarts") p1 <- echarts4r::e_charts_( data = dt1, x = XVar, dispose = TRUE, darkMode = TRUE, width = Width, height = Height) for(i in YVar) p1 <- echarts4r::e_river_(e = p1, serie = i) if(Debug) print("Plot.River 8b") # Finalize Plot Build if(MouseScroll && FacetRows == 1L && FacetCols == 1L) { p1 <- echarts4r::e_datazoom(e = p1, type = "inside", x_index = c(0,1)) } else if(MouseScroll && (FacetRows > 1L || FacetCols > 1L)) { p1 <- echarts4r::e_datazoom(e = p1, type = "inside", x_index = seq(0, FacetRows * FacetCols - 1, 1)) } else { p1 <- echarts4r::e_datazoom(e = p1, x_index = c(0,1)) } p1 <- echarts4r::e_theme(e = p1, name = EchartsTheme) p1 <- echarts4r::e_aria(e = p1, enabled = TRUE) p1 <- echarts4r::e_tooltip(e = p1, trigger = "axis", backgroundColor = "aliceblue") p1 <- echarts4r::e_toolbox_feature(e = p1, feature = c("saveAsImage","dataZoom")) p1 <- echarts4r::e_show_loading(e = p1, hide_overlay = TRUE, text = "Calculating...", color = "#000", text_color = TextColor, mask_color = "#000") p1 <- echarts4r::e_legend(e = p1, type = "scroll", orient = "vertical", right = 50, top = 40, height = "240px", textStyle = list(color = TextColor, fontWeight = "bold")) p1 <- echarts4r::e_brush(e = p1) p1 <- echarts4r::e_title( p1, Title, textStyle = list( color = TextColor, fontWeight = title.fontWeight, overflow = "truncate", # "none", "truncate", "break", ellipsis = '...', fontSize = title.fontSize, textShadowColor = title.textShadowColor, textShadowBlur = title.textShadowBlur, textShadowOffsetY = title.textShadowOffsetY, textShadowOffsetX = title.textShadowOffsetX)) return(p1) } #' @title Plot.Bar #' #' @description Build a bar plot by simply passing arguments to a single function #' #' @family Standard Plots #' #' @author Adrian Antico #' #' @param dt source data.table #' @param PreAgg logical #' @param YVar Y-Axis variable name #' @param XVar X-Axis variable name #' @param GroupVar Column name of Group Variable for distinct colored histograms by group levels #' @param LabelValues A vector of values. Requires PreAgg to be set to TRUE and you'll need to ensure LabelValues are ordered the same as dt. If NULL and ShowLabels is TRUE, then bar values will be displayed #' @param YVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param XVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param FacetRows Defaults to 1 which causes no faceting to occur vertically. Otherwise, supply a numeric value for the number of output grid rows #' @param FacetCols Defaults to 1 which causes no faceting to occur horizontally. Otherwise, supply a numeric value for the number of output grid columns #' @param FacetLevels Faceting rows x columns is the max number of levels allowed in a grid. If your GroupVar has more you can supply the levels to display. #' @param AggMethod Choose from 'mean', 'sum', 'sd', and 'median' #' @param Height "400px" #' @param Width "200px" #' @param Title title #' @param Title.YAxis NULL. If NULL, YVar name will be used #' @param Title.XAxis NULL. If NULL, XVar name will be used #' @param ShowLabels logical #' @param EchartsTheme "auritus","azul","bee-inspired","blue","caravan","carp","chalk","cool","dark-bold","dark","eduardo", #' "essos","forest","fresh-cut","fruit","gray","green","halloween","helianthus","infographic","inspired", #' "jazz","london","dark","macarons","macarons2","mint","purple-passion","red-velvet","red","roma","royal", #' "sakura","shine","tech-blue","vintage","walden","wef","weforum","westeros","wonderland" #' @param TimeLine logical #' @param MouseScroll logical, zoom via mouse scroll #' @param TextColor 'darkblue' #' @param title.fontSize 22 #' @param title.fontWeight "bold" #' @param title.textShadowColor '#63aeff' #' @param title.textShadowBlur 3 #' @param title.textShadowOffsetY 1 #' @param title.textShadowOffsetX -1 #' @param xaxis.fontSize 14 #' @param yaxis.fontSize 14 #' @param xaxis.rotate 0 #' @param yaxis.rotate 0 #' @param ContainLabel TRUE #' @param Debug Debugging purposes #' #' @examples #' # Create fake data #' data <- AutoPlots::FakeDataGenerator(N = 100000) #' #' # Echarts Bar Chart #' AutoPlots::Plot.Bar( #' dt = data, #' PreAgg = FALSE, #' XVar = "Factor_1", #' YVar = "Adrian", #' GroupVar = NULL, #' LabelValues = NULL, #' YVarTrans = "Identity", #' XVarTrans = "Identity", #' FacetRows = 1, #' FacetCols = 1, #' FacetLevels = NULL, #' AggMethod = 'mean', #' Height = NULL, #' Width = NULL, #' Title = 'Bar Plot', #' ShowLabels = FALSE, #' Title.YAxis = "Adrian", #' Title.XAxis = NULL, #' EchartsTheme = "macarons", #' MouseScroll = TRUE, #' TimeLine = TRUE, #' TextColor = "black", #' title.fontSize = 22, #' title.fontWeight = "bold", #' title.textShadowColor = '#63aeff', #' title.textShadowBlur = 3, #' title.textShadowOffsetY = 1, #' title.textShadowOffsetX = -1, #' xaxis.fontSize = 14, #' yaxis.fontSize = 14, #' xaxis.rotate = 0, #' yaxis.rotate = 0, #' ContainLabel = TRUE, #' Debug = FALSE) #' #' @return plot #' @export Plot.Bar <- function(dt = NULL, PreAgg = FALSE, XVar = NULL, YVar = NULL, GroupVar = NULL, LabelValues = NULL, YVarTrans = "Identity", XVarTrans = "Identity", FacetRows = 1, FacetCols = 1, FacetLevels = NULL, AggMethod = 'mean', Height = NULL, Width = NULL, Title = 'Bar Plot', ShowLabels = FALSE, Title.YAxis = NULL, Title.XAxis = NULL, EchartsTheme = "macarons", MouseScroll = TRUE, TimeLine = TRUE, TextColor = "white", title.fontSize = 22, title.fontWeight = "bold", title.textShadowColor = '#63aeff', title.textShadowBlur = 3, title.textShadowOffsetY = 1, title.textShadowOffsetX = -1, xaxis.fontSize = 14, yaxis.fontSize = 14, xaxis.rotate = 0, yaxis.rotate = 0, ContainLabel = TRUE, Debug = FALSE) { if(!data.table::is.data.table(dt)) tryCatch({data.table::setDT(dt)}, error = function(x) { dt <- data.table::as.data.table(dt) }) if(length(GroupVar) == 0L) TimeLine <- FALSE # Convert factor to character if(length(GroupVar) > 0L && class(dt[[GroupVar]])[1L] == "factor") { dt[, eval(GroupVar) := as.character(get(GroupVar))] } if(length(XVar) > 0L && class(dt[[XVar]])[1L] == "factor") { dt[, eval(XVar) := as.character(get(XVar))] } if(length(YVar) > 0L && class(dt[[YVar]])[1L] == "factor") { dt[, eval(YVar) := as.character(get(YVar))] } # Used multiple times check1 <- length(XVar) != 0 && length(YVar) != 0 check2 <- length(XVar) == 0 && length(YVar) != 0 check3 <- length(XVar) != 0 && length(YVar) == 0 # Define Aggregation function if(!PreAgg) { aggFunc <- SummaryFunction(AggMethod) } # Create base plot object numvars <- c() byvars <- c() if(check1) { if(length(GroupVar) != 0L) { if(!PreAgg) { if(length(FacetLevels) > 0L) { dt <- dt[get(GroupVar) %in% c(eval(FacetLevels)), .SD, .SDcols = c(YVar,XVar,GroupVar)] } if(any(tryCatch({class(dt[[eval(YVar)]])}, error = function(x) "bla") %in% c('numeric','integer'))) { numvars <- unique(c(numvars, YVar)) } else { byvars <- unique(c(byvars, YVar)) } if(any(tryCatch({class(dt[[eval(XVar)]])}, error = function(x) "bla") %in% c('numeric','integer'))) { if(length(numvars) > 0) { x <- length(unique(dt[[XVar]])) y <- length(unique(dt[[YVar]])) if(x > y) { byvars <- unique(c(byvars, YVar)) numvars[1L] <- XVar } else { byvars <- unique(c(byvars, XVar)) } } else { numvars <- unique(c(numvars, XVar)) } } else { byvars <- unique(c(byvars, XVar)) } if(any(tryCatch({class(dt[[eval(GroupVar)]])}, error = function(x) "bla") %in% c('numeric','integer'))) { dt[, eval(GroupVar) := as.character(get(GroupVar))] byvars <- unique(c(byvars, GroupVar)) } else { byvars <- unique(c(byvars, GroupVar)) } if(!is.null(byvars)) { temp <- dt[, lapply(.SD, noquote(aggFunc)), .SDcols = c(numvars), by = c(byvars)] for(i in byvars) { if(class(temp[[i]]) %in% c('numeric','integer')) { temp[, eval(i) := as.character(get(i))] } } } else { temp <- dt[, lapply(.SD, noquote(aggFunc)), .SDcols = c(numvars)] } } else { temp <- data.table::copy(dt) numvars <- ColNameFilter(data = temp, Types = 'numeric')[[1L]] byvars <- unlist(ColNameFilter(data = temp, Types = "character")) } # Transformation if(length(XVar) > 0L && class(temp[[XVar]])[1L] %in% c("numeric","integer")) { YVarTrans <- XVarTrans } if(YVarTrans != "Identity") { temp <- AutoTransformationCreate(data = temp, ColumnNames = numvars, Methods = YVarTrans)$Data } # Plot p1 <- echarts4r::e_charts_( temp |> dplyr::group_by(get(GroupVar[1L])), x = XVar, darkMode = TRUE, emphasis = list(focus = "series"), dispose = TRUE, width = Width, height = Height) if(ShowLabels) { p1 <- echarts4r::e_bar_(e = p1, YVar, label = list(show = TRUE)) } else { p1 <- echarts4r::e_bar_(e = p1, YVar) } if(MouseScroll && FacetRows == 1L && FacetCols == 1L) { p1 <- echarts4r::e_datazoom(e = p1, type = "inside", x_index = c(0,1)) } else if(MouseScroll && (FacetRows > 1L || FacetCols > 1L)) { p1 <- echarts4r::e_datazoom(e = p1, type = "inside", x_index = seq(0, FacetRows * FacetCols - 1, 1)) } else { p1 <- echarts4r::e_datazoom(e = p1, x_index = c(0,1)) } p1 <- echarts4r::e_theme(e = p1, name = EchartsTheme) p1 <- echarts4r::e_aria(e = p1, enabled = TRUE) p1 <- echarts4r::e_tooltip(e = p1, trigger = "axis", backgroundColor = "aliceblue") p1 <- echarts4r::e_toolbox_feature(e = p1, feature = c("saveAsImage","dataZoom")) p1 <- echarts4r::e_show_loading(e = p1, hide_overlay = TRUE, text = "Calculating...", color = "#000", text_color = TextColor, mask_color = "#000") p1 <- echarts4r::e_brush(e = p1) p1 <- echarts4r::e_title( p1, Title, textStyle = list( color = TextColor, fontWeight = title.fontWeight, overflow = "truncate", # "none", "truncate", "break", ellipsis = '...', fontSize = title.fontSize, textShadowColor = title.textShadowColor, textShadowBlur = title.textShadowBlur, textShadowOffsetY = title.textShadowOffsetY, textShadowOffsetX = title.textShadowOffsetX)) if(FacetRows > 1L || FacetCols > 1L) p1 <- echarts4r::e_facet( e = p1, rows = FacetRows, cols = FacetCols, legend_space = 16, legend_pos = "top") if(length(Title.XAxis) == 0L) { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "x", name = XVar, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = xaxis.fontSize), axisLabel = list( rotate = xaxis.rotate, grid = list(containLabel = ContainLabel))) } else { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "x", name = Title.XAxis, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = xaxis.fontSize), axisLabel = list( rotate = xaxis.rotate, grid = list(containLabel = ContainLabel))) } if(length(Title.YAxis) == 0L) { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "y", name = YVar, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = yaxis.fontSize), axisLabel = list( rotate = yaxis.rotate, grid = list(containLabel = ContainLabel))) } else { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "y", name = Title.YAxis, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = yaxis.fontSize), axisLabel = list( rotate = yaxis.rotate, grid = list(containLabel = ContainLabel))) } return(p1) } else { if(Debug) { print("BarPlot 2.b") print(PreAgg) } if(!PreAgg) { if(tryCatch({class(dt[[eval(YVar)]])[1L]}, error = function(x) "bla") %in% c('numeric','integer')) { numvars <- unique(c(numvars, YVar)) } else { byvars <- unique(c(byvars, YVar)) } if(tryCatch({class(dt[[eval(XVar)]])[1L]}, error = function(x) "bla") %in% c('numeric','integer')) { if(length(numvars) > 0) { x <- length(unique(dt[[XVar]])) y <- length(unique(dt[[YVar]])) if(x > y) { byvars <- unique(c(byvars, YVar)) numvars[1L] <- XVar } else { byvars <- unique(c(byvars, XVar)) } } else { numvars <- unique(c(numvars, XVar)) } } else { byvars <- unique(c(byvars, XVar)) } if(!is.null(byvars)) { temp <- dt[, lapply(.SD, noquote(aggFunc)), .SDcols = c(numvars), by = c(byvars)] for(i in byvars) { if(class(temp[[i]])[1L] %in% c('numeric','integer')) { temp[, eval(i) := as.character(get(i))] } } } else { temp <- dt[, lapply(.SD, noquote(aggFunc)), .SDcols = c(numvars)] } } else { temp <- data.table::copy(dt) if(Debug) print("BarPlot 2.bb") numvars <- ColNameFilter(data = temp, Types = 'numeric')[[1L]] byvars <- unlist(ColNameFilter(data = temp, Types = "character")) } if(Debug) print("BarPlot 2.bbb") # Transformation if(length(XVar) > 0L && class(temp[[XVar]])[1L] %in% c("numeric","integer")) { YVarTrans <- XVarTrans } if(Debug) print("BarPlot 2.bbbb") if(YVarTrans != "Identity") { temp <- AutoTransformationCreate(data = temp, ColumnNames = numvars, Methods = YVarTrans)$Data } if(Debug) print("BarPlot 2.bbbbb") # yvar <- temp[[YVar]] # xvar <- temp[[XVar]] # Plot if(XVar == "Importance" && YVar == "Variable") { XVar <- "Variable" YVar <- "Importance" } if(Debug) print("BarPlot 2.bbbbbb") p1 <- echarts4r::e_charts_( temp, x = XVar, dispose = TRUE, darkMode = TRUE, width = Width, height = Height) if(Debug) print("BarPlot 2.c") if(ShowLabels) { if(length(LabelValues) > 0L && PreAgg) { p1 <- echarts4r::e_charts_( temp, x = XVar, dispose = TRUE, darkMode = TRUE, width = Width, height = Height) |> echarts4r::e_bar_( YVar, bind = LabelValues, label = list( show = TRUE, formatter = "{b}", position = "outside")) } else { p1 <- echarts4r::e_bar_(e = p1, YVar, label = list(show = TRUE)) } } else { if(Debug) print("BarPlot 2.cc") p1 <- echarts4r::e_bar_(e = p1, YVar) } if(MouseScroll && FacetRows == 1L && FacetCols == 1L) { p1 <- echarts4r::e_datazoom(e = p1, type = "inside", x_index = c(0,1)) } else if(MouseScroll && (FacetRows > 1L || FacetCols > 1L)) { p1 <- echarts4r::e_datazoom(e = p1, type = "inside", x_index = seq(0, FacetRows * FacetCols - 1, 1)) } else { p1 <- echarts4r::e_datazoom(e = p1, x_index = c(0,1)) } if(Debug) print("BarPlot 2.cccc") p1 <- echarts4r::e_theme(e = p1, name = EchartsTheme) p1 <- echarts4r::e_aria(e = p1, enabled = TRUE) p1 <- echarts4r::e_tooltip(e = p1, trigger = "axis", backgroundColor = "aliceblue") p1 <- echarts4r::e_toolbox_feature(e = p1, feature = c("saveAsImage","dataZoom")) p1 <- echarts4r::e_show_loading(e = p1, hide_overlay = TRUE, text = "Calculating...", color = "#000", text_color = TextColor, mask_color = "#000") if(Debug) print("BarPlot 2.d") if(length(Title.XAxis) == 0L) { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "x", name = XVar, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = xaxis.fontSize), axisLabel = list( rotate = xaxis.rotate, grid = list(containLabel = ContainLabel))) } else { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "x", name = Title.XAxis, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = xaxis.fontSize), axisLabel = list( rotate = xaxis.rotate, grid = list(containLabel = ContainLabel))) } if(Debug) print("BarPlot 2.e") if(length(Title.YAxis) == 0L) { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "y", name = YVar, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = yaxis.fontSize), axisLabel = list( rotate = yaxis.rotate, grid = list(containLabel = ContainLabel))) } else { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "y", name = Title.YAxis, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = yaxis.fontSize), axisLabel = list( rotate = yaxis.rotate, grid = list(containLabel = ContainLabel))) } if(Debug) print("BarPlot 2.f") p1 <- echarts4r::e_brush(e = p1) p1 <- echarts4r::e_title( p1, Title, textStyle = list( color = TextColor, fontWeight = title.fontWeight, overflow = "truncate", # "none", "truncate", "break", ellipsis = '...', fontSize = title.fontSize, textShadowColor = title.textShadowColor, textShadowBlur = title.textShadowBlur, textShadowOffsetY = title.textShadowOffsetY, textShadowOffsetX = title.textShadowOffsetX)) if(Debug) print("BarPlot 2.g") if(FacetRows > 1L || FacetCols > 1L) { p1 <- echarts4r::e_facet(e = p1, rows = FacetRows, cols = FacetCols, legend_space = 16, legend_pos = "top") p1 <- echarts4r::e_legend(e = p1, type = "scroll", orient = "horizontal", right = 50, top = 40, height = "240px", textStyle = list(color = TextColor, fontWeight = "bold")) } else { p1 <- echarts4r::e_legend(e = p1, type = "scroll", orient = "vertical", right = 50, top = 40, height = "240px", textStyle = list(color = TextColor, fontWeight = "bold")) } if(Debug) print("BarPlot 2.h") return(p1) } } if(check2) { if(length(GroupVar) != 0) { if(!PreAgg) { if(any(tryCatch({class(dt[[eval(YVar)]])}, error = function(x) "bla") %in% c('numeric','integer'))) { numvars <- unique(c(numvars, YVar)) } else { byvars <- unique(c(byvars, YVar)) } if(any(tryCatch({class(dt[[eval(GroupVar)]])}, error = function(x) "bla") %in% c('numeric','integer'))) { numvars <- unique(c(numvars, GroupVar)) } else { byvars <- unique(c(byvars, GroupVar)) } if(!is.null(byvars)) { temp <- dt[, lapply(.SD, noquote(aggFunc)), .SDcols = c(numvars), by = c(byvars)] } else { temp <- dt[, lapply(.SD, noquote(aggFunc)), .SDcols = c(numvars)] } } else { temp <- data.table::copy(dt) numvars <- ColNameFilter(data = temp, Types = 'numeric')[[1L]] byvars <- unlist(ColNameFilter(data = temp, Types = "character")) } # Transformation if(length(XVar) > 0L && class(temp[[XVar]])[1L] %in% c("numeric","integer")) { YVarTrans <- XVarTrans } if(YVarTrans != "Identity") { temp <- AutoTransformationCreate(data = temp, ColumnNames = numvars, Methods = YVarTrans)$Data } p1 <- echarts4r::e_charts_( temp, x = GroupVar[1L], dispose = TRUE, darkMode = TRUE, width = Width, height = Height) if(ShowLabels) { p1 <- echarts4r::e_bar_(e = p1, YVar, label = list(show = TRUE)) } else { p1 <- echarts4r::e_bar_(e = p1, YVar) } if(MouseScroll && FacetRows == 1L && FacetCols == 1L) { p1 <- echarts4r::e_datazoom(e = p1, type = "inside", x_index = c(0,1)) } else if(MouseScroll && (FacetRows > 1L || FacetCols > 1L)) { p1 <- echarts4r::e_datazoom(e = p1, type = "inside", x_index = seq(0, FacetRows * FacetCols - 1, 1)) } else { p1 <- echarts4r::e_datazoom(e = p1, x_index = c(0,1)) } p1 <- echarts4r::e_theme(e = p1, name = EchartsTheme) p1 <- echarts4r::e_aria(e = p1, enabled = TRUE) p1 <- echarts4r::e_tooltip(e = p1, trigger = "axis", backgroundColor = "aliceblue") p1 <- echarts4r::e_toolbox_feature(e = p1, feature = c("saveAsImage","dataZoom")) p1 <- echarts4r::e_show_loading(e = p1, hide_overlay = TRUE, text = "Calculating...", color = "#000", text_color = TextColor, mask_color = "#000") if(length(Title.XAxis) == 0L) { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "x", name = XVar, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = xaxis.fontSize), axisLabel = list( rotate = xaxis.rotate, grid = list(containLabel = ContainLabel))) } else { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "x", name = Title.XAxis, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = xaxis.fontSize), axisLabel = list( rotate = xaxis.rotate, grid = list(containLabel = ContainLabel))) } if(length(Title.YAxis) == 0L) { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "y", name = YVar, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = yaxis.fontSize), axisLabel = list( rotate = yaxis.rotate, grid = list(containLabel = ContainLabel))) } else { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "y", name = Title.YAxis, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = yaxis.fontSize), axisLabel = list( rotate = yaxis.rotate, grid = list(containLabel = ContainLabel))) } p1 <- echarts4r::e_brush(e = p1) p1 <- echarts4r::e_title( p1, Title, textStyle = list( color = TextColor, fontWeight = title.fontWeight, overflow = "truncate", # "none", "truncate", "break", ellipsis = '...', fontSize = title.fontSize, textShadowColor = title.textShadowColor, textShadowBlur = title.textShadowBlur, textShadowOffsetY = title.textShadowOffsetY, textShadowOffsetX = title.textShadowOffsetX)) if(FacetRows > 1L || FacetCols > 1L) { p1 <- echarts4r::e_facet(e = p1, rows = FacetRows, cols = FacetCols, legend_space = 16, legend_pos = "top") p1 <- echarts4r::e_legend(e = p1, type = "scroll", orient = "horizontal", right = 50, top = 40, height = "240px", textStyle = list(color = TextColor, fontWeight = "bold")) } else { p1 <- echarts4r::e_legend(e = p1, type = "scroll", orient = "vertical", right = 50, top = 40, height = "240px", textStyle = list(color = TextColor, fontWeight = "bold")) } return(p1) } else { return(NULL) } } if(check3) { if(length(GroupVar) != 0) { if(!PreAgg) { if(any(tryCatch({class(dt[[eval(XVar)]])}, error = function(x) "bla") %in% c('numeric','integer'))) { numvars <- unique(c(numvars, XVar)) } else { byvars <- unique(c(byvars, XVar)) } if(any(tryCatch({class(dt[[eval(GroupVar)]])}, error = function(x) "bla") %in% c('numeric','integer'))) { numvars <- unique(c(numvars, GroupVar)) } else { byvars <- unique(c(byvars, GroupVar)) } if(!is.null(byvars)) { temp <- dt[, lapply(.SD, noquote(aggFunc)), .SDcols = c(numvars), by = c(byvars)] } else { temp <- dt[, lapply(.SD, noquote(aggFunc)), .SDcols = c(numvars)] } } else { temp <- data.table::copy(dt) numvars <- ColNameFilter(data = temp, Types = 'numeric')[[1L]] byvars <- unlist(ColNameFilter(data = temp, Types = "character")) } # Transformation if(length(XVar) > 0L && class(temp[[XVar]])[1L] %in% c("numeric","integer")) { YVarTrans <- XVarTrans } if(YVarTrans != "Identity") { temp <- AutoTransformationCreate(data = temp, ColumnNames = numvars, Methods = YVarTrans)$Data } # Plot p1 <- echarts4r::e_charts_( temp, x = GroupVar[1L], dispose = TRUE, darkMode = TRUE, width = Width, height = Height) if(ShowLabels) { p1 <- echarts4r::e_bar_(e = p1, XVar, label = list(show = TRUE)) } else { p1 <- echarts4r::e_bar_(e = p1, XVar) } if(MouseScroll && FacetRows == 1L && FacetCols == 1L) { p1 <- echarts4r::e_datazoom(e = p1, type = "inside", x_index = c(0,1)) } else if(MouseScroll && (FacetRows > 1L || FacetCols > 1L)) { p1 <- echarts4r::e_datazoom(e = p1, type = "inside", x_index = seq(0, FacetRows * FacetCols - 1, 1)) } else { p1 <- echarts4r::e_datazoom(e = p1, x_index = c(0,1)) } p1 <- echarts4r::e_theme(e = p1, name = EchartsTheme) p1 <- echarts4r::e_aria(e = p1, enabled = TRUE) p1 <- echarts4r::e_tooltip(e = p1, trigger = "axis", backgroundColor = "aliceblue") p1 <- echarts4r::e_toolbox_feature(e = p1, feature = c("saveAsImage","dataZoom")) p1 <- echarts4r::e_show_loading(e = p1, hide_overlay = TRUE, text = "Calculating...", color = "#000", text_color = TextColor, mask_color = "#000") if(length(Title.XAxis) == 0L) { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "x", name = XVar, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = xaxis.fontSize), axisLabel = list( rotate = xaxis.rotate, grid = list(containLabel = ContainLabel))) } else { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "x", name = Title.XAxis, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = xaxis.fontSize), axisLabel = list( rotate = xaxis.rotate, grid = list(containLabel = ContainLabel))) } if(length(Title.YAxis) == 0L) { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "y", name = YVar, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = yaxis.fontSize), axisLabel = list( rotate = yaxis.rotate, grid = list(containLabel = ContainLabel))) } else { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "y", name = Title.YAxis, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = yaxis.fontSize), axisLabel = list( rotate = yaxis.rotate, grid = list(containLabel = ContainLabel))) } p1 <- echarts4r::e_brush(e = p1) p1 <- echarts4r::e_title( p1, Title, textStyle = list( color = TextColor, fontWeight = title.fontWeight, overflow = "truncate", # "none", "truncate", "break", ellipsis = '...', fontSize = title.fontSize, textShadowColor = title.textShadowColor, textShadowBlur = title.textShadowBlur, textShadowOffsetY = title.textShadowOffsetY, textShadowOffsetX = title.textShadowOffsetX)) if(FacetRows > 1L || FacetCols > 1L) p1 <- echarts4r::e_facet(e = p1, rows = FacetRows, cols = FacetCols, legend_space = 16, legend_pos = "top") return(p1) } else { return(NULL) } } if(!check1 && !check2 && !check3) return(NULL) # Return plot return(p1) } #' @title Plot.ACF #' #' @description Build an autocorrelation plot by simply passing arguments to a single function #' #' @family Standard Plots #' #' @author Adrian Antico #' #' @param dt source data.table #' @param YVar Y-Axis variable name #' @param DateVar Date column in data #' @param TimeUnit Select from "hour", "day", "week", "month", "quarter", "year" #' @param MaxLags Max lag values to test #' @param YVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param AggMethod Choose from 'mean', 'sum', 'sd', and 'median' #' @param Height "400px" #' @param Width "200px" #' @param Title title #' @param EchartsTheme "auritus","azul","bee-inspired","blue","caravan","carp","chalk","cool","dark-bold","dark","eduardo", #' "essos","forest","fresh-cut","fruit","gray","green","halloween","helianthus","infographic","inspired", #' "jazz","london","dark","macarons","macarons2","mint","purple-passion","red-velvet","red","roma","royal", #' "sakura","shine","tech-blue","vintage","walden","wef","weforum","westeros","wonderland" #' @param TextColor 'darkblue' #' @param title.fontSize 22 #' @param title.fontWeight "bold" #' @param title.textShadowColor '#63aeff' #' @param title.textShadowBlur 3 #' @param title.textShadowOffsetY 1 #' @param title.textShadowOffsetX -1 #' @param xaxis.fontSize 14 #' @param yaxis.fontSize 14 #' @param xaxis.rotate 0 #' @param yaxis.rotate 0 #' @param ContainLabel TRUE #' @param Debug Debugging purposes #' @return plot #' @export Plot.ACF <- function(dt = NULL, YVar = NULL, DateVar = NULL, TimeUnit = NULL, MaxLags = 50, YVarTrans = "Identity", AggMethod = 'sum', Height = NULL, Width = NULL, Title = 'Autocorrelation Plot', EchartsTheme = "macarons", TextColor = "white", title.fontSize = 22, title.fontWeight = "bold", title.textShadowColor = '#63aeff', title.textShadowBlur = 3, title.textShadowOffsetY = 1, title.textShadowOffsetX = -1, xaxis.fontSize = 14, yaxis.fontSize = 14, xaxis.rotate = 0, yaxis.rotate = 0, ContainLabel = TRUE, Debug = FALSE) { if(!data.table::is.data.table(dt)) tryCatch({data.table::setDT(dt)}, error = function(x) { dt <- data.table::as.data.table(dt) }) dt1 <- data.table::copy(dt) # Convert factor to character if(length(YVar) > 0L && class(dt1[[YVar]])[1L] == "factor") { return(NULL) } # Define Aggregation function if(Debug) print("Plot.ACH 1") aggFunc <- SummaryFunction(AggMethod) if(Debug) print("Plot.ACH 2") # Transformation if(YVarTrans != "Identity") { dt1 <- AutoTransformationCreate(data = dt1, ColumnNames = YVar, Methods = YVarTrans)$Data } if(Debug) print("Plot.ACH 3") # Aggregate dt1 dt1 <- dt1[, lapply(.SD, noquote(aggFunc)), .SDcols = c(YVar), by = c(DateVar)] if(Debug) print("Plot.ACH 3.5") dt1 <- AutoLagRollStats( data = dt1, DateColumn = DateVar, Targets = YVar, TimeUnitAgg = TimeUnit, TimeGroups = TimeUnit, TimeUnit = TimeUnit, RollOnLag1 = TRUE, Type = "Lag", SimpleImpute = TRUE, Lags = seq_len(MaxLags)) if(Debug) print("Plot.ACH 4") # Autocorrelation data creation ACF_Data <- data.table::data.table(Lag = 1:50, Cor = 0.0, `Lower 95th` = 0.0, `Upper 95th` = 0.0) if(Debug) print("Plot.ACH 5") for(i in seq_len(MaxLags)) {# i = 1 lagCol <- names(dt1)[which(grepl(pattern = paste0("_LAG_",i,"_"), x = names(dt1)))] lag_test <- cor.test(x = dt1[[YVar]], y = dt1[[lagCol]]) data.table::set(ACF_Data, i = i, j = "Lag", value = i) data.table::set(ACF_Data, i = i, j = "Cor", value = lag_test$estimate) data.table::set(ACF_Data, i = i, j = "Lower 95th", value = lag_test$conf.int[1L]) data.table::set(ACF_Data, i = i, j = "Upper 95th", value = lag_test$conf.int[2L]) } if(Debug) print("Plot.ACH 6") # Plot p1 <- echarts4r::e_charts_( ACF_Data, x = "Lag", dispose = TRUE, darkMode = TRUE, width = Width, height = Height) if(Debug) print("Plot.ACH 7") p1 <- echarts4r::e_bar_(e = p1, "Cor") if(Debug) print("Plot.ACH 8") # MAX Band is not working currently so plot looks stupid with this # p1 <- echarts4r::e_band_( # e = p1, # min = "Lower 95th", max = "Upper 95th", stack = "confidence-band", # areaStyle = list(list(color = "#54535387"), list(color = "#54535387")) # ) # Alternative bands: just lines but they are correct p1 <- echarts4r::e_line_(e = p1, "Lower 95th", smooth = TRUE) p1 <- echarts4r::e_line_(e = p1, "Upper 95th", smooth = TRUE) # Extras if(Debug) print("Plot.ACH 10") p1 <- echarts4r::e_theme(e = p1, name = EchartsTheme) p1 <- echarts4r::e_aria(e = p1, enabled = TRUE) p1 <- echarts4r::e_tooltip(e = p1, trigger = "axis", backgroundColor = "aliceblue") p1 <- echarts4r::e_toolbox_feature(e = p1, feature = c("saveAsImage","dataZoom")) p1 <- echarts4r::e_show_loading(e = p1, hide_overlay = TRUE, text = "Calculating...", color = "#000", text_color = TextColor, mask_color = "#000") p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "x", name = "Lags", nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = xaxis.fontSize), axisLabel = list( rotate = xaxis.rotate, grid = list(containLabel = ContainLabel))) p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "y", name = "Correlation", nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = yaxis.fontSize), axisLabel = list( rotate = yaxis.rotate, grid = list(containLabel = ContainLabel))) p1 <- echarts4r::e_brush(e = p1) p1 <- echarts4r::e_title( p1, Title, textStyle = list( color = TextColor, fontWeight = title.fontWeight, overflow = "truncate", # "none", "truncate", "break", ellipsis = '...', fontSize = title.fontSize, textShadowColor = title.textShadowColor, textShadowBlur = title.textShadowBlur, textShadowOffsetY = title.textShadowOffsetY, textShadowOffsetX = title.textShadowOffsetX)) return(p1) } #' @title Plot.PACF #' #' @description Build a partial autocorrelation plot by simply passing arguments to a single function #' #' @family Standard Plots #' #' @author Adrian Antico #' #' @param dt source data.table #' @param YVar Y-Axis variable name #' @param DateVar Date column in data #' @param MaxLags Max value for lags to test #' @param TimeUnit Select from "hour", "day", "week", "month", "quarter", "year" #' @param YVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param AggMethod Choose from 'mean', 'sum', 'sd', and 'median' #' @param Height "400px" #' @param Width "200px" #' @param Title title #' @param EchartsTheme "auritus","azul","bee-inspired","blue","caravan","carp","chalk","cool","dark-bold","dark","eduardo", #' "essos","forest","fresh-cut","fruit","gray","green","halloween","helianthus","infographic","inspired", #' "jazz","london","dark","macarons","macarons2","mint","purple-passion","red-velvet","red","roma","royal", #' "sakura","shine","tech-blue","vintage","walden","wef","weforum","westeros","wonderland" #' @param TextColor 'darkblue' #' @param title.fontSize 22 #' @param title.fontWeight "bold" #' @param title.textShadowColor '#63aeff' #' @param title.textShadowBlur 3 #' @param title.textShadowOffsetY 1 #' @param title.textShadowOffsetX -1 #' @param xaxis.fontSize 14 #' @param yaxis.fontSize 14 #' @param xaxis.rotate 0 #' @param yaxis.rotate 0 #' @param ContainLabel TRUE #' @param Debug Debugging purposes #' @return plot #' @export Plot.PACF <- function(dt = NULL, YVar = NULL, DateVar = NULL, TimeUnit = NULL, MaxLags = 50, YVarTrans = "Identity", AggMethod = 'sum', Height = NULL, Width = NULL, Title = 'Partial Autocorrelation Plot', EchartsTheme = "macarons", TextColor = "white", title.fontSize = 22, title.fontWeight = "bold", title.textShadowColor = '#63aeff', title.textShadowBlur = 3, title.textShadowOffsetY = 1, title.textShadowOffsetX = -1, xaxis.fontSize = 14, yaxis.fontSize = 14, xaxis.rotate = 0, yaxis.rotate = 0, ContainLabel = TRUE, Debug = FALSE) { if(!data.table::is.data.table(dt)) tryCatch({data.table::setDT(dt)}, error = function(x) { dt <- data.table::as.data.table(dt) }) dt1 <- data.table::copy(dt) if(grepl(" ", YVar)) { data.table::setnames(x = dt1, old = YVar, new = gsub(pattern = " ", replacement = ".", x = YVar)) YVar <- gsub(pattern = " ", replacement = ".", x = YVar) } # Convert factor to character if(length(YVar) > 0L && class(dt1[[YVar]])[1L] == "factor") { return(NULL) } # Define Aggregation function if(Debug) print("Plot.PACH 1") aggFunc <- SummaryFunction(AggMethod) if(Debug) print("Plot.PACH 2") # Transformation if(YVarTrans != "Identity") { dt1 <- AutoTransformationCreate(data = dt1, ColumnNames = YVar, Methods = YVarTrans)$Data } if(Debug) print("Plot.PACH 3") # Aggregate dt1 dt1 <- dt1[, lapply(.SD, noquote(aggFunc)), .SDcols = c(YVar), by = c(DateVar)] if(Debug) print("Plot.PACH 3.5") dt1 <- AutoLagRollStats( data = dt1, DateColumn = DateVar, Targets = YVar, TimeUnitAgg = TimeUnit, TimeGroups = TimeUnit, TimeUnit = TimeUnit, RollOnLag1 = TRUE, Type = "Lag", SimpleImpute = TRUE, Lags = seq_len(MaxLags)) if(Debug) print("Plot.PACH 4") # Autocorrelation data creation PACF_Data <- data.table::data.table(Lag = 1:50, Cor = 0.0, `Lower 95th` = 0.0, `Upper 95th` = 0.0) LagCols <- c() if(Debug) print("Plot.ACH 5") for(i in seq_len(MaxLags)) {# i = 1L i = 2L LagCols[i] <- names(dt1)[which(grepl(pattern = paste0("_LAG_",i,"_"), x = names(dt1)))] if(i == 1L) { lag_test <- cor.test(x = dt1[[YVar]], y = dt1[[LagCols]]) data.table::set(PACF_Data, i = i, j = "Lag", value = i) data.table::set(PACF_Data, i = i, j = "Cor", value = lag_test$estimate) data.table::set(PACF_Data, i = i, j = "Lower 95th", value = lag_test$conf.int[1L]) data.table::set(PACF_Data, i = i, j = "Upper 95th", value = lag_test$conf.int[2L]) } else { x <- as.vector(lm(formula = as.formula(paste0(YVar, " ~ ", paste0(LagCols, collapse = " + "))), data = dt1)$residuals) lag_test <- cor.test(x = x, y = dt1[[LagCols[i]]]) data.table::set(PACF_Data, i = i, j = "Lag", value = i) data.table::set(PACF_Data, i = i, j = "Cor", value = lag_test$estimate) data.table::set(PACF_Data, i = i, j = "Lower 95th", value = lag_test$conf.int[1L]) data.table::set(PACF_Data, i = i, j = "Upper 95th", value = lag_test$conf.int[2L]) } } if(Debug) print("Plot.PACH 6") # Plot p1 <- echarts4r::e_charts_( PACF_Data, x = "Lag", dispose = TRUE, darkMode = TRUE, width = Width, height = Height) if(Debug) print("Plot.PACH 7") p1 <- echarts4r::e_bar_(e = p1, "Cor") if(Debug) print("Plot.PACH 8") p1 <- echarts4r::e_line_(e = p1, "Lower 95th", smooth = TRUE) if(Debug) print("Plot.PACH 9") p1 <- echarts4r::e_line_(e = p1, "Upper 95th", smooth = TRUE) # Extras if(Debug) print("Plot.PACH 10") p1 <- echarts4r::e_theme(e = p1, name = EchartsTheme) p1 <- echarts4r::e_aria(e = p1, enabled = TRUE) p1 <- echarts4r::e_tooltip(e = p1, trigger = "axis", backgroundColor = "aliceblue") p1 <- echarts4r::e_toolbox_feature(e = p1, feature = c("saveAsImage","dataZoom")) p1 <- echarts4r::e_show_loading(e = p1, hide_overlay = TRUE, text = "Calculating...", color = "#000", text_color = TextColor, mask_color = "#000") p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "x", name = "Lags", nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = xaxis.fontSize), axisLabel = list( rotate = xaxis.rotate, grid = list(containLabel = ContainLabel))) p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "y", name = "Correlation", nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = yaxis.fontSize), axisLabel = list( rotate = yaxis.rotate, grid = list(containLabel = ContainLabel))) p1 <- echarts4r::e_brush(e = p1) p1 <- echarts4r::e_title( p1, Title, textStyle = list( color = TextColor, fontWeight = title.fontWeight, overflow = "truncate", # "none", "truncate", "break", ellipsis = '...', fontSize = title.fontSize, textShadowColor = title.textShadowColor, textShadowBlur = title.textShadowBlur, textShadowOffsetY = title.textShadowOffsetY, textShadowOffsetX = title.textShadowOffsetX)) return(p1) } #' @title Plot.StackedBar #' #' @description Build a stacked bar plot vs a grouped bar plot #' #' @family Standard Plots #' #' @author Adrian Antico #' #' @param dt source data.table #' @param PreAgg logical #' @param YVar Y-Axis variable name #' @param XVar X-Axis variable name #' @param GroupVar Column name of Group Variable for distinct colored histograms by group levels #' @param YVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param XVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param FacetRows Defaults to 1 which causes no faceting to occur vertically. Otherwise, supply a numeric value for the number of output grid rows #' @param FacetCols Defaults to 1 which causes no faceting to occur horizontally. Otherwise, supply a numeric value for the number of output grid columns #' @param FacetLevels Faceting rows x columns is the max number of levels allowed in a grid. If your GroupVar has more you can supply the levels to display. #' @param AggMethod Choose from 'mean', 'sum', 'sd', and 'median' #' @param Height NULL #' @param Width NULL #' @param Title title #' @param Title.YAxis NULL. If NULL, YVar name will be used #' @param Title.XAxis NULL. If NULL, XVar name will be used #' @param ShowLabels logical #' @param EchartsTheme "auritus","azul","bee-inspired","blue","caravan","carp","chalk","cool","dark-bold","dark","eduardo", #' "essos","forest","fresh-cut","fruit","gray","green","halloween","helianthus","infographic","inspired", #' "jazz","london","dark","macarons","macarons2","mint","purple-passion","red-velvet","red","roma","royal", #' "sakura","shine","tech-blue","vintage","walden","wef","weforum","westeros","wonderland" #' @param TimeLine logical #' @param MouseScroll logical, zoom via mouse scroll #' @param TextColor 'darkblue' #' @param title.fontSize 22 #' @param title.fontWeight "bold" #' @param title.textShadowColor '#63aeff' #' @param title.textShadowBlur 3 #' @param title.textShadowOffsetY 1 #' @param title.textShadowOffsetX -1 #' @param xaxis.fontSize 14 #' @param yaxis.fontSize 14 #' @param xaxis.rotate 0 #' @param yaxis.rotate 0 #' @param ContainLabel TRUE #' @param Debug Debugging purposes #' #' @examples #' # Create fake data #' data <- AutoPlots::FakeDataGenerator(N = 100000) #' #' # Echarts Stacked Bar Chart #' AutoPlots::Plot.StackedBar( #' dt = data, #' PreAgg = FALSE, #' XVar = "Factor_1", #' YVar = "Adrian", #' GroupVar = "Factor_2", #' YVarTrans = "Identity", #' XVarTrans = "Identity", #' FacetRows = 1, #' FacetCols = 1, #' FacetLevels = NULL, #' AggMethod = 'mean', #' Height = NULL, #' Width = NULL, #' Title = "Stacked Bar", #' Title.YAxis = NULL, #' Title.XAxis = NULL, #' ShowLabels = FALSE, #' EchartsTheme = "macarons", #' MouseScroll = TRUE, #' TimeLine = TRUE, #' TextColor = "black", #' title.fontSize = 22, #' title.fontWeight = "bold", #' title.textShadowColor = '#63aeff', #' title.textShadowBlur = 3, #' title.textShadowOffsetY = 1, #' title.textShadowOffsetX = -1, #' yaxis.fontSize = 14, #' xaxis.fontSize = 14, #' xaxis.rotate = 0, #' yaxis.rotate = 0, #' ContainLabel = TRUE, #' Debug = FALSE) #' #' @return plot #' @export Plot.StackedBar <- function(dt = NULL, PreAgg = FALSE, XVar = NULL, YVar = NULL, GroupVar = NULL, YVarTrans = "Identity", XVarTrans = "Identity", FacetRows = 1, FacetCols = 1, FacetLevels = NULL, AggMethod = 'mean', Height = NULL, Width = NULL, Title = "Stacked Bar", Title.YAxis = NULL, Title.XAxis = NULL, ShowLabels = FALSE, EchartsTheme = "macarons", MouseScroll = TRUE, TimeLine = TRUE, TextColor = "white", title.fontSize = 22, title.fontWeight = "bold", title.textShadowColor = '#63aeff', title.textShadowBlur = 3, title.textShadowOffsetY = 1, title.textShadowOffsetX = -1, yaxis.fontSize = 14, xaxis.fontSize = 14, xaxis.rotate = 0, yaxis.rotate = 0, ContainLabel = TRUE, Debug = FALSE) { if(length(XVar) == 0L) return(NULL) if(length(YVar) == 0L) return(NULL) if(length(GroupVar) == 0L) return(NULL) if(!data.table::is.data.table(dt)) tryCatch({data.table::setDT(dt)}, error = function(x) { dt <- data.table::as.data.table(dt) }) # Convert factor to character if(length(GroupVar) > 0L && class(dt[[GroupVar]])[1L] %in% c("factor","integer","numeric")) { dt[, eval(GroupVar) := as.character(get(GroupVar))] } if(length(XVar) > 0L && class(dt[[XVar]])[1L] %in% c("factor","integer","numeric")) { dt[, eval(XVar) := as.character(get(XVar))] } if(length(YVar) > 0L && class(dt[[YVar]])[1L] == "factor") { dt[, eval(YVar) := as.character(get(YVar))] } if(class(dt[[YVar]])[1L] %in% c("character","factor") && class(dt[[XVar]])[1L] %in% c("numeric","integer")) { l <- YVar YVar <- XVar XVar <- l rm(l) } if(length(GroupVar) == 0L) TimeLine <- FALSE # Used multiple times check1 <- length(XVar) != 0 && length(YVar) != 0 && length(GroupVar) > 0L if(!PreAgg) { aggFunc <- SummaryFunction(AggMethod) } # Create base plot object numvars <- c() byvars <- c() if(check1) { if(!PreAgg) { if(length(FacetLevels) > 0L) { dt <- dt[get(GroupVar) %in% c(eval(FacetLevels)), .SD, .SDcols = c(YVar,XVar,GroupVar)] } if(any(tryCatch({class(dt[[eval(YVar)]])}, error = function(x) "bla") %in% c('numeric','integer'))) { numvars <- unique(c(numvars, YVar)) } else { byvars <- unique(c(byvars, YVar)) } if(any(tryCatch({class(dt[[eval(XVar)]])}, error = function(x) "bla") %in% c('numeric','integer'))) { if(length(numvars) > 0) { x <- length(unique(dt[[XVar]])) y <- length(unique(dt[[YVar]])) if(x > y) { byvars <- unique(c(byvars, YVar)) numvars[1L] <- XVar } else { byvars <- unique(c(byvars, XVar)) } } else { numvars <- unique(c(numvars, XVar)) } } else { byvars <- unique(c(byvars, XVar)) } if(any(tryCatch({class(dt[[eval(GroupVar)]])}, error = function(x) "bla") %in% c('numeric','integer'))) { dt[, eval(GroupVar) := as.character(get(GroupVar))] byvars <- unique(c(byvars, GroupVar)) } else { byvars <- unique(c(byvars, GroupVar)) } if(!is.null(byvars)) { temp <- dt[, lapply(.SD, noquote(aggFunc)), .SDcols = c(numvars), by = c(byvars)] for(i in byvars) { if(class(temp[[i]]) %in% c('numeric','integer')) { temp[, eval(i) := as.character(get(i))] } } } else { temp <- dt[, lapply(.SD, noquote(aggFunc)), .SDcols = c(numvars)] } } else { temp <- data.table::copy(dt) numvars <- ColNameFilter(data = temp, Types = 'numeric')[[1L]] byvars <- unlist(ColNameFilter(data = temp, Types = "character")) } # Transformation if(length(XVar) > 0L && class(temp[[XVar]])[1L] %in% c("numeric","integer")) { YVarTrans <- XVarTrans } if(YVarTrans != "Identity") { temp <- AutoTransformationCreate(data = temp, ColumnNames = numvars, Methods = YVarTrans)$Data } p1 <- echarts4r::e_charts_( data = temp |> dplyr::group_by(get(GroupVar[1L])), x = XVar, dispose = TRUE, darkMode = TRUE, emphasis = list(focus = "series"), width = Width, height = Height) if(ShowLabels) { p1 <- echarts4r::e_bar_( e = p1, YVar, stack = XVar, label = list(show = TRUE)) } else { p1 <- echarts4r::e_bar_( e = p1, YVar, stack = XVar) } if(MouseScroll && FacetRows == 1L && FacetCols == 1L) { p1 <- echarts4r::e_datazoom(e = p1, type = "inside", x_index = c(0,1)) } else if(MouseScroll && (FacetRows > 1L || FacetCols > 1L)) { p1 <- echarts4r::e_datazoom(e = p1, type = "inside", x_index = seq(0, FacetRows * FacetCols - 1, 1)) } else { p1 <- echarts4r::e_datazoom(e = p1, x_index = c(0,1)) } p1 <- echarts4r::e_theme(e = p1, name = EchartsTheme) p1 <- echarts4r::e_aria(e = p1, enabled = TRUE) p1 <- echarts4r::e_tooltip(e = p1, trigger = "axis", backgroundColor = "aliceblue") p1 <- echarts4r::e_toolbox_feature(e = p1, feature = c("saveAsImage","dataZoom")) p1 <- echarts4r::e_show_loading(e = p1, hide_overlay = TRUE, text = "Calculating...", color = "#000", text_color = TextColor, mask_color = "#000") if(length(Title.XAxis) == 0L) { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "x", name = XVar, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = xaxis.fontSize), axisLabel = list( rotate = xaxis.rotate, grid = list(containLabel = ContainLabel))) } else { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "x", name = Title.XAxis, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = xaxis.fontSize), axisLabel = list( rotate = xaxis.rotate, grid = list(containLabel = ContainLabel))) } if(length(Title.YAxis) == 0L) { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "y", name = YVar, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = yaxis.fontSize), axisLabel = list( rotate = yaxis.rotate, grid = list(containLabel = ContainLabel))) } else { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "y", name = Title.YAxis, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = yaxis.fontSize), axisLabel = list( rotate = yaxis.rotate, grid = list(containLabel = ContainLabel))) } p1 <- echarts4r::e_brush(e = p1) p1 <- echarts4r::e_title( p1, Title, textStyle = list( color = TextColor, fontWeight = title.fontWeight, overflow = "truncate", # "none", "truncate", "break", ellipsis = '...', fontSize = title.fontSize, textShadowColor = title.textShadowColor, textShadowBlur = title.textShadowBlur, textShadowOffsetY = title.textShadowOffsetY, textShadowOffsetX = title.textShadowOffsetX)) if(FacetRows > 1L || FacetCols > 1L) { p1 <- echarts4r::e_facet(e = p1, rows = FacetRows, cols = FacetCols, legend_space = 16, legend_pos = "top") p1 <- echarts4r::e_legend(e = p1, type = "scroll", orient = "horizontal", right = 50, top = 40, height = "240px", textStyle = list(color = TextColor, fontWeight = "bold")) } else { p1 <- echarts4r::e_legend(e = p1, type = "scroll", orient = "vertical", right = 50, top = 40, height = "240px", textStyle = list(color = TextColor, fontWeight = "bold")) } return(p1) } else { if(Debug) print("XVar, YVar, and GroupVar need to have length > 0") } } #' @title Plot.BarPlot3D #' #' @description Build a 3D Bar Plot #' #' @family Standard Plots #' @author Adrian Antico #' #' @param dt source data.table #' @param PreAgg logical. Is your data pre aggregated #' @param YVar Y-Axis variable name #' @param XVar X-Axis variable name #' @param ZVar Z-Axis variable name #' @param YVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param XVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param ZVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param FacetRows Defaults to 1 which causes no faceting to occur vertically. Otherwise, supply a numeric value for the number of output grid rows #' @param FacetCols Defaults to 1 which causes no faceting to occur horizontally. Otherwise, supply a numeric value for the number of output grid columns #' @param FacetLevels Faceting rows x columns is the max number of levels allowed in a grid. If your GroupVar has more you can supply the levels to display. #' @param Height "400px" #' @param Width "200px" #' @param MouseScroll logical, zoom via mouse scroll #' @param EchartsTheme "dark-blue" #' @param AggMethod 'mean', 'median', 'sum', 'sd', 'coeffvar', 'count' #' @param NumberBins = 21 #' @param NumLevels_Y = 20 #' @param NumLevels_X = 20 #' @param Title "Heatmap" #' @param ShowLabels character #' @param TextColor character #' @param Title.YAxis character #' @param Title.XAxis character #' @param title.fontSize 22 #' @param title.fontWeight "bold" #' @param title.textShadowColor '#63aeff' #' @param title.textShadowBlur 3 #' @param title.textShadowOffsetY 1 #' @param title.textShadowOffsetX -1 #' @param xaxis.fontSize 14 #' @param yaxis.fontSize 14 #' @param zaxis.fontSize 14 #' @param xaxis.rotate 0 #' @param yaxis.rotate 0 #' @param ContainLabel TRUE #' @param Debug Debugging purposes #' #' @examples #' # Create fake data #' data <- AutoPlots::FakeDataGenerator(N = 100000) #' #' # Echarts 3D Bar Chart #' AutoPlots::Plot.BarPlot3D( #' dt = data, #' PreAgg = FALSE, #' AggMethod = 'mean', #' XVar = "Factor_1", #' YVar = "Factor_2", #' ZVar = "Adrian", #' YVarTrans = "Identity", #' XVarTrans = "Identity", #' ZVarTrans = "Identity", #' FacetRows = 1, #' FacetCols = 1, #' FacetLevels = NULL, #' NumberBins = 21, #' NumLevels_Y = 33, #' NumLevels_X = 33, #' Height = NULL, #' Width = NULL, #' Title = "3D Bar Plot", #' ShowLabels = FALSE, #' Title.YAxis = NULL, #' Title.XAxis = NULL, #' EchartsTheme = "macarons", #' MouseScroll = TRUE, #' TextColor = "black", #' title.fontSize = 22, #' title.fontWeight = "bold", #' title.textShadowColor = '#63aeff', #' title.textShadowBlur = 3, #' title.textShadowOffsetY = 1, #' title.textShadowOffsetX = -1, #' yaxis.fontSize = 14, #' xaxis.fontSize = 14, #' zaxis.fontSize = 14, #' xaxis.rotate = 0, #' yaxis.rotate = 0, #' ContainLabel = TRUE, #' Debug = FALSE) #' #' @return plot #' @export Plot.BarPlot3D <- function(dt, PreAgg = FALSE, AggMethod = 'mean', XVar = NULL, YVar = NULL, ZVar = NULL, YVarTrans = "Identity", XVarTrans = "Identity", ZVarTrans = "Identity", FacetRows = 1, FacetCols = 1, FacetLevels = NULL, NumberBins = 21, NumLevels_Y = 33, NumLevels_X = 33, Height = NULL, Width = NULL, Title = "3D Bar Plot", ShowLabels = FALSE, Title.YAxis = NULL, Title.XAxis = NULL, EchartsTheme = "dark", MouseScroll = TRUE, TextColor = "white", title.fontSize = 22, title.fontWeight = "bold", title.textShadowColor = '#63aeff', title.textShadowBlur = 3, title.textShadowOffsetY = 1, title.textShadowOffsetX = -1, yaxis.fontSize = 14, xaxis.fontSize = 14, zaxis.fontSize = 14, xaxis.rotate = 0, yaxis.rotate = 0, ContainLabel = TRUE, Debug = FALSE) { if(!data.table::is.data.table(dt)) tryCatch({data.table::setDT(dt)}, error = function(x) { dt <- data.table::as.data.table(dt) }) # Convert factor to character if(length(ZVar) > 0L && class(dt[[ZVar]])[1L] %in% c("factor","character")) { dt[, eval(ZVar) := as.numeric(get(ZVar))] } if(length(XVar) > 0L && class(dt[[XVar]])[1L] == "factor") { dt[, eval(XVar) := as.character(get(XVar))] } if(length(YVar) > 0L && class(dt[[YVar]])[1L] == "factor") { dt[, eval(YVar) := as.character(get(YVar))] } # Subset cols dt1 <- dt[, .SD, .SDcols = c(XVar,YVar,ZVar)] x_check <- class(dt1[[XVar]])[1L] %in% c('numeric','integer') y_check <- class(dt1[[YVar]])[1L] %in% c('numeric','integer') x_y_num <- x_check && y_check x_num <- x_check && !y_check x_char <- !x_check && y_check all_char <- !x_check && !y_check Z.HoverFormat <- "%{zaxis.title.text}: %{y:,.2f}<br>" TimeLine <- FALSE if(TimeLine && length(FacetLevels) > 0) X_Scroll <- FALSE if(!PreAgg) { aggFunc <- SummaryFunction(AggMethod) } # XVar == numeric or integer && YVar == numeric or integer if(x_y_num) { # rank XVar and YVar if(!PreAgg) { dt1[, eval(XVar) := round(data.table::frank(dt1[[XVar]]) * NumberBins /.N) / NumberBins] dt1[, eval(YVar) := round(data.table::frank(dt1[[YVar]]) * NumberBins /.N) / NumberBins] data.table::setnames(dt1, eval(ZVar), 'Measure_Variable') dt1 <- dt1[, lapply(.SD, noquote(aggFunc)), .SDcols = c(ZVar), by = c(XVar,YVar)] } # Transformation if(ZVarTrans != "Identity") { dt1 <- AutoTransformationCreate(data = dt1, ColumnNames = "Measure_Variable", Methods = ZVarTrans)$Data } # Formatting vals <- unique(scales::rescale(c(dt1[['Measure_Variable']]))) o <- order(vals, decreasing = FALSE) cols <- scales::col_numeric("Purples", domain = NULL)(vals) colz <- setNames(data.frame(vals[o], cols[o]), NULL) # Create final data for plot g <- "Measure_Variable" p1 <- echarts4r::e_charts_( data = dt1, x = XVar, dispose = TRUE, darkMode = TRUE, width = Width, height = Height) if(ShowLabels) { p1 <- echarts4r::e_bar_3d_(e = p1, YVar, g, itemStyle = list(emphasis = list(shadowBlur = 10)), label = list(show = TRUE)) } else { p1 <- echarts4r::e_bar_3d_(e = p1, YVar, g, itemStyle = list(emphasis = list(shadowBlur = 10))) } p1 <- echarts4r::e_visual_map_(e = p1, g, show = FALSE) p1 <- echarts4r::e_tooltip(e = p1, trigger = "axis", backgroundColor = "aliceblue") p1 <- echarts4r::e_theme(e = p1, name = EchartsTheme) if(MouseScroll && FacetRows == 1L && FacetCols == 1L) { p1 <- echarts4r::e_datazoom(e = p1, type = "inside", x_index = c(0,1)) } else if(MouseScroll && (FacetRows > 1L || FacetCols > 1L)) { p1 <- echarts4r::e_datazoom(e = p1, type = "inside", x_index = seq(0, FacetRows * FacetCols - 1, 1)) } else { p1 <- echarts4r::e_datazoom(e = p1, x_index = c(0,1)) } p1 <- echarts4r::e_aria(e = p1, enabled = TRUE) p1 <- echarts4r::e_toolbox_feature(e = p1, feature = c("saveAsImage","dataZoom")) p1 <- echarts4r::e_show_loading(e = p1, hide_overlay = TRUE, text = "Calculating...", color = "#000", text_color = TextColor, mask_color = "#000") p1 <- echarts4r::e_brush(e = p1) p1 <- echarts4r::e_title( p1, Title, textStyle = list( color = TextColor, fontWeight = title.fontWeight, overflow = "truncate", # "none", "truncate", "break", ellipsis = '...', fontSize = title.fontSize, textShadowColor = title.textShadowColor, textShadowBlur = title.textShadowBlur, textShadowOffsetY = title.textShadowOffsetY, textShadowOffsetX = title.textShadowOffsetX)) if(FacetRows > 1L || FacetCols > 1L) p1 <- echarts4r::e_facet(e = p1, rows = FacetRows, cols = FacetCols, legend_space = 16, legend_pos = "top") return(p1) } # XVar == character && YVar == numeric or integer if(x_char) { # rank YVar data.table::setnames(dt1, eval(ZVar), 'Measure_Variable') if(!PreAgg) { dt1[, eval(YVar) := round(data.table::frank(dt1[[YVar]]) * NumberBins /.N) / NumberBins] temp <- dt1[, lapply(.SD, mean, na.rm = TRUE), .SDcols = c('Measure_Variable'), by = c(YVar)][order(-Measure_Variable)] temp <- temp[seq_len(min(NumLevels_X, temp[, .N]))][[1L]] dt1 <- dt1[get(YVar) %in% eval(temp)] dt1 <- dt1[, lapply(.SD, noquote(aggFunc)), .SDcols = c(ZVar), by = c(XVar,YVar)] } # Formatting vals <- unique(scales::rescale(c(dt1[['Measure_Variable']]))) o <- order(vals, decreasing = FALSE) cols <- scales::col_numeric("Purples", domain = NULL)(vals) colz <- setNames(data.frame(vals[o], cols[o]), NULL) # Transformation if(ZVarTrans != "Identity") { dt1 <- AutoTransformationCreate(data = dt1, ColumnNames = "Measure_Variable", Methods = ZVarTrans)$Data } # Create final data for plot g <- "Measure_Variable" p1 <- echarts4r::e_charts_( data = dt1, x = XVar, dispose = TRUE, darkMode = TRUE, width = Width, height = Height) if(ShowLabels) { p1 <- echarts4r::e_heatmap_(e = p1, YVar, g, itemStyle = list(emphasis = list(shadowBlur = 10)), label = list(show = TRUE)) } else { p1 <- echarts4r::e_heatmap_(e = p1, YVar, g, itemStyle = list(emphasis = list(shadowBlur = 10))) } p1 <- echarts4r::e_visual_map_(e = p1, g, show = FALSE) if(MouseScroll && FacetRows == 1L && FacetCols == 1L) { p1 <- echarts4r::e_datazoom(e = p1, type = "inside", x_index = c(0,1)) } else if(MouseScroll && (FacetRows > 1L || FacetCols > 1L)) { p1 <- echarts4r::e_datazoom(e = p1, type = "inside", x_index = seq(0, FacetRows * FacetCols - 1, 1)) } else { p1 <- echarts4r::e_datazoom(e = p1, x_index = c(0,1)) } p1 <- echarts4r::e_theme(e = p1, name = EchartsTheme) p1 <- echarts4r::e_aria(e = p1, enabled = TRUE) p1 <- echarts4r::e_show_loading(e = p1, hide_overlay = TRUE, text = "Calculating...", color = "#000", text_color = TextColor, mask_color = "#000") if(length(Title.XAxis) == 0L) { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "x", name = XVar, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = xaxis.fontSize), axisLabel = list( rotate = xaxis.rotate, grid = list(containLabel = ContainLabel))) } else { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "x", name = Title.XAxis, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = xaxis.fontSize), axisLabel = list( rotate = xaxis.rotate, grid = list(containLabel = ContainLabel))) } if(length(Title.YAxis) == 0L) { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "y", name = YVar, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = yaxis.fontSize), axisLabel = list( rotate = yaxis.rotate, grid = list(containLabel = ContainLabel))) } else { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "y", name = Title.YAxis, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = yaxis.fontSize), axisLabel = list( rotate = yaxis.rotate, grid = list(containLabel = ContainLabel))) } p1 <- echarts4r::e_axis_(e = p1, serie = NULL, axis = "z", name = ZVar, nameLocation = "middle", nameGap = 45, nameTextStyle = list(color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = yaxis.fontSize)) p1 <- echarts4r::e_brush(e = p1) p1 <- echarts4r::e_title( p1, Title, textStyle = list( color = TextColor, fontWeight = title.fontWeight, overflow = "truncate", # "none", "truncate", "break", ellipsis = '...', fontSize = title.fontSize, textShadowColor = title.textShadowColor, textShadowBlur = title.textShadowBlur, textShadowOffsetY = title.textShadowOffsetY, textShadowOffsetX = title.textShadowOffsetX)) if(FacetRows > 1L || FacetCols > 1L) p1 <- echarts4r::e_facet(e = p1, rows = FacetRows, cols = FacetCols, legend_space = 16, legend_pos = "top") return(p1) } # XVar == numeric or integer && YVar == character if(x_num) { # rank XVar if(!PreAgg) { dt1[, eval(XVar) := round(data.table::frank(dt1[[XVar]]) * NumberBins /.N) / NumberBins] data.table::setnames(dt1, eval(ZVar), 'Measure_Variable') # Top YVar Levels temp <- dt1[, lapply(.SD, mean, na.rm = TRUE), .SDcols = c('Measure_Variable'), by = c(YVar)][order(-Measure_Variable)] temp <- temp[seq_len(min(NumLevels_Y, temp[, .N]))][[1L]] dt1 <- dt1[, lapply(.SD, noquote(aggFunc)), .SDcols = c(ZVar), by = c(XVar,YVar)] # Transformation if(ZVarTrans != "Identity") { dt1 <- AutoTransformationCreate(data = dt1, ColumnNames = "Measure_Variable", Methods = ZVarTrans)$Data } # Formatting dt1 <- dt1[get(YVar) %in% eval(temp)] vals <- unique(scales::rescale(c(dt1[['Measure_Variable']]))) o <- order(vals, decreasing = FALSE) cols <- scales::col_numeric("Purples", domain = NULL)(vals) colz <- setNames(data.frame(vals[o], cols[o]), NULL) } # Create final dt1 for plot g <- "Measure_Variable" p1 <- echarts4r::e_charts_( data = dt1, x = XVar, dispose = TRUE, darkMode = TRUE, width = Width, height = Height) if(ShowLabels) { p1 <- echarts4r::e_heatmap_(e = p1, YVar, g, itemStyle = list(emphasis = list(shadowBlur = 10)), label = list(show = TRUE)) } else { p1 <- echarts4r::e_heatmap_(e = p1, YVar, g, itemStyle = list(emphasis = list(shadowBlur = 10))) } p1 <- echarts4r::e_visual_map_(e = p1, g, show = FALSE) p1 <- echarts4r::e_theme(e = p1, name = EchartsTheme) if(MouseScroll) { p1 <- echarts4r::e_datazoom(e = p1, Type = "inside", x_index = c(0,1)) } else { p1 <- echarts4r::e_datazoom(e = p1, x_index = c(0,1)) } p1 <- echarts4r::e_aria(e = p1, enabled = TRUE) p1 <- echarts4r::e_show_loading(e = p1, hide_overlay = TRUE, text = "Calculating...", color = "#000", text_color = TextColor, mask_color = "#000") if(length(Title.XAxis) == 0L) { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "x", name = XVar, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = xaxis.fontSize), axisLabel = list( rotate = xaxis.rotate, grid = list(containLabel = ContainLabel))) } else { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "x", name = Title.XAxis, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = xaxis.fontSize), axisLabel = list( rotate = xaxis.rotate, grid = list(containLabel = ContainLabel))) } if(length(Title.YAxis) == 0L) { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "y", name = YVar, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = yaxis.fontSize), axisLabel = list( rotate = yaxis.rotate, grid = list(containLabel = ContainLabel))) } else { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "y", name = Title.YAxis, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = yaxis.fontSize), axisLabel = list( rotate = yaxis.rotate, grid = list(containLabel = ContainLabel))) } p1 <- echarts4r::e_axis_(e = p1, serie = NULL, axis = "z", name = ZVar, nameLocation = "middle", nameGap = 45, nameTextStyle = list(color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = yaxis.fontSize)) p1 <- echarts4r::e_brush(e = p1) p1 <- echarts4r::e_title( p1, Title, textStyle = list( color = TextColor, fontWeight = title.fontWeight, overflow = "truncate", # "none", "truncate", "break", ellipsis = '...', fontSize = title.fontSize, textShadowColor = title.textShadowColor, textShadowBlur = title.textShadowBlur, textShadowOffsetY = title.textShadowOffsetY, textShadowOffsetX = title.textShadowOffsetX)) if(FacetRows > 1L || FacetCols > 1L) p1 <- echarts4r::e_facet(e = p1, rows = FacetRows, cols = FacetCols, legend_space = 16, legend_pos = "top") return(p1) } # XVar == character or integer && YVar == character if(all_char) { # Starter pack if(!PreAgg) { temp1 <- dt1[, lapply(.SD, mean, na.rm = TRUE), .SDcols = c(ZVar), by = c(YVar)][order(-get(ZVar))] temp1 <- temp1[seq_len(min(NumLevels_Y, temp1[, .N]))][[1L]] temp2 <- dt1[, lapply(.SD, mean, na.rm = TRUE), .SDcols = c(ZVar), by = c(XVar)][order(-get(ZVar))] temp2 <- temp2[seq_len(min(NumLevels_X, temp2[, .N]))][[1L]] dt1 <- dt1[get(YVar) %in% eval(temp1) & get(XVar) %in% eval(temp2), lapply(.SD, noquote(aggFunc)), .SDcols = c(ZVar), by = c(XVar,YVar)] } # Transformation if(length(ZVarTrans) > 0 && ZVarTrans != "Identity") { dt1 <- AutoTransformationCreate(data = dt1, ColumnNames = ZVar, Methods = ZVarTrans)$Data } if(XVar %in% c("Predict","p1")) data.table::setorderv(x = dt1, "Predict") p1 <- echarts4r::e_charts_( data = dt1, x = XVar, dispose = TRUE, darkMode = TRUE, width = Width, height = Height) if(ShowLabels) { p1 <- echarts4r::e_bar_3d_(e = p1, YVar, ZVar, coord_system = "cartesian3D", itemStyle = list(emphasis = list(shadowBlur = 10)), label = list(show = TRUE)) } else { p1 <- echarts4r::e_bar_3d_(e = p1, YVar, ZVar, coord_system = "cartesian3D", itemStyle = list(emphasis = list(shadowBlur = 10))) } p1 <- echarts4r::e_visual_map_(e = p1, ZVar, show = FALSE) p1 <- echarts4r::e_theme(e = p1, name = EchartsTheme) # They do nothing for this plot type if(MouseScroll) { p1 <- echarts4r::e_datazoom(e = p1, Type = "inside", x_index = c(0,1)) } else { p1 <- echarts4r::e_datazoom(e = p1, x_index = c(0,1)) } p1 <- echarts4r::e_aria(e = p1, enabled = TRUE) p1 <- echarts4r::e_show_loading(e = p1, hide_overlay = TRUE, text = "Calculating...", color = "#000", text_color = TextColor, mask_color = "#000") if(length(Title.XAxis) == 0L) { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "x", name = XVar, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = xaxis.fontSize), axisLabel = list( rotate = xaxis.rotate, grid = list(containLabel = ContainLabel))) } else { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "x", name = Title.XAxis, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = xaxis.fontSize), axisLabel = list( rotate = xaxis.rotate, grid = list(containLabel = ContainLabel))) } if(length(Title.YAxis) == 0L) { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "y", name = YVar, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = yaxis.fontSize), axisLabel = list( rotate = yaxis.rotate, grid = list(containLabel = ContainLabel))) } else { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "y", name = Title.YAxis, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = yaxis.fontSize), axisLabel = list( rotate = yaxis.rotate, grid = list(containLabel = ContainLabel))) } p1 <- echarts4r::e_axis_(e = p1, serie = NULL, axis = "z", name = ZVar, nameLocation = "middle", nameGap = 45, nameTextStyle = list(color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = yaxis.fontSize)) p1 <- echarts4r::e_brush(e = p1) p1 <- echarts4r::e_title( p1, Title, textStyle = list( color = TextColor, fontWeight = title.fontWeight, overflow = "truncate", # "none", "truncate", "break", ellipsis = '...', fontSize = title.fontSize, textShadowColor = title.textShadowColor, textShadowBlur = title.textShadowBlur, textShadowOffsetY = title.textShadowOffsetY, textShadowOffsetX = title.textShadowOffsetX)) if(FacetRows > 1L || FacetCols > 1L) p1 <- echarts4r::e_facet(e = p1, rows = FacetRows, cols = FacetCols, legend_space = 16, legend_pos = "top") return(p1) } } #' @title Plot.HeatMap #' #' @description Create heat maps with numeric or categorical dt #' #' @family Standard Plots #' @author Adrian Antico #' #' @param dt source data.table #' @param YVar Y-Axis variable name #' @param XVar X-Axis variable name #' @param ZVar Z-Axis variable name #' @param YVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param XVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param ZVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param FacetRows Defaults to 1 which causes no faceting to occur vertically. Otherwise, supply a numeric value for the number of output grid rows #' @param FacetCols Defaults to 1 which causes no faceting to occur horizontally. Otherwise, supply a numeric value for the number of output grid columns #' @param FacetLevels Faceting rows x columns is the max number of levels allowed in a grid. If your GroupVar has more you can supply the levels to display. #' @param Height "400px" #' @param Width "200px" #' @param MouseScroll logical, zoom via mouse scroll #' @param EchartsTheme "dark-blue" #' @param AggMethod 'mean', 'median', 'sum', 'sd', 'coeffvar', 'count' #' @param NumberBins = 21 #' @param NumLevels_Y = 20 #' @param NumLevels_X = 20. #' @param PreAgg logical #' @param TextColor color #' @param Title "Heatmap" #' @param ShowLabels character #' @param Title.YAxis character #' @param Title.XAxis character #' @param title.fontSize 22 #' @param title.fontWeight "bold" #' @param title.textShadowColor '#63aeff' #' @param title.textShadowBlur 3 #' @param title.textShadowOffsetY 1 #' @param title.textShadowOffsetX -1 #' @param xaxis.fontSize 14 #' @param yaxis.fontSize 14 #' @param xaxis.rotate 0 #' @param yaxis.rotate 0 #' @param ContainLabel TRUE #' @param Debug Debugging parameter #' #' @examples #' # Create fake data #' data <- AutoPlots::FakeDataGenerator(N = 100000) #' #' # Echarts Heatmap Plot Chart #' AutoPlots::Plot.HeatMap( #' dt = data, #' PreAgg = FALSE, #' XVar = "Factor_1", #' YVar = "Factor_2", #' ZVar = "Independent_Variable6", #' XVarTrans = "Identity", #' ZVarTrans = "Identity", #' FacetRows = 1, #' FacetCols = 1, #' FacetLevels = NULL, #' NumberBins = 21, #' NumLevels_Y = 33, #' NumLevels_X = 33, #' Height = NULL, #' Width = NULL, #' Title = "Heatmap", #' ShowLabels = FALSE, #' Title.YAxis = NULL, #' Title.XAxis = NULL, #' EchartsTheme = "macarons", #' MouseScroll = TRUE, #' TextColor = "black", #' title.fontSize = 22, #' title.fontWeight = "bold", #' title.textShadowColor = '#63aeff', #' title.textShadowBlur = 3, #' title.textShadowOffsetY = 1, #' title.textShadowOffsetX = -1, #' yaxis.fontSize = 14, #' xaxis.fontSize = 14, #' xaxis.rotate = 0, #' yaxis.rotate = 0, #' ContainLabel = TRUE, #' Debug = FALSE) #' #' @return plot #' @export Plot.HeatMap <- function(dt, PreAgg = FALSE, AggMethod = 'mean', XVar = NULL, YVar = NULL, ZVar = NULL, YVarTrans = "Identity", XVarTrans = "Identity", ZVarTrans = "Identity", FacetRows = 1, FacetCols = 1, FacetLevels = NULL, NumberBins = 21, NumLevels_Y = 33, NumLevels_X = 33, Height = NULL, Width = NULL, Title = "Heatmap", ShowLabels = FALSE, Title.YAxis = NULL, Title.XAxis = NULL, EchartsTheme = "dark", MouseScroll = TRUE, TextColor = "white", title.fontSize = 22, title.fontWeight = "bold", title.textShadowColor = '#63aeff', title.textShadowBlur = 3, title.textShadowOffsetY = 1, title.textShadowOffsetX = -1, yaxis.fontSize = 14, xaxis.fontSize = 14, xaxis.rotate = 0, yaxis.rotate = 0, ContainLabel = TRUE, Debug = FALSE) { if(!data.table::is.data.table(dt)) tryCatch({data.table::setDT(dt)}, error = function(x) { dt <- data.table::as.data.table(dt) }) # Convert factor to character if(length(ZVar) > 0L && class(dt[[ZVar]])[1L] %in% c("factor","character")) { dt[, eval(ZVar) := as.numeric(get(ZVar))] } if(length(XVar) > 0L && class(dt[[XVar]])[1L] == "factor") { dt[, eval(XVar) := as.character(get(XVar))] } if(length(YVar) > 0L && class(dt[[YVar]])[1L] == "factor") { dt[, eval(YVar) := as.character(get(YVar))] } # Subset cols dt1 <- dt[, .SD, .SDcols = c(XVar,YVar,ZVar)] x_check <- class(dt1[[XVar]])[1L] %in% c('numeric','integer') y_check <- class(dt1[[YVar]])[1L] %in% c('numeric','integer') x_y_num <- x_check && y_check x_num <- x_check && !y_check x_char <- !x_check && y_check all_char <- !x_check && !y_check Z.HoverFormat <- "%{zaxis.title.text}: %{y:,.2f}<br>" # XVar == numeric or integer && YVar == numeric or integer if(x_y_num) { # rank XVar and YVar if(!PreAgg) { dt1[, eval(XVar) := round(data.table::frank(dt1[[XVar]]) * NumberBins /.N) / NumberBins] dt1[, eval(YVar) := round(data.table::frank(dt1[[YVar]]) * NumberBins /.N) / NumberBins] } # Transformation if(ZVarTrans != "Identity") { dt1 <- AutoTransformationCreate(data = dt1, ColumnNames = ZVar, Methods = ZVarTrans)$Data } # Formatting vals <- unique(scales::rescale(c(dt1[[ZVar]]))) o <- order(vals, decreasing = FALSE) cols <- scales::col_numeric("Purples", domain = NULL)(vals) colz <- setNames(data.frame(vals[o], cols[o]), NULL) data.table::setnames(dt1, ZVar, "Measure_Variable") data.table::setorderv(x = dt1, cols = c(XVar,YVar),c(1L,1L)) # Create final data for plot g <- "Measure_Variable" p1 <- echarts4r::e_charts_( data = dt1, x = XVar, darkMode = TRUE, width = Width, height = Height)#, dispose = TRUE) if(ShowLabels) { p1 <- echarts4r::e_heatmap_(e = p1, YVar, g, itemStyle = list(emphasis = list(shadowBlur = 10)), label = list(show = TRUE)) } else { p1 <- echarts4r::e_heatmap_(e = p1, YVar, g, itemStyle = list(emphasis = list(shadowBlur = 10))) } if(MouseScroll) { p1 <- echarts4r::e_datazoom(e = p1, Type = "inside", x_index = c(0,1)) } else { p1 <- echarts4r::e_datazoom(e = p1, x_index = c(0,1)) } p1 <- echarts4r::e_visual_map_(e = p1, g, show = FALSE) p1 <- echarts4r::e_tooltip(e = p1, trigger = "axis", backgroundColor = "aliceblue") p1 <- echarts4r::e_theme(e = p1, name = EchartsTheme) p1 <- echarts4r::e_aria(e = p1, enabled = TRUE) p1 <- echarts4r::e_toolbox_feature(e = p1, feature = c("saveAsImage","dataZoom")) p1 <- echarts4r::e_show_loading(e = p1, hide_overlay = TRUE, text = "Calculating...", color = "#000", text_color = TextColor, mask_color = "#000") if(length(Title.XAxis) == 0L) { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "x", name = XVar, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = xaxis.fontSize), axisLabel = list( rotate = xaxis.rotate, grid = list(containLabel = ContainLabel))) } else { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "x", name = Title.XAxis, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = xaxis.fontSize), axisLabel = list( rotate = xaxis.rotate, grid = list(containLabel = ContainLabel))) } if(length(Title.YAxis) == 0L) { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "y", name = YVar, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = yaxis.fontSize), axisLabel = list( rotate = yaxis.rotate, grid = list(containLabel = ContainLabel))) } else { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "y", name = Title.YAxis, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = yaxis.fontSize), axisLabel = list( rotate = yaxis.rotate, grid = list(containLabel = ContainLabel))) } p1 <- echarts4r::e_axis_(e = p1, serie = NULL, axis = "z", name = ZVar, nameLocation = "middle", nameGap = 45, nameTextStyle = list(color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = yaxis.fontSize)) p1 <- echarts4r::e_brush(e = p1) p1 <- echarts4r::e_title( p1, Title, textStyle = list( color = TextColor, fontWeight = title.fontWeight, overflow = "truncate", ellipsis = '...', fontSize = title.fontSize, textShadowColor = title.textShadowColor, textShadowBlur = title.textShadowBlur, textShadowOffsetY = title.textShadowOffsetY, textShadowOffsetX = title.textShadowOffsetX)) return(p1) } # XVar == character && YVar == numeric or integer if(x_char) { # rank YVar if(!PreAgg) { dt1[, eval(YVar) := round(data.table::frank(dt1[[YVar]]) * NumberBins /.N) / NumberBins] data.table::setnames(dt1, eval(ZVar), 'Measure_Variable') # Top XVar Levels temp <- dt1[, lapply(.SD, mean, na.rm = TRUE), .SDcols = c('Measure_Variable'), by = c(XVar)][order(-Measure_Variable)] temp <- temp[seq_len(min(NumLevels_X, temp[, .N]))][[1L]] dt1 <- dt1[get(XVar) %in% eval(temp)] # Transformation if(ZVarTrans != "Identity") { dt1 <- AutoTransformationCreate(data = dt1, ColumnNames = "Measure_Variable", Methods = ZVarTrans)$Data } # Formatting vals <- unique(scales::rescale(c(dt1[['Measure_Variable']]))) o <- order(vals, decreasing = FALSE) cols <- scales::col_numeric("Purples", domain = NULL)(vals) colz <- setNames(data.frame(vals[o], cols[o]), NULL) } # Create final data for plot g <- "Measure_Variable" p1 <- echarts4r::e_charts_( data = dt1, x = XVar, darkMode = TRUE, dispose = TRUE, width = Width, height = Height) if(ShowLabels) { p1 <- echarts4r::e_heatmap_(e = p1, YVar, g, itemStyle = list(emphasis = list(shadowBlur = 10)), label = list(show = TRUE)) } else { p1 <- echarts4r::e_heatmap_(e = p1, YVar, g, itemStyle = list(emphasis = list(shadowBlur = 10))) } p1 <- echarts4r::e_visual_map_(e = p1, g, show = FALSE) if(MouseScroll && FacetRows == 1L && FacetCols == 1L) { p1 <- echarts4r::e_datazoom(e = p1, type = "inside", x_index = c(0,1)) } else if(MouseScroll && (FacetRows > 1L || FacetCols > 1L)) { p1 <- echarts4r::e_datazoom(e = p1, type = "inside", x_index = seq(0, FacetRows * FacetCols - 1, 1)) } else { p1 <- echarts4r::e_datazoom(e = p1, x_index = c(0,1)) } p1 <- echarts4r::e_theme(e = p1, name = EchartsTheme) p1 <- echarts4r::e_aria(e = p1, enabled = TRUE) p1 <- echarts4r::e_show_loading(e = p1, hide_overlay = TRUE, text = "Calculating...", color = "#000", text_color = TextColor, mask_color = "#000") if(length(Title.XAxis) == 0L) { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "x", name = XVar, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = xaxis.fontSize), axisLabel = list( rotate = xaxis.rotate, grid = list(containLabel = ContainLabel))) } else { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "x", name = Title.XAxis, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = xaxis.fontSize), axisLabel = list( rotate = xaxis.rotate, grid = list(containLabel = ContainLabel))) } if(length(Title.YAxis) == 0L) { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "y", name = YVar, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = yaxis.fontSize), axisLabel = list( rotate = yaxis.rotate, grid = list(containLabel = ContainLabel))) } else { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "y", name = Title.YAxis, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = yaxis.fontSize), axisLabel = list( rotate = yaxis.rotate, grid = list(containLabel = ContainLabel))) } p1 <- echarts4r::e_axis_(e = p1, serie = NULL, axis = "z", name = ZVar, nameLocation = "middle", nameGap = 45, nameTextStyle = list(color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = yaxis.fontSize)) p1 <- echarts4r::e_brush(e = p1) p1 <- echarts4r::e_tooltip(e = p1, trigger = "axis", backgroundColor = "aliceblue") p1 <- echarts4r::e_title( p1, Title, textStyle = list( color = TextColor, fontWeight = title.fontWeight, overflow = "truncate", # "none", "truncate", "break", ellipsis = '...', fontSize = title.fontSize, textShadowColor = title.textShadowColor, textShadowBlur = title.textShadowBlur, textShadowOffsetY = title.textShadowOffsetY, textShadowOffsetX = title.textShadowOffsetX)) return(p1) } # XVar == numeric or integer && YVar == character if(x_num) { # rank XVar if(!PreAgg) { dt1[, eval(XVar) := round(data.table::frank(dt1[[XVar]]) * NumberBins /.N) / NumberBins] data.table::setnames(dt1, eval(ZVar), 'Measure_Variable') # Top YVar Levels temp <- dt1[, lapply(.SD, mean, na.rm = TRUE), .SDcols = c('Measure_Variable'), by = c(YVar)][order(-Measure_Variable)] temp <- temp[seq_len(min(NumLevels_Y, temp[, .N]))][[1L]] # Transformation if(ZVarTrans != "Identity") { dt1 <- AutoTransformationCreate(data = dt1, ColumnNames = "Measure_Variable", Methods = ZVarTrans)$Data } # Formatting dt1 <- dt1[get(YVar) %in% eval(temp)] vals <- unique(scales::rescale(c(dt1[['Measure_Variable']]))) o <- order(vals, decreasing = FALSE) cols <- scales::col_numeric("Purples", domain = NULL)(vals) colz <- setNames(data.frame(vals[o], cols[o]), NULL) } # Create final dt1 for plot g <- "Measure_Variable" p1 <- echarts4r::e_charts_( data = dt1, x = XVar, dispose = TRUE, darkMode = TRUE, width = Width, height = Height) if(ShowLabels) { p1 <- echarts4r::e_heatmap_(e = p1, YVar, g, itemStyle = list(emphasis = list(shadowBlur = 10)), label = list(show = TRUE)) } else { p1 <- echarts4r::e_heatmap_(e = p1, YVar, g, itemStyle = list(emphasis = list(shadowBlur = 10))) } p1 <- echarts4r::e_visual_map_(e = p1, g, show = FALSE) p1 <- echarts4r::e_theme(e = p1, name = EchartsTheme) if(MouseScroll) { p1 <- echarts4r::e_datazoom(e = p1, Type = "inside", x_index = c(0,1)) } else { p1 <- echarts4r::e_datazoom(e = p1, x_index = c(0,1)) } p1 <- echarts4r::e_aria(e = p1, enabled = TRUE) p1 <- echarts4r::e_show_loading(e = p1, hide_overlay = TRUE, text = "Calculating...", color = "#000", text_color = TextColor, mask_color = "#000") if(length(Title.XAxis) == 0L) { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "x", name = XVar, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = xaxis.fontSize), axisLabel = list( rotate = xaxis.rotate, grid = list(containLabel = ContainLabel))) } else { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "x", name = Title.XAxis, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = xaxis.fontSize), axisLabel = list( rotate = xaxis.rotate, grid = list(containLabel = ContainLabel))) } if(length(Title.YAxis) == 0L) { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "y", name = YVar, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = yaxis.fontSize), axisLabel = list( rotate = yaxis.rotate, grid = list(containLabel = ContainLabel))) } else { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "y", name = Title.YAxis, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = yaxis.fontSize), axisLabel = list( rotate = yaxis.rotate, grid = list(containLabel = ContainLabel))) } p1 <- echarts4r::e_axis_(e = p1, serie = NULL, axis = "z", name = ZVar, nameLocation = "middle", nameGap = 45, nameTextStyle = list(color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = yaxis.fontSize)) p1 <- echarts4r::e_brush(e = p1) p1 <- echarts4r::e_tooltip(e = p1, trigger = "axis", backgroundColor = "aliceblue") p1 <- echarts4r::e_title( p1, Title, textStyle = list( color = TextColor, fontWeight = title.fontWeight, overflow = "truncate", # "none", "truncate", "break", ellipsis = '...', fontSize = title.fontSize, textShadowColor = title.textShadowColor, textShadowBlur = title.textShadowBlur, textShadowOffsetY = title.textShadowOffsetY, textShadowOffsetX = title.textShadowOffsetX)) return(p1) } # XVar == character or integer && YVar == character if(all_char) { # Starter pack if(!PreAgg) { if(Debug) print("Echarts PreAgg 1") if(AggMethod == 'mean') { temp_y <- dt1[, lapply(.SD, mean, na.rm = TRUE), .SDcols = c(ZVar), by = c(YVar)][order(-get(ZVar))] temp_x <- dt1[, lapply(.SD, mean, na.rm = TRUE), .SDcols = c(ZVar), by = c(XVar)][order(-get(ZVar))] temp_yy <- temp_y[seq_len(min(NumLevels_X, temp_y[, .N]))][[1L]] temp_xx <- temp_x[seq_len(min(NumLevels_Y, temp_x[, .N]))][[1L]] dt1 <- dt1[get(YVar) %in% eval(temp_yy) & get(XVar) %in% eval(temp_xx)] dt1 <- dt1[, lapply(.SD, mean, na.rm = TRUE), .SDcols = c(ZVar), by = c(XVar,YVar)] } else if(AggMethod == 'median') { temp_y <- dt1[, lapply(.SD, median, na.rm = TRUE), .SDcols = c(ZVar), by = c(YVar)][order(-get(ZVar))] temp_x <- dt1[, lapply(.SD, median, na.rm = TRUE), .SDcols = c(ZVar), by = c(XVar)][order(-get(ZVar))] temp_y <- temp_y[seq_len(min(NumLevels_X, temp_y[, .N]))][[1L]] temp_x <- temp_x[seq_len(min(NumLevels_Y, temp_x[, .N]))][[1L]] dt1 <- dt1[get(YVar) %in% eval(temp_y) & get(XVar) %in% eval(temp_x)] dt1 <- dt1[, lapply(.SD, median, na.rm = TRUE), .SDcols = c(ZVar), by = c(XVar,YVar)] } else if(AggMethod == 'sum') { temp_y <- dt1[, lapply(.SD, sum, na.rm = TRUE), .SDcols = c(ZVar), by = c(YVar)][order(-get(ZVar))] temp_x <- dt1[, lapply(.SD, sum, na.rm = TRUE), .SDcols = c(ZVar), by = c(XVar)][order(-get(ZVar))] temp_y <- temp_y[seq_len(min(NumLevels_X, temp_y[, .N]))][[1L]] temp_x <- temp_x[seq_len(min(NumLevels_Y, temp_x[, .N]))][[1L]] dt1 <- dt1[get(YVar) %in% eval(temp_y) & get(XVar) %in% eval(temp_x)] dt1 <- dt1[, lapply(.SD, sum, na.rm = TRUE), .SDcols = c(ZVar), by = c(XVar,YVar)] } else if(AggMethod == 'sd') { temp_y <- dt1[, lapply(.SD, sd, na.rm = TRUE), .SDcols = c(ZVar), by = c(YVar)][order(-get(ZVar))] temp_x <- dt1[, lapply(.SD, sd, na.rm = TRUE), .SDcols = c(ZVar), by = c(XVar)][order(-get(ZVar))] temp_y <- temp_y[seq_len(min(NumLevels_X, temp_y[, .N]))][[1L]] temp_x <- temp_x[seq_len(min(NumLevels_Y, temp_x[, .N]))][[1L]] dt1 <- dt1[get(YVar) %in% eval(temp_y) & get(XVar) %in% eval(temp_x)] dt1 <- dt1[, lapply(.SD, sd, na.rm = TRUE), .SDcols = c(ZVar), by = c(XVar,YVar)] } else if(AggMethod == 'coeffvar') { temp_y <- dt1[, lapply(.SD, .N, na.rm = TRUE), .SDcols = c(ZVar), by = c(YVar)][order(-get(ZVar))] temp_x <- dt1[, lapply(.SD, .N, na.rm = TRUE), .SDcols = c(ZVar), by = c(XVar)][order(-get(ZVar))] temp_y <- temp_y[seq_len(min(NumLevels_X, temp_y[, .N]))][[1L]] temp_x <- temp_x[seq_len(min(NumLevels_Y, temp_x[, .N]))][[1L]] dt1 <- dt1[get(YVar) %in% eval(temp_y) & get(XVar) %in% eval(temp_x)] dt1 <- dt1[, lapply(.SD, .N, na.rm = TRUE), .SDcols = c(ZVar), by = c(XVar,YVar)] } else if(AggMethod == 'count') { temp_y <- dt1[, lapply(.SD, .N, na.rm = TRUE), .SDcols = c(ZVar), by = c(YVar)][order(-get(ZVar))] temp_x <- dt1[, lapply(.SD, .N, na.rm = TRUE), .SDcols = c(ZVar), by = c(XVar)][order(-get(ZVar))] temp_y <- temp_y[seq_len(min(NumLevels_X, temp_y[, .N]))][[1L]] temp_x <- temp_x[seq_len(min(NumLevels_Y, temp_x[, .N]))][[1L]] dt1 <- dt1[get(YVar) %in% eval(temp_y) & get(XVar) %in% eval(temp_x)] dt1 <- dt1[, lapply(.SD, .N, na.rm = TRUE), .SDcols = c(ZVar), by = c(XVar,YVar)] } } # Transformation if(ZVarTrans != "Identity") { dt1 <- AutoTransformationCreate(data = dt1, ColumnNames = ZVar, Methods = ZVarTrans)$Data } # Create final dt1 for plot if(XVar %in% c("Predict","p1")) data.table::setorderv(x = dt1, "Predict") p1 <- echarts4r::e_charts_( data = dt1, x = XVar, dispose = TRUE, darkMode = TRUE, width = Width, height = Height) if(ShowLabels) { p1 <- echarts4r::e_heatmap_(e = p1, YVar, ZVar, itemStyle = list(emphasis = list(shadowBlur = 10)), label = list(show = TRUE)) } else { p1 <- echarts4r::e_heatmap_(e = p1, YVar, ZVar, itemStyle = list(emphasis = list(shadowBlur = 10))) } p1 <- echarts4r::e_visual_map_(e = p1, ZVar, show = FALSE) p1 <- echarts4r::e_theme(e = p1, name = EchartsTheme) if(MouseScroll) { p1 <- echarts4r::e_datazoom(e = p1, Type = "inside", x_index = c(0,1)) } else { p1 <- echarts4r::e_datazoom(e = p1, x_index = c(0,1)) } p1 <- echarts4r::e_aria(e = p1, enabled = TRUE) p1 <- echarts4r::e_show_loading(e = p1, hide_overlay = TRUE, text = "Calculating...", color = "#000", text_color = TextColor, mask_color = "#000") if(length(Title.XAxis) == 0L) { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "x", name = XVar, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = xaxis.fontSize), axisLabel = list( rotate = xaxis.rotate, grid = list(containLabel = ContainLabel))) } else { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "x", name = Title.XAxis, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = xaxis.fontSize), axisLabel = list( rotate = xaxis.rotate, grid = list(containLabel = ContainLabel))) } if(length(Title.YAxis) == 0L) { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "y", name = YVar, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = yaxis.fontSize), axisLabel = list( rotate = yaxis.rotate, grid = list(containLabel = ContainLabel))) } else { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "y", name = Title.YAxis, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = yaxis.fontSize), axisLabel = list( rotate = yaxis.rotate, grid = list(containLabel = ContainLabel))) } p1 <- echarts4r::e_brush(e = p1) p1 <- echarts4r::e_tooltip(e = p1, trigger = "axis", backgroundColor = "aliceblue") p1 <- echarts4r::e_title( p1, Title, textStyle = list( color = TextColor, fontWeight = title.fontWeight, overflow = "truncate", # "none", "truncate", "break", ellipsis = '...', fontSize = title.fontSize, textShadowColor = title.textShadowColor, textShadowBlur = title.textShadowBlur, textShadowOffsetY = title.textShadowOffsetY, textShadowOffsetX = title.textShadowOffsetX)) return(p1) } } # ---- # ---- # @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ---- # > Relationships Plot Functions ---- # @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ---- #' @title Plot.CorrMatrix #' #' @description Build a correlation matrix plot by simply passing arguments to a single function. It will sample your data using SampleSize number of rows. Sampled data is randomized. #' #' @family Standard Plots #' #' @author Adrian Antico #' #' @param dt source data.table #' @param CorrVars vector of variable names #' @param CorrVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param FacetRows Defaults to 1 which causes no faceting to occur vertically. Otherwise, supply a numeric value for the number of output grid rows #' @param FacetCols Defaults to 1 which causes no faceting to occur horizontally. Otherwise, supply a numeric value for the number of output grid columns #' @param FacetLevels Faceting rows x columns is the max number of levels allowed in a grid. If your GroupVar has more you can supply the levels to display. #' @param Method character #' @param MaxNAPercent numeric #' @param Height "400px" #' @param Width "200px" #' @param Title character #' @param ShowLabels character #' @param Title.YAxis character #' @param Title.XAxis character #' @param EchartsTheme "auritus","azul","bee-inspired","blue","caravan","carp","chalk","cool","dark-bold","dark","eduardo", #' "essos","forest","fresh-cut","fruit","gray","green","halloween","helianthus","infographic","inspired", #' "jazz","london","dark","macarons","macarons2","mint","purple-passion","red-velvet","red","roma","royal", #' "sakura","shine","tech-blue","vintage","walden","wef","weforum","westeros","wonderland" #' @param MouseScroll logical, zoom via mouse scroll #' @param PreAgg logical #' @param TextColor character hex #' @param title.fontSize 22 #' @param title.fontWeight "bold" #' @param title.textShadowColor '#63aeff' #' @param title.textShadowBlur 3 #' @param title.textShadowOffsetY 1 #' @param title.textShadowOffsetX -1 #' @param xaxis.fontSize 14 #' @param yaxis.fontSize 14 #' @param Debug Debugging purposes #' #' @examples #' # Create fake data #' data <- AutoPlots::FakeDataGenerator(N = 100000) #' #' # Echarts CorrMatrix Plot Chart #' AutoPlots::Plot.CorrMatrix( #' dt = data, #' CorrVars = c( #' "Adrian", #' "Independent_Variable1", #' "Independent_Variable2", #' "Independent_Variable3", #' "Independent_Variable4", #' "Independent_Variable5"), #' CorrVarTrans = "Identity", #' FacetRows = 1, #' FacetCols = 1, #' FacetLevels = NULL, #' Method = 'pearson', #' PreAgg = FALSE, #' MaxNAPercent = 0.05, #' Height = NULL, #' Width = NULL, #' Title = "Correlation Matrix", #' ShowLabels = FALSE, #' Title.YAxis = NULL, #' Title.XAxis = NULL, #' EchartsTheme = "macarons", #' MouseScroll = TRUE, #' TextColor = "black", #' title.fontSize = 22, #' title.fontWeight = "bold", #' title.textShadowColor = '#63aeff', #' title.textShadowBlur = 3, #' title.textShadowOffsetY = 1, #' title.textShadowOffsetX = -1, #' yaxis.fontSize = 14, #' xaxis.fontSize = 14, #' Debug = FALSE) #' #' @return plot #' @export Plot.CorrMatrix <- function(dt = NULL, CorrVars = NULL, CorrVarTrans = "Identity", FacetRows = 1, FacetCols = 1, FacetLevels = NULL, Method = 'spearman', PreAgg = FALSE, MaxNAPercent = 0.05, Height = NULL, Width = NULL, Title = "Correlation Matrix", ShowLabels = FALSE, Title.YAxis = NULL, Title.XAxis = NULL, EchartsTheme = "macarons", MouseScroll = TRUE, TextColor = "white", title.fontSize = 22, title.fontWeight = "bold", title.textShadowColor = '#63aeff', title.textShadowBlur = 3, title.textShadowOffsetY = 1, title.textShadowOffsetX = -1, yaxis.fontSize = 14, xaxis.fontSize = 14, Debug = FALSE) { # Filter out bad vars x <- c(); for(i in CorrVars) if(dt[, sd(get(i), na.rm = TRUE)] > 0L) x <- c(x, i) CorrVars <- x NN <- dt[,.N] x <- c(); for(i in CorrVars) if(sum(dt[, is.na(get(i))]) / NN <= MaxNAPercent) x <- c(x, i) CorrVars <- x # Plot if(!PreAgg) { if(!data.table::is.data.table(dt)) tryCatch({data.table::setDT(dt)}, error = function(x) { dt <- data.table::as.data.table(dt) }) dt1 <- na.omit(dt[, .SD, .SDcols = c(CorrVars)]) # Transformation if(CorrVarTrans != "Identity") { dt1 <- AutoTransformationCreate(data = dt1, ColumnNames = CorrVars, Methods = CorrVarTrans)$Data } for(i in seq_along(names(dt1))) { yy <- names(dt1)[i] zz <- nchar(yy) data.table::setnames(dt1, yy, substr(x = yy, start = max(0L, zz - 40L), stop = nchar(yy))) } corr_mat <- cor(method = tolower(Method), x = dt1) } else { corr_mat <- dt } if(Debug) { print("Plot.CorrMatrix Echarts") print(Width) print(Height) print(corr_mat) } p1 <- echarts4r::e_charts(data = corr_mat, width = Width, height = Height) p1 <- echarts4r::e_correlations(e = p1, order = "hclust") p1 <- echarts4r::e_tooltip(e = p1, trigger = "axis", backgroundColor = "aliceblue") if(MouseScroll && FacetRows == 1L && FacetCols == 1L) { p1 <- echarts4r::e_datazoom(e = p1, type = "inside", x_index = c(0,1)) } else if(MouseScroll && (FacetRows > 1L || FacetCols > 1L)) { p1 <- echarts4r::e_datazoom(e = p1, type = "inside", x_index = seq(0, FacetRows * FacetCols - 1, 1)) } else { p1 <- echarts4r::e_datazoom(e = p1, x_index = c(0,1)) } p1 <- echarts4r::e_theme(e = p1, name = EchartsTheme) p1 <- echarts4r::e_aria(e = p1, enabled = TRUE) p1 <- echarts4r::e_toolbox_feature(e = p1, feature = c("saveAsImage","dataZoom")) p1 <- echarts4r::e_show_loading(e = p1, hide_overlay = TRUE, text = "Calculating...", color = "#000", text_color = TextColor, mask_color = "#000") p1 <- echarts4r::e_brush(e = p1) p1 <- echarts4r::e_title( p1, Title, textStyle = list( color = TextColor, fontWeight = title.fontWeight, overflow = "truncate", # "none", "truncate", "break", ellipsis = '...', fontSize = title.fontSize, textShadowColor = title.textShadowColor, textShadowBlur = title.textShadowBlur, textShadowOffsetY = title.textShadowOffsetY, textShadowOffsetX = title.textShadowOffsetX)) # Return plot return(p1) } #' @title Plot.Parallel #' #' @description Build a parallel plot by simply passing arguments to a single function. It will sample your data using SampleSize number of rows. Sampled data is randomized. #' #' @family Standard Plots #' #' @author Adrian Antico #' #' @param dt source data.table #' @param SampleSize Sample size #' @param CorrVars vector of variable names #' @param FacetRows Defaults to 1 which causes no faceting to occur vertically. Otherwise, supply a numeric value for the number of output grid rows #' @param FacetCols Defaults to 1 which causes no faceting to occur horizontally. Otherwise, supply a numeric value for the number of output grid columns #' @param FacetLevels Faceting rows x columns is the max number of levels allowed in a grid. If your GroupVar has more you can supply the levels to display. #' @param Height "400px" #' @param Width "200px" #' @param Title character #' @param ShowLabels character #' @param Title.YAxis character #' @param Title.XAxis character #' @param EchartsTheme "auritus","azul","bee-inspired","blue","caravan","carp","chalk","cool","dark-bold","dark","eduardo", #' "essos","forest","fresh-cut","fruit","gray","green","halloween","helianthus","infographic","inspired", #' "jazz","london","dark","macarons","macarons2","mint","purple-passion","red-velvet","red","roma","royal", #' "sakura","shine","tech-blue","vintage","walden","wef","weforum","westeros","wonderland" #' @param MouseScroll logical, zoom via mouse scroll #' @param PreAgg logical #' @param TextColor character hex #' @param title.fontSize 22 #' @param title.fontWeight "bold" #' @param title.textShadowColor '#63aeff' #' @param title.textShadowBlur 3 #' @param title.textShadowOffsetY 1 #' @param title.textShadowOffsetX -1 #' @param xaxis.fontSize 14 #' @param yaxis.fontSize 14 #' @param Debug Debugging purposes #' #' @examples #' # Create data #' dt = AutoPlots::FakeDataGenerator(N = 100000) #' #' # Create plot #' AutoPlots::Plot.Parallel( #' dt = dt, #' SampleSize = 1000, #' CorrVars = c("Independent_Variable3", #' "Independent_Variable4", #' "Independent_Variable5", #' "Independent_Variable6", #' "Independent_Variable7"), #' FacetRows = 1, #' FacetCols = 1, #' FacetLevels = NULL, #' PreAgg = FALSE, #' Height = NULL, #' Width = NULL, #' Title = "Parallel Plot", #' ShowLabels = FALSE, #' Title.YAxis = NULL, #' Title.XAxis = NULL, #' EchartsTheme = "macarons", #' MouseScroll = TRUE, #' TextColor = "black", #' title.fontSize = 22, #' title.fontWeight = "bold", #' title.textShadowColor = '#63aeff', #' title.textShadowBlur = 3, #' title.textShadowOffsetY = 1, #' title.textShadowOffsetX = -1, #' yaxis.fontSize = 14, #' xaxis.fontSize = 14, #' Debug = FALSE) #' #' @return plot #' @export Plot.Parallel <- function(dt = NULL, SampleSize = 50000, CorrVars = NULL, FacetRows = 1, FacetCols = 1, FacetLevels = NULL, PreAgg = FALSE, Height = NULL, Width = NULL, Title = "Parallel Plot", ShowLabels = FALSE, Title.YAxis = NULL, Title.XAxis = NULL, EchartsTheme = "macarons", MouseScroll = TRUE, TextColor = "white", title.fontSize = 22, title.fontWeight = "bold", title.textShadowColor = '#63aeff', title.textShadowBlur = 3, title.textShadowOffsetY = 1, title.textShadowOffsetX = -1, yaxis.fontSize = 14, xaxis.fontSize = 14, Debug = FALSE) { if(!data.table::is.data.table(dt)) tryCatch({data.table::setDT(dt)}, error = function(x) { dt <- data.table::as.data.table(dt) }) # Plot if(!PreAgg) { if(!data.table::is.data.table(dt)) tryCatch({data.table::setDT(dt)}, error = function(x) { dt <- data.table::as.data.table(dt) }) dt1 <- na.omit(dt[, .SD, .SDcols = c(CorrVars)]) } else { dt1 <- dt } if(length(SampleSize) > 0L && dt1[,.N] > SampleSize) { dt1 <- dt1[order(runif(.N))][seq_len(SampleSize)] } if(Debug) { print("Plot.CorrMatrix Echarts") print(Width) print(Height) } # Names modification: because of the parse() I can't have spaces in the colnames old <- c() new <- c() for(i in seq_along(CorrVars)) { if(grepl(pattern = " ", x = CorrVars[i])) { old <- c(old, CorrVars[i]) new <- c(new, gsub(pattern = " ", replacement = ".", x = CorrVars[i])) } } if(length(new) > 0L) { CorrVars <- new data.table::setnames(dt1, old = old, new = new) } # Build Plot p1 <- echarts4r::e_charts(data = dt1, width = Width, height = Height) # Metaprog because issue with function accepting vector of names p1 <- eval( parse( text = c( "echarts4r::e_parallel_(e = p1, ", noquote( c( paste0(CorrVars[seq_len(length(CorrVars)-1L)], collpase = ","), CorrVars[length(CorrVars)]) ), ", opts = list(smooth = TRUE))" ) ) ) # Warning message: # Using an external vector in selections was deprecated in tidyselect 1.1.0. # ℹ Please use `all_of()` or `any_of()` instead. # # Was: # data %>% select(v) # # # Now: # data %>% select(all_of(v)) # # See <https://tidyselect.r-lib.org/reference/faq-external-vector.html>. # This warning is displayed once every 8 hours. # Call `lifecycle::last_lifecycle_warnings()` to see where this warning was generated. p1 <- echarts4r::e_tooltip(e = p1, trigger = "axis", backgroundColor = "aliceblue") if(MouseScroll && FacetRows == 1L && FacetCols == 1L) { p1 <- echarts4r::e_datazoom(e = p1, type = "inside", x_index = c(0,1)) } else if(MouseScroll && (FacetRows > 1L || FacetCols > 1L)) { p1 <- echarts4r::e_datazoom(e = p1, type = "inside", x_index = seq(0, FacetRows * FacetCols - 1, 1)) } else { p1 <- echarts4r::e_datazoom(e = p1, x_index = c(0,1)) } p1 <- echarts4r::e_theme(e = p1, name = EchartsTheme) p1 <- echarts4r::e_aria(e = p1, enabled = TRUE) p1 <- echarts4r::e_toolbox_feature(e = p1, feature = c("saveAsImage","dataZoom")) p1 <- echarts4r::e_show_loading(e = p1, hide_overlay = TRUE, text = "Calculating...", color = "#000", text_color = TextColor, mask_color = "#000") p1 <- echarts4r::e_brush(e = p1) p1 <- echarts4r::e_title( p1, Title, textStyle = list( color = TextColor, fontWeight = title.fontWeight, overflow = "truncate", # "none", "truncate", "break", ellipsis = '...', fontSize = title.fontSize, textShadowColor = title.textShadowColor, textShadowBlur = title.textShadowBlur, textShadowOffsetY = title.textShadowOffsetY, textShadowOffsetX = title.textShadowOffsetX)) # Return plot return(p1) } #' @title Plot.Copula #' #' @description Build a copula plot by simply passing arguments to a single function. It will sample your data using SampleSize number of rows. Sampled data is randomized. #' #' @family Standard Plots #' #' @author Adrian Antico #' @param dt source data.table #' @param SampleSize An integer for the number of rows to use. Sampled data is randomized. If NULL then ignored #' @param YVar Y-Axis variable name #' @param XVar X-Axis variable name #' @param GroupVar Requires an XVar and YVar already be defined #' @param YVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param XVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param FacetRows Defaults to 1 which causes no faceting to occur vertically. Otherwise, supply a numeric value for the number of output grid rows #' @param FacetCols Defaults to 1 which causes no faceting to occur horizontally. Otherwise, supply a numeric value for the number of output grid columns #' @param FacetLevels Faceting rows x columns is the max number of levels allowed in a grid. If your GroupVar has more you can supply the levels to display. #' @param Height "400px" #' @param Width "200px" #' @param Title 'Copula Plot' #' @param ShowLabels character #' @param Title.YAxis character #' @param Title.XAxis character #' @param AddGLM logical #' @param EchartsTheme = "dark-blue", #' @param TimeLine Logical #' @param MouseScroll logical, zoom via mouse scroll #' @param TextColor 'darkblue' #' @param title.fontSize 22 #' @param title.fontWeight "bold" #' @param title.textShadowColor '#63aeff' #' @param title.textShadowBlur 3 #' @param title.textShadowOffsetY 1 #' @param title.textShadowOffsetX -1 #' @param xaxis.fontSize 14 #' @param yaxis.fontSize 14 #' @param xaxis.rotate 0 #' @param yaxis.rotate 0 #' @param ContainLabel TRUE #' @param Debug Debugging purposes #' #' @examples #' # Create fake data #' data <- AutoPlots::FakeDataGenerator(N = 100000) #' #' # Echarts Copula Plot Chart #' AutoPlots::Plot.Copula( #' dt = data, #' SampleSize = 10000, #' XVar = "Independent_Variable8", #' YVar = "Adrian", #' GroupVar = NULL, #' YVarTrans = "Identity", #' XVarTrans = "Identity", #' FacetRows = 1, #' FacetCols = 1, #' FacetLevels = NULL, #' Height = NULL, #' Width = NULL, #' Title = 'Copula Plot', #' ShowLabels = FALSE, #' AddGLM = FALSE, #' Title.YAxis = NULL, #' Title.XAxis = NULL, #' EchartsTheme = "macarons", #' MouseScroll = TRUE, #' TimeLine = FALSE, #' TextColor = "black", #' yaxis.fontSize = 14, #' xaxis.fontSize = 14, #' title.fontSize = 22, #' title.fontWeight = "bold", #' title.textShadowColor = '#63aeff', #' title.textShadowBlur = 3, #' title.textShadowOffsetY = 1, #' title.textShadowOffsetX = -1, #' xaxis.rotate = 0, #' yaxis.rotate = 0, #' ContainLabel = TRUE, #' Debug = FALSE) #' #' @return plot #' @export Plot.Copula <- function(dt = NULL, SampleSize = 30000L, XVar = NULL, YVar = NULL, GroupVar = NULL, YVarTrans = "Identity", XVarTrans = "Identity", FacetRows = 1, FacetCols = 1, FacetLevels = NULL, Height = NULL, Width = NULL, Title = 'Copula Plot', ShowLabels = FALSE, AddGLM = FALSE, Title.YAxis = NULL, Title.XAxis = NULL, EchartsTheme = "macarons", MouseScroll = TRUE, TimeLine = FALSE, TextColor = "white", yaxis.fontSize = 14, xaxis.fontSize = 14, title.fontSize = 22, title.fontWeight = "bold", title.textShadowColor = '#63aeff', title.textShadowBlur = 3, title.textShadowOffsetY = 1, title.textShadowOffsetX = -1, xaxis.rotate = 0, yaxis.rotate = 0, ContainLabel = TRUE, Debug = FALSE) { if(!data.table::is.data.table(dt)) tryCatch({data.table::setDT(dt)}, error = function(x) { dt <- data.table::as.data.table(dt) }) if(length(GroupVar) == 0L) TimeLine <- FALSE if(TimeLine && length(FacetLevels) > 0) X_Scroll <- FALSE # Cap number of records if(Debug) print('Plot.Copula # Cap number of records') if(dt[,.N] > SampleSize) { dt1 <- dt[order(runif(.N))][seq_len(SampleSize)] } else { dt1 <- data.table::copy(dt) } dt1[, eval(YVar) := data.table::frank(get(YVar)) * (1 / 0.001) / .N * 0.001] dt1[, eval(XVar) := data.table::frank(get(XVar)) * (1 / 0.001) / .N * 0.001] if(length(GroupVar) == 0L) { if(Debug) print('Plot.Copula length(GroupVar) == 0L') if(Debug) print('Plot.Copula Echarts') dt1[, size_vals := seq_len(.N)/1000] sv <- "size_vals" p1 <- echarts4r::e_charts_( dt1, x = XVar, dispose = TRUE, darkMode = TRUE, width = Width, height = Height) if(ShowLabels) { p1 <- echarts4r::e_scatter_(e = p1, YVar, color = YVar, label = list(show = TRUE)) } else { p1 <- echarts4r::e_scatter_(e = p1, YVar, color = YVar) } # Add GLM if(AddGLM) { p1 <- echarts4r::e_glm( e = p1, smooth = TRUE, formula = get(YVar) ~ get(XVar)) } p1 <- echarts4r::e_visual_map_(e = p1, scale = echarts4r::e_scale, show = FALSE) if(MouseScroll && FacetRows == 1L && FacetCols == 1L) { p1 <- echarts4r::e_datazoom(e = p1, type = "inside", x_index = c(0,1)) } else if(MouseScroll && (FacetRows > 1L || FacetCols > 1L)) { p1 <- echarts4r::e_datazoom(e = p1, type = "inside", x_index = seq(0, FacetRows * FacetCols - 1, 1)) } else { p1 <- echarts4r::e_datazoom(e = p1, x_index = c(0,1)) } p1 <- echarts4r::e_theme(e = p1, name = EchartsTheme) p1 <- echarts4r::e_aria(e = p1, enabled = TRUE) p1 <- echarts4r::e_tooltip(e = p1, trigger = "axis", backgroundColor = "aliceblue") p1 <- echarts4r::e_toolbox_feature(e = p1, feature = c("saveAsImage","dataZoom")) p1 <- echarts4r::e_show_loading(e = p1, hide_overlay = TRUE, text = "Calculating...", color = "#000", text_color = TextColor, mask_color = "#000") p1 <- echarts4r::e_legend(e = p1, type = "scroll", orient = "vertical", right = 50, top = 40, height = "240px", textStyle = list(color = TextColor, fontWeight = "bold")) if(length(Title.XAxis) == 0L) { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "x", name = XVar, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = xaxis.fontSize), axisLabel = list( rotate = xaxis.rotate, grid = list(containLabel = ContainLabel))) } else { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "x", name = Title.XAxis, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = xaxis.fontSize), axisLabel = list( rotate = xaxis.rotate, grid = list(containLabel = ContainLabel))) } if(length(Title.YAxis) == 0L) { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "y", name = YVar, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = yaxis.fontSize), axisLabel = list( rotate = yaxis.rotate, grid = list(containLabel = ContainLabel))) } else { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "y", name = Title.YAxis, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = yaxis.fontSize), axisLabel = list( rotate = yaxis.rotate, grid = list(containLabel = ContainLabel))) } p1 <- echarts4r::e_brush(e = p1) p1 <- echarts4r::e_title( p1, Title, textStyle = list( color = TextColor, fontWeight = title.fontWeight, overflow = "truncate", # "none", "truncate", "break", ellipsis = '...', fontSize = title.fontSize, textShadowColor = title.textShadowColor, textShadowBlur = title.textShadowBlur, textShadowOffsetY = title.textShadowOffsetY, textShadowOffsetX = title.textShadowOffsetX)) } else { if(length(FacetLevels) > 0L) { dt1 <- dt1[get(GroupVar) %in% c(eval(FacetLevels)), .SD, .SDcols = c(YVar,XVar,GroupVar)] } if(Debug) print('Plot.Copula length(GroupVar) > 0L') if(Debug) print('Plot.Copula Echarts') if(TimeLine) { p1 <- echarts4r::e_charts_( dt1 |> dplyr::group_by(get(GroupVar[1L])), x = XVar, colorBy = GroupVar[1L], timeline = TRUE, darkMode = TRUE, emphasis = list(focus = "series"), dispose = TRUE, width = Width, height = Height) } else { p1 <- echarts4r::e_charts_( dt1 |> dplyr::group_by(get(GroupVar[1L])), x = XVar, dispose = TRUE, #darkMode = TRUE, emphasis = list(focus = "series"), width = Width, height = Height) } p1 <- echarts4r::e_scatter_(e = p1, YVar) # Add GLM if(AddGLM) { p1 <- echarts4r::e_glm( e = p1, smooth = TRUE, formula = get(YVar) ~ get(XVar)) } p1 <- echarts4r::e_visual_map_(e = p1, scale = echarts4r::e_scale, show = FALSE) if(MouseScroll && FacetRows == 1L && FacetCols == 1L) { p1 <- echarts4r::e_datazoom(e = p1, type = "inside", x_index = c(0,1)) } else if(MouseScroll && (FacetRows > 1L || FacetCols > 1L)) { p1 <- echarts4r::e_datazoom(e = p1, type = "inside", x_index = seq(0, FacetRows * FacetCols - 1, 1)) } else { p1 <- echarts4r::e_datazoom(e = p1, x_index = c(0,1)) } p1 <- echarts4r::e_axis_(e = p1, serie = NULL, axis = "x", name = XVar) p1 <- echarts4r::e_theme(e = p1, name = EchartsTheme) p1 <- echarts4r::e_aria(e = p1, enabled = TRUE) p1 <- echarts4r::e_tooltip(e = p1, trigger = "axis", backgroundColor = "aliceblue") p1 <- echarts4r::e_toolbox_feature(e = p1, feature = c("saveAsImage","dataZoom")) p1 <- echarts4r::e_show_loading(e = p1, hide_overlay = TRUE, text = "Calculating...", color = "#000", text_color = TextColor, mask_color = "#000") if(length(Title.XAxis) == 0L) { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "x", name = XVar, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = xaxis.fontSize), axisLabel = list( rotate = xaxis.rotate, grid = list(containLabel = ContainLabel))) } else { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "x", name = Title.XAxis, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = xaxis.fontSize), axisLabel = list( rotate = xaxis.rotate, grid = list(containLabel = ContainLabel))) } if(length(Title.YAxis) == 0L) { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "y", name = YVar, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = yaxis.fontSize), axisLabel = list( rotate = yaxis.rotate, grid = list(containLabel = ContainLabel))) } else { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "y", name = Title.YAxis, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = yaxis.fontSize), axisLabel = list( rotate = yaxis.rotate, grid = list(containLabel = ContainLabel))) } p1 <- echarts4r::e_brush(e = p1) p1 <- echarts4r::e_title( p1, Title, textStyle = list( color = TextColor, fontWeight = title.fontWeight, overflow = "truncate", # "none", "truncate", "break", ellipsis = '...', fontSize = title.fontSize, textShadowColor = title.textShadowColor, textShadowBlur = title.textShadowBlur, textShadowOffsetY = title.textShadowOffsetY, textShadowOffsetX = title.textShadowOffsetX)) if(FacetRows > 1L || FacetCols > 1L) { p1 <- echarts4r::e_facet(e = p1, rows = FacetRows, cols = FacetCols, legend_space = 16, legend_pos = "top") p1 <- echarts4r::e_legend(e = p1, type = "scroll", orient = "horizontal", right = 50, top = 40, height = "240px", textStyle = list(color = TextColor, fontWeight = "bold")) } else { p1 <- echarts4r::e_legend(e = p1, type = "scroll", orient = "vertical", right = 50, top = 40, height = "240px", textStyle = list(color = TextColor, fontWeight = "bold")) } } # Return plot return(p1) } #' @title Plot.Copula3D #' #' @description Build a 3D-copula plot by simply passing arguments to a single function. It will sample your data using SampleSize number of rows. Sampled data is randomized. #' #' @family Standard Plots #' #' @author Adrian Antico #' #' @param dt source data.table #' @param SampleSize An integer for the number of rows to use. Sampled data is randomized. If NULL then ignored #' @param YVar Y-Axis variable name #' @param XVar X-Axis variable name #' @param ZVar Z-Axis variable name #' @param GroupVar Requires an XVar and YVar already be defined #' @param YVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param XVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param ZVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param FacetRows Defaults to 1 which causes no faceting to occur vertically. Otherwise, supply a numeric value for the number of output grid rows #' @param FacetCols Defaults to 1 which causes no faceting to occur horizontally. Otherwise, supply a numeric value for the number of output grid columns #' @param FacetLevels Faceting rows x columns is the max number of levels allowed in a grid. If your GroupVar has more you can supply the levels to display. #' @param Height "400px" #' @param Width "200px" #' @param Title 'Copula3D Plot' #' @param ShowLabels character #' @param Title.YAxis character #' @param Title.XAxis character #' @param EchartsTheme = "dark-blue" #' @param TimeLine Logical #' @param TextColor 'darkblue' #' @param title.fontSize 22 #' @param title.fontWeight "bold" #' @param title.textShadowColor '#63aeff' #' @param title.textShadowBlur 3 #' @param title.textShadowOffsetY 1 #' @param title.textShadowOffsetX -1 #' @param xaxis.fontSize 14 #' @param yaxis.fontSize 14 #' @param zaxis.fontSize 14 #' @param xaxis.rotate 0 #' @param yaxis.rotate 0 #' @param zaxis.rotate 0 #' @param ContainLabel TRUE #' @param Debug Debugging purposes #' #' @examples #' # Create fake data #' data <- AutoPlots::FakeDataGenerator(N = 100000) #' data[, Independent_Variable9 := Independent_Variable9 * runif(.N)] #' #' # Echarts Copula Plot Chart #' AutoPlots::Plot.Copula3D( #' dt = data, #' SampleSize = 10000, #' XVar = "Adrian", #' YVar = "Independent_Variable9", #' ZVar = "Independent_Variable6", #' YVarTrans = "Identity", #' XVarTrans = "Identity", #' ZVarTrans = "Identity", #' FacetRows = 1, #' FacetCols = 1, #' FacetLevels = NULL, #' GroupVar = NULL, #' Height = NULL, #' Width = NULL, #' Title = 'Copula 3D', #' ShowLabels = FALSE, #' Title.YAxis = NULL, #' Title.XAxis = NULL, #' EchartsTheme = "macarons", #' TimeLine = FALSE, #' TextColor = "black", #' title.fontSize = 22, #' title.fontWeight = "bold", #' title.textShadowColor = '#63aeff', #' title.textShadowBlur = 3, #' title.textShadowOffsetY = 1, #' title.textShadowOffsetX = -1, #' yaxis.fontSize = 14, #' xaxis.fontSize = 14, #' zaxis.fontSize = 14, #' xaxis.rotate = 0, #' yaxis.rotate = 0, #' zaxis.rotate = 0, #' ContainLabel = TRUE, #' Debug = FALSE) #' #' @return plot #' @export Plot.Copula3D <- function(dt = NULL, SampleSize = 100000, XVar = NULL, YVar = NULL, ZVar = NULL, YVarTrans = "Identity", XVarTrans = "Identity", ZVarTrans = "Identity", FacetRows = 1, FacetCols = 1, FacetLevels = NULL, GroupVar = NULL, Height = NULL, Width = NULL, Title = 'Copula 3D', ShowLabels = FALSE, Title.YAxis = NULL, Title.XAxis = NULL, EchartsTheme = "dark-blue", TimeLine = FALSE, TextColor = "white", title.fontSize = 22, title.fontWeight = "bold", title.textShadowColor = '#63aeff', title.textShadowBlur = 3, title.textShadowOffsetY = 1, title.textShadowOffsetX = -1, yaxis.fontSize = 14, xaxis.fontSize = 14, zaxis.fontSize = 14, xaxis.rotate = 0, yaxis.rotate = 0, zaxis.rotate = 0, ContainLabel = TRUE, Debug = FALSE) { if(!data.table::is.data.table(dt)) tryCatch({data.table::setDT(dt)}, error = function(x) { dt <- data.table::as.data.table(dt) }) if(length(GroupVar) == 0L) TimeLine <- FALSE # Cap number of records if(Debug) print('Plot.Copula3D # Cap number of records') N <- dt[,.N] if(SampleSize > 50000L) SampleSize <- 50000L if(N > SampleSize) dt <- dt[order(runif(.N))][seq_len(SampleSize)] dt1 <- data.table::copy(dt) dt1[, eval(YVar) := data.table::frank(get(YVar)) * (1 / 0.001) / .N * 0.001] dt1[, eval(XVar) := data.table::frank(get(XVar)) * (1 / 0.001) / .N * 0.001] dt1[, eval(ZVar) := data.table::frank(get(ZVar)) * (1 / 0.001) / .N * 0.001] if(length(GroupVar) > 0L) { if(Debug) print('Plot.Copula3D length(GroupVar) > 0L') if(Debug) print('Plot.Copula3D Echarts') p1 <- echarts4r::e_charts_( dt1 |> dplyr::group_by(get(GroupVar[1L])), x = XVar, darkMode = TRUE, emphasis = list(focus = "series"), timeline = TimeLine, colorBy = GroupVar[1L], dispose = TRUE, width = Width, height = Height) if(ShowLabels) { p1 <- echarts4r::e_scatter_3d_(e = p1, YVar, ZVar, ZVar, GroupVar[[1L]], label = list(show = TRUE)) } else { p1 <- echarts4r::e_scatter_3d_(e = p1, YVar, ZVar, ZVar, GroupVar[[1L]]) } p1 <- echarts4r::e_theme(e = p1, name = EchartsTheme) p1 <- echarts4r::e_aria(e = p1, enabled = TRUE) p1 <- echarts4r::e_legend(e = p1, type = "scroll", orient = "vertical", right = 50, top = 40, height = "240px", textStyle = list(color = TextColor)) p1 <- echarts4r::e_tooltip(e = p1, trigger = "axis", backgroundColor = "aliceblue") p1 <- echarts4r::e_toolbox_feature(e = p1, feature = c("saveAsImage","dataZoom")) p1 <- echarts4r::e_show_loading(e = p1, hide_overlay = TRUE, text = "Calculating...", color = "#000", text_color = TextColor, mask_color = "#000") p1 <- echarts4r::e_legend(e = p1, type = "scroll", orient = "vertical", right = 50, top = 40, height = "240px", textStyle = list(color = TextColor, fontWeight = "bold")) p1 <- echarts4r::e_brush(e = p1) p1 <- echarts4r::e_title( p1, Title, textStyle = list( color = TextColor, fontWeight = title.fontWeight, overflow = "truncate", # "none", "truncate", "break", ellipsis = '...', fontSize = title.fontSize, textShadowColor = title.textShadowColor, textShadowBlur = title.textShadowBlur, textShadowOffsetY = title.textShadowOffsetY, textShadowOffsetX = title.textShadowOffsetX)) } else { if(Debug) print('Plot.Copula3D length(GroupVar) == 0L') if(Debug) print('Plot.Copula3D Echarts') p1 <- echarts4r::e_charts_( dt1, x = XVar, dispose = TRUE, darkMode = TRUE, width = Width, height = Height) if(ShowLabels) { p1 <- echarts4r::e_scatter_3d_(e = p1, YVar, ZVar, ZVar, label = list(show = TRUE)) } else { p1 <- echarts4r::e_scatter_3d_(e = p1, YVar, ZVar, ZVar) } p1 <- echarts4r::e_theme(e = p1, name = EchartsTheme) p1 <- echarts4r::e_aria(e = p1, enabled = TRUE) p1 <- echarts4r::e_tooltip(e = p1, trigger = "axis", backgroundColor = "aliceblue") p1 <- echarts4r::e_toolbox_feature(e = p1, feature = c("saveAsImage","dataZoom")) p1 <- echarts4r::e_show_loading(e = p1, hide_overlay = TRUE, text = "Calculating...", color = "#000", text_color = TextColor, mask_color = "#000") if(length(Title.XAxis) == 0L) { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "x", name = XVar, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = xaxis.fontSize), axisLabel = list( rotate = xaxis.rotate, grid = list(containLabel = ContainLabel))) } else { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "x", name = Title.XAxis, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = xaxis.fontSize), axisLabel = list( rotate = xaxis.rotate, grid = list(containLabel = ContainLabel))) } if(length(Title.YAxis) == 0L) { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "y", name = YVar, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = yaxis.fontSize), axisLabel = list( rotate = yaxis.rotate, grid = list(containLabel = ContainLabel))) } else { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "y", name = Title.YAxis, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = yaxis.fontSize), axisLabel = list( rotate = yaxis.rotate, grid = list(containLabel = ContainLabel))) } p1 <- echarts4r::e_axis_(e = p1, serie = NULL, axis = "z", name = ZVar, nameLocation = "middle", nameGap = 45, nameTextStyle = list(color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = xaxis.fontSize)) p1 <- echarts4r::e_brush(e = p1) p1 <- echarts4r::e_title( p1, Title, textStyle = list( color = TextColor, fontWeight = title.fontWeight, overflow = "truncate", # "none", "truncate", "break", ellipsis = '...', fontSize = title.fontSize, textShadowColor = title.textShadowColor, textShadowBlur = title.textShadowBlur, textShadowOffsetY = title.textShadowOffsetY, textShadowOffsetX = title.textShadowOffsetX)) if(FacetRows > 1L || FacetCols > 1L) p1 <- echarts4r::e_facet(e = p1, rows = FacetRows, cols = FacetCols, legend_space = 16, legend_pos = "top") } # Return plot return(p1) } #' @title Plot.Scatter #' #' @description Build a copula plot by simply passing arguments to a single function. It will sample your data using SampleSize number of rows. Sampled data is randomized. #' #' @family Standard Plots #' #' @author Adrian Antico #' #' @param dt source data.table #' @param SampleSize numeric #' @param YVar Y-Axis variable name #' @param XVar X-Axis variable name #' @param GroupVar Character variable #' @param YVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param XVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param FacetRows Defaults to 1 which causes no faceting to occur vertically. Otherwise, supply a numeric value for the number of output grid rows #' @param FacetCols Defaults to 1 which causes no faceting to occur horizontally. Otherwise, supply a numeric value for the number of output grid columns #' @param FacetLevels Faceting rows x columns is the max number of levels allowed in a grid. If your GroupVar has more you can supply the levels to display. #' @param Height "400px" #' @param Width "200px" #' @param Title character #' @param AddGLM logical #' @param tooltip.trigger "axis" #' @param ShowLabels character #' @param Title.YAxis character #' @param Title.XAxis character #' @param EchartsTheme "auritus","azul","bee-inspired","blue","caravan","carp","chalk","cool","dark-bold","dark","eduardo", #' "essos","forest","fresh-cut","fruit","gray","green","halloween","helianthus","infographic","inspired", #' "jazz","london","dark","macarons","macarons2","mint","purple-passion","red-velvet","red","roma","royal", #' "sakura","shine","tech-blue","vintage","walden","wef","weforum","westeros","wonderland" #' @param TimeLine logical #' @param MouseScroll logical, zoom via mouse scroll #' @param TextColor character hex #' @param title.fontSize 22 #' @param title.fontWeight "bold" #' @param title.textShadowColor '#63aeff' #' @param title.textShadowBlur 3 #' @param title.textShadowOffsetY 1 #' @param title.textShadowOffsetX -1 #' @param xaxis.fontSize 14 #' @param yaxis.fontSize 14 #' @param xaxis.rotate 0 #' @param yaxis.rotate 0 #' @param ContainLabel TRUE #' @param Debug Debugging purposes #' #' @examples #' # Create fake data #' data <- AutoPlots::FakeDataGenerator(N = 100000) #' data[, Independent_Variable8 := Independent_Variable8 * runif(.N)] #' #' # Echarts Scatter Plot Chart #' AutoPlots::Plot.Scatter( #' dt = data, #' SampleSize = 10000, #' XVar = "Independent_Variable10", #' YVar = "Independent_Variable8", #' GroupVar = NULL, #' YVarTrans = "Identity", #' XVarTrans = "Identity", #' FacetRows = 1, #' FacetCols = 1, #' FacetLevels = NULL, #' Height = NULL, #' Width = NULL, #' Title = 'Scatter Plot', #' ShowLabels = FALSE, #' AddGLM = FALSE, #' Title.YAxis = NULL, #' Title.XAxis = NULL, #' EchartsTheme = "blue", #' MouseScroll = TRUE, #' TimeLine = FALSE, #' TextColor = "black", #' title.fontSize = 22, #' title.fontWeight = "bold", #' title.textShadowColor = '#63aeff', #' title.textShadowBlur = 3, #' title.textShadowOffsetY = 1, #' title.textShadowOffsetX = -1, #' yaxis.fontSize = 14, #' xaxis.fontSize = 14, #' xaxis.rotate = 0, #' yaxis.rotate = 0, #' ContainLabel = TRUE, #' tooltip.trigger = "axis", #' Debug = FALSE) #' #' @return plot #' @export Plot.Scatter <- function(dt = NULL, SampleSize = 30000L, XVar = NULL, YVar = NULL, GroupVar = NULL, YVarTrans = "Identity", XVarTrans = "Identity", FacetRows = 1, FacetCols = 1, FacetLevels = NULL, Height = NULL, Width = NULL, Title = 'Scatter Plot', ShowLabels = FALSE, AddGLM = FALSE, Title.YAxis = NULL, Title.XAxis = NULL, EchartsTheme = "macarons", MouseScroll = TRUE, TimeLine = FALSE, TextColor = "white", title.fontSize = 22, title.fontWeight = "bold", title.textShadowColor = '#63aeff', title.textShadowBlur = 3, title.textShadowOffsetY = 1, title.textShadowOffsetX = -1, yaxis.fontSize = 14, xaxis.fontSize = 14, xaxis.rotate = 0, yaxis.rotate = 0, ContainLabel = TRUE, tooltip.trigger = "axis", Debug = FALSE) { if(length(GroupVar) == 0L) TimeLine <- FALSE if(TimeLine && length(FacetLevels) > 0) X_Scroll <- FALSE # Cap number of records if(Debug) print('Plot.Scatter # Cap number of records') if(length(SampleSize) == 0L) SampleSize <- 30000L if(!data.table::is.data.table(dt)) tryCatch({data.table::setDT(dt)}, error = function(x) { dt <- data.table::as.data.table(dt) }) if(dt[,.N] > SampleSize) { dt1 <- dt[order(runif(.N))][seq_len(SampleSize)] } else { dt1 <- data.table::copy(dt) } # Transformation if(YVarTrans != "Identity") { dt1 <- AutoTransformationCreate(data = dt1, ColumnNames = YVar, Methods = YVarTrans)$Data } # Transformation if(XVarTrans != "Identity") { dt1 <- AutoTransformationCreate(data = dt1, ColumnNames = XVar, Methods = XVarTrans)$Data } if(length(GroupVar) == 0L) { if(Debug) print('Plot.Scatter length(GroupVar) == 0L') if(Debug) print('Plot.Scatter Echarts') p1 <- echarts4r::e_charts_( dt1, x = XVar, dispose = TRUE, darkMode = TRUE, width = Width, height = Height) if(ShowLabels) { p1 <- echarts4r::e_scatter_3d_(e = p1, YVar, ZVar, ZVar, label = list(show = TRUE)) } else { p1 <- echarts4r::e_scatter_(e = p1, YVar) } # Add GLM if(AddGLM) { p1 <- echarts4r::e_glm( e = p1, smooth = TRUE, formula = get(YVar) ~ get(XVar)) } p1 <- echarts4r::e_visual_map_(e = p1, scale = echarts4r::e_scale, show = FALSE) if(MouseScroll && FacetRows == 1L && FacetCols == 1L) { p1 <- echarts4r::e_datazoom(e = p1, type = "inside", x_index = c(0,1)) } else if(MouseScroll && (FacetRows > 1L || FacetCols > 1L)) { p1 <- echarts4r::e_datazoom(e = p1, type = "inside", x_index = seq(0, FacetRows * FacetCols - 1, 1)) } else { p1 <- echarts4r::e_datazoom(e = p1, x_index = c(0,1)) } p1 <- echarts4r::e_theme(e = p1, name = EchartsTheme) p1 <- echarts4r::e_aria(e = p1, enabled = TRUE) p1 <- echarts4r::e_tooltip(e = p1, trigger = tooltip.trigger, backgroundColor = "aliceblue") p1 <- echarts4r::e_toolbox_feature(e = p1, feature = c("saveAsImage","dataZoom")) p1 <- echarts4r::e_show_loading(e = p1, hide_overlay = TRUE, text = "Calculating...", color = "#000", text_color = TextColor, mask_color = "#000") p1 <- echarts4r::e_legend(e = p1, type = "scroll", orient = "vertical", right = 50, top = 40, height = "240px", textStyle = list(color = TextColor, fontWeight = "bold")) if(length(Title.XAxis) == 0L) { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "x", name = XVar, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = xaxis.fontSize), axisLabel = list( rotate = xaxis.rotate, grid = list(containLabel = ContainLabel))) } else { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "x", name = Title.XAxis, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = xaxis.fontSize), axisLabel = list( rotate = xaxis.rotate, grid = list(containLabel = ContainLabel))) } if(length(Title.YAxis) == 0L) { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "y", name = YVar, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = yaxis.fontSize), axisLabel = list( rotate = yaxis.rotate, grid = list(containLabel = ContainLabel))) } else { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "y", name = Title.YAxis, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = yaxis.fontSize), axisLabel = list( rotate = yaxis.rotate, grid = list(containLabel = ContainLabel))) } p1 <- echarts4r::e_brush(e = p1) p1 <- echarts4r::e_title( p1, Title, textStyle = list( color = TextColor, fontWeight = title.fontWeight, overflow = "truncate", # "none", "truncate", "break", ellipsis = '...', fontSize = title.fontSize, textShadowColor = title.textShadowColor, textShadowBlur = title.textShadowBlur, textShadowOffsetY = title.textShadowOffsetY, textShadowOffsetX = title.textShadowOffsetX)) } else { if(Debug) print("SCatter 1") if((FacetRows > 1L || FacetCols > 1L) && length(FacetLevels) > 0L) { dt1 <- dt1[get(GroupVar) %in% c(eval(FacetLevels)), .SD, .SDcols = c(YVar,XVar,GroupVar)] } if(Debug) print("SCatter 2") if(Debug) print('Plot.Scatter length(GroupVar) > 0L') if(Debug) print('Plot.Scatter Echarts') p1 <- echarts4r::e_charts_( dt1 |> dplyr::group_by(get(GroupVar[1L])), x = XVar, timeline = TimeLine, darkMode = TRUE, emphasis = list(focus = "series"), colorBy = GroupVar[1L], dispose = TRUE, width = Width, height = Height) if(Debug) print("SCatter 3") if(ShowLabels) { p1 <- echarts4r::e_scatter_(e = p1, YVar, label = list(show = TRUE)) } else { p1 <- echarts4r::e_scatter_(e = p1, YVar) } if(Debug) print("SCatter 4") # Add GLM if(AddGLM) { p1 <- echarts4r::e_glm( e = p1, smooth = TRUE, formula = get(YVar) ~ get(XVar)) } if(Debug) print("SCatter 5") p1 <- echarts4r::e_visual_map_(e = p1, scale = echarts4r::e_scale, show = FALSE) if(MouseScroll && FacetRows == 1L && FacetCols == 1L) { p1 <- echarts4r::e_datazoom(e = p1, type = "inside", x_index = c(0,1)) } else if(MouseScroll && (FacetRows > 1L || FacetCols > 1L)) { p1 <- echarts4r::e_datazoom(e = p1, type = "inside", x_index = seq(0, FacetRows * FacetCols - 1, 1)) } else { p1 <- echarts4r::e_datazoom(e = p1, x_index = c(0,1)) } if(Debug) print("SCatter 6") p1 <- echarts4r::e_theme(e = p1, name = EchartsTheme) p1 <- echarts4r::e_aria(e = p1, enabled = TRUE) p1 <- echarts4r::e_tooltip(e = p1, trigger = "axis", backgroundColor = "aliceblue") p1 <- echarts4r::e_toolbox_feature(e = p1, feature = c("saveAsImage","dataZoom")) p1 <- echarts4r::e_show_loading(e = p1, hide_overlay = TRUE, text = "Calculating...", color = "#000", text_color = TextColor, mask_color = "#000") if(Debug) print("SCatter 7") if(length(Title.XAxis) == 0L) { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "x", name = XVar, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = xaxis.fontSize), axisLabel = list( rotate = xaxis.rotate, grid = list(containLabel = ContainLabel))) } else { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "x", name = Title.XAxis, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = xaxis.fontSize), axisLabel = list( rotate = xaxis.rotate, grid = list(containLabel = ContainLabel))) } if(length(Title.YAxis) == 0L) { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "y", name = YVar, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = yaxis.fontSize), axisLabel = list( rotate = yaxis.rotate, grid = list(containLabel = ContainLabel))) } else { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "y", name = Title.YAxis, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = yaxis.fontSize), axisLabel = list( rotate = yaxis.rotate, grid = list(containLabel = ContainLabel))) } if(Debug) print("SCatter 8") p1 <- echarts4r::e_brush(e = p1) p1 <- echarts4r::e_title( p1, Title, textStyle = list( color = TextColor, fontWeight = title.fontWeight, overflow = "truncate", # "none", "truncate", "break", ellipsis = '...', fontSize = title.fontSize, textShadowColor = title.textShadowColor, textShadowBlur = title.textShadowBlur, textShadowOffsetY = title.textShadowOffsetY, textShadowOffsetX = title.textShadowOffsetX)) if(FacetRows > 1L || FacetCols > 1L) { p1 <- echarts4r::e_facet(e = p1, rows = FacetRows, cols = FacetCols, legend_space = 16, legend_pos = "top") p1 <- echarts4r::e_legend(e = p1, type = "scroll", orient = "horizontal", right = 50, top = 40, height = "240px", textStyle = list(color = TextColor, fontWeight = "bold")) } else { p1 <- echarts4r::e_legend(e = p1, type = "scroll", orient = "vertical", right = 50, top = 40, height = "240px", textStyle = list(color = TextColor, fontWeight = "bold")) } } # Return plot return(p1) } #' @title Plot.Scatter3D #' #' @description Build a 3D-copula plot by simply passing arguments to a single function. It will sample your data using SampleSize number of rows. Sampled data is randomized. #' #' @family Standard Plots #' #' @author Adrian Antico #' #' @param dt source data.table #' @param SampleSize An integer for the number of rows to use. Sampled data is randomized. If NULL then ignored #' @param YVar Y-Axis variable name #' @param XVar X-Axis variable name #' @param ZVar Z-Axis variable name #' @param GroupVar Requires an XVar and YVar already be defined #' @param YVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param XVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param ZVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param FacetRows Defaults to 1 which causes no faceting to occur vertically. Otherwise, supply a numeric value for the number of output grid rows #' @param FacetCols Defaults to 1 which causes no faceting to occur horizontally. Otherwise, supply a numeric value for the number of output grid columns #' @param FacetLevels Faceting rows x columns is the max number of levels allowed in a grid. If your GroupVar has more you can supply the levels to display. #' @param Height "400px" #' @param Width "200px" #' @param Title 'Violin Plot' #' @param ShowLabels character #' @param Title.YAxis character #' @param Title.XAxis character #' @param EchartsTheme = "macaron" #' @param TimeLine Logical #' @param TextColor 'darkblue' #' @param title.fontSize 22 #' @param title.fontWeight "bold" #' @param title.textShadowColor '#63aeff' #' @param title.textShadowBlur 3 #' @param title.textShadowOffsetY 1 #' @param title.textShadowOffsetX -1 #' @param xaxis.fontSize 14 #' @param yaxis.fontSize 14 #' @param zaxis.fontSize 14 #' @param xaxis.rotate 0 #' @param zaxis.rotate 0 #' @param yaxis.rotate 0 #' @param ContainLabel TRUE #' @param Debug Debugging purposes #' #' @examples #' # Create fake data #' data <- AutoPlots::FakeDataGenerator(N = 100000) #' data[, Independent_Variable9 := Independent_Variable9 * runif(.N)] #' #' # Echarts Copula Plot Chart #' AutoPlots::Plot.Scatter3D( #' dt = data, #' SampleSize = 10000, #' XVar = "Adrian", #' YVar = "Independent_Variable9", #' ZVar = "Independent_Variable6", #' YVarTrans = "Identity", #' XVarTrans = "Identity", #' ZVarTrans = "Identity", #' FacetRows = 1, #' FacetCols = 1, #' FacetLevels = NULL, #' GroupVar = NULL, #' Height = NULL, #' Width = NULL, #' Title = 'Copula 3D', #' ShowLabels = FALSE, #' Title.YAxis = NULL, #' Title.XAxis = NULL, #' EchartsTheme = "macarons", #' TimeLine = FALSE, #' TextColor = "black", #' title.fontSize = 22, #' title.fontWeight = "bold", #' title.textShadowColor = '#63aeff', #' title.textShadowBlur = 3, #' title.textShadowOffsetY = 1, #' title.textShadowOffsetX = -1, #' yaxis.fontSize = 14, #' xaxis.fontSize = 14, #' zaxis.fontSize = 14, #' xaxis.rotate = 0, #' yaxis.rotate = 0, #' zaxis.rotate = 0, #' ContainLabel = TRUE, #' Debug = FALSE) #' #' @return plot #' @export Plot.Scatter3D <- function(dt = NULL, SampleSize = 100000, XVar = NULL, YVar = NULL, ZVar = NULL, GroupVar = NULL, YVarTrans = "Identity", XVarTrans = "Identity", ZVarTrans = "Identity", FacetRows = 1, FacetCols = 1, FacetLevels = NULL, Height = NULL, Width = NULL, Title = '3D Scatter', ShowLabels = FALSE, Title.YAxis = NULL, Title.XAxis = NULL, EchartsTheme = "macarons", TimeLine = FALSE, TextColor = "white", title.fontSize = 22, title.fontWeight = "bold", title.textShadowColor = '#63aeff', title.textShadowBlur = 3, title.textShadowOffsetY = 1, title.textShadowOffsetX = -1, yaxis.fontSize = 14, xaxis.fontSize = 14, zaxis.fontSize = 14, xaxis.rotate = 0, yaxis.rotate = 0, zaxis.rotate = 0, ContainLabel = TRUE, Debug = FALSE) { if(!data.table::is.data.table(dt)) tryCatch({data.table::setDT(dt)}, error = function(x) { dt <- data.table::as.data.table(dt) }) if(length(GroupVar) == 0L) TimeLine <- FALSE # Cap number of records if(Debug) print('Plot.Scatter3D # Cap number of records') if(length(SampleSize) == 0L) SampleSize <- 30000L if(dt[,.N] > SampleSize) { dt1 <- dt[order(runif(.N))][seq_len(SampleSize)] } else { dt1 <- data.table::copy(dt) } # Transformation if(YVarTrans != "Identity") { dt1 <- AutoTransformationCreate(data = dt1, ColumnNames = YVar, Methods = YVarTrans)$Data } # Transformation if(XVarTrans != "Identity") { dt1 <- AutoTransformationCreate(data = dt1, ColumnNames = XVar, Methods = XVarTrans)$Data } # Transformation if(ZVarTrans != "Identity") { dt1 <- AutoTransformationCreate(data = dt1, ColumnNames = ZVar, Methods = ZVarTrans)$Data } if(length(GroupVar) > 0L) { if(Debug) print('Plot.Scatter3D length(GroupVar) > 0L') if(Debug) print('Plot.Scatter3D Echarts') p1 <- echarts4r::e_charts_( dt1 |> dplyr::group_by(get(GroupVar[1L])), x = XVar, timeline = FALSE, colorBy = GroupVar[1L], dispose = TRUE, darkMode = TRUE, emphasis = list(focus = "series"), width = Width, height = Height) if(ShowLabels) { p1 <- echarts4r::e_scatter_3d_(e = p1, YVar, ZVar, GroupVar[1L], label = list(show = TRUE)) } else { p1 <- echarts4r::e_scatter_3d_(e = p1, YVar, ZVar, GroupVar[1L]) } p1 <- echarts4r::e_theme(e = p1, name = EchartsTheme) p1 <- echarts4r::e_aria(e = p1, enabled = TRUE) p1 <- echarts4r::e_tooltip(e = p1, trigger = "axis", backgroundColor = "aliceblue") p1 <- echarts4r::e_toolbox_feature(e = p1, feature = c("saveAsImage","dataZoom")) p1 <- echarts4r::e_show_loading(e = p1, hide_overlay = TRUE, text = "Calculating...", color = "#000", text_color = TextColor, mask_color = "#000") p1 <- echarts4r::e_brush(e = p1) p1 <- echarts4r::e_title( p1, Title, textStyle = list( color = TextColor, fontWeight = title.fontWeight, overflow = "truncate", # "none", "truncate", "break", ellipsis = '...', fontSize = title.fontSize, textShadowColor = title.textShadowColor, textShadowBlur = title.textShadowBlur, textShadowOffsetY = title.textShadowOffsetY, textShadowOffsetX = title.textShadowOffsetX)) if(FacetRows > 1L || FacetCols > 1L) { p1 <- echarts4r::e_facet(e = p1, rows = FacetRows, cols = FacetCols, legend_space = 16, legend_pos = "top") p1 <- echarts4r::e_legend(e = p1, type = "scroll", orient = "horizontal", right = 50, top = 40, height = "240px", textStyle = list(color = TextColor, fontWeight = "bold")) } else { p1 <- echarts4r::e_legend(e = p1, type = "scroll", orient = "vertical", right = 50, top = 40, height = "240px", textStyle = list(color = TextColor, fontWeight = "bold")) } } else { if(Debug) print('Plot.Scatter3D length(GroupVar) == 0L') if(Debug) print('Plot.Scatter3D Echarts') p1 <- echarts4r::e_charts_( dt1 |> dplyr::group_by(GroupVar[[1L]]), x = XVar, timeline = FALSE, dispose = TRUE, darkMode = TRUE, emphasis = list(focus = "series"), width = Width, height = Height) if(ShowLabels) { p1 <- echarts4r::e_scatter_3d_(e = p1, YVar, ZVar, ZVar, GroupVar[[1L]], label = list(show = TRUE)) } else { p1 <- echarts4r::e_scatter_3d_(e = p1, YVar, ZVar, ZVar, GroupVar[[1L]]) } p1 <- echarts4r::e_theme(e = p1, name = EchartsTheme) p1 <- echarts4r::e_aria(e = p1, enabled = TRUE) p1 <- echarts4r::e_tooltip(e = p1, trigger = "axis", backgroundColor = "aliceblue") p1 <- echarts4r::e_toolbox_feature(e = p1, feature = c("saveAsImage","dataZoom")) p1 <- echarts4r::e_show_loading(e = p1, hide_overlay = TRUE, text = "Calculating...", color = "#000", text_color = TextColor, mask_color = "#000") if(length(Title.XAxis) == 0L) { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "x", name = XVar, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = xaxis.fontSize), axisLabel = list( rotate = xaxis.rotate, grid = list(containLabel = ContainLabel))) } else { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "x", name = Title.XAxis, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = xaxis.fontSize), axisLabel = list( rotate = xaxis.rotate, grid = list(containLabel = ContainLabel))) } if(length(Title.YAxis) == 0L) { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "y", name = YVar, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = yaxis.fontSize), axisLabel = list( rotate = yaxis.rotate, grid = list(containLabel = ContainLabel))) } else { p1 <- echarts4r::e_axis_( e = p1, serie = NULL, axis = "y", name = Title.YAxis, nameLocation = "middle", nameGap = 45, nameTextStyle = list( color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = yaxis.fontSize), axisLabel = list( rotate = yaxis.rotate, grid = list(containLabel = ContainLabel))) } p1 <- echarts4r::e_axis_(e = p1, serie = NULL, axis = "z", name = ZVar, nameLocation = "middle", nameGap = 45, nameTextStyle = list(color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = xaxis.fontSize)) p1 <- echarts4r::e_brush(e = p1) p1 <- echarts4r::e_title( p1, Title, textStyle = list( color = TextColor, fontWeight = title.fontWeight, overflow = "truncate", # "none", "truncate", "break", ellipsis = '...', fontSize = title.fontSize, textShadowColor = title.textShadowColor, textShadowBlur = title.textShadowBlur, textShadowOffsetY = title.textShadowOffsetY, textShadowOffsetX = title.textShadowOffsetX)) } # Return plot return(p1) } # ---- # ---- # @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ---- # > Model Evaluation Plots ---- # @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ---- #' @title Plot.Residuals.Histogram #' #' @description Residuals Plot #' #' @author Adrian Antico #' @family Model Evaluation #' #' @param dt source data.table #' @param AggMethod character #' @param SampleSize numeric #' @param XVar X-Axis variable name #' @param YVar Y-Axis variable name #' @param GroupVar Character variable #' @param YVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param XVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param FacetRows Defaults to 1 which causes no faceting to occur vertically. Otherwise, supply a numeric value for the number of output grid rows #' @param FacetCols Defaults to 1 which causes no faceting to occur horizontally. Otherwise, supply a numeric value for the number of output grid columns #' @param FacetLevels Faceting rows x columns is the max number of levels allowed in a grid. If your GroupVar has more you can supply the levels to display. #' @param NumberBins numeric #' @param Title character #' @param Height "400px" #' @param Width "200px" #' @param ShowLabels character #' @param Title.YAxis character #' @param Title.XAxis character #' @param EchartsTheme "auritus","azul","bee-inspired","blue","caravan","carp","chalk","cool","dark-bold","dark","eduardo", #' "essos","forest","fresh-cut","fruit","gray","green","halloween","helianthus","infographic","inspired", #' "jazz","london","dark","macarons","macarons2","mint","purple-passion","red-velvet","red","roma","royal", #' "sakura","shine","tech-blue","vintage","walden","wef","weforum","westeros","wonderland" #' @param TimeLine logical #' @param MouseScroll logical, zoom via mouse scroll #' @param TextColor Not Implemented #' @param title.fontSize 22 #' @param title.fontWeight "bold" #' @param title.textShadowColor '#63aeff' #' @param title.textShadowBlur 3 #' @param title.textShadowOffsetY 1 #' @param title.textShadowOffsetX -1 #' @param xaxis.fontSize 14 #' @param yaxis.fontSize 14 #' @param xaxis.rotate 0 #' @param yaxis.rotate 0 #' @param ContainLabel TRUE #' @param Debug Debugging purposes #' @return plot #' @export Plot.Residuals.Histogram <- function(dt = NULL, AggMethod = 'mean', SampleSize = 100000, XVar = NULL, YVar = NULL, GroupVar = NULL, YVarTrans = "Identity", XVarTrans = "Identity", FacetRows = 1, FacetCols = 1, FacetLevels = NULL, NumberBins = 20, Height = NULL, Width = NULL, Title = 'Residuals Histogram', ShowLabels = FALSE, Title.YAxis = NULL, Title.XAxis = "Target - Predicted", EchartsTheme = "macarons", MouseScroll = TRUE, TimeLine = FALSE, TextColor = "white", title.fontSize = 22, title.fontWeight = "bold", title.textShadowColor = '#63aeff', title.textShadowBlur = 3, title.textShadowOffsetY = 1, title.textShadowOffsetX = -1, xaxis.fontSize = 14, yaxis.fontSize = 14, xaxis.rotate = 0, yaxis.rotate = 0, ContainLabel = TRUE, Debug = FALSE) { # Subset cols, define Target - Predicted, NULL YVar in data, Update YVar def, Ensure GroupVar is length(1) if(length(SampleSize) == 0L) SampleSize <- 30000L if(!data.table::is.data.table(dt)) tryCatch({data.table::setDT(dt)}, error = function(x) { dt <- data.table::as.data.table(dt) }) if(Debug) print("here 1") if(Debug) print(head(dt)) # Subset columns dt1 <- dt[, .SD, .SDcols = c(XVar,YVar,GroupVar)] # Shrink display data dt1 <- dt1[order(runif(.N))][seq_len(min(.N, SampleSize))] # Prepare data dt1[, `Target - Predicted` := get(YVar) - get(XVar)] data.table::set(dt1, j = c(YVar), value = NULL) YVar <- "Target - Predicted" if(length(GroupVar) > 0L) GroupVar <- GroupVar[1L] if(Debug) print("here 2") if(Debug) print(head(dt1)) # Faceting shrink if(length(GroupVar) > 0L) { data.table::setorderv(x = dt1, cols = c(GroupVar), 1L) if(Debug) print(head(dt1)) dt1 <- dt1[order(get(GroupVar))] if(Debug) print(head(dt1)) } if(Debug) print("here 3.1") if(Debug) print(head(dt1)) if(length(GroupVar) > 0L && (FacetRows > 1L || FacetCols > 1L)) { dt1 <- dt1[get(GroupVar) %in% c(eval(FacetLevels)), .SD, .SDcols = c(YVar,GroupVar)] } else { dt1 <- dt1[, .SD, .SDcols = c(YVar,GroupVar)] } if(Debug) print("here 3") if(Debug) print(head(dt1)) # Data Prep2 if(Debug) print("Plot.Residuals.Histogram") tl <- if(length(GroupVar) == 0L || length(FacetLevels) > 0) FALSE else TimeLine # Transformation # "PercRank" "Standardize" # "Asinh" "Log" "LogPlus1" "Sqrt" "Asin" "Logit" "BoxCox" "YeoJohnson" if(YVarTrans != "Identity") { dt1 <- tryCatch({AutoTransformationCreate(data = dt1, ColumnNames = YVar, Methods = YVarTrans)$Data}, error = function(x) dt1) } if(Debug) print("here 4") if(Debug) print(head(dt1)) # Create base plot object if(Debug) print('Create Plot with only data') dt1 <- dt1[!is.na(get(YVar))] p1 <- AutoPlots::Plot.Histogram( dt = dt1, SampleSize = SampleSize, XVar = NULL, YVar = YVar, GroupVar = GroupVar, YVarTrans = YVarTrans, XVarTrans = XVarTrans, FacetRows = FacetRows, FacetCols = FacetCols, FacetLevels = FacetLevels, NumberBins = NumberBins, Height = Height, Width = Width, MouseScroll = MouseScroll, Title = Title, ShowLabels = ShowLabels, Title.YAxis = Title.YAxis, Title.XAxis = Title.XAxis, EchartsTheme = EchartsTheme, TimeLine = TimeLine, TextColor = "white", title.fontSize = title.fontSize, title.fontWeight = title.fontWeight, title.textShadowColor = title.textShadowColor, title.textShadowBlur = title.textShadowBlur, title.textShadowOffsetY = title.textShadowOffsetY, title.textShadowOffsetX = title.textShadowOffsetX, xaxis.fontSize = xaxis.fontSize, yaxis.fontSize = yaxis.fontSize, Debug = Debug) return(p1) } #' @title Plot.Residuals.Scatter #' #' @description Residuals_2 Plot #' #' @author Adrian Antico #' @family Model Evaluation #' #' @param dt source data.table #' @param AggMethod character #' @param SampleSize numeric #' @param XVar X-Axis variable name #' @param YVar Y-Axis variable name #' @param GroupVar Character variable #' @param YVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param XVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param FacetRows Defaults to 1 which causes no faceting to occur vertically. Otherwise, supply a numeric value for the number of output grid rows #' @param FacetCols Defaults to 1 which causes no faceting to occur horizontally. Otherwise, supply a numeric value for the number of output grid columns #' @param FacetLevels Faceting rows x columns is the max number of levels allowed in a grid. If your GroupVar has more you can supply the levels to display. #' @param Height "400px" #' @param Width "200px" #' @param Title character #' @param ShowLabels character #' @param Title.YAxis character #' @param Title.XAxis character #' @param EchartsTheme "auritus","azul","bee-inspired","blue","caravan","carp","chalk","cool","dark-bold","dark","eduardo", #' "essos","forest","fresh-cut","fruit","gray","green","halloween","helianthus","infographic","inspired", #' "jazz","london","dark","macarons","macarons2","mint","purple-passion","red-velvet","red","roma","royal", #' "sakura","shine","tech-blue","vintage","walden","wef","weforum","westeros","wonderland" #' @param TimeLine logical #' @param MouseScroll logical, zoom via mouse scroll #' @param TextColor "Not Implemented" #' @param Debug Debugging purposes #' @return plot #' @export Plot.Residuals.Scatter <- function(dt = NULL, AggMethod = 'mean', SampleSize = 100000, XVar = NULL, YVar = NULL, GroupVar = NULL, YVarTrans = "Identity", XVarTrans = "Identity", FacetRows = 1, FacetCols = 1, FacetLevels = NULL, Height = NULL, Width = NULL, MouseScroll = TRUE, Title = 'Residual Scatterplot', ShowLabels = FALSE, Title.YAxis = "Target - Predicted", Title.XAxis = "Predicted", EchartsTheme = "macarons", TimeLine = FALSE, TextColor = "white", Debug = FALSE) { # Data Prep1 if(length(SampleSize) == 0L) SampleSize <- 30000L if(!data.table::is.data.table(dt)) tryCatch({data.table::setDT(dt)}, error = function(x) { dt <- data.table::as.data.table(dt) }) dt1 <- dt[, .SD, .SDcols = c(XVar,YVar,GroupVar)] if(dt1[, .N] > SampleSize) dt1 <- dt1[order(runif(.N))][seq_len(SampleSize)] dt1[, `Target - Predicted` := get(YVar) - get(XVar)] if(length(GroupVar) > 0L) GroupVar <- GroupVar[1L] if(length(GroupVar) > 0L) { dt1[, eval(XVar) := round(data.table::frank(get(XVar)) * 20 / .N) / 20, by = c(GroupVar[1L])] } else { dt1[, eval(XVar) := round(data.table::frank(get(XVar)) * 20 / .N) / 20] } YVar <- "Target - Predicted" # Data Prep2 tl <- if(length(GroupVar) == 0L) FALSE else TimeLine data.table::setorderv(x = dt1, cols = c(GroupVar[1L], XVar)) dt1 <- dt1[!is.na(get(YVar))] dt1 <- dt1[!is.na(get(XVar))] # Build Plot p1 <- AutoPlots::Plot.Scatter( dt = dt1, SampleSize = SampleSize, YVar = "Target - Predicted", XVar = XVar, GroupVar = GroupVar[1L], YVarTrans = YVarTrans, XVarTrans = XVarTrans, FacetRows = FacetRows, FacetCols = FacetCols, FacetLevels = FacetLevels, Height = Height, Title.YAxis = YVar, Title.XAxis = paste0(XVar, " every 5th Percentile"), ShowLabels = ShowLabels, Width = Width, MouseScroll = MouseScroll, Title = Title, EchartsTheme = EchartsTheme, TimeLine = tl, TextColor = TextColor, tooltip.trigger = "item", Debug = Debug) return(p1) } #' @title Plot.Calibration.Line #' #' @description This function automatically builds calibration plots and calibration boxplots for model evaluation using regression, quantile regression, and binary and multinomial classification #' #' @author Adrian Antico #' @family Model Evaluation #' #' @param dt source data.table #' @param AggMethod character #' @param XVar X-Axis variable name #' @param YVar Y-Axis variable name #' @param GroupVar Character variable #' @param YVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param XVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param FacetRows Defaults to 1 which causes no faceting to occur vertically. Otherwise, supply a numeric value for the number of output grid rows #' @param FacetCols Defaults to 1 which causes no faceting to occur horizontally. Otherwise, supply a numeric value for the number of output grid columns #' @param FacetLevels Faceting rows x columns is the max number of levels allowed in a grid. If your GroupVar has more you can supply the levels to display. #' @param NumberBins numeric #' @param Height "400px" #' @param Width "200px" #' @param Title character #' @param ShowLabels character #' @param Title.YAxis character #' @param Title.XAxis character #' @param EchartsTheme "auritus","azul","bee-inspired","blue","caravan","carp","chalk","cool","dark-bold","dark","eduardo", #' "essos","forest","fresh-cut","fruit","gray","green","halloween","helianthus","infographic","inspired", #' "jazz","london","dark","macarons","macarons2","mint","purple-passion","red-velvet","red","roma","royal", #' "sakura","shine","tech-blue","vintage","walden","wef","weforum","westeros","wonderland" #' @param TimeLine logical #' @param MouseScroll logical, zoom via mouse scroll #' @param TextColor "Not Implemented" #' @param Debug Debugging purposes #' @return plot #' @export Plot.Calibration.Line <- function(dt = NULL, AggMethod = 'mean', XVar = NULL, YVar = NULL, GroupVar = NULL, YVarTrans = "Identity", XVarTrans = "Identity", FacetRows = 1, FacetCols = 1, FacetLevels = NULL, NumberBins = 21, Height = NULL, Width = NULL, Title = 'Calibration Line', ShowLabels = FALSE, Title.YAxis = NULL, Title.XAxis = NULL, EchartsTheme = "macarons", TimeLine = FALSE, MouseScroll = TRUE, TextColor = "white", Debug = FALSE) { if(Debug) print("here 1") if(!data.table::is.data.table(dt)) tryCatch({data.table::setDT(dt)}, error = function(x) { dt <- data.table::as.data.table(dt) }) if(Debug) print("here 2") # YVar check y_class <- class(dt[[YVar]])[1L] if(Debug) print("here 3") # Define Aggregation function if(Debug) print("here 3.1") if(Debug) print("Plot.PartialDependence.Line # Define Aggregation function") if(Debug) print("here 3.2") aggFunc <- SummaryFunction(AggMethod) if(Debug) print("here 4") # Regression and Classification else MultiClass if(!y_class %in% c("character","factor")) { if(Debug) print("here 5") # Minimize data before moving on if(Debug) print("Plot.Calibration.Line # Minimize data before moving on") Ncols <- ncol(dt) if(Ncols > 2L && length(GroupVar) == 0L) { dt1 <- data.table::copy(dt[, .SD, .SDcols = c(YVar, XVar)]) } else if(Ncols > 3L && length(GroupVar) > 0L) { dt1 <- data.table::copy(dt[, .SD, .SDcols = c(YVar, XVar, GroupVar[[1L]])]) } else { dt1 <- data.table::copy(dt) } if(Debug) print("here 6") # If actual is in factor form, convert to numeric if(Debug) print("Plot.Calibration.Line # If actual is in factor form, convert to numeric") if(!is.numeric(dt1[[YVar]])) { data.table::set(dt1, j = YVar, value = as.numeric(as.character(dt1[[YVar]]))) } if(Debug) print("here 7") # Add a column that ranks predicted values if(length(GroupVar) > 0L) { if(Debug) print("here 8a") if(Debug) print("Plot.Calibration.Line # if(length(GroupVar) > 0L)") if(length(FacetLevels) > 0L) { dt1 <- dt1[get(GroupVar) %in% c(eval(FacetLevels)), .SD, .SDcols = c(YVar,XVar,GroupVar)] } dt1[, Percentile := round(data.table::frank(get(XVar)) * NumberBins / .N) / NumberBins, by = c(GroupVar[1L])] dt1 <- dt1[, lapply(.SD, noquote(aggFunc)), by = c("Percentile",GroupVar[1L])] dt1[, `Target - Predicted` := get(YVar) - get(XVar)] data.table::setorderv(x = dt1, cols = c("Percentile",GroupVar[1L]), c(1L,1L)) } else { if(Debug) print("here 8b") if(Debug) print("Plot.Calibration.Line # if(length(GroupVar) == 0L)") dt1[, rank := round(data.table::frank(get(XVar)) * NumberBins / .N) / NumberBins] dt1 <- dt1[, lapply(.SD, noquote(aggFunc)), by = "rank"] dt1 <- data.table::melt.data.table(data = dt1, id.vars = "rank", measure.vars = c(YVar,XVar)) data.table::setnames(dt1, names(dt1), c("Percentile", "Variable", YVar)) data.table::setorderv(x = dt1, cols = c("Percentile","Variable"), c(1L,1L)) } # Build Plot if(Debug) print("Plot.Calibration.Line # AutoPlots::Plot.Line()") yvar <- if(length(GroupVar) > 0L) "Target - Predicted" else YVar gv <- if(length(GroupVar) == 0L) "Variable" else GroupVar tl <- if(length(GroupVar) == 0L) FALSE else TimeLine # dt1 <- dt1[!is.na(get(yvar))] if(Debug) print(dt1) if(Debug) print("here 9") p1 <- AutoPlots::Plot.Line( dt = dt1, PreAgg = TRUE, YVar = yvar, XVar = "Percentile", GroupVar = gv, YVarTrans = YVarTrans, XVarTrans = XVarTrans, FacetRows = FacetRows, FacetCols = FacetCols, FacetLevels = FacetLevels, Title.YAxis = yvar, Title.XAxis = "Predicted", ShowLabels = ShowLabels, MouseScroll = MouseScroll, Height = Height, Width = Width, Title = 'Calibration Line Plot', EchartsTheme = EchartsTheme, TimeLine = tl, TextColor = TextColor, Debug = Debug) # dt = dt1 # PreAgg = TRUE # YVar = yvar # XVar = "Percentile" # GroupVar = gv # YVarTrans = YVarTrans # XVarTrans = XVarTrans # FacetRows = FacetRows # FacetCols = FacetCols # FacetLevels = FacetLevels # Title.YAxis = yvar # Title.XAxis = paste0("Predicted every 5th Percentile") # ShowLabels = ShowLabels # Height = Height # Width = Width # Title = 'Calibration Line Plot' # EchartsTheme = EchartsTheme # TimeLine = tl # X_Scroll = X_Scroll # Y_Scroll = Y_Scroll # TextColor = TextColor # Debug = Debug return(p1) } else { # multiclass model if(Debug) print("here 5") # Minimize data before moving on if(Debug) print("Plot.PartialDependence.Line # Minimize data before moving on") GroupVar <- tryCatch({GroupVar[1L]}, error = function(x) NULL) if(Debug) print("here 6") # Shrink data if(Debug) print(dt) if(Debug) print(YVar) yvar_levels <- as.character(dt[, unique(get(YVar))]) dt1 <- data.table::copy(dt[, .SD, .SDcols = c(GroupVar, XVar, YVar, yvar_levels)]) if(Debug) print("here 7") # Dummify Target nam <- data.table::copy(names(dt1)) dt1 <- DummifyDT(data = dt1, cols = YVar, TopN = length(yvar_levels), KeepFactorCols = FALSE, OneHot = FALSE, SaveFactorLevels = FALSE, SavePath = getwd(), ImportFactorLevels = FALSE, FactorLevelsList = NULL, ClustScore = FALSE, ReturnFactorLevels = FALSE) nam <- setdiff(names(dt1), nam) if(Debug) print("here 8") # Melt Predict Cols dt2 <- data.table::melt.data.table( data = if(length(GroupVar) == 0L) dt1[, .SD, .SDcols = c(names(dt1)[!names(dt1) %in% XVar])] else dt1, id.vars = c(GroupVar), measure.vars = names(dt1)[!names(dt1) %in% c(GroupVar, YVar, XVar, nam)], variable.name = "Level", value.name = XVar, na.rm = TRUE, variable.factor = FALSE) if(Debug) print("here 9") # Melt Target Cols dt3 <- data.table::melt.data.table( data = dt1, id.vars = c(GroupVar,XVar), measure.vars = nam, variable.name = "Level", value.name = YVar, na.rm = TRUE, variable.factor = FALSE) if(Debug) print("here 10") # Join data dt2[, eval(YVar) := dt3[[YVar]]] if(Debug) print("here 11") # Add New Target yvar <- "Target - Predicted" dt2[, eval(yvar) := get(YVar) - get(XVar)] if(length(GroupVar) > 0L) { dt2[, GroupVariables := do.call(paste, c(.SD, sep = ' :: ')), .SDcols = c(GroupVar, "Level")] GroupVar <- "GroupVariables" if(FacetRows > 1L || FacetCols > 1L) { FacetLevels <- as.character(dt2[, unique(GroupVariables)]) FacetLevels <- FacetLevels[seq_len(min(length(FacetLevels),FacetRows*FacetCols))] dt2 <- dt2[GroupVariables %chin% c(eval(FacetLevels))] } } else if(length(GroupVar) == 0L && (FacetRows > 1L || FacetCols > 1L)) { FacetLevels <- yvar_levels[seq_len(min(length(yvar_levels), FacetRows * FacetCols))] dt2 <- dt2[Level %chin% c(eval(FacetLevels))] } if(Debug) print("here 12") # Subset Cols if(length(GroupVar) > 0L) { dt2 <- dt2[, .SD, .SDcols = c("GroupVariables", yvar, XVar)] dt2[, eval(XVar) := round(data.table::frank(get(XVar)) * NumberBins / .N) / NumberBins, by = c(GroupVar[1L])] dt2 <- dt2[, lapply(.SD, noquote(aggFunc)), by = c(XVar,GroupVar)] } else { dt2 <- dt2[, .SD, .SDcols = c(yvar, XVar, "Level")] dt2[, eval(XVar) := round(data.table::frank(get(XVar)) * NumberBins / .N) / NumberBins] dt2 <- dt2[, lapply(.SD, noquote(aggFunc)), by = c(XVar,"Level")] } if(Debug) print("here 13") # Build if(Debug) print("Plot.PartialDependence.Line --> AutoPlots::Plot.Line()") dt2 <- dt2[!is.na(get(yvar))] if(Debug) print("here 14") p1 <- AutoPlots::Plot.Line( dt = dt2, PreAgg = TRUE, AggMethod = "mean", EchartsTheme = EchartsTheme, TimeLine = FALSE, XVar = XVar, YVar = yvar, GroupVar = if(length(GroupVar) > 0L) "GroupVariables" else "Level", YVarTrans = YVarTrans, XVarTrans = XVarTrans, FacetRows = FacetRows, FacetCols = FacetCols, FacetLevels = FacetLevels, MouseScroll = MouseScroll, Area = FALSE, Smooth = TRUE, ShowSymbol = FALSE, Height = Height, Width = Width, Title = "Calibration Line Plot", Title.YAxis = yvar, Title.XAxis = "Predicted", TextColor = TextColor, Debug = Debug) return(p1) } } #' @title Plot.Calibration.Box #' #' @description This function automatically builds calibration plots and calibration boxplots for model evaluation using regression, quantile regression, and binary and multinomial classification #' #' @author Adrian Antico #' @family Model Evaluation #' #' @param dt source data.table #' @param SampleSize numeric #' @param XVar X-Axis variable name #' @param YVar Y-Axis variable name #' @param AggMethod character #' @param GroupVar Character variable #' @param YVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param XVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param FacetRows Defaults to 1 which causes no faceting to occur vertically. Otherwise, supply a numeric value for the number of output grid rows #' @param FacetCols Defaults to 1 which causes no faceting to occur horizontally. Otherwise, supply a numeric value for the number of output grid columns #' @param FacetLevels Faceting rows x columns is the max number of levels allowed in a grid. If your GroupVar has more you can supply the levels to display. #' @param Height "400px" #' @param Width "200px" #' @param NumberBins numeric #' @param Title character #' @param ShowLabels character #' @param Title.YAxis character #' @param Title.XAxis character #' @param EchartsTheme "auritus","azul","bee-inspired","blue","caravan","carp","chalk","cool","dark-bold","dark","eduardo", #' "essos","forest","fresh-cut","fruit","gray","green","halloween","helianthus","infographic","inspired", #' "jazz","london","dark","macarons","macarons2","mint","purple-passion","red-velvet","red","roma","royal", #' "sakura","shine","tech-blue","vintage","walden","wef","weforum","westeros","wonderland" #' @param TimeLine logical #' @param MouseScroll logical, zoom via mouse scroll #' @param TextColor "Not Implemented" #' @param Debug Debugging purposes #' @return plot #' @export Plot.Calibration.Box <- function(dt = NULL, SampleSize = 100000L, AggMethod = 'mean', XVar = NULL, YVar = NULL, GroupVar = NULL, YVarTrans = "Identity", XVarTrans = "Identity", FacetRows = 1, FacetCols = 1, FacetLevels = NULL, NumberBins = 21, Height = NULL, Width = NULL, Title = 'Calibration Box', MouseScroll = TRUE, ShowLabels = FALSE, Title.YAxis = NULL, Title.XAxis = NULL, EchartsTheme = "macarons", TimeLine = FALSE, TextColor = "white", Debug = FALSE) { if(Debug) print("Plot.Calibration.Box 1") # Minimize data before moving on if(!data.table::is.data.table(dt)) tryCatch({data.table::setDT(dt)}, error = function(x) { dt <- data.table::as.data.table(dt) }) if(Debug) print("Plot.Calibration.Box 2") if(dt[, .N] > SampleSize) dt <- dt[order(runif(.N))][seq_len(SampleSize)] if(Debug) print("Plot.Calibration.Box 3") Ncols <- ncol(dt) if(Ncols > 2L && length(GroupVar) == 0L) { dt1 <- data.table::copy(dt[, .SD, .SDcols = c(YVar, XVar)]) } else if(Ncols > 3L && length(GroupVar) > 0L) { dt1 <- data.table::copy(dt[, .SD, .SDcols = c(YVar, XVar, GroupVar[[1L]])]) } else { dt1 <- data.table::copy(dt) } if(Debug) print("Plot.Calibration.Box 4") # If actual is in factor form, convert to numeric if(!is.numeric(dt1[[YVar]])) { data.table::set(dt1, j = YVar, value = as.numeric(as.character(dt1[[YVar]]))) } if(Debug) print("Plot.Calibration.Box 5") # Add a column that ranks predicted values if(Debug) print(paste0("NumberBins = ", NumberBins)) if(length(GroupVar) > 0L) { dt1[, rank := round(data.table::frank(get(XVar)) * NumberBins / .N) / NumberBins, by = c(GroupVar[1L])] } else { dt1[, rank := round(data.table::frank(get(XVar)) * NumberBins / .N) / NumberBins] } if(Debug) print("Plot.Calibration.Box 6") dt1[, `Target - Predicted` := get(YVar) - get(XVar)] data.table::setnames(dt1, "rank", "Percentile") if(length(GroupVar) > 0L) { data.table::setorderv(x = dt1, cols = c("Percentile", GroupVar[1L]), c(1L,1L)) } else { data.table::setorderv(x = dt1, cols = "Percentile", 1L) } if(Debug) print("Plot.Calibration.Box 7") dt1 <- dt1[, .SD, .SDcols = c("Target - Predicted","Percentile")] if(!is.character(dt1[["Percentile"]])) dt1[, Percentile := as.character(Percentile)] if(Debug) print("Plot.Calibration.Box 8") # Plot if(Debug) print(paste0("TimeLine for Plot.Box=", TimeLine)) dt1 <- dt1[!is.na(`Target - Predicted`)] if(Debug) print("Plot.Calibration.Box 9") p1 <- Plot.Box( dt = dt1, SampleSize = SampleSize, XVar = "Percentile", YVar = "Target - Predicted", GroupVar = GroupVar, YVarTrans = YVarTrans, XVarTrans = XVarTrans, FacetRows = FacetRows, FacetCols = FacetCols, ShowLabels = ShowLabels, Title.YAxis = "Target - Predicted", Title.XAxis = paste0("Predicted Every 5th Percentile"), FacetLevels = NULL, Height = Height, Width = Width, Title = 'Calibration Box Plot', MouseScroll = MouseScroll, EchartsTheme = EchartsTheme, TimeLine = TimeLine, TextColor = TextColor, Debug = Debug) return(p1) } #' @title Plot.PartialDependence.Line #' #' @description This function automatically builds partial dependence calibration plots #' #' @author Adrian Antico #' @family Model Evaluation #' #' @param dt source data.table #' @param XVar X-Axis variable name #' @param YVar Y-Axis variable name #' @param ZVar character #' @param NumberBins numeric #' @param Title character #' @param ShowLabels character #' @param Title.YAxis character #' @param Title.XAxis character #' @param YVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param XVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param ZVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param FacetRows Defaults to 1 which causes no faceting to occur vertically. Otherwise, supply a numeric value for the number of output grid rows #' @param FacetCols Defaults to 1 which causes no faceting to occur horizontally. Otherwise, supply a numeric value for the number of output grid columns #' @param FacetLevels Faceting rows x columns is the max number of levels allowed in a grid. If your GroupVar has more you can supply the levels to display. #' @param Height "400px" #' @param Width "200px" #' @param EchartsTheme "auritus","azul","bee-inspired","blue","caravan","carp","chalk","cool","dark-bold","dark","eduardo", #' "essos","forest","fresh-cut","fruit","gray","green","halloween","helianthus","infographic","inspired", #' "jazz","london","dark","macarons","macarons2","mint","purple-passion","red-velvet","red","roma","royal", #' "sakura","shine","tech-blue","vintage","walden","wef","weforum","westeros","wonderland" #' @param EchartsLabels character #' @param MouseScroll logical, zoom via mouse scroll #' @param TimeLine logical #' @param TextColor hex character #' @param AggMethod character #' @param GroupVar Character variable #' @param Debug Debugging purposes #' @return plot #' @export Plot.PartialDependence.Line <- function(dt = NULL, XVar = NULL, YVar = NULL, ZVar = NULL, YVarTrans = "Identity", XVarTrans = "Identity", ZVarTrans = "Identity", FacetRows = 1, FacetCols = 1, FacetLevels = NULL, GroupVar = NULL, NumberBins = 20, AggMethod = "mean", Height = NULL, Width = NULL, Title = "Partial Dependence Line", ShowLabels = FALSE, Title.YAxis = NULL, Title.XAxis = NULL, EchartsTheme = "macarons", MouseScroll = TRUE, EchartsLabels = FALSE, TimeLine = TRUE, TextColor = "white", Debug = FALSE) { if(!data.table::is.data.table(dt)) tryCatch({data.table::setDT(dt)}, error = function(x) { dt <- data.table::as.data.table(dt) }) # YVar check yvar_class <- class(dt[[YVar]])[1L] xvar_class <- class(dt[[XVar]][1L]) # Define Aggregation function if(Debug) print("Plot.PartialDependence.Line # Define Aggregation function") aggFunc <- SummaryFunction(AggMethod) # Regression and Classification else MultiClass if(yvar_class %in% c("numeric","integer")) { # Minimize data before moving on if(Debug) print("Plot.PartialDependence.Line # Minimize data before moving on") Ncols <- ncol(dt) if(Ncols > 2L && length(GroupVar) == 0L) { dt1 <- data.table::copy(dt[, .SD, .SDcols = c(YVar, XVar, ZVar)]) } else if(Ncols > 3L && length(GroupVar) > 0L) { dt1 <- data.table::copy(dt[, .SD, .SDcols = c(YVar, XVar, ZVar, GroupVar[1L])]) } else { dt1 <- data.table::copy(dt) } # If actual is in factor form, convert to numeric if(Debug) print("Plot.PartialDependence.Line # If actual is in factor form, convert to numeric") if(!is.numeric(dt1[[YVar]])) { data.table::set(dt1, j = YVar, value = as.numeric(as.character(dt1[[YVar]]))) } # Data Mgt if(length(GroupVar) > 0L) { if(Debug) print("Plot.PartialDependence.Line # if(length(GroupVar) > 0L)") if(!xvar_class %in% c("factor","character","Date","IDate","POSIXct","IDateTime")) { dt1[, eval(XVar) := round(data.table::frank(get(XVar)) * NumberBins / .N) / NumberBins, by = c(GroupVar[1L])] } dt1 <- dt1[, lapply(.SD, noquote(aggFunc)), by = c(XVar,GroupVar[1L])] dt1[, `Target - Predicted` := get(YVar) - get(ZVar)] data.table::setorderv(x = dt1, cols = c(XVar,GroupVar[1L]), c(1L,1L)) yvar <- "Target - Predicted" gv <- GroupVar tl <- TimeLine } else { if(Debug) print("Plot.PartialDependence.Line # if(length(GroupVar) == 0L)") if(!xvar_class %in% c("factor","character","Date","IDate","POSIXct","IDateTime")) { dt1[, eval(XVar) := round(data.table::frank(get(XVar)) * NumberBins / .N) / NumberBins] } dt1 <- dt1[, lapply(.SD, noquote(aggFunc)), by = eval(XVar)] dt1 <- data.table::melt.data.table(data = dt1, id.vars = eval(XVar), measure.vars = c(YVar,ZVar)) data.table::setnames(dt1, names(dt1), c(XVar, "Variable", YVar)) data.table::setorderv(x = dt1, cols = c(XVar,"Variable"), c(1L,1L)) yvar <- YVar gv <- "Variable" tl <- FALSE } # Build if(Debug) print("Plot.PartialDependence.Line --> AutoPlots::Plot.Line()") dt1 <- dt1[!is.na(get(yvar))] p1 <- AutoPlots::Plot.Line( Area = FALSE, dt = dt1, PreAgg = TRUE, AggMethod = "mean", EchartsTheme = EchartsTheme, TimeLine = tl, XVar = XVar, YVar = yvar, GroupVar = gv, YVarTrans = YVarTrans, XVarTrans = XVarTrans, FacetRows = FacetRows, FacetCols = FacetCols, FacetLevels = FacetLevels, ShowLabels = ShowLabels, MouseScroll = MouseScroll, Title.YAxis = if(length(GroupVar) > 0L) "Target - Predicted" else "Target & Predicted", Title.XAxis = XVar, Height = Height, Width = Width, Title = "Partial Dependence", TextColor = TextColor, Debug = Debug) return(p1) } else { # multiclass model # Minimize data before moving on if(Debug) print("Plot.PartialDependence.Line # Minimize data before moving on") GroupVar <- tryCatch({GroupVar[1L]}, error = function(x) NULL) # Shrink data yvar_levels <- as.character(dt[, unique(get(YVar))]) dt1 <- data.table::copy(dt[, .SD, .SDcols = c(GroupVar, XVar, YVar, yvar_levels)]) # Dummify Target nam <- data.table::copy(names(dt1)) dt1 <- DummifyDT(data = dt1, cols = YVar, TopN = length(yvar_levels), KeepFactorCols = FALSE, OneHot = FALSE, SaveFactorLevels = FALSE, SavePath = getwd(), ImportFactorLevels = FALSE, FactorLevelsList = NULL, ClustScore = FALSE, ReturnFactorLevels = FALSE) nam <- setdiff(names(dt1), nam) # Melt Predict Cols dt2 <- data.table::melt.data.table( data = dt1, id.vars = c(GroupVar, XVar), measure.vars = names(dt1)[!names(dt1) %in% c(GroupVar, XVar, YVar, nam)], variable.name = "Level", value.name = ZVar, na.rm = TRUE, variable.factor = FALSE) # Melt Target Cols dt3 <- data.table::melt.data.table( data = dt1, id.vars = c(GroupVar, XVar), measure.vars = nam, variable.name = "Level", value.name = YVar, na.rm = TRUE, variable.factor = FALSE) # Join data dt2[, eval(YVar) := dt3[[YVar]]] # Update Args if(length(GroupVar) > 0L) { dt2[, GroupVariables := do.call(paste, c(.SD, sep = ' :: ')), .SDcols = c(GroupVar, "Level")] GroupVar <- "GroupVariables" if(FacetRows > 1L && FacetCols > 1L) { FacetLevels <- as.character(dt2[, unique(GroupVariables)]) FacetLevels <- FacetLevels[seq_len(min(length(FacetLevels),FacetRows*FacetCols))] dt2 <- dt2[GroupVariables %chin% c(eval(FacetLevels))] } } else if(length(GroupVar) == 0L && (FacetRows > 1L || FacetCols > 1L)) { FacetLevels <- yvar_levels[seq_len(min(length(yvar_levels), FacetRows * FacetCols))] dt2 <- dt2[Level %chin% c(eval(FacetLevels))] } # Add New Target yvar <- "Target - Predicted" dt2[, eval(yvar) := get(YVar) - get(ZVar)] # Subset Cols if(length(GroupVar) > 0L) { dt2 <- dt2[, .SD, .SDcols = c("GroupVariables", yvar, XVar)] if(!xvar_class %in% c("factor","character","Date","IDate","POSIXct","IDateTime")) { dt2[, eval(XVar) := round(data.table::frank(get(XVar)) * NumberBins / .N) / NumberBins, by = c(GroupVar[1L])] } dt2 <- dt2[, lapply(.SD, noquote(aggFunc)), by = c(XVar,GroupVar)] } else { dt2 <- dt2[, .SD, .SDcols = c(yvar, XVar, "Level")] if(!xvar_class %in% c("factor","character","Date","IDate","POSIXct","IDateTime")) { dt2[, eval(XVar) := round(data.table::frank(get(XVar)) * NumberBins / .N) / NumberBins] } dt2 <- dt2[, lapply(.SD, noquote(aggFunc)), by = c(XVar,"Level")] } # Build if(Debug) print("Plot.PartialDependence.Line --> AutoPlots::Plot.Line()") dt2 <- dt2[!is.na(get(yvar))] p1 <- AutoPlots::Plot.Line( dt = dt2, PreAgg = TRUE, AggMethod = "mean", EchartsTheme = EchartsTheme, TimeLine = FALSE, XVar = XVar, YVar = yvar, GroupVar = if(length(GroupVar) > 0L) "GroupVariables" else "Level", YVarTrans = YVarTrans, XVarTrans = XVarTrans, FacetRows = FacetRows, FacetCols = FacetCols, FacetLevels = FacetLevels, ShowLabels = ShowLabels, MouseScroll = MouseScroll, Title.YAxis = if(length(GroupVar) > 0L) "Target - Predicted" else "Target & Predicted", Title.XAxis = XVar, Area = FALSE, Smooth = TRUE, ShowSymbol = FALSE, Height = Height, Width = Width, Title = "Partial Dependence", TextColor = TextColor, Debug = Debug) return(p1) } } #' @title Plot.PartialDependence.Box #' #' @description This function automatically builds partial dependence calibration plots #' #' @author Adrian Antico #' @family Model Evaluation #' #' @param dt source data.table #' @param SampleSize numeric #' @param XVar X-Axis variable name #' @param YVar Y-Axis variable name #' @param ZVar character #' @param YVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param XVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param ZVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param FacetRows Defaults to 1 which causes no faceting to occur vertically. Otherwise, supply a numeric value for the number of output grid rows #' @param FacetCols Defaults to 1 which causes no faceting to occur horizontally. Otherwise, supply a numeric value for the number of output grid columns #' @param FacetLevels Faceting rows x columns is the max number of levels allowed in a grid. If your GroupVar has more you can supply the levels to display. #' @param NumberBins numeric #' @param PreAgg logical #' @param Title character #' @param ShowLabels character #' @param Title.YAxis character #' @param Title.XAxis character #' @param Height "400px" #' @param Width "200px" #' @param EchartsTheme "auritus","azul","bee-inspired","blue","caravan","carp","chalk","cool","dark-bold","dark","eduardo", #' "essos","forest","fresh-cut","fruit","gray","green","halloween","helianthus","infographic","inspired", #' "jazz","london","dark","macarons","macarons2","mint","purple-passion","red-velvet","red","roma","royal", #' "sakura","shine","tech-blue","vintage","walden","wef","weforum","westeros","wonderland" #' @param EchartsLabels character #' @param TimeLine logical #' @param MouseScroll logical, zoom via mouse scroll #' @param TextColor hex character #' @param AggMethod character #' @param GroupVar Character variable #' @param Debug Debugging purposes #' @return plot #' @export Plot.PartialDependence.Box <- function(dt = NULL, PreAgg = FALSE, SampleSize = 100000L, XVar = NULL, YVar = NULL, ZVar = NULL, GroupVar = NULL, YVarTrans = "Identity", XVarTrans = "Identity", ZVarTrans = "Identity", FacetRows = 1, FacetCols = 1, FacetLevels = NULL, NumberBins = 20, AggMethod = "mean", Height = NULL, Width = NULL, Title = "Partial Dependence Box", ShowLabels = FALSE, Title.YAxis = NULL, Title.XAxis = NULL, EchartsTheme = "macarons", MouseScroll = TRUE, EchartsLabels = FALSE, TimeLine = TRUE, TextColor = "white", Debug = FALSE) { if(!data.table::is.data.table(dt)) tryCatch({data.table::setDT(dt)}, error = function(x) { dt <- data.table::as.data.table(dt) }) GroupVar <- NULL # Minimize data before moving on if(Debug) print("Plot.PartialDependence.Box # Minimize data before moving on") Ncols <- ncol(dt) if(Ncols > 3L) { dt1 <- data.table::copy(dt[, .SD, .SDcols = c(YVar, XVar, ZVar)]) } else { dt1 <- data.table::copy(dt) } # If actual is in factor form, convert to numeric if(Debug) print("Plot.PartialDependence.Box # If actual is in factor form, convert to numeric") if(!is.numeric(dt1[[YVar]])) { data.table::set(dt1, j = YVar, value = as.numeric(as.character(dt1[[YVar]]))) } # Add a column that ranks predicted values dt1[, eval(XVar) := as.character(round(data.table::frank(get(XVar)) * (NumberBins) / .N) / NumberBins)] dt1[, `Target - Predicted` := get(YVar) - get(ZVar)] data.table::setorderv(x = dt1, cols = XVar, 1L) # Build Plot tl <- if(length(GroupVar) == 0L) FALSE else TimeLine # Build if(Debug) print("Plot.PartialDependence.Box --> AutoPlots::Plot.Box()") dt1 <- dt1[!is.na(`Target - Predicted`)] p1 <- AutoPlots::Plot.Box( dt = dt1, SampleSize = SampleSize, XVar = XVar, YVar = "Target - Predicted", GroupVar = NULL, YVarTrans = YVarTrans, XVarTrans = XVarTrans, FacetRows = 1, FacetCols = 1, FacetLevels = NULL, ShowLabels = ShowLabels, Title.YAxis = "Target & Predicted", Title.XAxis = paste0(XVar, " Every 5th Percentile"), Height = Height, Width = Width, Title = "Partial Dependence", MouseScroll = MouseScroll, EchartsTheme = EchartsTheme, TimeLine = tl, TextColor = TextColor, Debug = Debug) return(p1) } #' @title Plot.PartialDependence.HeatMap #' #' @description This function automatically builds partial dependence calibration plots #' #' @author Adrian Antico #' @family Model Evaluation #' #' @param dt source data.table #' @param XVar X-Axis variable name #' @param YVar Y-Axis variable name #' @param ZVar character #' @param YVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param XVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param ZVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param FacetRows Defaults to 1 which causes no faceting to occur vertically. Otherwise, supply a numeric value for the number of output grid rows #' @param FacetCols Defaults to 1 which causes no faceting to occur horizontally. Otherwise, supply a numeric value for the number of output grid columns #' @param FacetLevels Faceting rows x columns is the max number of levels allowed in a grid. If your GroupVar has more you can supply the levels to display. #' @param NumberBins numeric #' @param Height "400px" #' @param Width "200px" #' @param Title character #' @param ShowLabels character #' @param Title.YAxis character #' @param Title.XAxis character #' @param EchartsTheme "auritus","azul","bee-inspired","blue","caravan","carp","chalk","cool","dark-bold","dark","eduardo", #' "essos","forest","fresh-cut","fruit","gray","green","halloween","helianthus","infographic","inspired", #' "jazz","london","dark","macarons","macarons2","mint","purple-passion","red-velvet","red","roma","royal", #' "sakura","shine","tech-blue","vintage","walden","wef","weforum","westeros","wonderland" #' @param EchartsLabels character #' @param TimeLine logical #' @param MouseScroll logical, zoom via mouse scroll #' @param TextColor hex character #' @param AggMethod character #' @param GroupVar Character variable #' @param Debug Debugging purposes #' @return plot #' @export Plot.PartialDependence.HeatMap <- function(dt = NULL, XVar = NULL, YVar = NULL, ZVar = NULL, GroupVar = NULL, YVarTrans = "Identity", XVarTrans = "Identity", ZVarTrans = "Identity", FacetRows = 1, FacetCols = 1, FacetLevels = NULL, NumberBins = 21, AggMethod = "mean", Height = NULL, Width = NULL, Title = "Partial Dependence Heatmap", ShowLabels = FALSE, MouseScroll = TRUE, Title.YAxis = NULL, Title.XAxis = NULL, EchartsTheme = "macarons", EchartsLabels = FALSE, TimeLine = TRUE, TextColor = "white", Debug = FALSE) { if(!data.table::is.data.table(dt)) tryCatch({data.table::setDT(dt)}, error = function(x) { dt <- data.table::as.data.table(dt) }) # YVar check yvar_class <- class(dt[[YVar]])[1L] # Define Aggregation function if(Debug) print("Plot.PartialDependence.Line # Define Aggregation function") aggFunc <- SummaryFunction(AggMethod) # Regression and Classification else MultiClass if(yvar_class %in% c("numeric","integer")) { GroupVar <- NULL # Minimize data before moving on if(Debug) print("Plot.PartialDependence.HeatMap # Minimize data before moving on") Ncols <- ncol(dt) dt1 <- data.table::copy(dt[, .SD, .SDcols = c(YVar, XVar, ZVar)]) if(Debug) print("Plot.PartialDependence.HeatMap # Define Aggregation function") aggFunc <- SummaryFunction(AggMethod) if(Debug) print("Plot.PartialDependence.HeatMap # if(length(GroupVar) == 0L)") for(i in seq_along(XVar)) { if(class(dt[[XVar[i]]][1L]) %in% c("numeric","integer")) { if(Debug) print(paste0('here ', XVar[i])) dt1[, eval(XVar[i]) := as.character(round(data.table::frank(get(XVar[i])) * NumberBins / .N / NumberBins, 3), 1L)] } else { if(Debug) print(paste0('there ', XVar[i])) dt1[, eval(XVar[i]) := as.character(get(XVar[i]))] } } if(Debug) print("here 2") dt1 <- dt1[, lapply(.SD, noquote(aggFunc)), by = c(eval(XVar))] if(Debug) print("here 3") dt1[, `Target - Predicted` := get(YVar) - get(ZVar)] if(Debug) print("here 4") ZVar <- "Target - Predicted" if(length(XVar) > 1L) { if(Debug) print("here 5.1") YVar <- XVar[2L] XVar <- XVar[1L] data.table::setorderv(x = dt1, cols = c(XVar,YVar),c(1L,1L)) for(i in c(XVar,YVar)) dt1[, eval(i) := get(i)] # Build if(Debug) print("Plot.PartialDependence.HeatMap --> AutoPlots::Plot.HeatMap()") dt1 <- dt1[!is.na(get(YVar))] p1 <- AutoPlots::Plot.HeatMap( dt = dt1, PreAgg = TRUE, AggMethod = "mean", EchartsTheme = EchartsTheme, XVar = XVar, YVar = YVar, ZVar = ZVar, YVarTrans = YVarTrans, XVarTrans = XVarTrans, ZVarTrans = ZVarTrans, ShowLabels = ShowLabels, MouseScroll = MouseScroll, Title.YAxis = YVar, Title.XAxis = XVar, Height = Height, Width = Width, Title = "Partial Dependence Heatmap: Target - Predicted", TextColor = TextColor, NumberBins = NumberBins, Debug = Debug) return(p1) } else { if(Debug) print("here 5.2") data.table::setorderv(x = dt1, cols = XVar,1L) if(Debug) print("here 5.3") dt1 <- dt1[!is.na(get(ZVar))] if(Debug) print("here 5.4") # data.table::fwrite(dt1, file = "C:/Users/Bizon/Documents/GitHub/rappwd/dt1.csv") # dt1 <- data.table::fread(file = "C:/Users/Bizon/Documents/GitHub/rappwd/dt1.csv") # EchartsTheme <- "macarons" # ShowLabels <- FALSE # Height = "200px" # Width = "400px" # XVar = "GroupVariable" # ZVar = "Target - Predicted" dt1 <- dt1[, .SD, .SDcols = c(XVar, ZVar)] p1 <- AutoPlots::Plot.Bar( dt = dt1, PreAgg = TRUE, XVar = XVar, YVar = ZVar, GroupVar = NULL, YVarTrans = "Identity", XVarTrans = "Identity", FacetRows = 1, FacetCols = 1, FacetLevels = NULL, AggMethod = "mean", Height = Height, Width = Width, MouseScroll = MouseScroll, Title = "Partial Dependence Bar Plot: Target - Predicted", ShowLabels = ShowLabels, Title.YAxis = "Target - Predicted", Title.XAxis = XVar, EchartsTheme = EchartsTheme, TimeLine = TRUE, TextColor = "white", title.fontSize = 22, title.fontWeight = "bold", title.textShadowColor = "#63aeff", title.textShadowBlur = 3, title.textShadowOffsetY = 1, title.textShadowOffsetX = -1, xaxis.fontSize = 14, yaxis.fontSize = 14, Debug = Debug) return(p1) } } else { # Minimize data before moving on if(Debug) print("Plot.PartialDependence.Line # Minimize data before moving on") # Shrink data yvar_levels <- as.character(dt[, unique(get(YVar))]) dt1 <- data.table::copy(dt[, .SD, .SDcols = c(XVar, YVar, yvar_levels)]) # Dummify Target nam <- data.table::copy(names(dt1)) dt1 <- DummifyDT(data = dt1, cols = YVar, TopN = length(yvar_levels), KeepFactorCols = FALSE, OneHot = FALSE, SaveFactorLevels = FALSE, SavePath = getwd(), ImportFactorLevels = FALSE, FactorLevelsList = NULL, ClustScore = FALSE, ReturnFactorLevels = FALSE) nam <- setdiff(names(dt1), nam) # Melt Predict Cols dt2 <- data.table::melt.data.table( data = dt1, id.vars = XVar, measure.vars = names(dt1)[!names(dt1) %in% c(XVar, YVar, nam)], variable.name = "Level", value.name = ZVar, na.rm = TRUE, variable.factor = FALSE) # Melt Target Cols dt3 <- data.table::melt.data.table( data = dt1, id.vars = XVar, measure.vars = nam, variable.name = "Level", value.name = YVar, na.rm = TRUE, variable.factor = FALSE) # Join data dt2[, eval(YVar) := dt3[[YVar]]] # Add New Target yvar <- "Target - Predicted" dt2[, eval(yvar) := get(YVar) - get(ZVar)] # Subset Cols dt2 <- dt2[, .SD, .SDcols = c(yvar, XVar, "Level")] for(i in seq_along(XVar)) { if(class(dt[[XVar]][i]) %in% c("numeric","integer")) { dt1[, eval(XVar[i]) := as.character(round(data.table::frank(get(XVar[i])) * NumberBins / .N / NumberBins, 3), 1L)] } else { dt1[, eval(XVar[i]) := as.character(get(XVar[i]))] } } dt2 <- dt2[, lapply(.SD, noquote(aggFunc)), by = c(XVar,"Level")] # Build if(Debug) print("Plot.PartialDependence.HeatMap --> AutoPlots::Plot.HeatMap()") dt2 <- dt2[!is.na(get(yvar))] p1 <- AutoPlots::Plot.HeatMap( dt = dt2, PreAgg = TRUE, AggMethod = "mean", EchartsTheme = EchartsTheme, XVar = XVar, YVar = "Level", ZVar = yvar, YVarTrans = YVarTrans, XVarTrans = XVarTrans, ZVarTrans = ZVarTrans, Title.YAxis = YVar, Title.XAxis = XVar, Height = Height, Width = Width, MouseScroll = MouseScroll, Title = "Partial Dependence Heatmap: Target - Predicted", TextColor = TextColor, NumberBins = NumberBins, Debug = Debug) return(p1) } } #' @title Plot.VariableImportance #' #' @description Generate variable importance plots #' #' @author Adrian Antico #' @family Model Evaluation #' #' @param dt source data.table #' @param AggMethod Choose from 'mean', 'sum', 'sd', and 'median' #' @param XVar Column name of X-Axis variable. If NULL then ignored #' @param YVar Column name of Y-Axis variable. If NULL then ignored #' @param GroupVar Column name of Group Variable for distinct colored histograms by group levels #' @param YVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param XVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param FacetRows Defaults to 1 which causes no faceting to occur vertically. Otherwise, supply a numeric value for the number of output grid rows #' @param FacetCols Defaults to 1 which causes no faceting to occur horizontally. Otherwise, supply a numeric value for the number of output grid columns #' @param FacetLevels Faceting rows x columns is the max number of levels allowed in a grid. If your GroupVar has more you can supply the levels to display. #' @param Height "400px" #' @param Width "200px" #' @param Title title #' @param ShowLabels character #' @param Title.YAxis character #' @param Title.XAxis character #' @param EchartsTheme "auritus","azul","bee-inspired","blue","caravan","carp","chalk","cool","dark-bold","dark","eduardo", #' "essos","forest","fresh-cut","fruit","gray","green","halloween","helianthus","infographic","inspired", #' "jazz","london","dark","macarons","macarons2","mint","purple-passion","red-velvet","red","roma","royal", #' "sakura","shine","tech-blue","vintage","walden","wef","weforum","westeros","wonderland" #' @param TimeLine logical #' @param TextColor 'darkblue' #' @param title.fontSize 22 #' @param title.fontWeight "bold" #' @param title.textShadowColor '#63aeff' #' @param title.textShadowBlur 3 #' @param title.textShadowOffsetY 1 #' @param title.textShadowOffsetX -1 #' @param xaxis.fontSize 14 #' @param yaxis.fontSize 14 #' @param Debug Debugging purposes #' @return plot #' @export Plot.VariableImportance <- function(dt = NULL, XVar = NULL, YVar = NULL, GroupVar = NULL, YVarTrans = "Identity", XVarTrans = "Identity", FacetRows = 1, FacetCols = 1, FacetLevels = NULL, AggMethod = 'mean', Height = NULL, Width = NULL, Title = 'Variable Importance Plot', ShowLabels = FALSE, Title.YAxis = NULL, Title.XAxis = NULL, EchartsTheme = "macarons", TimeLine = TRUE, TextColor = "white", title.fontSize = 22, title.fontWeight = "bold", title.textShadowColor = '#63aeff', title.textShadowBlur = 3, title.textShadowOffsetY = 1, title.textShadowOffsetX = -1, xaxis.fontSize = 14, yaxis.fontSize = 14, Debug = FALSE) { if(!data.table::is.data.table(dt)) tryCatch({data.table::setDT(dt)}, error = function(x) { dt <- data.table::as.data.table(dt) }) # Plot dt <- dt[order(Importance)] Var <- names(which(unlist(lapply(dt, is.character)))) Var2 <- names(which(unlist(lapply(dt, is.numeric))))[1L] if(length(Var) == 0L) { Var <- names(which(unlist(lapply(dt, is.factor)))) dt[, eval(Var) := as.character(get(Var))] } dt <- dt[!is.na(get(YVar))] p1 <- echarts4r::e_charts_( dt, x = Var, dispose = TRUE, darkMode = TRUE, width = Width, height = Height) p1 <- echarts4r::e_bar_(e = p1, Var2) p1 <- echarts4r::e_theme(e = p1, name = EchartsTheme) p1 <- echarts4r::e_aria(e = p1, enabled = TRUE) p1 <- echarts4r::e_tooltip(e = p1, trigger = "axis", backgroundColor = "aliceblue") p1 <- echarts4r::e_toolbox_feature(e = p1, feature = c("saveAsImage","dataZoom")) p1 <- echarts4r::e_show_loading(e = p1, hide_overlay = TRUE, text = "Calculating...", color = "#000", text_color = TextColor, mask_color = "#000") p1 <- echarts4r::e_brush(e = p1) p1 <- echarts4r::e_title( p1, Title, textStyle = list( color = TextColor, fontWeight = title.fontWeight, overflow = "truncate", # "none", "truncate", "break", ellipsis = '...', fontSize = title.fontSize, textShadowColor = title.textShadowColor, textShadowBlur = title.textShadowBlur, textShadowOffsetY = title.textShadowOffsetY, textShadowOffsetX = title.textShadowOffsetX)) p1 <- echarts4r::e_flip_coords(e = p1) return(p1) } #' @title Plot.ROC #' #' @description ROC Plot #' #' @author Adrian Antico #' @family Model Evaluation #' #' @param dt source data.table #' @param XVar X-Axis variable name #' @param YVar Y-Axis variable name #' @param AggMethod character #' @param GroupVar Character variable #' @param YVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param XVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param FacetRows Defaults to 1 which causes no faceting to occur vertically. Otherwise, supply a numeric value for the number of output grid rows #' @param FacetCols Defaults to 1 which causes no faceting to occur horizontally. Otherwise, supply a numeric value for the number of output grid columns #' @param FacetLevels Faceting rows x columns is the max number of levels allowed in a grid. If your GroupVar has more you can supply the levels to display. #' @param Height "400px" #' @param Width "200px" #' @param Title character #' @param ShowLabels character #' @param Title.YAxis character #' @param Title.XAxis character #' @param EchartsTheme "auritus","azul","bee-inspired","blue","caravan","carp","chalk","cool","dark-bold","dark","eduardo", #' "essos","forest","fresh-cut","fruit","gray","green","halloween","helianthus","infographic","inspired", #' "jazz","london","dark","macarons","macarons2","mint","purple-passion","red-velvet","red","roma","royal", #' "sakura","shine","tech-blue","vintage","walden","wef","weforum","westeros","wonderland" #' @param TimeLine logical #' @param MouseScroll logical, zoom via mouse scroll #' @param SampleSize numeric #' @param TextColor character hex #' @param Debug Debugging purposes #' @return plot #' @export Plot.ROC <- function(dt = NULL, SampleSize = 100000, XVar = NULL, YVar = NULL, GroupVar = NULL, YVarTrans = "Identity", XVarTrans = "Identity", FacetRows = 1, FacetCols = 1, FacetLevels = NULL, AggMethod = 'mean', Height = NULL, Width = NULL, Title = 'ROC Plot', ShowLabels = FALSE, Title.YAxis = "True Positive Rate", Title.XAxis = "1 - False Positive Rate", EchartsTheme = "macarons", MouseScroll = TRUE, TimeLine = FALSE, TextColor = "white", Debug = FALSE) { # ROC fastROC <- function(preds, target) { class_sorted <- target[order(preds, decreasing = TRUE)] TPR <- cumsum(class_sorted) / sum(target) FPR <- cumsum(class_sorted == 0) / sum(target == 0) return( list( tpr = TPR, fpr = FPR ) ) } # AUC fastAUC <- function(preds, target) { x <- preds y <- target x1 = x[y == 1]; n1 = length(x1); x2 = x[y == 0]; n2 = length(x2); r = rank(c(x1,x2)) auc = (sum(r[1:n1]) - n1 * (n1 + 1) / 2) / n1 / n2 return(auc) } if(!data.table::is.data.table(dt)) tryCatch({data.table::setDT(dt)}, error = function(x) { dt <- data.table::as.data.table(dt) }) # YVar check yvar_class <- class(dt[[YVar]])[1L] if(yvar_class %in% c("factor","character")) { # Shrink data yvar_levels <- as.character(dt[, unique(get(YVar))]) dt1 <- data.table::copy(dt[, .SD, .SDcols = c(XVar, YVar, yvar_levels, GroupVar)]) # Dummify Target nam <- data.table::copy(names(dt1)) dt1 <- DummifyDT(data = dt1, cols = YVar, TopN = length(yvar_levels), KeepFactorCols = FALSE, OneHot = FALSE, SaveFactorLevels = FALSE, SavePath = getwd(), ImportFactorLevels = FALSE, FactorLevelsList = NULL, ClustScore = FALSE, ReturnFactorLevels = FALSE) nam <- setdiff(names(dt1), nam) # Melt Predict Cols dt2 <- data.table::melt.data.table( data = dt1[, .SD, .SDcols = c(names(dt1)[!names(dt1) %in% c(nam,XVar)])], id.vars = GroupVar, measure.vars = names(dt1)[!names(dt1) %in% c(nam,XVar,GroupVar)], variable.name = "Level", value.name = XVar, na.rm = TRUE, variable.factor = FALSE) # Melt Target Cols dt3 <- data.table::melt.data.table( data = dt1[, .SD, .SDcols = c(names(dt1)[!names(dt1) %in% c(yvar_levels,XVar)])], id.vars = GroupVar, measure.vars = nam, variable.name = "Level", value.name = YVar, na.rm = TRUE, variable.factor = FALSE) # Join data dt2[, eval(YVar) := dt3[[YVar]]] # Update Args if(length(GroupVar) > 0L) { dt2[, GroupVariables := do.call(paste, c(.SD, sep = ' :: ')), .SDcols = c(GroupVar, "Level")] GroupVar <- "GroupVariables" if(FacetRows > 1L && FacetCols > 1L) { FacetLevels <- as.character(dt2[, unique(GroupVariables)]) FacetLevels <- FacetLevels[seq_len(min(length(FacetLevels),FacetRows*FacetCols))] dt2 <- dt2[GroupVariables %chin% c(eval(FacetLevels))] } } else if(length(GroupVar) == 0L && (FacetRows > 1L || FacetCols > 1L)) { FacetLevels <- yvar_levels[seq_len(min(length(yvar_levels), FacetRows * FacetCols))] dt2 <- dt2[Level %chin% c(eval(FacetLevels))] GroupVar <- "Level" } else { GroupVar <- "Level" } } else { dt2 <- data.table::copy(dt) } # Data Prep1 if(Debug) print("ROC 1") if(length(GroupVar) > 0L) { vals <- sort(unique(dt2[[GroupVar]])) for(i in seq_along(vals)) { # i = 1 temp <- dt2[get(GroupVar) %in% eval(vals[i])] if(Debug) { print(i) print("ROC 2") } ROC <- tryCatch({fastROC(temp[[XVar]], temp[[YVar]])}, error = function(x) NULL) if(i == 1L && length(ROC) > 0L) { data <- data.table::data.table( GroupLevels = vals[i], Sensitivity = 1-ROC$fpr, Specificity = ROC$tpr) } else if(length(ROC) > 0L) { data <- data.table::rbindlist(list( data, data.table::data.table( GroupLevels = vals[i], Sensitivity = 1-ROC$fpr, Specificity = ROC$tpr) )) } } if(Debug) print("ROC 3") # For Title: auc = AUC AUC <- tryCatch({fastAUC(temp[[XVar]], temp[[YVar]])}, error = function(x) NULL) if(Debug) print("ROC 4") } else { ROC <- tryCatch({fastROC(dt2[[XVar]], dt2[[YVar]])}, error = function(x) NULL) AUC <- tryCatch({fastAUC(dt2[[XVar]], dt2[[YVar]])}, error = function(x) NULL) data <- data.table::data.table( GroupLevels = 0L, Sensitivity = 1-ROC$fpr, Specificity = ROC$tpr) } if(Debug) print("ROC 5") # Data Prep2 if(Debug) print("Plot.Calibration.Line # AutoPlots::Plot.Line()") data[, `1 - Specificity` := 1 - Specificity] data.table::set(data, j = "Specificity", value = NULL) YVar <- "Sensitivity" XVar <- "1 - Specificity" tl <- if(length(GroupVar) == 0L) FALSE else TimeLine if(length(GroupVar) > 0L && (FacetRows > 1L && FacetCols > 1L)) { title <- paste0(Title, ":\nMicro-AUC: ", 100 * round(AUC, 3), "%\n*Excluding cases of all 1's or 0's") } title <- paste0(Title, ":\nMicro-AUC: ", 100 * round(AUC, 3), "%") gv <- if(length(GroupVar) > 0L) "GroupLevels" else NULL data.table::setorderv(x = data, cols = c(gv, "Sensitivity")) if(Debug) print("ROC 6") # Build Plot (Line or Area) if(length(GroupVar) > 0L && FacetRows == 1L && FacetCols == 1L) { p1 <- AutoPlots::Plot.Line( dt = data, PreAgg = TRUE, Smooth = TRUE, Area = FALSE, ShowSymbol = FALSE, Alpha = 0.50, EchartsTheme = EchartsTheme, TimeLine = tl, YVar = YVar, XVar = XVar, GroupVar = gv, YVarTrans = YVarTrans, XVarTrans = XVarTrans, FacetRows = FacetRows, FacetCols = FacetCols, FacetLevels = FacetLevels, MouseScroll = MouseScroll, Height = Height, Width = Width, Title = title, TextColor = TextColor, Debug = Debug) } else { p1 <- AutoPlots::Plot.Area( dt = data, PreAgg = TRUE, Smooth = TRUE, ShowSymbol = FALSE, Alpha = 0.50, EchartsTheme = EchartsTheme, TimeLine = tl, YVar = YVar, XVar = XVar, GroupVar = gv, YVarTrans = YVarTrans, XVarTrans = XVarTrans, FacetRows = FacetRows, FacetCols = FacetCols, FacetLevels = FacetLevels, MouseScroll = MouseScroll, Height = Height, Width = Width, Title = title, TextColor = TextColor, Debug = Debug) } # Return return(p1) } #' @title Plot.ConfusionMatrix #' #' @description Generate variable importance plots #' #' @author Adrian Antico #' @family Model Evaluation #' #' @param EchartsTheme "auritus","azul","bee-inspired","blue","caravan","carp","chalk","cool","dark-bold","dark","eduardo", #' "essos","forest","fresh-cut","fruit","gray","green","halloween","helianthus","infographic","inspired", #' "jazz","london","dark","macarons","macarons2","mint","purple-passion","red-velvet","red","roma","royal", #' "sakura","shine","tech-blue","vintage","walden","wef","weforum","westeros","wonderland" #' @param TimeLine logical #' @param dt source data.table #' @param PreAgg FALSE #' @param XVar Column name of X-Axis variable. If NULL then ignored #' @param YVar Column name of Y-Axis variable. If NULL then ignored #' @param ZVar = "N" #' @param YVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param XVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param ZVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param FacetRows Defaults to 1 which causes no faceting to occur vertically. Otherwise, supply a numeric value for the number of output grid rows #' @param FacetCols Defaults to 1 which causes no faceting to occur horizontally. Otherwise, supply a numeric value for the number of output grid columns #' @param FacetLevels Faceting rows x columns is the max number of levels allowed in a grid. If your GroupVar has more you can supply the levels to display. #' @param NumberBins = 21, #' @param NumLevels_X = NumLevels_Y, #' @param NumLevels_Y = NumLevels_X, #' @param GroupVar Column name of Group Variable for distinct colored histograms by group levels #' @param MouseScroll logical, zoom via mouse scroll #' @param Height "400px" #' @param Width "200px" #' @param Title title #' @param ShowLabels character #' @param Title.YAxis character #' @param Title.XAxis character #' @param xaxis.rotate numeric #' @param yaxis.rotate numeric #' @param ContainLabel logical #' @param GroupVar = NULL #' @param AggMethod Choose from 'mean', 'sum', 'sd', and 'median' #' @param TextColor 'darkblue' #' @param Debug Debugging purposes #' #' @return plot #' @export Plot.ConfusionMatrix <- function(dt = NULL, PreAgg = FALSE, XVar = NULL, YVar = NULL, ZVar = "N", YVarTrans = "Identity", XVarTrans = "Identity", ZVarTrans = "Identity", FacetRows = 1, FacetCols = 1, FacetLevels = NULL, NumberBins = 21, NumLevels_X = 50, NumLevels_Y = 50, Height = NULL, Width = NULL, Title = "Confusion Matrix", ShowLabels = FALSE, Title.YAxis = NULL, Title.XAxis = NULL, EchartsTheme = "macarons", MouseScroll = TRUE, TimeLine = TRUE, TextColor = "white", AggMethod = "count", GroupVar = NULL, xaxis.rotate = 0, yaxis.rotate = 0, ContainLabel = TRUE, Debug = FALSE) { if(!data.table::is.data.table(dt)) tryCatch({data.table::setDT(dt)}, error = function(x) { dt <- data.table::as.data.table(dt) }) # YVar check yvar_class <- class(dt[[YVar]])[1L] if(yvar_class %in% c("factor","character")) { dt1 <- data.table::copy(dt[, .SD, .SDcols = c(XVar, YVar, GroupVar)]) dt1[, paste0(XVar,"_") := .N, by = XVar] dt1[, paste0(YVar,"_") := .N, by = YVar] dt4 <- dt1[, list(N = .N, Mean.X = mean(get(paste0(XVar,"_")), na.rm = TRUE)), by = c(YVar,XVar)] dt4[, `Mean.X` := N / Mean.X] ZVar <- "Mean.X" } else if(!PreAgg) { if(length(unique(dt[[XVar]])) > 2L) { dt[, classPredict := data.table::fifelse(get(XVar) > 0.5, 1, 0)] } dt4 <- data.table::CJ(unique(dt[[YVar]]), unique(dt[["classPredict"]])) data.table::setnames(dt4, c("V1","V2"), c(YVar, XVar)) dt3 <- dt[, list(Metric = .N), by = c(YVar, "classPredict")] data.table::setkeyv(x = dt3, cols = c(YVar, "classPredict")) data.table::setkeyv(x = dt4, cols = c(YVar, XVar)) dt4[dt3, Metric := i.Metric] data.table::set(dt4, i = which(is.na(dt4[["Metric"]])), j = "Metric", value = 0) if(Debug) print("Confusion Matrix Plot.Heatmap") dt4[, `Proportion in Target` := sum(Metric), by = eval(YVar)] dt4[, `Proportion in Target` := data.table::fifelse(`Proportion in Target` > 0, Metric / `Proportion in Target`, 0)] ZVar = "Proportion in Target" } else { dt4 <- data.table::copy(dt) } # Corr Matrix for the automatic ordering data.table::setorderv(dt4, c(XVar,YVar), c(1L,1L)) dt4 <- dt4[!is.na(get(ZVar))] p1 <- Plot.HeatMap( PreAgg = TRUE, EchartsTheme = EchartsTheme, Title = Title, dt = dt4, YVar = YVar, XVar = XVar, ZVar = ZVar, Height = Height, Width = Width, AggMethod = if(!PreAgg) "centroidial" else AggMethod, NumberBins = NumberBins, NumLevels_X = NumLevels_X, NumLevels_Y = NumLevels_Y, MouseScroll = MouseScroll, xaxis.rotate = xaxis.rotate, yaxis.rotate = yaxis.rotate, ContainLabel = ContainLabel) return(p1) } #' @title Plot.Lift #' #' @description Create a cumulative gains chart #' #' @family Model Evaluation #' #' @author Adrian Antico #' #' @param dt source data.table #' @param XVar X-Axis variable name #' @param YVar Y-Axis variable name #' @param ZVar character #' @param GroupVar Character variable #' @param YVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param XVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param ZVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param FacetRows Defaults to 1 which causes no faceting to occur vertically. Otherwise, supply a numeric value for the number of output grid rows #' @param FacetCols Defaults to 1 which causes no faceting to occur horizontally. Otherwise, supply a numeric value for the number of output grid columns #' @param FacetLevels Faceting rows x columns is the max number of levels allowed in a grid. If your GroupVar has more you can supply the levels to display. #' @param NumberBins numeric #' @param PreAgg logical #' @param NumberBins numeric #' @param Height "400px" #' @param Width "200px" #' @param Title character #' @param ShowLabels character #' @param Title.YAxis character #' @param Title.XAxis character #' @param EchartsTheme "auritus","azul","bee-inspired","blue","caravan","carp","chalk","cool","dark-bold","dark","eduardo", #' "essos","forest","fresh-cut","fruit","gray","green","halloween","helianthus","infographic","inspired", #' "jazz","london","dark","macarons","macarons2","mint","purple-passion","red-velvet","red","roma","royal", #' "sakura","shine","tech-blue","vintage","walden","wef","weforum","westeros","wonderland" #' @param TimeLine logical #' @param MouseScroll logical, zoom via mouse scroll #' @param TextColor character hex #' @param Debug Debugging purposes #' @return plot #' @export Plot.Lift <- function(dt = NULL, PreAgg = FALSE, XVar = NULL, YVar = NULL, ZVar = "N", GroupVar = NULL, YVarTrans = "Identity", XVarTrans = "Identity", ZVarTrans = "Identity", FacetRows = 1, FacetCols = 1, FacetLevels = NULL, NumberBins = 20, Height = NULL, Width = NULL, Title = "Confusion Matrix", ShowLabels = FALSE, Title.YAxis = "Lift", Title.XAxis = "Population", EchartsTheme = "macarons", MouseScroll = TRUE, TimeLine = TRUE, TextColor = "white", Debug = FALSE) { if(Debug) print("here 0") if(Debug) print(data.table::is.data.table(dt)) if(!data.table::is.data.table(dt)) { tryCatch({data.table::setDT(dt)}, error = function(x) { dt <- data.table::as.data.table(dt) }) } if(Debug) print("here 1") # YVar check yvar_class <- class(dt[[YVar]])[1L] if(yvar_class %in% c("factor","character")) { if(Debug) print("here 2") # Shrink data yvar_levels <- as.character(as.character(dt[, unique(get(YVar))])) dt1 <- data.table::copy(dt[, .SD, .SDcols = c(XVar, YVar, yvar_levels, GroupVar)]) if(Debug) print("here 3") # Dummify Target nam <- data.table::copy(names(dt1)) dt1 <- DummifyDT(data = dt1, cols = YVar, TopN = length(yvar_levels), KeepFactorCols = FALSE, OneHot = FALSE, SaveFactorLevels = FALSE, SavePath = getwd(), ImportFactorLevels = FALSE, FactorLevelsList = NULL, ClustScore = FALSE, ReturnFactorLevels = FALSE) nam <- setdiff(names(dt1), nam) if(Debug) print("here 4") # Melt Predict Cols dt2 <- data.table::melt.data.table( data = dt1[, .SD, .SDcols = c(names(dt1)[!names(dt1) %in% c(nam,XVar)])], id.vars = GroupVar, measure.vars = names(dt1)[!names(dt1) %in% c(nam,XVar,GroupVar)], variable.name = "Level", value.name = XVar, na.rm = TRUE, variable.factor = FALSE) if(Debug) print("here 5") # Melt Target Cols dt3 <- data.table::melt.data.table( data = dt1[, .SD, .SDcols = c(names(dt1)[!names(dt1) %in% c(yvar_levels,XVar)])], id.vars = GroupVar, measure.vars = nam, variable.name = "Level", value.name = YVar, na.rm = TRUE, variable.factor = FALSE) if(Debug) print("here 6") # Join data dt2[, eval(YVar) := dt3[[YVar]]] if(Debug) print("here 7") # Update Args if(length(GroupVar) > 0L) { dt2[, GroupVariables := do.call(paste, c(.SD, sep = ' :: ')), .SDcols = c(GroupVar, "Level")] GroupVar <- "GroupVariables" if(FacetRows > 1L && FacetCols > 1L) { FacetLevels <- as.character(dt2[, unique(GroupVariables)]) FacetLevels <- FacetLevels[seq_len(min(length(FacetLevels),FacetRows*FacetCols))] dt2 <- dt2[GroupVariables %chin% c(eval(FacetLevels))] } else { FacetLevels <- yvar_levels } } else { if(FacetRows > 1L && FacetCols > 1L) { FacetLevels <- yvar_levels FacetLevels <- FacetLevels[seq_len(min(length(FacetLevels),FacetRows*FacetCols))] dt2 <- dt2[Level %chin% c(eval(FacetLevels))] } else { FacetLevels <- yvar_levels } GroupVar <- "Level" dt2 <- dt2[Level %chin% c(eval(FacetLevels))] GroupVar <- "Level" } } else { dt2 <- data.table::copy(dt) } if(Debug) print("here 9") if(yvar_class %in% c("factor","character") || length(GroupVar) > 0L) { Levels <- sort(as.character(unique(dt2[[GroupVar]]))) dl <- list() if(Debug) print("Start For-Loop") if(length(NumberBins) == 0L) NumberBins <- 21 if(max(NumberBins) > 1L) NumberBins <- c(seq(1/NumberBins, 1 - 1/NumberBins, 1/NumberBins), 1) for(i in Levels) {# i = Levels[i] if(Debug) print("iter") if(Debug) print(i) dt_ <- dt2[get(GroupVar) %in% eval(i)] if(Debug) print(" iter 2") dt_[, NegScore := -get(XVar)] if(Debug) print(" iter 3") if(Debug) print(" iter 4") Cuts <- quantile(x = dt_[["NegScore"]], na.rm = TRUE, probs = NumberBins) if(Debug) print(" iter 5") dt_[, eval(YVar) := as.character(get(YVar))] if(Debug) print(" iter 6") grp <- dt_[, .N, by = eval(YVar)][order(N)] if(Debug) print(" iter 7") smaller_class <- grp[1L, 1L][[1L]] if(Debug) print(" iter 8") dt3 <- round(100 * sapply(Cuts, function(x) { dt_[NegScore <= x & get(YVar) == eval(smaller_class), .N] / dt_[get(YVar) == eval(smaller_class), .N] }), 2) if(Debug) print(" iter 9") dt3 <- rbind(dt3, -Cuts) if(Debug) print(" iter 10") rownames(dt3) <- c("Lift", "Score.Point") if(Debug) print(" iter 11") dt4 <- grp[1,2] / (grp[2,2] + grp[1,2]) if(Debug) print(" iter 12") dt5 <- data.table::as.data.table(t(dt3)) if(Debug) print(" iter 13") dt5[, Population := as.numeric(100 * eval(NumberBins))] if(Debug) print(" iter 14") dt5[, Lift := round(Lift / 100 / NumberBins, 2)] if(Debug) print(" iter 15") dt5[, Level := eval(i)] if(Debug) print(" iter 16") if(data.table::is.data.table(dt5)) { if(Debug) print(" iter rbindlist") dl[[i]] <- data.table::rbindlist(list( data.table::data.table(Lift = 0, Score.Point = 0, Population = 0, Level = eval(i)), dt5 ), use.names = TRUE) } } if(Debug) print(" For Loop Done: rbindlist") dt6 <- data.table::rbindlist(dl) } else { if(Debug) print("here 10") # Data Prep dt2[, NegScore := -get(XVar)] NumberBins <- c(seq(1/NumberBins, 1 - 1/NumberBins, 1/NumberBins), 1) Cuts <- quantile(x = dt2[["NegScore"]], na.rm = TRUE, probs = NumberBins) dt2[, eval(YVar) := as.character(get(YVar))] grp <- dt2[, .N, by = eval(YVar)][order(N)] smaller_class <- grp[1L, 1L][[1L]] dt3 <- round(100 * sapply(Cuts, function(x) { dt2[NegScore <= x & get(YVar) == eval(smaller_class), .N] / dt2[get(YVar) == eval(smaller_class), .N] }), 2) dt3 <- rbind(dt3, -Cuts) rownames(dt3) <- c("Lift", "Score.Point") dt4 <- grp[1,2] / (grp[2,2] + grp[1,2]) dt5 <- data.table::as.data.table(t(dt3)) dt5[, Population := as.numeric(100 * eval(NumberBins))] dt5[, Lift := round(Lift / 100 / NumberBins, 2)] if(data.table::is.data.table(dt5)) { dt6 <- data.table::rbindlist(list( data.table::data.table(Score.Point = 0, Population = 0, Lift = 0), dt5 ), use.names = TRUE) } } if(Debug) print("here 11") # Build if(Debug) print(names(dt6)) if("Level" %in% names(dt6)) { dt6 <- dt6[Population > 0, .SD, .SDcols = c("Population","Lift", "Level")] GroupVar <- "Level" } else { dt6 <- dt6[Population > 0, .SD, .SDcols = c("Population","Lift")] } if(Debug) print("here 12") if(FacetRows == 1L && FacetCols == 1L && length(GroupVar) > 0L) { if(Debug) print("here 13") #dt6 <- dt6[!is.na(Lift)] p1 <- AutoPlots::Plot.Line( dt = dt6, PreAgg = TRUE, XVar = "Population", YVar = "Lift", GroupVar = GroupVar, YVarTrans = YVarTrans, XVarTrans = XVarTrans, FacetRows = FacetRows, FacetCols = FacetCols, ShowLabels = ShowLabels, Title.YAxis = "Lift", Title.XAxis = "Population", FacetLevels = NULL, Height = Height, Width = Width, Title = Title, Area = FALSE, Smooth = TRUE, ShowSymbol = FALSE, MouseScroll = MouseScroll, EchartsTheme = EchartsTheme, TimeLine = FALSE, TextColor = TextColor, Debug = FALSE) } else { if(Debug) print("here 14") #dt6 <- dt6[!is.na(Lift)] p1 <- AutoPlots::Plot.Area( dt = dt6, PreAgg = TRUE, XVar = "Population", YVar = "Lift", GroupVar = GroupVar, YVarTrans = YVarTrans, XVarTrans = XVarTrans, FacetRows = FacetRows, FacetCols = FacetCols, FacetLevels = NULL, Height = Height, Width = Width, Title = Title, ShowLabels = ShowLabels, MouseScroll = MouseScroll, Title.YAxis = "Lift", Title.XAxis = "Population", Smooth = TRUE, ShowSymbol = FALSE, EchartsTheme = EchartsTheme, TimeLine = FALSE, TextColor = TextColor, Debug = FALSE) } if(Debug) print("here 16") if(Debug) print("here 17") p1 <- echarts4r::e_labels(e = p1, show = TRUE) # Return return(p1) } #' @title Plot.Gains #' #' @description Create a cumulative gains chart #' #' @family Model Evaluation #' #' @author Adrian Antico #' #' @param dt source data.table #' @param XVar X-Axis variable name #' @param YVar Y-Axis variable name #' @param ZVar character #' @param GroupVar Character variable #' @param YVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param XVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param ZVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param FacetRows Defaults to 1 which causes no faceting to occur vertically. Otherwise, supply a numeric value for the number of output grid rows #' @param FacetCols Defaults to 1 which causes no faceting to occur horizontally. Otherwise, supply a numeric value for the number of output grid columns #' @param FacetLevels Faceting rows x columns is the max number of levels allowed in a grid. If your GroupVar has more you can supply the levels to display. #' @param NumberBins numeric #' @param PreAgg logical #' @param NumberBins numeric #' @param Height NULL #' @param Width NULL #' @param Title character #' @param ShowLabels character #' @param Title.YAxis character #' @param Title.XAxis character #' @param EchartsTheme "auritus","azul","bee-inspired","blue","caravan","carp","chalk","cool","dark-bold","dark","eduardo", #' "essos","forest","fresh-cut","fruit","gray","green","halloween","helianthus","infographic","inspired", #' "jazz","london","dark","macarons","macarons2","mint","purple-passion","red-velvet","red","roma","royal", #' "sakura","shine","tech-blue","vintage","walden","wef","weforum","westeros","wonderland" #' @param TimeLine logical #' @param MouseScroll logical, zoom via mouse scroll #' @param TextColor character hex #' @param Debug Debugging purposes #' @return plot #' @export Plot.Gains <- function(dt = NULL, PreAgg = FALSE, XVar = NULL, YVar = NULL, ZVar = "N", GroupVar = NULL, YVarTrans = "Identity", XVarTrans = "Identity", ZVarTrans = "Identity", FacetRows = 1, FacetCols = 1, FacetLevels = NULL, NumberBins = 20, Height = NULL, Width = NULL, Title = "Gains Plot", ShowLabels = FALSE, Title.YAxis = "Gain", Title.XAxis = "Population", EchartsTheme = "macarons", MouseScroll = TRUE, TimeLine = TRUE, TextColor = "white", Debug = FALSE) { if(Debug) print("here 1") if(!data.table::is.data.table(dt)) tryCatch({data.table::setDT(dt)}, error = function(x) { dt <- data.table::as.data.table(dt) }) # YVar check yvar_class <- class(dt[[YVar]])[1L] if(yvar_class %in% c("factor","character")) { if(Debug) print("here 2") # Shrink data yvar_levels <- as.character(as.character(dt[, unique(get(YVar))])) dt1 <- data.table::copy(dt[, .SD, .SDcols = c(XVar, YVar, yvar_levels, GroupVar)]) if(Debug) print("here 3") # Dummify Target nam <- data.table::copy(names(dt1)) dt1 <- DummifyDT(data = dt1, cols = YVar, TopN = length(yvar_levels), KeepFactorCols = FALSE, OneHot = FALSE, SaveFactorLevels = FALSE, SavePath = getwd(), ImportFactorLevels = FALSE, FactorLevelsList = NULL, ClustScore = FALSE, ReturnFactorLevels = FALSE) nam <- setdiff(names(dt1), nam) if(Debug) print("here 4") # Melt Predict Cols dt2 <- data.table::melt.data.table( data = dt1[, .SD, .SDcols = c(names(dt1)[!names(dt1) %in% c(nam,XVar)])], id.vars = GroupVar, measure.vars = names(dt1)[!names(dt1) %in% c(nam,XVar,GroupVar)], variable.name = "Level", value.name = XVar, na.rm = TRUE, variable.factor = FALSE) if(Debug) print("here 5") # Melt Target Cols dt3 <- data.table::melt.data.table( data = dt1[, .SD, .SDcols = c(names(dt1)[!names(dt1) %in% c(yvar_levels,XVar)])], id.vars = GroupVar, measure.vars = nam, variable.name = "Level", value.name = YVar, na.rm = TRUE, variable.factor = FALSE) if(Debug) print("here 6") # Join data dt2[, eval(YVar) := dt3[[YVar]]] if(Debug) print("here 7") # Update Args if(length(GroupVar) > 0L) { dt2[, GroupVariables := do.call(paste, c(.SD, sep = ' :: ')), .SDcols = c(GroupVar, "Level")] GroupVar <- "GroupVariables" if(FacetRows > 1L && FacetCols > 1L) { FacetLevels <- as.character(dt2[, unique(GroupVariables)]) FacetLevels <- FacetLevels[seq_len(min(length(FacetLevels),FacetRows*FacetCols))] dt2 <- dt2[GroupVariables %chin% c(eval(FacetLevels))] } else { FacetLevels <- yvar_levels } } else { if(FacetRows > 1L && FacetCols > 1L) { FacetLevels <- yvar_levels FacetLevels <- FacetLevels[seq_len(min(length(FacetLevels),FacetRows*FacetCols))] dt2 <- dt2[Level %chin% c(eval(FacetLevels))] } else { FacetLevels <- yvar_levels } GroupVar <- "Level" dt2 <- dt2[Level %chin% c(eval(FacetLevels))] GroupVar <- "Level" } } else { dt2 <- data.table::copy(dt) } if(Debug) print("here 9") if(yvar_class %in% c("factor","character") || length(GroupVar) > 0L) { Levels <- sort(as.character(unique(dt2[[GroupVar]]))) dl <- list() if(Debug) print("Start For-Loop") if(length(NumberBins) == 0L) NumberBins <- 21 if(max(NumberBins) > 1L) NumberBins <- c(seq(1/NumberBins, 1 - 1/NumberBins, 1/NumberBins), 1) for(i in Levels) {# i = 1 if(Debug) print("iter") if(Debug) print(i) dt_ <- dt2[get(GroupVar) %in% eval(i)] if(Debug) print(" iter 2") dt_[, NegScore := -get(XVar)] if(Debug) print(" iter 3") if(Debug) print(" iter 4") Cuts <- quantile(x = dt_[["NegScore"]], na.rm = TRUE, probs = NumberBins) if(Debug) print(" iter 5") dt_[, eval(YVar) := as.character(get(YVar))] if(Debug) print(" iter 6") grp <- dt_[, .N, by = eval(YVar)][order(N)] if(Debug) print(" iter 7") smaller_class <- grp[1L, 1L][[1L]] if(Debug) print(" iter 8") dt3 <- round(100 * sapply(Cuts, function(x) { dt_[NegScore <= x & get(YVar) == eval(smaller_class), .N] / dt_[get(YVar) == eval(smaller_class), .N] }), 2) if(Debug) print(" iter 9") dt3 <- rbind(dt3, -Cuts) if(Debug) print(" iter 10") rownames(dt3) <- c("Gain", "Score.Point") if(Debug) print(" iter 11") dt4 <- grp[1,2] / (grp[2,2] + grp[1,2]) if(Debug) print(" iter 12") dt5 <- data.table::as.data.table(t(dt3)) if(Debug) print(" iter 13") dt5[, Population := as.numeric(100 * eval(NumberBins))] if(Debug) print(" iter 14") dt5[, Gain := round(Gain / 100 / NumberBins, 2)] if(Debug) print(" iter 15") dt5[, Level := eval(i)] if(Debug) print(" iter 16") if(data.table::is.data.table(dt5)) { if(Debug) print(" iter rbindlist") dl[[i]] <- data.table::rbindlist(list( data.table::data.table(Gain = 0, Score.Point = 0, Population = 0, Level = eval(i)), dt5 ), use.names = TRUE) } } dt6 <- data.table::rbindlist(dl) if(Debug) print(" For Loop Done: rbindlist") if("Level" %in% names(dt5)) { dt6 <- dt6[Population > 0, .SD, .SDcols = c("Population","Gain", "Level")] GroupVar <- "Level" } else { dt6 <- dt6[Population > 0, .SD, .SDcols = c("Population","Gain")] } } else { if(Debug) print("here 10") # Data Prep dt2[, NegScore := -get(XVar)] NumberBins <- c(seq(1/NumberBins, 1 - 1/NumberBins, 1/NumberBins), 1) Cuts <- quantile(x = dt2[["NegScore"]], na.rm = TRUE, probs = NumberBins) dt2[, eval(YVar) := as.character(get(YVar))] grp <- dt2[, .N, by = eval(YVar)][order(N)] smaller_class <- grp[1L, 1L][[1L]] dt3 <- round(100 * sapply(Cuts, function(x) { dt2[NegScore <= x & get(YVar) == eval(smaller_class), .N] / dt2[get(YVar) == eval(smaller_class), .N] }), 2) dt3 <- rbind(dt3, -Cuts) rownames(dt3) <- c("Gain", "Score.Point") dt4 <- grp[1,2] / (grp[2,2] + grp[1,2]) dt5 <- data.table::as.data.table(t(dt3)) dt5[, Population := as.numeric(100 * eval(NumberBins))] dt5[, Gain := round(Gain / 100 / NumberBins, 2)] if(data.table::is.data.table(dt5)) { dt6 <- data.table::rbindlist(list( data.table::data.table(Gain = 0, Score.Point = 0, Population = 0), dt5 ), use.names = TRUE) } } if(Debug) print("here 11") # Build if(Debug) print(names(dt6)) if(length(GroupVar) > 0L && GroupVar %in% names(dt6)) { dt6 <- dt6[Population > 0, .SD, .SDcols = c("Population","Gain", GroupVar)] } else { dt6 <- dt6[Population > 0, .SD, .SDcols = c("Population","Gain")] } if(Debug) print("here 12") if(FacetRows == 1L && FacetCols == 1L && length(GroupVar) > 0L) { if(Debug) print("here 13") #dt6 <- dt6[!is.na(Gain)] p1 <- AutoPlots::Plot.Line( dt = dt6, PreAgg = TRUE, XVar = "Population", YVar = "Gain", GroupVar = GroupVar, YVarTrans = YVarTrans, XVarTrans = XVarTrans, FacetRows = FacetRows, FacetCols = FacetCols, FacetLevels = NULL, ShowLabels = ShowLabels, Title.YAxis = "Gain", Title.XAxis = "Population", Height = Height, Width = Width, Title = Title, MouseScroll = MouseScroll, Area = FALSE, Smooth = TRUE, ShowSymbol = FALSE, EchartsTheme = EchartsTheme, TimeLine = FALSE, TextColor = TextColor, Debug = FALSE) } else { if(Debug) print("here 14") #dt6 <- dt6[!is.na(Gain)] p1 <- AutoPlots::Plot.Area( dt = dt6, PreAgg = TRUE, XVar = "Population", YVar = "Gain", GroupVar = GroupVar, YVarTrans = YVarTrans, XVarTrans = XVarTrans, FacetRows = FacetRows, FacetCols = FacetCols, FacetLevels = NULL, ShowLabels = ShowLabels, Title.YAxis = "Gain", Title.XAxis = "Population", Height = Height, Width = Width, Title = Title, MouseScroll = MouseScroll, Smooth = TRUE, ShowSymbol = FALSE, EchartsTheme = EchartsTheme, TimeLine = FALSE, TextColor = TextColor, Debug = FALSE) } if(Debug) print("here 16") if(Debug) print("here 17") p1 <- echarts4r::e_labels(e = p1, show = TRUE) # Return return(p1) } #' @title Plot.BinaryMetrics #' #' @description Line plot of evaluation metrics across thresholds #' #' @author Adrian Antico #' @family Model Evaluation #' #' @param dt source data.table #' @param SampleSize numeric #' @param XVar X-Axis variable name #' @param YVar Y-Axis variable name #' @param ZVar character #' @param YVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param XVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param ZVarTrans "Asinh", "Log", "LogPlus1", "Sqrt", "Asin", "Logit", "PercRank", "Standardize", "BoxCox", "YeoJohnson" #' @param CostMatrixWeights vector length 4. FP, FP, FN, TP #' @param Height "400px" #' @param Width "200px" #' @param FacetRows Defaults to 1 which causes no faceting to occur vertically. Otherwise, supply a numeric value for the number of output grid rows #' @param FacetCols Defaults to 1 which causes no faceting to occur horizontally. Otherwise, supply a numeric value for the number of output grid columns #' @param FacetLevels Faceting rows x columns is the max number of levels allowed in a grid. If your GroupVar has more you can supply the levels to display. #' @param Metrics Multiple selection "Utility","MCC","Accuracy","F1_Score","F2_Score","F0.5_Score","ThreatScore","TPR","TNR","FNR","FPR","FDR","FOR" #' @param NumberBins numeric #' @param PreAgg logical #' @param Title character #' @param ShowLabels character #' @param Title.YAxis character #' @param Title.XAxis character #' @param EchartsTheme "auritus","azul","bee-inspired","blue","caravan","carp","chalk","cool","dark-bold","dark","eduardo", #' "essos","forest","fresh-cut","fruit","gray","green","halloween","helianthus","infographic","inspired", #' "jazz","london","dark","macarons","macarons2","mint","purple-passion","red-velvet","red","roma","royal", #' "sakura","shine","tech-blue","vintage","walden","wef","weforum","westeros","wonderland" #' @param EchartsLabels character #' @param TimeLine logical #' @param MouseScroll logical, zoom via mouse scroll #' @param TextColor hex character #' @param AggMethod character #' @param GroupVar Character variable #' @param Debug Debugging purposes #' @return plot #' @export Plot.BinaryMetrics <- function(dt = NULL, PreAgg = FALSE, AggMethod = "mean", SampleSize = 100000L, XVar = NULL, YVar = NULL, ZVar = NULL, Metrics = c("Utility","MCC","Accuracy","F1_Score","F2_Score","F0.5_Score","ThreatScore","TPR","TNR","FNR","FPR","FDR","FOR"), GroupVar = NULL, YVarTrans = "Identity", XVarTrans = "Identity", ZVarTrans = "Identity", FacetRows = 1, FacetCols = 1, FacetLevels = NULL, CostMatrixWeights = c(0,1,1,0), NumberBins = 20, Height = NULL, Width = NULL, Title = "Binary Metrics", MouseScroll = TRUE, ShowLabels = FALSE, Title.YAxis = NULL, Title.XAxis = NULL, EchartsTheme = "macarons", EchartsLabels = FALSE, TimeLine = TRUE, TextColor = "white", Debug = FALSE) { if(!data.table::is.data.table(dt)) tryCatch({data.table::setDT(dt)}, error = function(x) { dt <- data.table::as.data.table(dt) }) # Minimize data before moving on if(Debug) print("Plot.PartialDependence.Box # Minimize data before moving on") Ncols <- ncol(dt) if(Ncols > 2L && length(GroupVar) == 0L) { dt1 <- data.table::copy(dt[, .SD, .SDcols = c(YVar, XVar, ZVar)]) } else if(Ncols > 3L && length(GroupVar) > 0L) { dt1 <- data.table::copy(dt[, .SD, .SDcols = c(YVar, XVar, ZVar, GroupVar[1L])]) } else { dt1 <- data.table::copy(dt) } # If actual is in factor form, convert to numeric if(Debug) print("Plot.PartialDependence.Box # If actual is in factor form, convert to numeric") if(!is.numeric(dt1[[YVar]])) { data.table::set(dt1, j = YVar, value = as.numeric(as.character(dt1[[YVar]]))) } # Build Plot tl <- if(length(GroupVar) == 0L) FALSE else TimeLine dt2 <- BinaryMetrics( ValidationData. = dt1, TargetColumnName. = "BinaryTarget", CostMatrixWeights. = CostMatrixWeights, SaveModelObjects. = FALSE) dt3 <- data.table::melt.data.table( data = dt2, id.vars = "Threshold", measure.vars = Metrics) # Build if(Debug) print("AutoPlots::Plot.BinaryMetrics --> AutoPlots::Plot.Line()") p1 <- AutoPlots::Plot.Line( dt = dt3, PreAgg = TRUE, AggMethod = "mean", Area = FALSE, SampleSize = SampleSize, XVar = XVar, YVar = YVar, GroupVar = GroupVar, YVarTrans = YVarTrans, XVarTrans = XVarTrans, FacetRows = FacetRows, FacetCols = FacetCols, FacetLevels = FacetLevels, MouseScroll = MouseScroll, Height = Height, Width = Width, Title = Title, EchartsTheme = EchartsTheme, TimeLine = tl, TextColor = TextColor, Debug = Debug) return(p1) } #' @title Plot.ShapImportance #' #' @description Plot.ShapImportance variable importance #' #' @family Model Evaluation #' @author Adrian Antico #' #' @param dt source data.table #' @param PreAgg logical #' @param YVar Names of shap columns #' @param GroupVar Name of by variable #' @param EchartsTheme "dark-blue" #' @param FacetRows Defaults to 1 which causes no faceting to occur vertically. Otherwise, supply a numeric value for the number of output grid rows #' @param FacetCols Defaults to 1 which causes no faceting to occur horizontally. Otherwise, supply a numeric value for the number of output grid columns #' @param FacetLevels Faceting rows x columns is the max number of levels allowed in a grid. If your GroupVar has more you can supply the levels to display. #' @param AggMethod "mean", "median", "sum", "sd", "skewness","kurtosis", "coeffvar", "meanabs", "medianabs", "sumabs", "sdabs", "skewnessabs", "kurtosisabs", "CoeffVarabs" #' @param NumberBins = 21 #' @param NumLevels_Y = 20 #' @param NumLevels_X = 20 #' @param TextColor character #' @param Height "400px" #' @param Width "200px" #' @param Title "Heatmap" #' @param ShowLabels character #' @param Title.YAxis character #' @param Title.XAxis character #' @param Debug = FALSE #' @return plot #' @export Plot.ShapImportance <- function(dt, PreAgg = FALSE, AggMethod = 'meanabs', YVar = NULL, GroupVar = NULL, FacetRows = 1, FacetCols = 1, FacetLevels = NULL, NumberBins = 21, NumLevels_X = 33, NumLevels_Y = 33, Height = NULL, Width = NULL, Title = "Shap Importance", ShowLabels = FALSE, Title.YAxis = NULL, Title.XAxis = NULL, EchartsTheme = "dark", TextColor = "white", Debug = FALSE) { if(Debug) print("ShapImportance Step 1") # Subset columns if(!PreAgg) { if(!data.table::is.data.table(dt)) tryCatch({data.table::setDT(dt)}, error = function(x) { dt <- data.table::as.data.table(dt) }) if(Debug) print("ShapImportance Step 2") if(length(GroupVar) > 1L) GroupVar <- GroupVar[1L] if(length(YVar) == 0L) YVar <- names(dt)[names(dt) %like% "Shap_"] dt1 <- dt[, .SD, .SDcols = c(YVar, GroupVar)] # Define Aggregation function if(Debug) print("Plot.ShapImportance # Define Aggregation function") if(Debug) print(AggMethod) aggFunc <- SummaryFunction(AggMethod) if(length(GroupVar) > 0L) { dt1 <- dt1[, lapply(.SD, FUN = noquote(aggFunc)), by = c(GroupVar)] dt2 <- data.table::melt.data.table(data = dt1, id.vars = c(GroupVar), measure.vars = YVar, variable.name = "Variable", value.name = "Importance") } else { dt1 <- dt1[, lapply(.SD, FUN = noquote(aggFunc))] dt2 <- data.table::melt.data.table(data = dt1, id.vars = NULL, measure.vars = YVar, variable.name = "Variable", value.name = "Importance") } } else { dt2 <- data.table::copy(dt) } # Add a column that ranks predicted values if(length(GroupVar) > 0L) { p1 <- AutoPlots::Plot.HeatMap( dt = dt2, PreAgg = TRUE, AggMethod = "mean", YVar = "Variable", XVar = GroupVar, ZVar = "Importance", NumberBins = 21, NumLevels_X = NumLevels_Y, NumLevels_Y = NumLevels_X, MouseScroll = FALSE, Height = Height, Width = Width, Title = paste0("Shap Importance: AggMethod = ", AggMethod), EchartsTheme = EchartsTheme, Y_Scroll = Y_Scroll) return(p1) } else { if(Debug) print("Right Here Yo") p1 <- AutoPlots::Plot.VariableImportance( dt = dt2, AggMethod = 'mean', XVar = "Variable", YVar = "Importance", GroupVar = NULL, YVarTrans = "Identity", XVarTrans = "Identity", FacetRows = FacetRows, FacetCols = FacetCols, FacetLevels = FacetLevels, Height = Height, Width = Width, Title = paste0("Shap Importance: AggMethod = ", AggMethod), EchartsTheme = EchartsTheme, TimeLine = TimeLine, TextColor = TextColor, Debug = Debug) return(p1) } } # ---- # ---- # @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ---- # > Stocks Plots Functions ---- # @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ---- # #' @noRd # holidayNYSE <- function(year = getRmetricsOptions("currentYear")) { # # A function implemented by Diethelm Wuertz # # improved speed and handling of time zone by Yohan Chalabi # # # Description: # # Returns 'timeDate' object for full-day NYSE holidays # # # Arguments: # # year - an integer variable or vector for the year(s) # # ISO-8601 formatted as "CCYY" where easter or # # easter related feasts should be computed. # # # Value: # # Returns the holiday calendar for the NYSE formatted as # # 'timeDate' object. # # # Details: # # The "New York Stock Exchange" calendar starts from year 1885. # # The rules are listed at the web site http://www.nyse.com. # # # Example: # # > holiday.NYSE(2004) # # [1] "America/New_York" # # [1] [2004-01-01] [2004-01-19] [2004-02-16] [2004-04-09] # # [5] [2004-05-31] [2004-07-05] [2004-09-06] [2004-11-25] # # # FUNCTION: # library(timeDate) # # Settings: # holidays <- NULL # # # Iterate years: # for (y in year ) { # if (y >= 1885) # holidays <- c(holidays, as.character(USNewYearsDay(y))) # if (y >= 1885) # holidays <- c(holidays, as.character(USIndependenceDay(y))) # if (y >= 1885) # holidays <- c(holidays, as.character(USThanksgivingDay(y))) # if (y >= 1885) # holidays <- c(holidays, as.character(USChristmasDay(y))) # if (y >= 1887) # holidays <- c(holidays, as.character(USLaborDay(y))) # if (y != 1898 & y != 1906 & y != 1907) # holidays <- c(holidays, as.character(USGoodFriday(y))) # if (y >= 1909 & y <= 1953) # holidays <- c(holidays, as.character(USColumbusDay(y))) # if (y >= 1998) # holidays <- c(holidays, as.character(USMLKingsBirthday(y))) # if (y >= 1896 & y <= 1953) # holidays <- c(holidays, as.character(USLincolnsBirthday(y))) # if (y <= 1970) # holidays <- c(holidays, as.character(USWashingtonsBirthday(y))) # if (y > 1970) # holidays <- c(holidays, as.character(USPresidentsDay(y))) # if (y == 1918 | y == 1921 | (y >= 1934 & y <= 1953)) # holidays <- c(holidays, as.character(USVeteransDay(y))) # if (y <= 1968 | y == 1972 | y == 1976 | y == 1980) # holidays <- c(holidays, as.character(USElectionDay(y))) # if (y <= 1970) # holidays <- c(holidays, as.character(USDecorationMemorialDay(y))) # if (y >= 1971) # holidays <- c(holidays, as.character(USMemorialDay(y))) # } # # # Sort and Convert to 'timeDate': # holidays <- sort(holidays) # ans <- timeDate(format(holidays), zone = "NewYork", FinCenter = "NewYork") # # # Move Sunday Holidays to Monday: # posix1 <- as.POSIXlt(ans, tz = "GMT") # ans <- ans + as.integer(posix1$wday==0) * 24 * 3600 # # # After July 3, 1959, move Saturday holidays to Friday # # ... except if at the end of monthly/yearly accounting period # # this is the last business day of a month. # posix2 <- as.POSIXlt(as.POSIXct(ans, tz = "GMT") - 24 * 3600) # y <- posix2$year + 1900 # m <- posix2$mon + 1 # calendar <- timeCalendar(y = y+(m+1)%/%13, # m = m+1-(m+1)%/%13*12, d = 1, # zone = "GMT", FinCenter = "GMT") # lastday <- as.POSIXlt(calendar - 24*3600, tz = "GMT")$mday # lon <- .last.of.nday(year = y, month = m, lastday = lastday, nday = 5) # ExceptOnLastFriday <- timeDate(format(lon), zone = "NewYork", # FinCenter = "NewYork") # ans <- ans - as.integer(ans >= timeDate("1959-07-03", # zone ="GMT", FinCenter = "GMT") & # as.POSIXlt(ans, tz = "GMT")$wday == 6 & # (ans - 24*3600) != ExceptOnLastFriday ) * 24 * 3600 # # # Remove Remaining Weekend Dates: # posix3 <- as.POSIXlt(ans, tz = "GMT") # ans <- ans[ !(posix3$wday == 0 | posix3$wday == 6)] # # # Return Value: # ans # } # # #' @noRd # StockSymbols <- function() { # x <- jsonlite::fromJSON("https://api.polygon.io/v3/reference/tickers?active=true&sort=ticker&order=asc&limit=1000&apiKey=hvyL7ZOsKK_5PNplOmv55tBTRd8rdA20") # xx <- data.table::setDT(x$results) # return(xx[, .SD, .SDcols = c(names(xx)[c(1,2,5,6,12)])]) # } # # #' @noRd # GetAllTickers <- function() { # x <- jsonlite::fromJSON("https://api.polygon.io/v3/reference/tickers?active=true&sort=ticker&order=asc&limit=1000&apiKey=hvyL7ZOsKK_5PNplOmv55tBTRd8rdA20") # xx <- data.table::setDT(x$results) # counter <- 1000L # while(is.list(x)) { # if(Debug) print(paste0('Working on first ', counter, ' ticker symbols')) # x <- tryCatch({jsonlite::fromJSON(paste0(x$next_url, "&apiKey=hvyL7ZOsKK_5PNplOmv55tBTRd8rdA20"))}, error = function(x) 1) # if(x != 1) { # xx <- data.table::rbindlist(list(xx, data.table::setDT(x$results)), fill = TRUE, use.names = TRUE) # counter <- counter + 1000L # Sys.sleep(12L) # } else { # break # } # } # #xx <- xx[, .SD, .SDcols = c(names(xx)[c(1,2,5,6,12)])] # PostGRE_RemoveCreateAppend( # data = xx, # TableName = "ticker_data", # CloseConnection = TRUE, # CreateSchema = NULL, # Host = "localhost", # DBName = "RemixAutoML", # User = "postgres", # Port = 5432, # Password = "Aa1028#@", # Temporary = FALSE, # Connection = NULL, # Append = TRUE) # return(xx) # } # # #' @noRd # OptionsSymbols <- function() { # x <- jsonlite::fromJSON('https://api.polygon.io/v3/reference/tickers/types?asset_class=options&locale=us&apiKey=hvyL7ZOsKK_5PNplOmv55tBTRd8rdA20') # xx <- data.table::setDT(x$results) # return(xx[, .SD, .SDcols = c(names(xx)[c(1,2,5,6,12)])]) # } # # #' @noRd # CryptoSymbols <- function() { # x <- jsonlite::fromJSON('https://api.polygon.io/v3/reference/tickers/types?asset_class=crypto&locale=us&apiKey=hvyL7ZOsKK_5PNplOmv55tBTRd8rdA20') # xx <- data.table::setDT(x$results) # return(xx[, .SD, .SDcols = c(names(xx)[c(1,2,5,6,12)])]) # } # # #' @noRd # Financials <- function() { # x <- jsonlite::fromJSON("https://api.polygon.io/vX/reference/financials?apiKey=hvyL7ZOsKK_5PNplOmv55tBTRd8rdA20") # } # # #' @title StockData # #' # #' @description Create stock data for plotting using Plot.Stock() # #' # #' @family Stock Plots # #' @author Adrian Antico # #' # #' @param PolyOut NULL. If NULL, data is pulled. If supplied, data is not pulled. # #' @param Type 'candlestick', 'ohlc' # #' @param Metric Stock Price, Percent Returns (use symbol for percent), Percent Log Returns (use symbol for percent), Index, Quadratic Variation # #' @param TimeAgg = 'days', 'weeks', 'months' # #' @param Symbol ticker symbol string # #' @param CompanyName company name if you have it. ends up in title, that is all # #' @param StartDate Supply a start date. E.g. '2022-01-01' # #' @param EndDate Supply an end date. E.g. `Sys.Date()` # #' @param APIKey Supply your polygon API key # #' @param timeElapsed = 60 # #' # #' @export # StockData <- function(PolyOut = NULL, # Symbol = 'TSLA', # CompanyName = 'Tesla Inc. Common Stock', # Metric = 'Stock Price', # TimeAgg = 'days', # StartDate = '2022-01-01', # EndDate = Sys.Date(), # APIKey = NULL, # timeElapsed = 61, # Debug = FALSE) { # # if(length(APIKey) == 0L) return(NULL) # # StartDate <- as.Date(StartDate) # EndDate <- min(Sys.Date()-1, as.Date(EndDate)) # # # Use data if provided # if(!data.table::is.data.table(PolyOut)) { # if(Debug) print("here 1a") # PolyOut <- jsonlite::fromJSON(paste0("https://api.polygon.io/v2/aggs/ticker/",Symbol,"/range/1/day/",StartDate, "/", EndDate, "?adjusted=true&sort=asc&limit=10000&apiKey=", APIKey)) # # data <- data.table::as.data.table(PolyOut$results) # data[, Date := as.Date(lubridate::as_datetime((t+10800000)/1000, origin = "1970-01-01"))] # if(Debug) print(head(data)) # # tryCatch({ # if(TimeAgg == 'weeks') { # data[, Date := lubridate::floor_date(Date, unit = 'weeks')] # data <- data[, lapply(.SD, mean, na.rm = TRUE), .SD = c('v','vw','o','c','h','l','t','n'), by = 'Date'] # } else if(TimeAgg == 'months') { # data[, Date := lubridate::floor_date(Date, unit = 'months')] # data <- data[, lapply(.SD, mean, na.rm = TRUE), .SD = c('v','vw','o','c','h','l','t','n'), by = 'Date'] # } else if(TimeAgg == 'quarters') { # data[, Date := lubridate::floor_date(Date, unit = 'quarters')] # data <- data[, lapply(.SD, mean, na.rm = TRUE), .SD = c('v','vw','o','c','h','l','t','n'), by = 'Date'] # } else if(TimeAgg == 'years') { # data[, Date := lubridate::floor_date(Date, unit = 'years')] # data <- data[, lapply(.SD, mean, na.rm = TRUE), .SD = c('v','vw','o','c','h','l','t','n'), by = 'Date'] # } # # if(Metric == '% Returns') { # for(i in c('o','c','h','l')) data[, paste0(i) := get(i) / data.table::shift(x = get(i)) - 1] # data <- data[seq_len(.N)[-1L]] # } else if(Metric == '% Log Returns') { # for(i in c('o','c','h','l')) data[, paste0(i) := log(get(i)) - log(data.table::shift(x = get(i)))] # data <- data[seq_len(.N)[-1L]] # } else if(Metric == 'Index') { # for(i in c('o','c','h','l')) data[, paste0(i) := get(i) / data.table::first(get(i))] # } else if(Metric == 'Quadratic Variation') { # for(i in c('o','c','h','l')) data[, temp_temp := data.table::shift(x = get(i), n = 1L, fill = NA, type = 'lag')][, paste0(i) := (get(i) - temp_temp)^2][, temp_temp := NULL] # data <- data[seq_len(.N)[-1L]] # } # }, error = function(x) NULL) # # } else { # if(Debug) print("here 1b") # data <- PolyOut # if(Debug) print(head(data)) # } # # return(list(results = data, PolyOut = PolyOut, CompanyName = CompanyName, Symbol = Symbol, Metric = Metric, StartDate = StartDate, EndDate = EndDate, APIKey = APIKey)) # } # #' @title Plot.Stock # #' # #' @description Create a candlestick plot for stocks. See https://plotly.com/r/figure-labels/ # #' # #' @family Stock Plots # #' @author Adrian Antico # #' # #' @param Type 'candlestick', 'ohlc' # #' @param StockDataOutput PolyOut returned from StockData() # #' @param Width = "1450px" # #' @param Height = "600px" # #' @param EchartsTheme = "macarons" # #' @param ShadowBlur = 5. Chart boxes' shadow blur amount. This attribute should be used along with shadowColor,shadowOffsetX, shadowOffsetY to set shadow to component # #' @param ShadowColor "black" # #' @param ShadowOffsetX 0 # #' @param ShadowOffsetY 0 # #' @param TextColor = "white" # #' @param title.fontSize = 22 # #' @param title.fontWeight = "bold", # norma # #' @param title.textShadowColor = '#63aeff' # #' @param title.textShadowBlur = 3 # #' @param title.textShadowOffsetY = 1 # #' @param title.textShadowOffsetX = -1 # #' @param xaxis.fontSize = 14 # #' @param yaxis.fontSize = 14 # #' # #' @export # Plot.Stock <- function(StockDataOutput, # Type = 'candlestick', # Metric = "Stock Price", # Width = NULL, # Height = NULL, # EchartsTheme = "macarons", # TextColor = "white", # ShadowBlur = 0, # ShadowColor = "black", # ShadowOffsetX = 0, # ShadowOffsetY = 0, # title.fontSize = 14, # title.fontWeight = "bold", # title.textShadowColor = '#63aeff', # title.textShadowBlur = 3, # title.textShadowOffsetY = 1, # title.textShadowOffsetX = -1, # Color = "green", # Color0 = "red", # BorderColor = "transparent", # BorderColor0 = "transparent", # BorderColorDoji = "transparent", # xaxis.fontSize = 14, # yaxis.fontSize = 14, # Debug = FALSE) { # # # Width = "1450px" # # Height = "600px" # # EchartsTheme = "macarons" # # TextColor = "white" # # ShadowBlur = 5 # # title.fontSize = 22 # # title.fontWeight = "bold" # # title.textShadowColor = '#63aeff' # # title.textShadowBlur = 3 # # title.textShadowOffsetY = 1 # # title.textShadowOffsetX = -1 # # Color = "green" # # Color0 = "red" # # BorderColor = "transparent" # # BorderColor0 = "transparent" # # BorderColorDoji = "transparent" # # xaxis.fontSize = 14 # #if(missing(StockDataOutput)) stop('StockDataOutput cannot be missing') # #if(Type == 'CandlestickPlot') Type <- 'candlestick' # # Build base plot depending on GroupVar availability # dt <- StockDataOutput$results # dt[, Date := as.character(Date)] # p1 <- echarts4r::e_charts_( # data = dt, # x = "Date", # dispose = TRUE, # darkMode = TRUE, # width = Width, # height = Height) # p1 <- echarts4r::e_candle_( # e = p1, # high = "h", # low = "l", # closing = "c", # opening = "o", # itemStyle = list( # #shadowBlur = ShadowBlur, # #shadowColor = ShadowColor, # #shadowOffsetX = ShadowOffsetX, # #shadowOffsetY = ShadowOffsetY, # color = Color, # color0 = Color0, # backgroundColor = "white", # borderColor = BorderColor, # borderColor0 = BorderColor0, # borderColorDoji = BorderColorDoji # ), # name = StockDataOutput$Symbol) # # # Finalize Plot Build # p1 <- echarts4r::e_legend(e = p1, show = FALSE) # p1 <- echarts4r::e_theme(e = p1, name = EchartsTheme) # p1 <- echarts4r::e_aria(e = p1, enabled = TRUE) # p1 <- echarts4r::e_tooltip(e = p1 , trigger = "axis") # p1 <- echarts4r::e_toolbox_feature(e = p1, feature = c("saveAsImage","dataZoom")) # p1 <- echarts4r::e_show_loading(e = p1, hide_overlay = TRUE, text = "Calculating...", color = "#000", text_color = TextColor, mask_color = "#000") # # p1 <- echarts4r::e_axis_(e = p1, serie = NULL, axis = "x", name = "Date", nameLocation = "middle", nameGap = 45, nameTextStyle = list(color = TextColor, fontStyle = "normal", fontWeight = "bold", fontSize = xaxis.fontSize)) # p1 <- echarts4r::e_brush(e = p1) # p1 <- echarts4r::e_datazoom(e = p1, x_index = c(0,1)) # p1 <- echarts4r::e_title( # p1, # text = if(length(StockDataOutput$CompanyName) == 0L) paste0(StockDataOutput$Symbol, ": ", StockDataOutput$StartDate, " to ", StockDataOutput$EndDate) else paste0(StockDataOutput$CompanyName, " - ", StockDataOutput$Symbol, ": ", StockDataOutput$StartDate, " to ", StockDataOutput$EndDate, " :: Measure: ", Metric), # textStyle = list( # color = TextColor, # fontWeight = title.fontWeight, # overflow = "truncate", # "none", "truncate", "break", # ellipsis = '...', # fontSize = title.fontSize, # textShadowColor = title.textShadowColor, # textShadowBlur = title.textShadowBlur, # textShadowOffsetY = title.textShadowOffsetY, # textShadowOffsetX = title.textShadowOffsetX)) # if(Debug) print("Plot.Line no group Echarts 9") # return(p1) # } # ---- # ----
/scratch/gouwar.j/cran-all/cranData/AutoPlots/R/PlotFunctions.R
# Pipeline_function -------------------------------------------------------- #' @title AutoScore STEP(i): Rank variables with machine learning (AutoScore Module 1) #' @param train_set A processed \code{data.frame} that contains data to be analyzed, for training. #' @param validation_set A processed \code{data.frame} that contains data to be analyzed, only for auc-based ranking. #' @param method method for ranking. Options: 1. `rf` - random forest (default), 2. `auc` - auc-based (required validation set). For "auc", univariate models will be built based on the train set, and the variable ranking is constructed via the AUC performance of corresponding univariate models on the validation set (`validation_set`). #' @param ntree Number of trees in the random forest (Default: 100). #' @details The first step in the AutoScore framework is variable ranking. We use random forest (RF), #' an ensemble machine learning algorithm, to identify the top-ranking predictors for subsequent score generation. #' This step correspond to Module 1 in the AutoScore paper. #' @return Returns a vector containing the list of variables and its ranking generated by machine learning (random forest) #' @examples #' # see AutoScore Guidebook for the whole 5-step workflow #' data("sample_data") #' names(sample_data)[names(sample_data) == "Mortality_inpatient"] <- "label" #' ranking <- AutoScore_rank(sample_data, ntree = 50) #' @references #' \itemize{ #' \item{Breiman, L. (2001), Random Forests, Machine Learning 45(1), 5-32} #' \item{Xie F, Chakraborty B, Ong MEH, Goldstein BA, Liu N. AutoScore: A Machine Learning-Based Automatic Clinical Score Generator and #' Its Application to Mortality Prediction Using Electronic Health Records. JMIR Medical Informatics 2020;8(10):e21798} #' } #' @seealso \code{\link{AutoScore_parsimony}}, \code{\link{AutoScore_weighting}}, \code{\link{AutoScore_fine_tuning}}, \code{\link{AutoScore_testing}}, Run \code{vignette("Guide_book", package = "AutoScore")} to see the guidebook or vignette. #' @export #' @importFrom randomForest randomForest importance #' AutoScore_rank <- function(train_set, validation_set = NULL, method = "rf", ntree = 100) { # set.seed(4) if (method == "rf") { train_set <- AutoScore_impute(train_set) train_set$label <- as.factor(train_set$label) model <- randomForest::randomForest(label ~ ., data = train_set, ntree = ntree, preProcess = "scale" ) # estimate variable importance importance <- randomForest::importance(model, scale = F) # summarize importance names(importance) <- rownames(importance) importance <- sort(importance, decreasing = T) cat("The ranking based on variable importance was shown below for each variable: \n") print(importance) plot_importance(importance) return(importance) } if (method == "auc") { if (is.null(validation_set)) { stop("Error: Please specify the validation set","\n",call.=FALSE) } imputation <- AutoScore_impute(train_set, validation_set) train_set <- imputation$train validation_set <- imputation$validation vars <- names(train_set) vars <- vars[vars != "label"] train_set$label <- as.factor(train_set$label) AUC <- rep(0, length(vars)) for (i in 1:length(vars)) { # log <- sprintf("--------%s--------", vars[i]) # print(log) if (length(unique(train_set[[vars[i]]])) > 1) { model <- glm(label ~ ., data = train_set[c("label", vars[i])], family = binomial(link = "logit")) pred <- predict(model, newdata = validation_set[c("label", vars[i])]) # confusionMatrix(pred, as.factor(as.character(val_set$label))) roc_obj <- roc(response = validation_set$label, predictor = as.numeric(pred), quiet = TRUE) AUC[i] <- auc(roc_obj)[[1]] } else { # if model can't be built AUC[i] = 0 } } # summarize importance (AUC) names(AUC) <- vars AUC <- sort(AUC, decreasing = T) cat("The auc-based ranking based on variable importance was shown below for each variable: \n") print(AUC) plot_importance(AUC) return(AUC) } else { warning("Please specify methods among available options: rf, auc\n") } } #' @title AutoScore STEP(ii): Select the best model with parsimony plot (AutoScore Modules 2+3+4) #' @param train_set A processed \code{data.frame} that contains data to be analyzed, for training. #' @param validation_set A processed \code{data.frame} that contains data for validation purpose. #' @param rank the raking result generated from AutoScore STEP(i) \code{\link{AutoScore_rank}} #' @param n_min Minimum number of selected variables (Default: 1). #' @param n_max Maximum number of selected variables (Default: 20). #' @param max_score Maximum total score (Default: 100). #' @param cross_validation If set to \code{TRUE}, cross-validation would be used for generating parsimony plot, which is #' suitable for small-size data. Default to \code{FALSE} #' @param fold The number of folds used in cross validation (Default: 10). Available if \code{cross_validation = TRUE}. #' @param categorize Methods for categorize continuous variables. Options include "quantile" or "kmeans" (Default: "quantile"). #' @param quantiles Predefined quantiles to convert continuous variables to categorical ones. (Default: c(0, 0.05, 0.2, 0.8, 0.95, 1)) Available if \code{categorize = "quantile"}. #' @param max_cluster The max number of cluster (Default: 5). Available if \code{categorize = "kmeans"}. #' @param do_trace If set to TRUE, all results based on each fold of cross-validation would be printed out and plotted (Default: FALSE). Available if \code{cross_validation = TRUE}. #' @param auc_lim_min Min y_axis limit in the parsimony plot (Default: 0.5). #' @param auc_lim_max Max y_axis limit in the parsimony plot (Default: "adaptive"). #' @details This is the second step of the general AutoScore workflow, to generate the parsimony plot to help select a parsimonious model. #' In this step, it goes through AutoScore Module 2,3 and 4 multiple times and to evaluate the performance under different variable list. #' The generated parsimony plot would give researcher an intuitive figure to choose the best models. #' If data size is small (ie, <5000), an independent validation set may not be a wise choice. Then, we suggest using cross-validation #' to maximize the utility of data. Set \code{cross_validation=TRUE}. Run \code{vignette("Guide_book", package = "AutoScore")} to see the guidebook or vignette. #' @return List of AUC value for different number of variables #' @examples #' \donttest{ #' # see AutoScore Guidebook for the whole 5-step workflow #' data("sample_data") #' names(sample_data)[names(sample_data) == "Mortality_inpatient"] <- "label" #' out_split <- split_data(data = sample_data, ratio = c(0.7, 0.1, 0.2)) #' train_set <- out_split$train_set #' validation_set <- out_split$validation_set #' ranking <- AutoScore_rank(train_set, ntree=100) #' AUC <- AutoScore_parsimony( #' train_set, #' validation_set, #' rank = ranking, #' max_score = 100, #' n_min = 1, #' n_max = 20, #' categorize = "quantile", #' quantiles = c(0, 0.05, 0.2, 0.8, 0.95, 1) #' )} #' @references #' \itemize{ #' \item{Xie F, Chakraborty B, Ong MEH, Goldstein BA, Liu N, AutoScore: A Machine Learning-Based Automatic Clinical #' Score Generator and Its Application to Mortality Prediction Using Electronic Health Records, #' JMIR Med Inform 2020;8(10):e21798, doi: 10.2196/21798} #' } #' @seealso \code{\link{AutoScore_rank}}, \code{\link{AutoScore_weighting}}, \code{\link{AutoScore_fine_tuning}}, \code{\link{AutoScore_testing}}, Run \code{vignette("Guide_book", package = "AutoScore")} to see the guidebook or vignette. #' @export #' @import pROC AutoScore_parsimony <- function(train_set, validation_set, rank, max_score = 100, n_min = 1, n_max = 20, cross_validation = FALSE, fold = 10, categorize = "quantile", quantiles = c(0, 0.05, 0.2, 0.8, 0.95, 1), max_cluster = 5, do_trace = FALSE, auc_lim_min = 0.5, auc_lim_max = "adaptive") { if (n_max > length(rank)) { warning( "WARNING: the n_max (", n_max, ") is larger the number of all variables (", length(rank), "). We Automatically revise the n_max to ", length(rank) ) n_max <- length(rank) } # Cross Validation scenario if (cross_validation == TRUE) { # Divide the data equally into n fold, record its index number #set.seed(4) index <- list() all <- 1:length(train_set[, 1]) for (i in 1:(fold - 1)) { a <- sample(all, trunc(length(train_set[, 1]) / fold)) index <- append(index, list(a)) all <- all[!(all %in% a)] } index <- c(index, list(all)) # Create a new variable auc_set to store all AUC value during the cross-validation auc_set <- data.frame(rep(0, n_max - n_min + 1)) # for each fold, generate train_set and validation_set for (j in 1:fold) { validation_set_temp <- train_set[index[[j]],] train_set_tmp <- train_set[-index[[j]],] #variable_list <- names(rank) AUC <- c() # Go through AUtoScore Module 2/3/4 in the loop for (i in n_min:n_max) { variable_list <- names(rank)[1:i] train_set_1 <- train_set_tmp[, c(variable_list, "label")] validation_set_1 <- validation_set_temp[, c(variable_list, "label")] model_roc <- compute_auc_val( train_set_1, validation_set_1, variable_list, categorize, quantiles, max_cluster, max_score ) #print(auc(model_roc)) AUC <- c(AUC, auc(model_roc)) } # plot parsimony plot for each fold names(AUC) <- n_min:n_max # only print and plot when do_trace = TRUE if (do_trace) { print(paste("list of AUC values for fold", j)) print(data.frame(AUC)) plot( AUC, main = paste("Parsimony plot (cross validation) for fold", j), xlab = "Number of Variables", ylab = "Area Under the Curve", col = "#2b8cbe", lwd = 2, type = "o" ) } # store AUC result from each fold into "auc_set" auc_set <- cbind(auc_set, data.frame(AUC)) } # finish loop and then output final results averaged by all folds auc_set$rep.0..n_max...n_min...1. <- NULL auc_set$sum <- rowSums(auc_set) / fold cat("***list of final mean AUC values through cross-validation are shown below \n") print(data.frame(auc_set$sum)) # output final results and plot parsimony plot plot(plot_auc(AUC = auc_set$sum, variables = names(rank)[n_min:n_max], num = n_min:n_max, auc_lim_min = auc_lim_min, auc_lim_max = auc_lim_max, ylab = "Area Under the Curve", title = paste0("Final Parsimony plot based on ", fold, "-fold Cross Validation"))) return(auc_set) } # if Cross validation is FALSE else{ AUC <- c() # Go through AutoScore Module 2/3/4 in the loop for (i in n_min:n_max) { cat(paste("Select", i, "Variable(s): ")) variable_list <- names(rank)[1:i] train_set_1 <- train_set[, c(variable_list, "label")] validation_set_1 <- validation_set[, c(variable_list, "label")] model_roc <- compute_auc_val( train_set_1, validation_set_1, variable_list, categorize, quantiles, max_cluster, max_score ) print(auc(model_roc)) AUC <- c(AUC, auc(model_roc)) } plot(plot_auc(AUC = AUC, variables = names(rank)[n_min:n_max], num = n_min:n_max, auc_lim_min = auc_lim_min, auc_lim_max = auc_lim_max, ylab = "Area Under the Curve", title = "Parsimony plot on the validation set")) names(AUC) <- names(rank)[n_min:n_max] return(AUC) } } #' @title AutoScore STEP(iii): Generate the initial score with the final list of variables (Re-run AutoScore Modules 2+3) #' @param train_set A processed \code{data.frame} that contains data to be analyzed, for training. #' @param validation_set A processed \code{data.frame} that contains data for validation purpose. #' @param final_variables A vector containing the list of selected variables, selected from Step(ii)\code{\link{AutoScore_parsimony}}. Run \code{vignette("Guide_book", package = "AutoScore")} to see the guidebook or vignette. #' @param max_score Maximum total score (Default: 100). #' @param categorize Methods for categorize continuous variables. Options include "quantile" or "kmeans" (Default: "quantile"). #' @param quantiles Predefined quantiles to convert continuous variables to categorical ones. (Default: c(0, 0.05, 0.2, 0.8, 0.95, 1)) Available if \code{categorize = "quantile"}. #' @param max_cluster The max number of cluster (Default: 5). Available if \code{categorize = "kmeans"}. #' @param metrics_ci whether to calculate confidence interval for the metrics of sensitivity, specificity, etc. #' @return Generated \code{cut_vec} for downstream fine-tuning process STEP(iv) \code{\link{AutoScore_fine_tuning}}. #' @references #' \itemize{ #' \item{Xie F, Chakraborty B, Ong MEH, Goldstein BA, Liu N. AutoScore: A Machine Learning-Based Automatic Clinical Score Generator and #' Its Application to Mortality Prediction Using Electronic Health Records. JMIR Medical Informatics 2020;8(10):e21798} #' } #' @seealso \code{\link{AutoScore_rank}}, \code{\link{AutoScore_parsimony}}, \code{\link{AutoScore_fine_tuning}}, \code{\link{AutoScore_testing}}, Run \code{vignette("Guide_book", package = "AutoScore")} to see the guidebook or vignette. #' @export #' @import pROC ggplot2 AutoScore_weighting <- function(train_set, validation_set, final_variables, max_score = 100, categorize = "quantile", max_cluster = 5, quantiles = c(0, 0.05, 0.2, 0.8, 0.95, 1), metrics_ci = FALSE) { # prepare train_set and Validation Set cat("****Included Variables: \n") print(data.frame(variable_name = final_variables)) train_set_1 <- train_set[, c(final_variables, "label")] validation_set_1 <- validation_set[, c(final_variables, "label")] # AutoScore Module 2 : cut numeric and transfer categories and generate "cut_vec" cut_vec <- get_cut_vec( train_set_1, categorize = categorize, quantiles = quantiles, max_cluster = max_cluster ) train_set_2 <- transform_df_fixed(train_set_1, cut_vec) validation_set_2 <- transform_df_fixed(validation_set_1, cut_vec) # AutoScore Module 3 : Score weighting score_table <- compute_score_table(train_set_2, max_score, final_variables) cat("****Initial Scores: \n") #print(as.data.frame(score_table)) print_scoring_table(scoring_table = score_table, final_variable = final_variables) # Using "assign_score" to generate score based on new dataset and Scoring table "score_table" validation_set_3 <- assign_score(validation_set_2, score_table) validation_set_3$total_score <- rowSums(subset(validation_set_3, select = names(validation_set_3)[names(validation_set_3) != "label"])) y_validation <- validation_set_3$label # Intermediate evaluation based on Validation Set plot_roc_curve(validation_set_3$total_score, as.numeric(y_validation) - 1) cat("***Performance (based on validation set):\n") print_roc_performance(y_validation, validation_set_3$total_score, threshold = "best", metrics_ci = metrics_ci) cat( "***The cutoffs of each variable generated by the AutoScore are saved in cut_vec. You can decide whether to revise or fine-tune them \n" ) #print(cut_vec) return(cut_vec) } #' @title AutoScore STEP(iv): Fine-tune the score by revising cut_vec with domain knowledge (AutoScore Module 5) #' @description Domain knowledge is essential in guiding risk model development. #' For continuous variables, the variable transformation is a data-driven process (based on "quantile" or "kmeans" ). #' In this step, the automatically generated cutoff values for each continuous variable can be fine-tuned #' by combining, rounding, and adjusting according to the standard clinical norm. Revised \code{cut_vec} will be input with domain knowledge to #' update scoring table. User can choose any cut-off values/any number of categories. Then final Scoring table will be generated. Run \code{vignette("Guide_book", package = "AutoScore")} to see the guidebook or vignette. #' @param train_set A processed \code{data.frame} that contains data to be analyzed, for training. #' @param validation_set A processed \code{data.frame} that contains data for validation purpose. #' @param final_variables A vector containing the list of selected variables, selected from Step(ii) \code{\link{AutoScore_parsimony}}. Run \code{vignette("Guide_book", package = "AutoScore")} to see the guidebook or vignette. #' @param max_score Maximum total score (Default: 100). #' @param cut_vec Generated from STEP(iii) \code{\link{AutoScore_weighting}}.Please follow the guidebook #' @param metrics_ci whether to calculate confidence interval for the metrics of sensitivity, specificity, etc. #' @return Generated final table of scoring model for downstream testing #' @examples #' ## Please see the guidebook or vignettes #' @references #' \itemize{ #' \item{Xie F, Chakraborty B, Ong MEH, Goldstein BA, Liu N. AutoScore: A Machine Learning-Based Automatic Clinical Score Generator and #' Its Application to Mortality Prediction Using Electronic Health Records. JMIR Medical Informatics 2020;8(10):e21798} #' } #' @seealso \code{\link{AutoScore_rank}}, \code{\link{AutoScore_parsimony}}, \code{\link{AutoScore_weighting}}, \code{\link{AutoScore_testing}},Run \code{vignette("Guide_book", package = "AutoScore")} to see the guidebook or vignette. #' @export #' @import pROC ggplot2 AutoScore_fine_tuning <- function(train_set, validation_set, final_variables, cut_vec, max_score = 100, metrics_ci = FALSE) { # Prepare train_set and Validation Set train_set_1 <- train_set[, c(final_variables, "label")] validation_set_1 <- validation_set[, c(final_variables, "label")] # AutoScore Module 2 : cut numeric and transfer categories (based on fix "cut_vec" vector) train_set_2 <- transform_df_fixed(train_set_1, cut_vec = cut_vec) validation_set_2 <- transform_df_fixed(validation_set_1, cut_vec = cut_vec) # AutoScore Module 3 : Score weighting score_table <- compute_score_table(train_set_2, max_score, final_variables) cat("***Fine-tuned Scores: \n") #print(as.data.frame(score_table)) print_scoring_table(scoring_table = score_table, final_variable = final_variables) # Using "assign_score" to generate score based on new dataset and Scoring table "score_table" validation_set_3 <- assign_score(validation_set_2, score_table) validation_set_3$total_score <- rowSums(subset(validation_set_3, select = names(validation_set_3)[names(validation_set_3) != "label"])) ## which name ="label" y_validation <- validation_set_3$label # Intermediate evaluation based on Validation Set after fine-tuning plot_roc_curve(validation_set_3$total_score, as.numeric(y_validation) - 1) cat("***Performance (based on validation set, after fine-tuning):\n") print_roc_performance(y_validation, validation_set_3$total_score, threshold = "best", metrics_ci = metrics_ci) return(score_table) } #' @title AutoScore STEP(v): Evaluate the final score with ROC analysis (AutoScore Module 6) #' @param test_set A processed \code{data.frame} that contains data for testing purpose. This \code{data.frame} should have same format as #' \code{train_set} (same variable names and outcomes) #' @param final_variables A vector containing the list of selected variables, selected from Step(ii) \code{\link{AutoScore_parsimony}}. Run \code{vignette("Guide_book", package = "AutoScore")} to see the guidebook or vignette. #' @param scoring_table The final scoring table after fine-tuning, generated from STEP(iv) \code{\link{AutoScore_fine_tuning}}.Please follow the guidebook #' @param cut_vec Generated from STEP(iii) \code{\link{AutoScore_weighting}}.Please follow the guidebook #' @param threshold Score threshold for the ROC analysis to generate sensitivity, specificity, etc. If set to "best", the optimal threshold will be calculated (Default:"best"). #' @param with_label Set to TRUE if there are labels in the test_set and performance will be evaluated accordingly (Default:TRUE). #' Set it to "FALSE" if there are not "label" in the "test_set" and the final predicted scores will be the output without performance evaluation. #' @param metrics_ci whether to calculate confidence interval for the metrics of sensitivity, specificity, etc. #' @return A data frame with predicted score and the outcome for downstream visualization. #' @examples #' ## Please see the guidebook or vignettes #' @references #' \itemize{ #' \item{Xie F, Chakraborty B, Ong MEH, Goldstein BA, Liu N. AutoScore: A Machine Learning-Based Automatic Clinical Score Generator and #' Its Application to Mortality Prediction Using Electronic Health Records. JMIR Medical Informatics 2020;8(10):e21798} #' } #' @seealso \code{\link{AutoScore_rank}}, \code{\link{AutoScore_parsimony}}, \code{\link{AutoScore_weighting}}, \code{\link{AutoScore_fine_tuning}}, \code{\link{print_roc_performance}}, Run \code{vignette("Guide_book", package = "AutoScore")} to see the guidebook or vignette. #' @export #' @import pROC ggplot2 AutoScore_testing <- function(test_set, final_variables, cut_vec, scoring_table, threshold = "best", with_label = TRUE, metrics_ci = TRUE) { if (with_label) { # prepare test set: categorization and "assign_score" test_set_1 <- test_set[, c(final_variables, "label")] test_set_2 <- transform_df_fixed(test_set_1, cut_vec = cut_vec) test_set_3 <- assign_score(test_set_2, scoring_table) test_set_3$total_score <- rowSums(subset(test_set_3, select = names(test_set_3)[names(test_set_3) != "label"])) test_set_3$total_score[which(is.na(test_set_3$total_score))] <- 0 y_test <- test_set_3$label # Final evaluation based on testing set plot_roc_curve(test_set_3$total_score, as.numeric(y_test) - 1) cat("***Performance using AutoScore:\n") model_roc <- roc(y_test, test_set_3$total_score, quiet = T) print_roc_performance(y_test, test_set_3$total_score, threshold = threshold, metrics_ci = metrics_ci) #Modelprc <- pr.curve(test_set_3$total_score[which(y_test == 1)],test_set_3$total_score[which(y_test == 0)],curve = TRUE) #values<-coords(model_roc, "best", ret = c("specificity", "sensitivity", "accuracy", "npv", "ppv", "precision"), transpose = TRUE) pred_score <- data.frame(pred_score = test_set_3$total_score, Label = y_test) return(pred_score) } else { test_set_1 <- test_set[, c(final_variables)] test_set_2 <- transform_df_fixed(test_set_1, cut_vec = cut_vec) test_set_3 <- assign_score(test_set_2, scoring_table) test_set_3$total_score <- rowSums(subset(test_set_3, select = names(test_set_3)[names(test_set_3) != "label"])) test_set_3$total_score[which(is.na(test_set_3$total_score))] <- 0 pred_score <- data.frame(pred_score = test_set_3$total_score, Label = NA) return(pred_score) } } # Direct_function --------------------------------------------------------- #' @title AutoScore function: Univariable Analysis #' @description Perform univariable analysis and generate the result table with odd ratios. #' @param df data frame after checking #' @return result of univariate analysis #' @examples #' data("sample_data") #' names(sample_data)[names(sample_data) == "Mortality_inpatient"] <- "label" #' uni_table<-compute_uni_variable_table(sample_data) #' @export compute_uni_variable_table <- function(df) { uni_table <- data.frame() for (i in names(df)[names(df) != "label"]) { model <- glm( as.formula("label ~ ."), data = subset(df, select = c("label", i)), family = binomial, na.action = na.omit ) a <- cbind(exp(cbind(OR = coef(model), confint.default(model))), summary(model)$coef[, "Pr(>|z|)"]) uni_table <- rbind(uni_table, a) } uni_table <- uni_table[!grepl("Intercept", row.names(uni_table), ignore.case = T), ] uni_table <- round(uni_table, digits = 3) uni_table$V4[uni_table$V4 < 0.001] <- "<0.001" uni_table$OR <- paste(uni_table$OR, "(", uni_table$`2.5 %`, "-", uni_table$`97.5 %`, ")", sep = "") uni_table$`2.5 %` <- NULL uni_table$`97.5 %` <- NULL names(uni_table)[names(uni_table) == "V4"] <- "p value" return(uni_table) } #' @title AutoScore function: Multivariate Analysis #' @description Generate tables for multivariate analysis #' @param df data frame after checking #' @return result of the multivariate analysis #' @examples #' data("sample_data") #' names(sample_data)[names(sample_data) == "Mortality_inpatient"] <- "label" #' multi_table<-compute_multi_variable_table(sample_data) #' @export compute_multi_variable_table <- function(df) { model <- glm(label ~ ., data = df, family = binomial, na.action = na.omit) multi_table <- cbind(exp(cbind( adjusted_OR = coef(model), confint.default(model) )), summary(model)$coef[, "Pr(>|z|)"]) multi_table <- multi_table[!grepl("Intercept", row.names(multi_table), ignore.case = T), ] multi_table <- round(multi_table, digits = 3) multi_table <- as.data.frame(multi_table) multi_table$V4[multi_table$V4 < 0.001] <- "<0.001" multi_table$adjusted_OR <- paste( multi_table$adjusted_OR, "(", multi_table$`2.5 %`, "-", multi_table$`97.5 %`, ")", sep = "" ) multi_table$`2.5 %` <- NULL multi_table$`97.5 %` <- NULL names(multi_table)[names(multi_table) == "V4"] <- "p value" return(multi_table) } #' @title AutoScore function: Print receiver operating characteristic (ROC) performance #' @description Print receiver operating characteristic (ROC) performance #' @param label outcome variable #' @param score predicted score #' @param threshold Threshold for analyze sensitivity, specificity and other metrics. Default to "best" #' @param metrics_ci whether to calculate confidence interval for the metrics of sensitivity, specificity, etc. #' @seealso \code{\link{AutoScore_testing}} #' @return No return value and the ROC performance will be printed out directly. #' @export #' @import pROC print_roc_performance <- function(label, score, threshold = "best", metrics_ci = FALSE) { if (sum(is.na(score)) > 0) warning("NA in the score: ", sum(is.na(score))) model_roc <- roc(label, score, quiet = T) cat("AUC: ", round(auc(model_roc), 4), " ") print(ci(model_roc)) if (threshold == "best") { threshold <- ceiling(coords(model_roc, "best", ret = "threshold", transpose = TRUE)) cat("Best score threshold: >=", threshold, "\n") } else { cat("Score threshold: >=", threshold, "\n") } cat("Other performance indicators based on this score threshold: \n") if(metrics_ci){ roc <- ci.coords( model_roc, threshold , ret = c("specificity", "sensitivity", "npv", "ppv"), transpose = TRUE ) cat( "Sensitivity: ", round(roc$sensitivity[2], 4), " 95% CI: ", round(roc$sensitivity[1], 4), "-", round(roc$sensitivity[3], 4), "\n", sep = "" ) cat( "Specificity: ", round(roc$specificity[2], 4), " 95% CI: ", round(roc$specificity[1], 4), "-", round(roc$specificity[3], 4), "\n", sep = "" ) cat( "PPV: ", round(roc$ppv[2], 4), " 95% CI: ", round(roc$ppv[1], 4), "-", round(roc$ppv[3], 4), "\n", sep = "" ) cat( "NPV: ", round(roc$npv[2], 4), " 95% CI: ", round(roc$npv[1], 4), "-", round(roc$npv[3], 4), "\n", sep = "" )} else{ roc <- coords( model_roc, threshold , ret = c("specificity", "sensitivity", "npv", "ppv"), transpose = TRUE ) cat( "Sensitivity: ", round(roc[2], 4), "\n", sep = "" ) cat( "Specificity: ", round(roc[1], 4), "\n", sep = "" ) cat( "PPV: ", round(roc[4], 4), "\n", sep = "" ) cat( "NPV: ", round(roc[3], 4), "\n", sep = "" )} } #' @title AutoScore function: Print conversion table based on final performance evaluation #' @description Print conversion table based on final performance evaluation #' @param pred_score a vector with outcomes and final scores generated from \code{\link{AutoScore_testing}} #' @param by specify correct method for categorizing the threshold: by "risk" or "score".Default to "risk" #' @param values A vector of threshold for analyze sensitivity, specificity and other metrics. Default to "c(0.01,0.05,0.1,0.2,0.5)" #' @seealso \code{\link{AutoScore_testing}} #' @return No return value and the conversion will be printed out directly. #' @export #' @import pROC knitr conversion_table<-function(pred_score, by = "risk", values = c(0.01,0.05,0.1,0.2,0.5)){ glmmodel<-glm(Label~pred_score,data = pred_score,family = binomial(link="logit")) pred_score$pred_risk<-predict(glmmodel,newdata=pred_score, type = "response") rtotoal<-data.frame(matrix(nrow=0,ncol=7)) Modelroc<-roc(pred_score$Label,pred_score$pred_risk) if(by=="risk"){ for(i in values){ r<-data.frame(i) r$i<-paste(r$i*100,"%",sep="") names(r)[1]<-"Predicted Risk" r$`Score cut-off`<-paste("",min(pred_score[pred_score$pred_risk>=i,]$pred_score),sep="") r$`Percentage of patients (%)`<-round(length(pred_score[pred_score$pred_risk>=i,][,1])/length(pred_score[,1]),digits = 2)*100 r1<-organize_performance(ci.coords(Modelroc,x=i ,input="threshold", ret=c("accuracy", "sensitivity","specificity" , "ppv", "npv" ))) #r1$X1<-NULL r<-cbind(r,r1) rtotoal<-rbind(rtotoal,r) } names(rtotoal)<-c("Predicted Risk [>=]", "Score cut-off [>=]", "Percentage of patients (%)","Accuracy (95% CI)", "Sensitivity (95% CI)", "Specificity (95% CI)", "PPV (95% CI)", "NPV (95% CI)") }else if(by=="score"){ for(i in values){ r<-data.frame(i) risk<-min(pred_score[pred_score$pred_score>=i,]$pred_risk) #risk<-round(risk,3) r$risk<-paste(round(risk,3)*100,"%",sep="") r$`Percentage of patients (%)`<-round(length(pred_score[pred_score$pred_risk>=risk,][,1])/length(pred_score[,1]),digits = 2)*100 r1<-organize_performance(ci.coords(Modelroc,x=risk ,input="threshold", ret=c("accuracy", "sensitivity","specificity" , "ppv", "npv" ))) #r1$X1<-NULL r<-cbind(r,r1) rtotoal<-rbind(rtotoal,r) } names(rtotoal)<-c("Score cut-off [>=]","Predicted Risk [>=]", "Percentage of patients (%)","Accuracy (95% CI)", "Sensitivity (95% CI)", "Specificity (95% CI)", "PPV (95% CI)", "NPV (95% CI)") } else{ stop('ERROR: please specify correct method for categorizing the threshold: by "risk" or "score".')} kable(rtotoal,align=c(rep('c',times=7))) } # Internal_function ------------------------------------------------------- ## built-in function for AutoScore below ## Those functions are cited by pipeline functions #' @title Internal function: Compute scoring table based on training dataset (AutoScore Module 3) #' @description Compute scoring table based on training dataset #' @param train_set_2 Processed training set after variable transformation (AutoScore Module 2) #' @param max_score Maximum total score #' @param variable_list List of included variables #' @return A scoring table compute_score_table <- function(train_set_2, max_score, variable_list) { #AutoScore Module 3 : Score weighting # First-step logistic regression model <- glm(label ~ ., family = binomial(link = "logit"), data = train_set_2) coef_vec <- coef(model) if (length(which(is.na(coef_vec))) > 0) { warning(" WARNING: GLM output contains NULL, Replace NULL with 1") coef_vec[which(is.na(coef_vec))] <- 1 } train_set_2 <- change_reference(train_set_2, coef_vec) # Second-step logistic regression model <- glm(label ~ ., family = binomial(link = "logit"), data = train_set_2) coef_vec <- coef(model) if (length(which(is.na(coef_vec))) > 0) { warning(" WARNING: GLM output contains NULL, Replace NULL with 1") coef_vec[which(is.na(coef_vec))] <- 1 } # rounding for final scoring table "score_table" coef_vec_tmp <- round(coef_vec / min(coef_vec[-1])) score_table <- add_baseline(train_set_2, coef_vec_tmp) # normalization according to "max_score" and regenerate score_table total_max <- max_score total <- 0 for (i in 1:length(variable_list)) total <- total + max(score_table[grepl(variable_list[i], names(score_table))]) score_table <- round(score_table / (total / total_max)) return(score_table) } #' @title Internal function: Compute AUC based on validation set for plotting parsimony (AutoScore Module 4) #' @description Compute AUC based on validation set for plotting parsimony #' @param train_set_1 Processed training set #' @param validation_set_1 Processed validation set #' @param max_score Maximum total score #' @param variable_list List of included variables #' @param categorize Methods for categorize continuous variables. Options include "quantile" or "kmeans" #' @param quantiles Predefined quantiles to convert continuous variables to categorical ones. Available if \code{categorize = "quantile"}. #' @param max_cluster The max number of cluster (Default: 5). Available if \code{categorize = "kmeans"}. #' @return A List of AUC for parsimony plot compute_auc_val <- function(train_set_1, validation_set_1, variable_list, categorize, quantiles, max_cluster, max_score) { # AutoScore Module 2 : cut numeric and transfer categories cut_vec <- get_cut_vec( train_set_1, categorize = categorize, quantiles = quantiles, max_cluster = max_cluster ) train_set_2 <- transform_df_fixed(train_set_1, cut_vec) validation_set_2 <- transform_df_fixed(validation_set_1, cut_vec) if (sum(is.na(validation_set_2)) > 0) warning("NA in the validation_set_2: ", sum(is.na(validation_set_2))) if (sum(is.na(train_set_2)) > 0) warning("NA in the train_set_2: ", sum(is.na(train_set_2))) # AutoScore Module 3 : Variable Weighting score_table <- compute_score_table(train_set_2, max_score, variable_list) if (sum(is.na(score_table)) > 0) warning("NA in the score_table: ", sum(is.na(score_table))) # Using "assign_score" to generate score based on new dataset and Scoring table "score_table" validation_set_3 <- assign_score(validation_set_2, score_table) if (sum(is.na(validation_set_3)) > 0) warning("NA in the validation_set_3: ", sum(is.na(validation_set_3))) validation_set_3$total_score <- rowSums(subset(validation_set_3, select = names(validation_set_3)[names(validation_set_3) != "label"])) y_validation <- validation_set_3$label # plot_roc_curve(validation_set_3$total_score,as.numeric(y_validation)-1) # calculate AUC value model_roc <- roc(y_validation, validation_set_3$total_score, quiet = T) return(model_roc) } #' @title Internal Function: Plotting ROC curve #' @param prob Predicate probability #' @param labels Actual outcome(binary) #' @param quiet if set to TRUE, there will be no trace printing #' @return No return value and the ROC curve will be plotted. #' @import pROC plot_roc_curve <- function(prob, labels, quiet = TRUE) { #library(pROC) # prob<-predict(model.glm,newdata=X_test, type = 'response') model_roc <- roc(labels, prob, quiet = quiet) auc <- auc(model_roc) auc_ci <- ci.auc(model_roc) roc.data <- data.frame( fpr = as.vector(coords(model_roc, "local maximas", ret = "1-specificity", transpose = TRUE)), tpr = as.vector(coords(model_roc, "local maximas", ret = "sensitivity", transpose = TRUE))) auc_ci <- sort(as.numeric(auc_ci)) # should include AUC and 95% CI clr <- rgb(red = 41, green = 70, blue = 76, maxColorValue = 255) clr_axis <- rgb(red = 25, green = 24, blue = 24, maxColorValue = 255) p<-ggplot(data.frame(fpr = roc.data$fpr, tpr = roc.data$tpr), aes_string(x = "fpr", ymin = 0, ymax = "tpr")) + #geom_ribbon(alpha = 0.2, fill = clr) + geom_line(aes_string(y = "tpr"), color = clr, lwd = 1.2) + geom_abline(slope = 1, intercept = 0, lty = 2, lwd = 0.3, color = clr_axis) + # scale_color_manual(values = ) + scale_x_continuous(expand = c(0, 0), limits = c(0, 1)) + scale_y_continuous(expand = c(0, 0), limits = c(0, 1)) + labs(x = "1-Specificity", y = "Sensitivity", title = "Receiver Operating Characteristic Curve", subtitle = sprintf("AUC=%.3f, 95%% CI: %.3f-%.3f", auc_ci[2], auc_ci[1], auc_ci[3])) + theme_classic() + theme(plot.margin = unit(c(0.5,0.5,0.5,0.5),"cm"), axis.text= element_text(size=12), text = element_text(size = 12, color = clr_axis), #text = element_text(family = "Tahoma", size = 12, color = clr_axis), # axis.line = element_line(color = clr_axis, size = 0.3), axis.line = element_blank(), axis.ticks.length = unit(0.15, units = "cm"), panel.border = element_rect(color = clr_axis, fill = NA)) print(p) } organize_performance<-function(w1){ df <- data.frame(w1) df <- round(df, digits = 3)*100 df1 <- data.frame(1) df1 <- data.frame(`Accuracy (95% CI)`=paste(df$accuracy.50.,"% (",df$accuracy.2.5.,"-",df$accuracy.97.5.,"%)",sep = ""), `Sensitivity (95% CI)`=paste(df$sensitivity.50.,"% (",df$sensitivity.2.5.,"-",df$sensitivity.97.5.,"%)",sep = ""), `Specificity (95% CI)`=paste(df$specificity.50.,"% (",df$specificity.2.5.,"-",df$specificity.97.5.,"%)",sep = ""), `PPV (95% CI)`=paste(df$ppv.50.,"% (",df$ppv.2.5.,"-",df$ppv.97.5.,"%)",sep = ""), `NPV (95% CI)`=paste(df$npv.50.,"% (",df$npv.2.5.,"-",df$npv.97.5.,"%)",sep = ""), check.names = FALSE) #print(df1) return(df1) } #' 20000 simulated ICU admission data, with the same distribution as the data in the MIMIC-III ICU database #' #' @description 20000 simulated samples, with the same distribution as the data in the MIMIC-III ICU database. It is used for demonstration only in the Guidebook. Run \code{vignette("Guide_book", package = "AutoScore")} to see the guidebook or vignette. #' \itemize{ #' \item{Johnson, A., Pollard, T., Shen, L. et al. MIMIC-III, a freely accessible critical care database. Sci Data 3, 160035 (2016).} #' } "sample_data" #' 1000 simulated ICU admission data, with the same distribution as the data in the MIMIC-III ICU database #' #' @description 1000 simulated samples, with the same distribution as the data in the MIMIC-III ICU database. It is used for demonstration only in the Guidebook. Run \code{vignette("Guide_book", package = "AutoScore")} to see the guidebook or vignette. #' \itemize{ #' \item{Johnson, A., Pollard, T., Shen, L. et al. MIMIC-III, a freely accessible critical care database. Sci Data 3, 160035 (2016).} #' } "sample_data_small" #' 20000 simulated ICU admission data with missing values #' #' @description 20000 simulated samples with missing values, which can be used for demostrating AutoScore workflow dealing with missing values. #' \itemize{ #' \item{Johnson, A., Pollard, T., Shen, L. et al. MIMIC-III, a freely accessible critical care database. Sci Data 3, 160035 (2016).} #' } "sample_data_with_missing"
/scratch/gouwar.j/cran-all/cranData/AutoScore/R/AutoScore.R